code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
/**
* @license
*
* Copyright 2011 Google Inc.
*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| JavaScript |
/**
* @license
*
* Copyright 2011 Google Inc.
*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| JavaScript |
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
| JavaScript |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
// Copyright 2011 Google
/**
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
| JavaScript |
/*
* Metro JS for jQuery
* http://drewgreenwell.com/
* For details and usage info see: http://drewgreenwell.com/projects/metrojs
Copyright (C) 2012, Drew Greenwell
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function () {
jQuery.fn.metrojs = {};
/* Preload Images */
// Usage: jQuery(['img1.jpg','img2.jpg']).metrojs.preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
jQuery.fn.metrojs.preloadImages = function (callback) {
var checklist = jQuery(this).toArray();
var $img = jQuery("<img style='display:none;'>").appendTo("body");
jQuery(this).each(function () {
$img.attr({ src: this }).load(function () {
var src = jQuery(this).attr('src');
for (var i = 0; i < checklist.length; i++) {
if (checklist[i] == element) { checklist.splice(i, 1); }
}
if (checklist.length == 0) { callback(); }
});
});
$img.remove();
}; jQuery.fn.liveTile = function (method) {
if (pubMethods[method]) {
var args = [];
for (var i = 1; i <= arguments.length; i++) {
args[i - 1] = arguments[i];
}
return pubMethods[method].apply(this, args);
} else if (typeof method === 'object' || !method) {
return pubMethods.init.apply(this, arguments);
} else {
jQuery.error('Method ' + method + ' does not exist on jQuery.liveTile');
}
};
jQuery.fn.liveTile.State = {
RUNNING: "running",
STOPPED: "stopped"
};
jQuery.fn.liveTile.defaults = {
mode: 'slide', // 'slide', 'flip', 'flip-list'
speed: 500, // how fast should animations be performed, in milliseconds
initDelay: -1, // how long to wait before the initial animation
delay: 5000, // how long to wait between animations
stops: "100%", // how much of the back tile should 'slide' reveal before starting a delay
stack: false, // should tiles in slide mode appear stacked (e.g Me tile)
direction: 'vertical', // which direction should animations be performed(horizontal | vertical)
tileCssSelector: '>div,>li', // The selector used by slide, flip, and flip-list mode to choose the front and back containers
listTileCssSelector: '>div,>p,>img,>a', // The selector used by flip-tile mode to choose the front and back containers.2
imageCssSelector: '>img,>a>img', // the selector used to choose a an image to apply a src or background to
ignoreDataAttributes: false, // should data attributes be ignored
pauseOnHover: false, // should tile animations be paused on hover in and restarted on hover out
repeatCount: -1, // number of times to repeat the animation
animationComplete: function (tileData, $front, $back) {
},
preloadImages: false, // should the images arrays be preloaded
fadeSlideSwap: false, // fade any image swaps on slides (e.g. mode: 'slide', stops:'50%', frontImages: ['img1.jpg', 'img2.jpg'])
appendBack: true, // appends the .last tile if one doesnt exist (slide and flip only)
triggerDelay: function (idx) { // used by flip-list to decide how random the tile flipping should be
return Math.random() * 3000;
},
alwaysTrigger: false, // used by flip-list to decide if all tiles are triggered every time
frontImages: null, // a list of images to use for the front
frontIsRandom: true, // should images be chosen at random or in order
frontIsBackgroundImage: false, // set the src attribute or css background-image property
frontIsInGrid: false, // only chooses one item for each iteration in flip-list
backImages: null, // a list of images to use for the back
backIsRandom: true, // should images be chosen at random or in order
backIsBackgroundImage: false, // set the src attribute or css background-image property
backIsInInGrid: false, // only chooses one item for each iteration in flip-list
flipListOnHover: false, // should items in flip-list flip and stop when hovered
useModernizr: (typeof (window.Modernizr) != "undefined"), // checks to see if modernizer is already in use
useHardwareAccel: true, // should css animations, transitions and transforms be used when available
$front: null, // the jQuery element to use as the front face of the tile; this will bypass tileCssSelector
$back: null // the jQuery element to use as the back face of the tile; this will bypass tileCssSelector
};
var privMethods = {
//a shuffle method to provide more randomness than sort
//credit: http://javascript.about.com/library/blshuffle.htm
//*avoiding prototype for sharepoint compatability
shuffleArray: function (array) {
var s = [];
while (array.length) s.push(array.splice(Math.random() * array.length, 1));
while (s.length) array.push(s.pop());
return array;
},
setTimer: function (func, interval) {
return setInterval(func, interval);
},
stopTimer: function (handle) {
clearInterval(handle);
return null;
},
setExtraProperties: function ($ele, imageObj) {
if (typeof (imageObj.alt) != "undefined")
$ele.attr("alt", imageObj.alt);
var $parent = $ele.parent();
if (typeof (imageObj.href) != "undefined" && $parent[0].tagName == "A") {
$parent.attr("href", imageObj.href);
if (typeof (imageObj.target) != "undefined")
$parent.attr("target", imageObj.target);
if (typeof (imageObj.onclick) != "undefined") {
$parent.attr("onclick", imageObj.onclick);
$ele.attr("onclick", "");
}
} else {
if (typeof (imageObj.onclick) != "undefined")
$ele.attr("onclick", imageObj.onclick);
}
},
// changes the src or background image property of an image in a flip-list
handleListItemSwap: function ($cont, image, isBgroundImg, stgs) {
var $img = $cont.find(stgs.imageCssSelector);
if (!isBgroundImg) {
$img.attr("src", image.src);
} else {
$img.css({ backgroundImage: "url('" + image.src + "')" });
}
privMethods.setExtraProperties($img, image);
},
handleSlide: function (isSlidingUp, $cont, swapFrontSource, stgs, index) {
if (!isSlidingUp && swapFrontSource) {
var image;
var $img = $cont.find(stgs.imageCssSelector);
image = stgs.frontImages[index];
if (stgs.fadeSlideSwap == true) {
$img.fadeOut(function () {
$img.attr("src", image.src);
privMethods.setExtraProperties($img, image);
$img.fadeIn();
});
} else {
$img.attr("src", image.src);
privMethods.setExtraProperties($img, image);
}
}
},
// fired if an image swap is needed. gets the image and applies properties
handleSwap: function ($cont, isFront, stgs, index) {
var image = privMethods.getImage(isFront, stgs, index);
var $img = $cont.find(stgs.imageCssSelector);
$img.attr("src", image.src);
privMethods.setExtraProperties($img, image);
},
// get an image from the frontImages or backImages array
getImage: function (isFront, stgs, index) {
var imgs = (isFront) ? stgs.frontImages : stgs.backImages;
var image;
image = imgs[Math.min(index, imgs.length - 1)];
return image;
}
};
var pubMethods = {
init: function (options) {
// Setup the public options for the livetile
var stgs = {};
jQuery.extend(stgs, jQuery.fn.liveTile.defaults, options);
//is there at least one item in the front images list?
var swapFrontSource = (typeof (stgs.frontImages) == 'object' && (stgs.frontImages instanceof Array) && stgs.frontImages.length > 0);
//is there at least one item in the back images list?
var swapBackSource = (typeof (stgs.backImages) == 'object' && (stgs.backImages instanceof Array) && stgs.backImages.length > 0);
var canTransform = false;
var canTransition = false;
var canTransform3d = false;
var canAnimate = false;
var canFlip3d = stgs.useHardwareAccel;
if (stgs.useHardwareAccel == true) {
if (stgs.useModernizr == false) {
//determine if the browser supports the neccessary accelerated features
if (typeof (window.MetroModernizr) != "undefined") {
canTransform = window.MetroModernizr.canTransform;
canTransition = window.MetroModernizr.canTransition;
canTransform3d = window.MetroModernizr.canTransform3d;
canAnimate = window.MetroModernizr.canAnimate;
} else {
window.MetroModernizr = {};
/***** check for browser capabilities credit: modernizr-1.7 *****/
var mod = 'metromodernizr';
var docElement = document.documentElement;
var docHead = document.head || document.getElementsByTagName('head')[0];
var modElem = document.createElement(mod);
var m_style = modElem.style;
var prefixes = ' -webkit- -moz- -o- -ms- -khtml- '.split(' ');
var domPrefixes = 'Webkit Moz O ms Khtml'.split(' ');
var test_props = function (props, callback) {
for (var i in props) {
if (m_style[props[i]] !== undefined && (!callback || callback(props[i], modElem))) {
return true;
}
}
};
var test_props_all = function (prop, callback) {
var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1),
props = (prop + ' ' + domPrefixes.join(uc_prop + ' ') + uc_prop).split(' ');
return !!test_props(props, callback);
};
var test_3d = function () {
var ret = !!test_props(['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']);
if (ret && 'webkitPerspective' in docElement.style) {
// Webkit allows this media query to succeed only if the feature is enabled.
// '@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d),(modernizr){ ... }'
ret = testMediaQuery('@media (' + prefixes.join('transform-3d),(') + 'metromodernizr)');
}
return ret;
};
var testMediaQuery = function (mq) {
var st = document.createElement('style'),
div = document.createElement('div'),
ret;
st.textContent = mq + '{#metromodernizr{height:3px}}';
docHead.appendChild(st);
div.id = 'metromodernizr';
docElement.appendChild(div);
ret = div.offsetHeight === 3;
st.parentNode.removeChild(st);
div.parentNode.removeChild(div);
return !!ret;
};
canTransform = !!test_props(['transformProperty', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform']);
canTransition = test_props_all('transitionProperty');
canTransform3d = test_3d();
canAnimate = test_props_all('animationName');
window.MetroModernizr.canTransform = canTransform;
window.MetroModernizr.canTransition = canTransition;
window.MetroModernizr.canTransform3d = canTransform3d;
window.MetroModernizr.canAnimate = canAnimate;
docElement = null;
docHead = null;
modElem = null;
m_style = null;
}
} else {
canTransform = jQuery("html").hasClass("csstransforms");
canTransition = jQuery("html").hasClass("csstransitions");
canTransform3d = jQuery("html").hasClass("csstransforms3d");
canAnimate = jQuery("html").hasClass("cssanimations");
}
}
canFlip3d = canFlip3d && canAnimate && canTransform && canTransform3d;
/****** end capabilities check ******/
if (stgs.preloadImages) {
if (swapFrontSource)
jQuery(stgs.frontImages).metrojs.preloadImages(function () { });
if (swapBackSource)
jQuery(stgs.backImages).metrojs.preloadImages(function () { });
}
return jQuery(this).each(function (tileIndex) {
var $this = jQuery(this);
$this.slideTimer = null;
var tdata = {}; //an object to store settings for later access
tdata.state = $this.slideTimer == null ? jQuery.fn.liveTile.State.STOPPED : jQuery.fn.liveTile.State.RUNNING;
tdata.speed = (!stgs.ignoreDataAttributes && typeof ($this.data("speed")) != "undefined") ? $this.data("speed") : stgs.speed;
tdata.delay = (!stgs.ignoreDataAttributes && typeof ($this.data("delay")) != "undefined") ? $this.data("delay") : stgs.delay;
if (tdata.delay < -1)
tdata.delay = stgs.triggerDelay(tileIndex);
else if (tdata.delay < 0)
tdata.delay = 3500 + (Math.random() * 4501);
tdata.stops = (!stgs.ignoreDataAttributes && typeof ($this.data("stops")) != "undefined") ? $this.data("stops") : stgs.stops;
tdata.stack = (!stgs.ignoreDataAttributes && typeof ($this.data("stack")) != "undefined") ? $this.data("stack") : stgs.mode;
tdata.mode = (!stgs.ignoreDataAttributes && typeof ($this.data("mode")) != "undefined") ? $this.data("mode") : stgs.mode;
tdata.direction = (!stgs.ignoreDataAttributes && typeof ($this.data("direction")) != "undefined") ? $this.data("direction") : stgs.direction;
tdata.useHwAccel = (!stgs.ignoreDataAttributes && typeof ($this.data("ha")) != "undefined") ? $this.data("ha") : stgs.useHardwareAccel;
tdata.initDelay = (!stgs.ignoreDataAttributes && typeof ($this.data("initdelay")) != "undefined") ? $this.data("initdelay") : (stgs.initDelay < 0) ? tdata.delay : stgs.initDelay;
tdata.repeatCount = (!stgs.ignoreDataAttributes && typeof ($this.data("repeat")) != "undefined") ? $this.data("repeat") : stgs.repeatCount;
tdata.hasRun = false; // init delay flag
tdata.isReversed = false;
tdata.loopCount = 0;
tdata.slideIndex = 0;
//convert stops if needed
tdata.stops = (typeof (stgs.stops) == 'object' && (stgs.stops instanceof Array)) ? stgs.stops : ('' + tdata.stops).split(',');
//add the mode to the tile if it's not already there.
$this.addClass(tdata.mode);
var $tileContainer = $this.find(stgs.tileCssSelector);
var $firstContainer = null;
if (stgs.$front != null && stgs.$front.length > 0) {
$firstContainer = (tdata.mode == "flip-list") ? null : (tdata.mode == 'slide') ?
stgs.$front.addClass('slide-front') :
stgs.$front.addClass('flip-front');
} else {
$firstContainer = (tdata.mode == "flip-list") ? null : (tdata.mode == 'slide') ?
$tileContainer.first().addClass('slide-front') :
$tileContainer.first().addClass('flip-front');
}
var lClass = (tdata.mode == 'slide') ? 'slide-back' : 'flip-back';
var $scndContainer = null;
if (stgs.$back != null && stgs.$back.length > 0) {
$scndContainer = (tdata.mode == "flip-list") ? null : stgs.$back.addClass(lClass);
} else {
$scndContainer = (tdata.mode == "flip-list") ? null : ($tileContainer.length > 1) ?
$tileContainer.last().addClass(lClass) :
(stgs.appendBack == true) ?
jQuery('<div class="' + lClass + '"></div>').appendTo($this) :
jQuery('<div></div>');
}
var height = $this.height();
var width = $this.width();
var margin = (tdata.direction == "vertical") ? height / 2 : width / 2;
var staticCount = 0;
var staticIndexBack = 0;
var staticIndexFront = 0;
var doAnimations = false;
var flistData = []; // an array to cache flip list selectors
var frontRandomBag = [];
var prevFrontIndex = -1;
var backRandomBag = [];
var prevBackIndex = -1;
/* Mouse over and out functions*/
if (stgs.pauseOnHover) {
$this.find(stgs.tileCssSelector).hover(
function () {
tdata.stopTimer(false);
},
function () {
tdata.setTimer();
});
}
// prep tiles
if (tdata.mode == 'flip-list') {
$this.find(stgs.tileCssSelector).each(function () {
var $li = jQuery(this);
var $front = stgs.$front != null ? stgs.$front : $li.find(stgs.listTileCssSelector).first().addClass("flip-front");
if ($li.find(stgs.listTileCssSelector).length == 1 && stgs.appendBack == true) {
$li.append("<div></div>");
}
var $back = stgs.$back != null ? stgs.$back : $li.find(stgs.listTileCssSelector).last().addClass("flip-back").css({ marginTop: "0px" });
if (canFlip3d && tdata.useHwAccel) {
$li.addClass("ha");
$front.addClass("ha").data("tile", { animating: false });
$back.addClass("ha").data("tile", { animating: false });
if (stgs.flipListOnHover == true) {
$front.bind("mouseout.liveTile", null, function () {
$this.flipListItem(false, $li, $back, $front);
});
$back.bind("mouseout.liveTile", null, function () {
$this.flipListItem(true, $li, $front, $back);
});
}
} else {
if (stgs.flipListOnHover == true) {
$front.bind("mouseout.liveTile", function () {
$this.flipListItem(true, $li, $front, $back);
});
$back.bind("mouseout.liveTile", function () {
$this.flipListItem(false, $li, $back, $front);
});
}
}
});
} else if (tdata.mode == 'slide') {
if (tdata.stack == true) {
if (tdata.direction == "vertical") {
$scndContainer.css({ top: -height + 'px' });
} else {
$scndContainer.css({ left: -width + 'px' });
}
}
if (canTransition && tdata.useHwAccel) {
$this.addClass("ha");
$firstContainer.addClass("ha").data("tile", { animating: false });
}
} else if (tdata.mode == 'flip') {
if (canFlip3d && tdata.useHwAccel) {
$this.addClass("ha");
$firstContainer.addClass("ha").data("tile", { animating: false });
$scndContainer.addClass("ha").data("tile", { animating: false });
} else {
var fCss = (tdata.direction == "vertical") ?
{ height: '0px', width: width + 'px', marginTop: margin + 'px', opacity: '0'} :
{ height: '100%', width: '0px !important', marginLeft: margin + 'px', opacity: '0' };
var fCss2 = (tdata.direction == "vertical") ?
{ height: '100%', width: '100%', marginTop: '0px', opacity: '1'} :
{ height: '100%', width: '100%', marginLeft: '0px', opacity: '1' };
$scndContainer.css(fCss);
$firstContainer.css(fCss2);
//temp fix
// TODO: debug and remove instances of jQuery.browser for compatibility with jq 1.8+
if (tdata.repeatCount > -1 && jQuery.browser.msie) {
tdata.repeatCount += 1;
}
// if (tdata.direction == "horizontal")
// $scndContainer.css({ marginLeft: $scndContainer.width() / 2 + 'px', width: '0px' });
// else
// $scndContainer.css({ marginTop: $scndContainer.height() / 2 + 'px', height: '0px' });
}
}
//slide animation
$this.slide = function (callback) {
if (typeof (callback) == "undefined" || callback == null)
callback = null;
if (tdata.repeatCount > -1) {
if (tdata.loopCount > tdata.repeatCount) {
tdata.stopTimer(false);
tdata.loopCount = 0;
tdata.hasRun = false;
$this.data("LiveTile", tdata);
return;
}
}
if (!doAnimations)
return;
var clojIsReversed = tdata.isReversed;
var fData = $firstContainer.data("tile");
var stop = jQuery.trim(tdata.stops[tdata.slideIndex]);
var pxIdx = stop.indexOf('px');
var offset = 0;
var amount = 0
var metric = (tdata.direction == "vertical") ? height : width;
var prop = (tdata.direction == "vertical") ? "top" : "left";
if (pxIdx > 0) {
amount = parseInt(stop.substring(0, pxIdx));
offset = (amount - metric) + 'px';
} else {
//is a percentage
amount = parseInt(stop.replace('%', ''));
offset = (amount - 100) + '%';
}
if (canTransition && tdata.useHwAccel) {
if (typeof (fData.animated) != "undefined" && fData.animated == true)
return;
fData.animated = true;
var css = {
WebkitTransitionProperty: prop, WebkitTransitionDuration: tdata.speed + 'ms',
MozTransitionProperty: prop, MozTransitionDuration: tdata.speed + 'ms',
OTransitionProperty: prop, OTransitionDuration: tdata.speed + 'ms',
msTransitionProperty: prop, msTransitionDuration: tdata.speed + 'ms',
KhtmlTransitionProperty: prop, KhtmlTransitionDuration: tdata.speed + 'ms',
TransitionProperty: prop, TransitionDuration: tdata.speed + 'ms'
};
if (tdata.direction == "vertical") {
css.top = (clojIsReversed && tdata.stops.length == 1) ? "0px" : stop;
} else {
css.left = (clojIsReversed && tdata.stops.length == 1) ? "0px" : stop;
}
$firstContainer.css(css);
if (tdata.stack == true) {
if (tdata.direction == "vertical") {
css.top = (clojIsReversed && tdata.stops.length == 1) ? -metric + 'px' : offset;
} else {
css.left = (clojIsReversed && tdata.stops.length == 1) ? -metric + 'px' : offset;
}
$scndContainer.css(css);
}
window.setTimeout(function () {
var index = staticCount;
if (swapFrontSource && stgs.frontIsRandom) {
//make sure the random bag is ready
if (frontRandomBag.length == 0) {
for (var i = 0; i < stgs.frontImages.length; i++) {
//make sure there's not an immediate repeat
if (i != prevBackIndex || stgs.frontImages.length == 1)
frontRandomBag[i] = i;
}
frontRandomBag = privMethods.shuffleArray(frontRandomBag);
}
index = frontRandomBag.pop();
prevFrontIndex = index;
}
privMethods.handleSlide(clojIsReversed, $firstContainer, swapFrontSource, stgs, index);
fData.animated = false;
$firstContainer.data("tile", fData);
if (!clojIsReversed && swapFrontSource) {
staticCount += 1;
if (staticCount >= stgs.frontImages.length)
staticCount = 0;
}
stgs.animationComplete(tdata, $firstContainer, $scndContainer);
if (callback != null)
callback();
}, tdata.speed);
} else {
if ($firstContainer.is(':animated')) {
return;
}
var uCss = (tdata.direction == "vertical") ?
{ top: (clojIsReversed && tdata.stops.length == 1) ? "0px" : stop} :
{ left: (clojIsReversed && tdata.stops.length == 1) ? "0px" : stop };
var dCss = (tdata.direction == "vertical") ?
{ top: (clojIsReversed && tdata.stops.length == 1) ? -metric + 'px' : offset} :
{ left: (clojIsReversed && tdata.stops.length == 1) ? -metric + 'px' : offset };
$firstContainer.animate(uCss, tdata.speed, function () {
var index = staticCount;
if (swapFrontSource && stgs.frontIsRandom) {
//make sure the random bag is ready
if (frontRandomBag.length == 0) {
for (var i = 0; i < stgs.frontImages.length; i++) {
//make sure there's not an immediate repeat
if (i != prevBackIndex || stgs.frontImages.length == 1)
frontRandomBag[i] = i;
}
frontRandomBag = privMethods.shuffleArray(frontRandomBag);
}
index = frontRandomBag.pop();
prevFrontIndex = index;
}
privMethods.handleSlide(clojIsReversed, $firstContainer, swapFrontSource, stgs, index);
if (!clojIsReversed && swapFrontSource) {
staticCount += 1;
if (staticCount >= stgs.frontImages.length)
staticCount = 0;
}
stgs.animationComplete(tdata, $firstContainer, $scndContainer);
if (callback != null)
callback();
});
if (tdata.stack == true) {
$scndContainer.animate(dCss, tdata.speed, function () { });
}
}
//increment slide count
tdata.slideIndex += 1;
if (tdata.slideIndex >= tdata.stops.length) {
tdata.slideIndex = 0;
tdata.isReversed = !tdata.isReversed;
tdata.loopCount += 1;
}
};
//flip mode
$this.flip = function (callback) {
if (typeof (callback) == "undefined" || callback == null)
callback = null;
if (tdata.repeatCount > -1) {
if (tdata.loopCount > tdata.repeatCount) {
tdata.stopTimer(false);
tdata.loopCount = 0;
// TODO: debug and remove instances of jQuery.browser for compatibility with jq 1.8+
if (jQuery.browser.msie) /* straighten out issue with loopcount in IE */
tdata.loopCount += 1;
tdata.hasRun = false;
$this.data("LiveTile", tdata);
return;
} else {
tdata.loopCount += 1;
}
}
if (canFlip3d && tdata.useHwAccel) {
var spd = (tdata.speed * 2); // accelerated flip speeds are calculated on 1/2 rotation rather than 1/4 rotation like jQuery animate
var duration = spd + 'ms';
var aniFName = (tdata.direction == "vertical") ? 'flipfront180' : 'flipfrontY180';
var aniBName = (tdata.direction == "vertical") ? 'flipback180' : 'flipbackY180';
var data = $firstContainer.data("tile");
if (typeof (data.animated) != "undefined" && data.animated == true) {
return;
}
data.animated = true;
if (doAnimations) {
if (tdata.isReversed) {
var uCss = {
WebkitAnimationPlayState: 'running', WebkitAnimationName: aniBName, WebkitAnimationDuration: duration,
MozAnimationPlayState: 'running', MozAnimationName: aniBName, MozAnimationDuration: duration,
OAnimationPlayState: 'running', OAnimationName: aniBName, OAnimationDuration: duration,
msAnimationPlayState: 'running', msAnimationName: aniBName, msAnimationDuration: duration,
AnimationPlayState: 'running', AnimationName: aniBName, AnimationDuration: duration
};
$firstContainer.css(uCss).data("tile", data);
uCss.WebkitAnimationName = aniFName;
uCss.MozAnimationName = aniFName;
uCss.msAnimationName = aniFName;
uCss.OAnimationName = aniFName;
uCss.AnimationName = aniFName;
$scndContainer.css(uCss).data("tile", data);
window.setTimeout(function () {
if (swapBackSource) { // change the source image when the animation is finished
var isRandom = stgs.backIsRandom;
var index = staticIndexBack;
if (isRandom) {
//make sure the random bag is ready
if (backRandomBag.length == 0) {
for (var i = 0; i < stgs.backImages.length; i++) {
//make sure there's not an immediate repeat
if (i != prevBackIndex || stgs.backImages.length == 1)
backRandomBag[i] = i;
}
backRandomBag = privMethods.shuffleArray(backRandomBag);
}
index = backRandomBag.pop();
prevBackIndex = index;
}
privMethods.handleSwap($scndContainer, false, stgs, index);
staticIndexBack += 1;
if (staticIndexBack >= stgs.backImages.length) {
staticIndexBack = 0;
}
}
stgs.animationComplete(tdata, $firstContainer, $scndContainer);
if (callback != null)
callback();
data.animated = false;
$firstContainer.data("tile", data);
$scndContainer.data("tile", data);
}, spd);
} else {
var dCss = { WebkitAnimationPlayState: 'running', WebkitAnimationName: aniFName, WebkitAnimationDuration: duration,
MozAnimationPlayState: 'running', MozAnimationName: aniFName, MozAnimationDuration: duration,
OAnimationPlayState: 'running', OAnimationName: aniFName, OAnimationDuration: duration,
msAnimationPlayState: 'running', msAnimationName: aniFName, msAnimationDuration: duration,
AnimationPlayState: 'running', AnimationName: aniFName, AnimationDuration: duration
};
$firstContainer.css(dCss).data("tile", data);
dCss.WebkitAnimationName = aniBName;
dCss.MozAnimationName = aniBName;
dCss.msAnimationName = aniBName;
dCss.OAnimationName = aniBName;
dCss.AnimationName = aniBName;
$scndContainer.css(dCss).data("tile", data);
window.setTimeout(function () {
if (swapFrontSource) {
// change the source image when the animation is finished
var isRandom = stgs.frontIsRandom;
var index = staticIndexFront;
if (isRandom) {
//make sure the random bag is ready
if (frontRandomBag.length == 0) {
for (var i = 0; i < stgs.frontImages.length; i++) {
//make sure there's not an immediate repeat
if (i != prevBackIndex || stgs.frontImages.length == 1)
frontRandomBag[i] = i;
}
frontRandomBag = privMethods.shuffleArray(frontRandomBag);
}
index = frontRandomBag.pop();
prevFrontIndex = index;
}
privMethods.handleSwap($firstContainer, true, stgs, index);
staticIndexFront += 1;
if (staticIndexFront >= stgs.frontImages.length) {
staticIndexFront = 0;
}
}
stgs.animationComplete(tdata, $scndContainer, $firstContainer);
if (callback != null) {
callback();
}
data.animated = false;
$firstContainer.data("tile", data);
$scndContainer.data("tile", data);
}, spd);
}
}
//an interval isnt needed
tdata.isReversed = !tdata.isReversed;
} else {
//crossbrowser single tile flip illusion (works best with images)
if (tdata.isReversed) {
var upCss = (tdata.direction == "vertical") ?
{ height: '0px', width: '100%', marginTop: margin + 'px', opacity: '0'} :
{ height: '100%', width: '0px', marginLeft: margin + 'px', opacity: '0' };
var upCss2 = (tdata.direction == "vertical") ?
{ height: '100%', width: '100%', marginTop: '0px', opacity: '1'} :
{ height: '100%', width: '100%', marginLeft: '0px', opacity: '1' };
$firstContainer.stop().animate(upCss, { duration: tdata.speed });
window.setTimeout(function () {
$scndContainer.stop().animate(upCss2, { duration: tdata.speed });
if (swapFrontSource) {
var isRandom = stgs.frontIsRandom;
var index = staticIndexFront;
if (isRandom) {
//make sure the random bag is ready
if (frontRandomBag.length == 0) {
for (var i = 0; i < stgs.frontImages.length; i++) {
//make sure there's not an immediate repeat
if (i != prevFrontIndex || stgs.frontImages.length == 1)
frontRandomBag[i] = i;
}
frontRandomBag = privMethods.shuffleArray(frontRandomBag);
}
index = frontRandomBag.pop();
prevFrontIndex = index;
}
privMethods.handleSwap($firstContainer, true, stgs, index);
staticIndexFront += 1;
if (staticIndexFront >= stgs.frontImages.length) {
staticIndexFront = 0;
}
}
tdata.isReversed = !tdata.isReversed;
stgs.animationComplete(tdata, $scndContainer, $firstContainer);
if (callback != null)
callback();
}, tdata.speed);
} else {
var dwnCss = (tdata.direction == "vertical") ?
{ height: '0px', width: '100%', marginTop: margin + 'px', opacity: '0'} :
{ height: '100%', width: '0px', marginLeft: margin + 'px', opacity: '0' };
var dwnCss2 = (tdata.direction == "vertical") ?
{ height: '100%', width: '100%', marginTop: '0px', opacity: '1'} :
{ height: '100%', width: '100%', marginLeft: '0px', opacity: '1' };
$scndContainer.stop().animate(dwnCss, { duration: tdata.speed });
window.setTimeout(function () {
$firstContainer.stop().animate(dwnCss2, { duration: tdata.speed });
if (swapBackSource) {
var isRandom = stgs.backIsRandom;
var index = staticIndexBack;
if (isRandom) {
//make sure the random bag is ready
if (backRandomBag.length == 0) {
for (var i = 0; i < stgs.backImages.length; i++) {
//make sure there's not an immediate repeat
if (i != prevBackIndex || stgs.backImages.length == 1)
backRandomBag[i] = i;
}
backRandomBag = privMethods.shuffleArray(backRandomBag);
}
index = backRandomBag.pop();
prevBackIndex = index;
}
privMethods.handleSwap($scndContainer, false, stgs, index);
staticIndexBack += 1;
if (staticIndexBack >= stgs.backImages.length) {
staticIndexBack = 0;
}
}
tdata.isReversed = !tdata.isReversed;
stgs.animationComplete(tdata, $firstContainer, $scndContainer);
if (callback != null)
callback();
}, tdata.speed);
}
}
};
// flip arbitrary number of items and swap sources accordingly
$this.flipList = function (callback) {
if (typeof (callback) == "undefined" || callback == null)
callback = null;
if (tdata.repeatCount > -1) {
if (tdata.loopCount > tdata.repeatCount) {
tdata.stopTimer(false);
tdata.loopCount = 0;
tdata.hasRun = false;
$this.data("LiveTile", tdata);
return;
} else {
tdata.loopCount += 1;
}
}
var fBag = []; // two bags to make sure we don't duplicate images
var bBag = [];
var $tiles = $this.find(stgs.tileCssSelector);
//in case we want to pick one image per loop
var fStaticRndm = 0;
if (swapFrontSource) {
if (frontRandomBag.length == 0) {
for (var i = 0; i < stgs.frontImages.length; i++) {
if (i != prevFrontIndex || stgs.frontImages.length == 1)
frontRandomBag[i] = i;
}
frontRandomBag = privMethods.shuffleArray(frontRandomBag);
}
fStaticRndm = frontRandomBag.pop();
prevFrontIndex = fStaticRndm;
}
var bStaticRndm = 0;
if (swapBackSource) {
if (backRandomBag.length == 0) {
for (var i = 0; i < stgs.backImages.length; i++) {
if (i != prevBackIndex || stgs.backImages.length == 1)
backRandomBag[i] = i;
}
backRandomBag = privMethods.shuffleArray(backRandomBag);
}
bStaticRndm = backRandomBag.pop();
prevBackIndex = bStaticRndm;
}
$tiles.each(function (idx) {
var $t = jQuery(this);
if (flistData.length < idx + 1) {
// cache the selector
var data = {};
data.$front = $t.find(stgs.listTileCssSelector).first();
data.$back = $t.find(stgs.listTileCssSelector).last();
data.isReversed = false;
flistData[idx] = data;
}
var $front = flistData[idx].$front;
var $back = flistData[idx].$back;
var tDelay = stgs.triggerDelay(idx);
var triggerSpeed = (tDelay > 0) ? (tdata.speed + tDelay) : tdata.speed;
var trigger = (stgs.alwaysTrigger == false) ? ((Math.random() * 351) > 150 ? true : false) : true;
var newImage;
if (flistData[idx].isReversed) {
if (trigger) {
window.setTimeout(function () {
flistData[idx].isReversed = false;
if (!swapFrontSource) {
$this.flipListItem(true, $t, $front, $back);
} else {
var isRandom = stgs.frontIsRandom;
var isInGrid = stgs.frontIsInGrid;
var isBground = stgs.frontIsBackgroundImage;
var frontImages = stgs.frontImages;
if (isRandom && !isInGrid) {
//make sure the random bag is ready
if (fBag.length == 0) {
for (var i = 0; i < stgs.frontImages.length; i++) {
fBag[i] = i;
}
fBag = privMethods.shuffleArray(fBag);
}
newImage = frontImages[fBag.pop()];
} else {
if (!isInGrid) {
newImage = frontImages[Math.min(idx, frontImages.length)];
} else {
newImage = frontImages[Math.min(fStaticRndm, frontImages.length)];
}
}
$this.flipListItem(true, $t, $front, $back, newImage, isBground);
}
}, triggerSpeed);
}
} else {
if (trigger) {
window.setTimeout(function () {
flistData[idx].isReversed = true;
if (!swapBackSource) {
$this.flipListItem(false, $t, $back, $front);
} else {
var isRandom = stgs.backIsRandom;
var isInGrid = stgs.backIsInGrid;
var isBground = stgs.backIsBackgroundImage;
var backImages = stgs.backImages;
if (isRandom && !isInGrid) {
//make sure the random bag is ready
if (bBag.length == 0) {
for (var i = 0; i < stgs.backImages.length; i++) {
bBag[i] = i;
}
bBag = privMethods.shuffleArray(bBag);
}
newImage = backImages[bBag.pop()];
} else {
if (!isInGrid) {
newImage = backImages[Math.min(idx, backImages.length)];
} else {
newImage = backImages[Math.min(bStaticRndm, backImages.length)];
}
}
$this.flipListItem(false, $t, $back, $front, newImage, isBground);
}
}, triggerSpeed);
}
}
});
window.setTimeout(function () {
tdata.isReversed = !tdata.isReversed;
}, tdata.speed);
};
//does the actual animation of a flip list item
$this.flipListItem = function (isFront, $itm, $front, $back, newSrc, isBgroundImg) {
var dir = (!stgs.ignoreDataAttributes && typeof ($itm.data("direction")) != "undefined") ? $itm.data("direction") : tdata.direction;
if (canFlip3d && tdata.useHwAccel) {
// avoid any z-index flickering from reversing an animation too early
isBgroundImg = isFront ? stgs.frontIsBackgroundImage : stgs.backIsBackgroundImage;
var animating = isFront ? $front.data("tile").animating : $back.data("tile").animating;
if (animating == true) {
return;
}
var spd = (tdata.speed * 2);
var duration = spd + 'ms';
var aniFName = (dir == "vertical") ? 'flipfront180' : 'flipfrontY180';
var aniBName = (dir == "vertical") ? 'flipback180' : 'flipbackY180';
var fCss = {
WebkitAnimationPlayState: 'running', WebkitAnimationName: aniBName, WebkitAnimationDuration: duration,
MozAnimationPlayState: 'running', MozAnimationName: aniBName, MozAnimationDuration: duration,
msAnimationPlayState: 'running', msAnimationName: aniBName, msAnimationDuration: duration,
OAnimationPlayState: 'running', OAnimationName: aniBName, OAnimationDuration: duration,
AnimationPlayState: 'running', AnimationName: aniBName, AnimationDuration: duration
};
var bCss = {
WebkitAnimationPlayState: 'running', WebkitAnimationName: aniFName, WebkitAnimationDuration: duration,
MozAnimationPlayState: 'running', MozAnimationName: aniFName, MozAnimationDuration: duration,
msAnimationPlayState: 'running', msAnimationName: aniFName, msAnimationDuration: duration,
OAnimationPlayState: 'running', OAnimationName: aniFName, OAnimationDuration: duration,
AnimationPlayState: 'running', AnimationName: aniFName, AnimationDuration: duration
};
$front.css(fCss).data("tile").animating = true;
$back.css(bCss).data("tile").animating = true;
window.setTimeout(function () {
if (typeof (newSrc) != "undefined") {
privMethods.handleListItemSwap($front, newSrc, isBgroundImg, stgs);
}
$front.data("tile").animating = false;
$back.data("tile").animating = false;
}, 0); // once the animation is half through it can be reversed
} else {
var height = $itm.height();
var width = $itm.width();
var margin = (dir == "vertical") ? height / 2 : width / 2;
var uCss = (dir == "vertical") ?
{ height: '0px', width: '100%', marginTop: margin + 'px', opacity: 0} :
{ height: '100%', width: '0px', marginLeft: margin + 'px', opacity: 0 };
var dCss = (dir == "vertical") ?
{ height: '100%', width: '100%', marginTop: '0px', opacity: 1} :
{ height: '100%', width: '100%', marginLeft: '0px', opacity: 1 };
$front.stop().animate(uCss, { duration: tdata.speed });
window.setTimeout(function () {
$back.stop().animate(dCss, { duration: tdata.speed });
if (typeof (newSrc) != "undefined") {
privMethods.handleListItemSwap($front, newSrc, isBgroundImg, stgs);
}
}, tdata.speed);
}
};
/* Delay the tile action*/
tdata.doAction = function () {
var action = null;
tdata.stopTimer(false);
switch (tdata.mode) {
case 'slide':
action = $this.slide;
break;
case 'flip':
action = $this.flip;
break;
case 'flip-list':
action = $this.flipList;
break;
}
var callBack = function () {
tdata.setTimer();
};
if (action != null) {
doAnimations = true;
action(callBack);
}
};
tdata.setTimer = function () {
var action = null;
switch (tdata.mode) {
case 'slide':
action = $this.slide;
break;
case 'flip':
action = $this.flip;
break;
case 'flip-list':
action = $this.flipList;
break;
}
if (action != null) {
if (tdata.hasRun == false) {
window.setTimeout(function () {
doAnimations = true;
action();
tdata.setTimer();
}, tdata.initDelay);
} else {
if ($this.slideTimer != null)
$this.slideTimer = privMethods.stopTimer($this.slideTimer);
$this.slideTimer = privMethods.setTimer(function () { doAnimations = true; action(); }, tdata.speed + tdata.delay);
}
}
tdata.hasRun = true;
};
tdata.stopTimer = function (restart) {
$this.slideTimer = privMethods.stopTimer($this.slideTimer);
doAnimations = false;
if (typeof (restart) != "undefined" && restart == true) {
tdata.setTimer();
}
};
$this.data("LiveTile", tdata);
tdata.setTimer();
});
},
animate: function () {
jQuery(this).each(function () {
var tData = jQuery(this).data("LiveTile");
tData.doAction();
});
},
destroy: function () {
jQuery(this).each(function () {
var $t = jQuery(this);
$t.unbind(".liveTile");
var $tile = jQuery(this).data("LiveTile");
if ($tile != null) {
$tile.stopTimer(false);
$t.removeData("LiveTile");
$t.removeData("ha");
$t.removeData("tile");
delete $tile;
delete $t.slide;
delete $t.flip;
delete $t.flipList;
delete $t.liveTile;
}
});
},
stop: function (restart) {
jQuery(this).each(function () {
var $tile = jQuery(this).data("LiveTile");
$tile.stopTimer(restart);
$tile.loopCount = 0;
$tile.hasRun = false;
});
},
pause: function () {
jQuery(this).each(function () {
jQuery(this).data("LiveTile").stopTimer();
});
},
play: function () {
jQuery(this).each(function () {
jQuery(this).data("LiveTile").setTimer();
});
}
};jQuery.fn.metrojs.theme = {};
jQuery.fn.metrojs.theme.loadDefaultTheme = function (stgs) {
if (typeof (stgs) == "undefined" || stgs == null) {
stgs = jQuery.fn.metrojs.theme.defaults;
} else {
var stg = jQuery.fn.metrojs.theme.defaults;
jQuery.extend(stg, stgs);
stgs = stg;
}
//get theme from local storage or set base theme
var hasLocalStorage = typeof (window.localStorage) != "undefined";
var hasKeyAndValue = function (key) {
return (typeof (window.localStorage[key]) != "undefined" && window.localStorage[key] != null);
};
if (stgs.applyTheme == true) {
if (hasLocalStorage && (!hasKeyAndValue("Metro.JS.AccentColor") || !hasKeyAndValue("Metro.JS.BaseAccentColor"))) {
//base theme
window.localStorage["Metro.JS.AccentColor"] = stgs.accentColor;
window.localStorage["Metro.JS.BaseAccentColor"] = stgs.baseTheme;
jQuery(stgs.accentCssSelector).addClass(stgs.accentColor).data("accent", stgs.accentColor);
jQuery(stgs.baseThemeCssSelector).addClass(stgs.baseTheme);
if (typeof (stgs.loaded == "function"))
stgs.loaded(stgs.baseTheme, stgs.accentColor);
//preload light theme image
if (typeof (stgs.preloadAltBaseTheme) != "undefined" && stgs.preloadAltBaseTheme)
jQuery([(stgs.baseTheme == 'dark') ? stgs.metroLightUrl : stgs.metroDarkUrl]).metrojs.preloadImages(function () { });
} else {
if (hasLocalStorage) {
stgs.accentColor = window.localStorage["Metro.JS.AccentColor"];
stgs.baseTheme = window.localStorage["Metro.JS.BaseAccentColor"];
jQuery(stgs.accentCssSelector).addClass(stgs.accentColor).data("accent", stgs.accentColor);
jQuery(stgs.baseThemeCssSelector).addClass(stgs.baseTheme);
if (typeof (stgs.loaded == "function"))
stgs.loaded(stgs.baseTheme, stgs.accentColor);
} else {
jQuery(stgs.accentCssSelector).addClass(stgs.accentColor).data("accent", stgs.accentColor);
jQuery(stgs.baseThemeCssSelector).addClass(stgs.baseTheme);
if (typeof (stgs.loaded == "function"))
stgs.loaded(stgs.baseTheme, stgs.accentColor);
//preload light theme image
if (typeof (stgs.preloadAltBaseTheme) != "undefined" && stgs.preloadAltBaseTheme)
jQuery([(stgs.baseTheme == 'dark') ? stgs.metroLightUrl : stgs.metroDarkUrl]).metrojs.preloadImages(function () { });
}
}
}
};
jQuery.fn.metrojs.theme.applyTheme = function (tColor, aColor, stgs) {
if (typeof (stgs) == "undefined" || stgs == null) {
stgs = jQuery.fn.metrojs.theme.defaults;
} else {
var stg = jQuery.fn.metrojs.theme.defaults;
jQuery.extend(stg, stgs);
stgs = stg;
}
if (typeof (tColor) != "undefined" && tColor != null) {
if (typeof (window.localStorage) != "undefined") {
window.localStorage["Metro.JS.BaseAccentColor"] = tColor;
}
var $theme = jQuery(stgs.baseThemeCssSelector);
if ($theme.length > 0) {
if (tColor == "dark")
$theme.addClass("dark").removeClass("light");
else if (tColor == "light")
$theme.addClass("light").removeClass("dark");
}
}
if (typeof (aColor) != "undefined" && aColor != null) {
if (typeof (window.localStorage) != "undefined") {
window.localStorage["Metro.JS.AccentColor"] = aColor;
}
var $accent = jQuery(stgs.accentCssSelector);
if ($accent.length > 0) {
var themeset = false;
$accent.each(function () {
jQuery(this).addClass(aColor);
var dAccent = jQuery(this).data("accent");
if (dAccent != aColor) {
var cleanClass = jQuery(this).attr("class").replace(dAccent, "");
cleanClass = cleanClass.replace(/(\s)+/, ' ');
jQuery(this).attr("class", cleanClass);
jQuery(this).data("accent", aColor);
themeset = true;
}
});
if (themeset && typeof (stgs.accentPicked) == "function")
stgs.accentPicked(aColor);
}
}
};
// default options for theme
jQuery.fn.metrojs.theme.defaults = {
baseThemeCssSelector: 'body', // selector to place dark or light class after load or selection
accentCssSelector: '.tiles', // selector to place accent color class after load or selection
accentColor: 'blue', // the default accent color. options are blue, brown, green, lime, magenta, mango, pink, purple, red, teal
baseTheme: 'dark' // the default theme color. options are dark, light
};jQuery.fn.applicationBar = function (options) {
/* Setup the public options for the applicationBar */
var stgs = typeof (jQuery.fn.metrojs.theme) != "undefined" ? jQuery.fn.metrojs.theme.defaults : {};
jQuery.extend(stgs, jQuery.fn.applicationBar.defaults, options);
if (typeof (jQuery.fn.metrojs.theme) != "undefined")
jQuery.fn.metrojs.theme.loadDefaultTheme(stgs);
//this should really only run once but we can support multiple application bars
jQuery(this).each(function () {
var $this = jQuery(this);
//unfortunately we have to sniff out mobile browsers because of the inconsistent implementation of position:fixed
//most desktop methods return false positives on a mobile
if (navigator.userAgent.match(/(Android|webOS|iPhone|iPod|BlackBerry|PIE|IEMobile)/i)) {
$this.css({ position: 'absolute', bottom: '0px' });
}
$this.animateAppBar = function (isExpanded) {
var hgt = isExpanded ? stgs.collapseHeight : stgs.expandHeight;
if (isExpanded)
$this.removeClass("expanded");
else
if (!$this.hasClass("expanded"))
$this.addClass("expanded");
$this.stop().animate({ height: hgt }, { duration: stgs.duration });
};
$this.find("a.etc").click(function () {
$this.animateAppBar($this.hasClass("expanded"));
});
if (stgs.bindKeyboard == true) {
jQuery(document.documentElement).keyup(function (event) {
// handle cursor keys
if (event.keyCode == 38) {
// expand
if (!$this.hasClass("expanded")) {
$this.animateAppBar(false);
}
} else if (event.keyCode == 40) {
// collapse
if ($this.hasClass("expanded")) {
$this.animateAppBar(true);
}
}
});
}
if (typeof (jQuery.fn.metrojs.theme) != "undefined") {
$this.find(".theme-options>li>a").click(function () {
var accent = jQuery(this).attr("class").replace("accent", "").replace(" ", "");
jQuery.fn.metrojs.theme.applyTheme(null, accent, stgs);
});
$this.find(".base-theme-options>li>a").click(function () {
var accent = jQuery(this).attr("class").replace("accent", '').replace(' ', '');
jQuery.fn.metrojs.theme.applyTheme(accent, null, stgs);
if (typeof (stgs.themePicked) == "function")
stgs.themePicked(accent);
});
}
});
};
// default options for applicationBar, the theme defaults are merged with this object when the applicationBar function is called
jQuery.fn.applicationBar.defaults = {
applyTheme: true, // should the theme be loaded from local storage and applied to the page
themePicked: function (tColor) { }, // called when a new theme is chosen. the chosen theme (dark | light)
accentPicked: function (aColor) { }, // called when a new accent is chosen. the chosen theme (blue, mango, purple, etc.)
loaded: function (tColor, aColor) { }, // called if applyTheme is true onload when a theme has been loaded from local storage or overridden by options
duration: 500, // how fast should animation be performed, in milliseconds
expandHeight: "320px", // height the application bar to expand to when opened
collapseHeight: "60px", // height the application bar will collapse back to when closed
bindKeyboard: true, // should up and down keys on keyborad be bound to the application bar
metroLightUrl: 'images/metroIcons_light.jpg', // the url for the metro light icons (only needed if preload 'preloadAltBaseTheme' is true)
metroDarkUrl: 'images/metroIcons.jpg', // the url for the metro dark icons (only needed if preload 'preloadAltBaseTheme' is true)
preloadAltBaseTheme: false // should the applicationBar icons be pre loaded for the alternate theme to enable fast theme switching
};})(); | JavaScript |
//initiated autoincrement checkboxes
function initAutoincrement()
{
var i=0;
while(document.getElementById('i'+i+'_autoincrement')!=undefined)
{
document.getElementById('i'+i+'_autoincrement').disabled = true;
i++;
}
}
//makes sure autoincrement can only be selected when integer type is selected
function toggleAutoincrement(i)
{
var type = document.getElementById('i'+i+'_type');
var primarykey = document.getElementById('i'+i+'_primarykey');
var autoincrement = document.getElementById('i'+i+'_autoincrement');
if(!autoincrement) return false;
if(type.value=='INTEGER' && primarykey.checked)
autoincrement.disabled = false;
else
{
autoincrement.disabled = true;
autoincrement.checked = false;
}
}
function toggleNull(i)
{
var pk = document.getElementById('i'+i+'_primarykey');
var notnull = document.getElementById('i'+i+'_notnull');
if(pk.checked)
{
notnull.disabled = true;
notnull.checked = true;
}
else
{
notnull.disabled = false;
}
}
//finds and checks all checkboxes for all rows on the Browse or Structure tab for a table
function checkAll(field)
{
var i=0;
while(document.getElementById('check_'+i)!=undefined)
{
document.getElementById('check_'+i).checked = true;
i++;
}
}
//finds and unchecks all checkboxes for all rows on the Browse or Structure tab for a table
function uncheckAll(field)
{
var i=0;
while(document.getElementById('check_'+i)!=undefined)
{
document.getElementById('check_'+i).checked = false;
i++;
}
}
//unchecks the ignore checkbox if user has typed something into one of the fields for adding new rows
function changeIgnore(area, e, u)
{
if(area.value!="")
{
if(document.getElementById(e)!=undefined)
document.getElementById(e).checked = false;
if(document.getElementById(u)!=undefined)
document.getElementById(u).checked = false;
}
}
//moves fields from select menu into query textarea for SQL tab
function moveFields()
{
var fields = document.getElementById("fieldcontainer");
var selected = new Array();
for(var i=0; i<fields.options.length; i++)
if(fields.options[i].selected)
selected.push(fields.options[i].value);
for(var i=0; i<selected.length; i++)
insertAtCaret("queryval", '"'+selected[i].replace(/"/g,'""')+'"');
}
//helper function for moveFields
function insertAtCaret(areaId,text)
{
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ));
if(br=="ie")
{
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
strPos = range.text.length;
}
else if(br=="ff")
strPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0,strPos);
var back = (txtarea.value).substring(strPos,txtarea.value.length);
txtarea.value=front+text+back;
strPos = strPos + text.length;
if(br=="ie")
{
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
range.moveStart ('character', strPos);
range.moveEnd ('character', 0);
range.select();
}
else if(br=="ff")
{
txtarea.selectionStart = strPos;
txtarea.selectionEnd = strPos;
txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}
function notNull(checker)
{
document.getElementById(checker).checked = false;
}
function disableText(checker, textie)
{
if(checker.checked)
{
document.getElementById(textie).value = "";
document.getElementById(textie).disabled = true;
}
else
{
document.getElementById(textie).disabled = false;
}
}
function toggleExports(val)
{
document.getElementById("exportoptions_sql").style.display = "none";
document.getElementById("exportoptions_csv").style.display = "none";
document.getElementById("exportoptions_"+val).style.display = "block";
}
function toggleImports(val)
{
document.getElementById("importoptions_sql").style.display = "none";
document.getElementById("importoptions_csv").style.display = "none";
document.getElementById("importoptions_"+val).style.display = "block";
}
function openHelp(section)
{
PopupCenter('?help=1#'+section, "Help Section");
}
var helpsec = false;
function PopupCenter(pageURL, title)
{
helpsec = window.open(pageURL, title, "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=300");
}
function checkLike(srchField, selOpt){
if(selOpt=="LIKE%"){
var textArea = document.getElementById(srchField);
textArea.value = "%" + textArea.value + "%";
}
} | JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
/*
* Utility Javascript methods for DSpace
*/
// Popup window - here so it can be referred to by several methods
var popupWindow;
// =========================================================
// Methods for e-person popup window
// =========================================================
// Add to list of e-people on this page -- invoked by eperson popup window
function addEPerson(id, email, name)
{
var newplace = window.document.epersongroup.eperson_id.options.length;
if (newplace > 0 && window.document.epersongroup.eperson_id.options[0].value == "")
{
newplace = 0;
}
// First we check to see if e-person is already there
for (var i = 0; i < window.document.epersongroup.eperson_id.options.length; i++)
{
if (window.document.epersongroup.eperson_id.options[i].value == id)
{
newplace = -1;
}
}
if (newplace > -1)
{
window.document.epersongroup.eperson_id.options[newplace] = new Option(name + " (" + email + ")", id);
}
}
// Add to list of groups on this page -- invoked by eperson popup window
function addGroup(id, name)
{
var newplace = window.document.epersongroup.group_ids.options.length;
if (newplace > 0 && window.document.epersongroup.group_ids.options[0].value == "")
{
newplace = 0;
}
// First we check to see if group is already there
for (var i = 0; i < window.document.epersongroup.group_ids.options.length; i++)
{
// is it in the list already
if (window.document.epersongroup.group_ids.options[i].value == id)
{
newplace = -1;
}
// are we trying to add the new group to the new group on an Edit Group page (recursive)
if (window.document.epersongroup.group_id)
{
if (window.document.epersongroup.group_id.value == id)
{
newplace = -1;
}
}
}
if (newplace > -1)
{
window.document.epersongroup.group_ids.options[newplace] = new Option(name + " (" + id + ")", id);
}
}
// This needs to be invoked in the 'onClick' javascript event for buttons
// on pages with a dspace:selecteperson element in them
function finishEPerson()
{
selectAll(window.document.epersongroup.eperson_id);
if (popupWindow != null)
{
popupWindow.close();
}
}
// This needs to be invoked in the 'onClick' javascript event for buttons
// on pages with a dspace:selecteperson element in them
function finishGroups()
{
selectAll(window.document.epersongroup.group_ids);
if (popupWindow != null)
{
popupWindow.close();
}
}
// =========================================================
// Miscellaneous utility methods
// =========================================================
// Open a popup window (or bring to front if already open)
function popup_window(winURL, winName)
{
var props = 'scrollBars=yes,resizable=yes,toolbar=no,menubar=no,location=no,directories=no,width=640,height=480';
popupWindow = window.open(winURL, winName, props);
popupWindow.focus();
}
// Select all options in a <SELECT> list
function selectAll(sourceList)
{
for(var i = 0; i < sourceList.options.length; i++)
{
if ((sourceList.options[i] != null) && (sourceList.options[i].value != ""))
sourceList.options[i].selected = true;
}
return true;
}
// Deletes the selected options from supplied <SELECT> list
function removeSelected(sourceList)
{
var maxCnt = sourceList.options.length;
for(var i = maxCnt - 1; i >= 0; i--)
{
if ((sourceList.options[i] != null) && (sourceList.options[i].selected == true))
{
sourceList.options[i] = null;
}
}
}
// Disables accidentally submitting a form when the "Enter" key is pressed.
// Just add "onkeydown='return disableEnterKey(event);'" to form.
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //Internet Explorer
else
key = e.which; //Firefox & Netscape
if(key == 13) //if "Enter" pressed, then disable!
return false;
else
return true;
}
//******************************************************
// Functions used by controlled vocabulary add-on
// There might be overlaping with existing functions
//******************************************************
function expandCollapse(node, contextPath) {
node = node.parentNode;
var childNode = (node.getElementsByTagName("ul"))[0];
if(!childNode) return false;
var image = node.getElementsByTagName("img")[0];
if(childNode.style.display != "block") {
childNode.style.display = "block";
image.src = contextPath + "/image/controlledvocabulary/m.gif";
image.alt = "Collapse search term category";
} else {
childNode.style.display = "none";
image.src = contextPath + "/image/controlledvocabulary/p.gif";
image.alt = "Expand search term category";
}
return false;
}
function getAnchorText(ahref) {
if(isMicrosoft()) return ahref.childNodes.item(0).nodeValue;
else return ahref.text;
}
function getTextValue(node) {
if(node.nodeName == "A") {
return getAnchorText(node);
} else {
return "";
}
}
function getParentTextNode(node) {
var parentNode = node.parentNode.parentNode.parentNode;
var children = parentNode.childNodes;
var textNode;
for(var i=0; i< children.length; i++) {
var child = children.item(i);
if(child.className == "value") {
return child;
}
}
return null;
}
function ec(node, contextPath) {
expandCollapse(node, contextPath);
return false;
}
function i(node) {
return sendBackToParentWindow(node);
}
function getChildrenByTagName(rootNode, tagName) {
var children = rootNode.childNodes;
var result = new Array(0);
if(children == null) return result;
for(var i=0; i<children.length; i++) {
if(children[i].tagName == tagName) {
var elementArray = new Array(1);
elementArray[0] = children[i];
result = result.concat(elementArray);
}
}
return result;
}
function popUp(URL) {
var page;
page = window.open(URL, 'controlledvocabulary', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=650,height=450');
}
function isNetscape(v) {
return isBrowser("Netscape", v);
}
function isMicrosoft(v) {
return isBrowser("Microsoft", v);
}
function isMicrosoft() {
return isBrowser("Microsoft", 0);
}
function isBrowser(b,v) {
browserOk = false;
versionOk = false;
browserOk = (navigator.appName.indexOf(b) != -1);
if (v == 0) versionOk = true;
else versionOk = (v <= parseInt(navigator.appVersion));
return browserOk && versionOk;
}
// type submission function
function SetDocType()
{
document.edit_metadata.submit();
}
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// Client-side scripting to support DSpace Choice Control
function authoritySuggest(field, div, url, indicator)
{
new Ajax.Autocompleter(field, div, url, {paramName: "value", minChars: 3,
indicator: indicator, afterUpdateElement : updateAuthority});
}
function updateAuthority(field, li)
{
var parts = field.id.split("_");
var authority = field.id + '_authority';
if (parts.length > 0){
if(!isNaN(parseInt(parts[parts.length-1]))){
authority = "";
for(i=0; i < parts.length-1; i++){
authority += parts[i] + "_";
}
authority += "authority_" + parts[parts.length-1];
}
}
//var confidence = field.id + '_confidence';
document.getElementById(authority).value = li.id;
} | JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// script.aculo.us builder.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010
// Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Builder = {
NODEMAP: {
AREA: 'map',
CAPTION: 'table',
COL: 'table',
COLGROUP: 'table',
LEGEND: 'fieldset',
OPTGROUP: 'select',
OPTION: 'select',
PARAM: 'object',
TBODY: 'table',
TD: 'table',
TFOOT: 'table',
TH: 'table',
THEAD: 'table',
TR: 'table'
},
// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
// due to a Firefox bug
node: function(elementName) {
elementName = elementName.toUpperCase();
// try innerHTML approach
var parentTag = this.NODEMAP[elementName] || 'div';
var parentElement = document.createElement(parentTag);
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
} catch(e) {}
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
if(element && (element.tagName.toUpperCase() != elementName))
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
if(!element) element = document.createElement(elementName);
// abort if nothing could be created
if(!element) return;
// attributes (or text)
if(arguments[1])
if(this._isStringOrNumber(arguments[1]) ||
(arguments[1] instanceof Array) ||
arguments[1].tagName) {
this._children(element, arguments[1]);
} else {
var attrs = this._attributes(arguments[1]);
if(attrs.length) {
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" +elementName + " " +
attrs + "></" + elementName + ">";
} catch(e) {}
element = parentElement.firstChild || null;
// workaround firefox 1.0.X bug
if(!element) {
element = document.createElement(elementName);
for(attr in arguments[1])
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
if(element.tagName.toUpperCase() != elementName)
element = parentElement.getElementsByTagName(elementName)[0];
}
}
// text, or array of children
if(arguments[2])
this._children(element, arguments[2]);
return $(element);
},
_text: function(text) {
return document.createTextNode(text);
},
ATTR_MAP: {
'className': 'class',
'htmlFor': 'for'
},
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
'="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'"') + '"');
return attrs.join(" ");
},
_children: function(element, children) {
if(children.tagName) {
element.appendChild(children);
return;
}
if(typeof children=='object') { // array can hold nodes and text
children.flatten().each( function(e) {
if(typeof e=='object')
element.appendChild(e);
else
if(Builder._isStringOrNumber(e))
element.appendChild(Builder._text(e));
});
} else
if(Builder._isStringOrNumber(children))
element.appendChild(Builder._text(children));
},
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
},
build: function(html) {
var element = this.node('div');
$(element).update(html.strip());
return element.down();
},
dump: function(scope) {
if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
tags.each( function(tag){
scope[tag] = function() {
return Builder.node.apply(Builder, [tag].concat($A(arguments)));
};
});
}
}; | JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;
// open hidden layer
function mopen(id)
{
// cancel close timer
mcancelclosetime();
// close old layer
if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
// get new layer and show it
ddmenuitem = document.getElementById(id);
ddmenuitem.style.visibility = 'visible';
}
// close showed layer
function mclose()
{
if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}
// go close timer
function mclosetime()
{
closetimer = window.setTimeout(mclose, timeout);
}
// cancel close timer
function mcancelclosetime()
{
if(closetimer)
{
window.clearTimeout(closetimer);
closetimer = null;
}
}
// close layer when click-out
// -->
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// Client-side scripting to support DSpace Choice Control
// IMPORTANT NOTE:
// This code depends on a *MODIFIED* version of the
// script.aculo.us controls v1.8.2, fixed to avoid a bug that
// affects autocomplete in Firefox 3. This code is included in DSpace.
// Entry points:
// 1. DSpaceAutocomplete -- add autocomplete (suggest) to an input field
//
// 2. DSpaceChoiceLookup -- create popup window with authority choices
//
// @Author: Larry Stone <lcs@hulmail.harvard.edu>
// $Revision $
// -------------------- support for Autocomplete (Suggest)
// Autocomplete utility:
// Arguments:
// formID -- ID attribute of form tag
// args properties:
// metadataField -- metadata field e.g. dc_contributor_author
// inputName -- input field name for text input, or base of "Name" pair
// authorityName -- input field name in which to set authority
// containerID -- ID attribute of DIV to hold the menu objects
// indicatorID -- ID attribute of element to use as a "loading" indicator
// confidenceIndicatorID -- ID of element on which to set confidence
// confidenceName - NAME of confidence input (not ID)
// contextPath -- URL path prefix (i.e. webapp contextPath) for DSpace.
// collection -- db ID of dspace collection to serve as context
// isClosed -- true if authority value is required, false = non-auth allowed
// XXX Can't really enforce "isClosed=true" with autocomplete, user can type anything
//
// NOTE: Successful autocomplete always sets confidence to 'accepted' since
// authority value (if any) *was* chosen interactively by a human.
function DSpaceSetupAutocomplete(formID, args)
{
if (args.authorityName == null)
args.authorityName = dspace_makeFieldInput(args.inputName,'_authority');
var form = document.getElementById(formID);
var inputID = form.elements[args.inputName].id;
var authorityID = null;
if (form.elements[args.authorityName] != null)
authorityID = form.elements[args.authorityName].id;
// AJAX menu source, can add &query=TEXT
var choiceURL = args.contextPath+"/choices/"+args.metadataField;
var collID = args.collection == null ? -1 : args.collection;
// field in whcih to store authority value
var options =
{
// class name of spans that contain value in li elements
select: "value",
// make up query args for AJAX callback
parameters: 'collection='+collID+'&format=ul',
callback:
function(inField, querystring) {
return querystring+"&query="+inField.value;
},
// called after target field is updated
afterUpdateElement:
function(ignoreField, li)
{
// NOTE: lookup element late because it might not be in DOM
// at the time we evaluate the function..
var authInput = document.getElementById(authorityID);
var authValue = li == null ? "" : li.getAttribute("authority");
if (authInput != null)
{
authInput.value = authValue;
// update confidence input's value too if available.
if (args.confidenceName != null)
{
var confInput = authInput.form.elements[args.confidenceName];
if (confInput != null)
confInput.value = 'accepted';
}
}
// make indicator blank if no authority value
DSpaceUpdateConfidence(document, args.confidenceIndicatorID,
authValue == null || authValue == '' ? 'blank' :'accepted');
}
};
if (args.indicatorID != null)
options.indicator = args.indicatorID;
// be sure to turn off autocomplete, it absorbs arrow-key events!
form.elements[args.inputName].setAttribute("autocomplete", "off");
new Ajax.Autocompleter(inputID, args.containerID, choiceURL, options);
}
// -------------------- support for Lookup Popup
// Create popup window with authority choices for value of an input field.
// This is intended to be called by onClick of a "Lookup" or "Add" button.
function DSpaceChoiceLookup(url, field, formID, valueInput, authInput,
confIndicatorID, collectionID, isName, isRepeating)
{
// fill in URL
url += '?field='+field+'&formID='+formID+'&valueInput='+valueInput+
'&authorityInput='+authInput+'&collection='+collectionID+
'&isName='+isName+'&isRepeating='+isRepeating+'&confIndicatorID='+confIndicatorID;
// primary input field - for positioning popup.
var inputFieldName = isName ? dspace_makeFieldInput(valueInput,'_last') : valueInput;
var inputField = document.getElementById(formID).elements[inputFieldName];
// scriptactulous magic to figure out true offset:
var cOffset = 0;
if (inputField != null)
cOffset = $(inputField).cumulativeOffset();
var width = 600; // XXX guesses! these should be params, or configured..
var height = 470;
var left;
var top;
if (window.screenX == null) {
left = window.screenLeft + cOffset.left - (width/2);
top = window.screenTop + cOffset.top - (height/2);
} else {
left = window.screenX + cOffset.left - (width/2);
top = window.screenY + cOffset.top - (height/2);
}
if (left < 0) left = 0;
if (top < 0) top = 0;
var pw = window.open(url, 'ignoreme',
'width='+width+',height='+height+',left='+left+',top='+top+
',toolbar=no,menubar=no,location=no,status=no,resizable');
if (window.focus) pw.focus();
return false;
}
// Run this as the Lookup page is loaded to initialize DOM objects, load choices
function DSpaceChoicesSetup(form)
{
// find the "LEGEND" in fieldset, which acts as page title,
// and save it as a bogus form element, e.g. elements['statline']
var fieldset = document.getElementById('aspect_general_ChoiceLookupTransformer_list_choicesList');
for (i = 0; i < fieldset.childNodes.length; ++i)
{
if (fieldset.childNodes[i].nodeName == 'LEGEND')
{
form.statline = fieldset.childNodes[i];
form.statline_template = fieldset.childNodes[i].innerHTML;
fieldset.childNodes[i].innerHTML = "Loading...";
break;
}
}
DSpaceChoicesLoad(form);
}
// populate the "select" with options from ajax request
// stash some parameters as properties of the "select" so we can add to
// the last start index to query for next set of results.
function DSpaceChoicesLoad(form)
{
var field = form.elements['paramField'].value;
var value = form.elements['paramValue'].value;
var start = form.elements['paramStart'].value;
var limit = form.elements['paramLimit'].value;
var formID = form.elements['paramFormID'].value;
var collID = form.elements['paramCollection'].value;
var isName = form.elements['paramIsName'].value == 'true';
var isRepeating = form.elements['paramIsRepeating'].value == 'true';
var isClosed = form.elements['paramIsClosed'].value == 'true';
var contextPath = form.elements['contextPath'].value;
var fail = form.elements['paramFail'].value;
var valueInput = form.elements['paramValueInput'].value;
var nonAuthority = "";
if (form.elements['paramNonAuthority'] != null)
nonAuthority = form.elements['paramNonAuthority'].value;
// get value from form inputs in opener if not explicitly supplied
if (value.length == 0)
{
var of = window.opener.document.getElementById(formID);
if (isName)
value = makePersonName(of.elements[dspace_makeFieldInput(valueInput,'_last')].value,
of.elements[dspace_makeFieldInput(valueInput,'_first')].value);
else
value = of.elements[valueInput].value;
// if this is a repeating input, clear the source value so that e.g.
// clicking "Next" on a submit-describe page will not *add* the proposed
// lookup text as a metadata value:
if (isRepeating)
{
if (isName)
{
of.elements[dspace_makeFieldInput(valueInput,'_last')].value = null;
of.elements[dspace_makeFieldInput(valueInput,'_first')].value = null;
}
else
of.elements[valueInput].value = null;
}
}
// start spinner
var indicator = document.getElementById('lookup_indicator_id');
if (indicator != null)
indicator.style.display = "inline";
new Ajax.Request(contextPath+"/choices/"+field,
{
method: "get",
parameters: {
query: value,
format: 'select',
collection: collID,
start: start,
limit: limit
},
// triggered by any exception, even in success
onException: function(req, e) {
window.alert(fail+" Exception="+e);
if (indicator != null) indicator.style.display = "none";
},
// when http load of choices fails
onFailure: function() {
window.alert(fail+" HTTP error resonse");
if (indicator != null) indicator.style.display = "none";
},
// format is <select><option authority="key" value="val">label</option>...
onSuccess: function(transport) {
var ul = transport.responseXML.documentElement;
var err = ul.getAttributeNode('error');
if (err != null && err.value == 'true')
window.alert(fail+" Server indicates error in response.");
var opts = ul.getElementsByTagName('option');
// update range message and update 'more' button
var oldStart = 1 * ul.getAttributeNode('start').value;
var nextStart = oldStart + opts.length;
var lastTotal = ul.getAttributeNode('total').value;
var resultMore = ul.getAttributeNode('more');
form.elements['more'].disabled = !(resultMore != null && resultMore.value == 'true');
form.elements['paramStart'].value = nextStart;
// clear select first
var select = form.elements['chooser'];
for (var i = select.length-1; i >= 0; --i)
select.remove(i);
// load select and look for default selection
var selectedByValue = -1; // select by value match
var selectedByChoices = -1; // Choice says its selected
for (var i = 0; i < opts.length; ++i)
{
var opt = opts.item(i);
var olabel = "";
for (var j = 0; j < opt.childNodes.length; ++j)
{
var node = opt.childNodes[j];
if (node.nodeName == "#text")
olabel += node.data;
}
var ovalue = opt.getAttributeNode('value').value;
var option = new Option(olabel, ovalue);
option.authority = opt.getAttributeNode('authority').value;
select.add(option, null);
if (value == ovalue)
selectedByValue = select.options.length - 1;
if (opt.getAttributeNode('selected') != null)
selectedByChoices = select.options.length - 1;
}
// add non-authority option if needed.
if (!isClosed)
{
select.add(new Option(dspace_formatMessage(nonAuthority, value), value), null);
}
var defaultSelected = -1;
if (selectedByChoices >= 0)
defaultSelected = selectedByChoices;
else if (selectedByValue >= 0)
defaultSelected = selectedByValue;
else if (select.options.length == 1)
defaultSelected = 0;
// load default-selected value
if (defaultSelected >= 0)
{
select.options[defaultSelected].defaultSelected = true;
var so = select.options[defaultSelected];
if (isName)
{
form.elements['text1'].value = lastNameOf(so.value);
form.elements['text2'].value = firstNameOf(so.value);
}
else
form.elements['text1'].value = so.value;
}
// turn off spinner
if (indicator != null)
indicator.style.display = "none";
// "results" status line
var statLast = nextStart + (isClosed ? 2 : 1);
form.statline.innerHTML =
dspace_formatMessage(form.statline_template,
oldStart+1, statLast, Math.max(lastTotal,statLast), value);
}
});
}
// handler for change event on choice selector - load new values
function DSpaceChoicesSelectOnChange ()
{
// "this" is the window,
var form = document.getElementById('aspect_general_ChoiceLookupTransformer_div_lookup');
var select = form.elements['chooser'];
var so = select.options[select.selectedIndex];
var isName = form.elements['paramIsName'].value == 'true';
if (isName)
{
form.elements['text1'].value = lastNameOf(so.value);
form.elements['text2'].value = firstNameOf(so.value);
}
else
form.elements['text1'].value = so.value;
}
// handler for lookup popup's accept (or add) button
// stuff values back to calling page, force an add if necessary, and close.
function DSpaceChoicesAcceptOnClick ()
{
var select = this.form.elements['chooser'];
var isName = this.form.elements['paramIsName'].value == 'true';
var isRepeating = this.form.elements['paramIsRepeating'].value == 'true';
var valueInput = this.form.elements['paramValueInput'].value;
var authorityInput = this.form.elements['paramAuthorityInput'].value;
var formID = this.form.elements['paramFormID'].value;
var confIndicatorID = this.form.elements['paramConfIndicatorID'] == null?null:this.form.elements['paramConfIndicatorID'].value;
// default the authority input if not supplied.
if (authorityInput.length == 0)
authorityInput = dspace_makeFieldInput(valueInput,'_authority');
// always stuff text fields back into caller's value input(s)
if (valueInput.length > 0)
{
var of = window.opener.document.getElementById(formID);
if (isName)
{
of.elements[dspace_makeFieldInput(valueInput,'_last')].value = this.form.elements['text1'].value;
of.elements[dspace_makeFieldInput(valueInput,'_first')].value = this.form.elements['text2'].value;
}
else
of.elements[valueInput].value = this.form.elements['text1'].value;
if (authorityInput.length > 0 && of.elements[authorityInput] != null)
{
// conf input is auth input, substitute '_confidence' for '_authority'
// if conf fieldname is FIELD_confidence_NUMBER, then '_authority_' => '_confidence_'
var confInput = "";
var ci = authorityInput.lastIndexOf("_authority_");
if (ci < 0)
confInput = authorityInput.substring(0, authorityInput.length-10)+'_confidence';
else
confInput = authorityInput.substring(0, ci)+"_confidence_"+authorityInput.substring(ci+11);
// DEBUG:
// window.alert('Setting fields auth="'+authorityInput+'", conf="'+confInput+'"');
var authValue = null;
if (select.selectedIndex >= 0 && select.options[select.selectedIndex].authority != null)
{
authValue = select.options[select.selectedIndex].authority;
of.elements[authorityInput].value = authValue;
}
if (of.elements[confInput] != null)
of.elements[confInput].value = 'accepted';
// make indicator blank if no authority value
DSpaceUpdateConfidence(window.opener.document, confIndicatorID,
authValue == null || authValue == '' ? 'blank' :'accepted');
}
// force the submit button -- if there is an "add"
if (isRepeating)
{
var add = of.elements["submit_"+valueInput+"_add"];
if (add != null)
add.click();
else
alert('Sanity check: Cannot find button named "submit_'+valueInput+'_add"');
}
}
window.close();
return false;
}
// handler for lookup popup's more button
function DSpaceChoicesMoreOnClick ()
{
DSpaceChoicesLoad(this.form);
}
// handler for lookup popup's cancel button
function DSpaceChoicesCancelOnClick ()
{
window.close();
return false;
}
// -------------------- Utilities
// DSpace person-name conventions, see DCPersonName
function makePersonName(lastName, firstName)
{
return (firstName == null || firstName.length == 0) ? lastName :
lastName+", "+firstName;
}
// DSpace person-name conventions, see DCPersonName
function firstNameOf(personName)
{
var comma = personName.indexOf(",");
return (comma < 0) ? "" : stringTrim(personName.substring(comma+1));
}
// DSpace person-name conventions, see DCPersonName
function lastNameOf(personName)
{
var comma = personName.indexOf(",");
return stringTrim((comma < 0) ? personName : personName.substring(0, comma));
}
// replicate java String.trim()
function stringTrim(str)
{
var start = 0;
var end = str.length;
for (; str.charAt(start) == ' '&& start < end; ++start) ;
for (; end > start && str.charAt(end-1) == ' '; --end) ;
return str.slice(start, end);
}
// format utility - replace @1@, @2@ etc with args 1, 2, 3..
// NOTE params MUST be monotonically increasing
// NOTE we can't use "{1}" like the i18n catalog because it elides them!!
// ...UNLESS maybe it were to be fixed not to when no params...
function dspace_formatMessage()
{
var template = dspace_formatMessage.arguments[0];
var i;
for (i = 1; i < arguments.length; ++i)
{
var pattern = '@'+i+'@';
if (template.search(pattern) >= 0)
template = template.replace(pattern, dspace_formatMessage.arguments[i]);
}
return template;
}
// utility to make sub-field name of input field, e.g. _last, _first, _auth..
// if name ends with _1, _2 etc, put sub-name BEFORE the number
function dspace_makeFieldInput(name, sub)
{
var i = name.search("_[0-9]+$");
if (i < 0)
return name+sub;
else
return name.substr(0, i)+sub+name.substr(i);
}
// update the class value of confidence-indicating element
function DSpaceUpdateConfidence(doc, confIndicatorID, newValue)
{
// sanity checks - need valid ID and a real DOM object
if (confIndicatorID == null || confIndicatorID == "")
return;
var confElt = doc.getElementById(confIndicatorID);
if (confElt == null)
return;
// add or update CSS class with new confidence value, e.g. "cf-accepted".
if (confElt.className == null)
confElt.className = "cf-"+newValue;
else
{
var classes = confElt.className.split(" ");
var newClasses = "";
var found = false;
for (var i = 0; i < classes.length; ++i)
{
if (classes[i].match('^cf-[a-zA-Z0-9]+$'))
{
newClasses += "cf-"+newValue+" ";
found = true;
}
else
newClasses += classes[i]+" ";
}
if (!found)
newClasses += "cf-"+newValue+" ";
confElt.className = newClasses;
}
}
// respond to "onchanged" event on authority input field
// set confidence to 'accepted' if authority was changed by user.
function DSpaceAuthorityOnChange(self, confValueID, confIndicatorID)
{
var confidence = 'accepted';
if (confValueID != null && confValueID != '')
{
var confValueField = document.getElementById(confValueID);
if (confValueField != null)
confValueField.value = confidence;
}
DSpaceUpdateConfidence(document, confIndicatorID, confidence)
return false;
}
// respond to click on the authority-value lock button in Edit Item Metadata:
// "button" is bound to the image input for the lock button, "this"
function DSpaceToggleAuthorityLock(button, authInputID)
{
// sanity checks - need valid ID and a real DOM object
if (authInputID == null || authInputID == '')
return false;
var authInput = document.getElementById(authInputID);
if (authInput == null)
return false;
// look for is-locked or is-unlocked in class list:
var classes = button.className.split(' ');
var newClass = '';
var newLocked = false;
var found = false;
for (var i = 0; i < classes.length; ++i)
{
if (classes[i] == 'is-locked')
{
newLocked = false;
found = true;
}
else if (classes[i] == 'is-unlocked')
{
newLocked = true;
found = true;
}
else
newClass += classes[i]+' ';
}
if (!found)
return false;
// toggle the image, and set readability
button.className = newClass + (newLocked ? 'is-locked' : 'is-unlocked') + ' ';
authInput.readOnly = newLocked;
return false;
}
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
importClass(Packages.javax.mail.internet.AddressException);
importClass(Packages.org.dspace.app.xmlui.utils.FlowscriptUtils);
importClass(Packages.org.dspace.core.ConfigurationManager);
importClass(Packages.org.dspace.core.Context);
importClass(Packages.org.dspace.content.Collection);
importClass(Packages.org.dspace.eperson.EPerson);
importClass(Packages.org.dspace.eperson.AccountManager);
importClass(Packages.org.dspace.eperson.Subscribe);
importClass(Packages.org.dspace.app.xmlui.utils.AuthenticationUtil);
importClass(Packages.org.dspace.app.xmlui.utils.ContextUtil);
importClass(Packages.java.lang.String);
/**
* This class defines the workflows for three flows within the EPerson aspect.
*
* FIXME: add more documentation
*
* @author Scott Phillips
*/
/** These functions should be common to all Manakin Flow scripts */
function getObjectModel()
{
return FlowscriptUtils.getObjectModel(cocoon);
}
function getDSContext()
{
return ContextUtil.obtainContext(getObjectModel());
}
function getEPerson()
{
return getDSContext().getCurrentUser();
}
/**
* Preform a new user registration.
*/
function doRegister()
{
var token = cocoon.request.get("token");
if (token == null)
{
// We have no token, this is the initial form. First ask the user for their email address
// and then send them a token.
var accountExists = false;
var errors = new Array();
do {
var email = cocoon.request.getParameter("email");
cocoon.sendPageAndWait("register/start",{"email" : email, "errors" : errors.join(','), "accountExists" : accountExists});
var errors = new Array();
accountExists = false;
var submit_forgot = cocoon.request.getParameter("submit_forgot");
if (submit_forgot != null)
{
// The user attempted to register with an email address that all ready exists then they clicked
// the "I forgot my password" button. In this case, we send them a forgot password token.
AccountManager.sendForgotPasswordInfo(getDSContext(),email);
getDSContext().commit();
cocoon.sendPage("forgot/verify", {"email":email});
return;
}
email = cocoon.request.getParameter("email");
email = email.toLowerCase(); // all emails should be lowercase
var epersonFound = (EPerson.findByEmail(getDSContext(),email) != null);
if (epersonFound)
{
accountExists = true;
continue;
}
var canRegister = AuthenticationUtil.canSelfRegister(getObjectModel(), email);
if (canRegister)
{
try
{
// May throw the AddressException or a varity of SMTP errors.
AccountManager.sendRegistrationInfo(getDSContext(),email);
getDSContext().commit();
}
catch (error)
{
// If any errors occure while trying to send the email set the field in error.
errors = new Array("email");
continue;
}
cocoon.sendPage("register/verify", { "email":email, "forgot":"false" });
return;
}
else
{
cocoon.sendPage("register/cannot", { "email" : email});
return;
}
} while (accountExists || errors.length > 0)
}
else
{
// We have a token. Find out who the it's for
var email = AccountManager.getEmail(getDSContext(), token);
if (email == null)
{
cocoon.sendPage("register/invalid-token");
return;
}
var setPassword = AuthenticationUtil.allowSetPassword(getObjectModel(),email);
var errors = new Array();
do {
cocoon.sendPageAndWait("register/profile",{"email" : email, "allowSetPassword":setPassword , "errors" : errors.join(',')});
// If the user had to retry the form a user may allready be created.
var eperson = EPerson.findByEmail(getDSContext(),email);
if (eperson == null)
{
eperson = AuthenticationUtil.createNewEperson(getObjectModel(),email);
}
// Log the user in so that they can update their own information.
getDSContext().setCurrentUser(eperson);
errors = updateInformation(eperson);
if (setPassword)
{
var passwordErrors = updatePassword(eperson);
errors = errors.concat(passwordErrors);
}
// Log the user back out.
getDSContext().setCurrentUser(null);
} while (errors.length > 0)
// Log the newly created user in.
AuthenticationUtil.logIn(getObjectModel(),eperson);
AccountManager.deleteToken(getDSContext(), token);
getDSContext().commit();
cocoon.sendPage("register/finished");
return;
}
}
/**
* Preform a forgot password processes.
*/
function doForgotPassword()
{
var token = cocoon.request.get("token");
if (token == null)
{
// We have no token, this is the initial form. First ask the user for their email address
// and then send them a token.
var email = cocoon.request.getParameter("email");
var errors = new Array();
do {
cocoon.sendPageAndWait("forgot/start",{"email" : email, "errors" : errors.join(',')});
email = cocoon.request.getParameter("email");
errors = new Array();
var epersonFound = (EPerson.findByEmail(getDSContext(),email) != null);
if (!epersonFound)
{
// No eperson found for the given address, set the field in error and let
// the user try again.
errors = new Array("email");
continue;
}
// An Eperson was found for the given email, so use the forgot password
// mechanism. This may throw a AddressException if the email is ill-formed.
AccountManager.sendForgotPasswordInfo(getDSContext(),email);
getDSContext().commit();
} while (errors.length > 0)
cocoon.sendPage("forgot/verify", {"email":email});
}
else
{
// We have a token. Find out who the it's for
var email = AccountManager.getEmail(getDSContext(), token);
if (email == null)
{
cocoon.sendPage("forgot/invalid-token");
return;
}
var epersonFound = (AccountManager.getEPerson(getDSContext(), token) != null);
if (!epersonFound)
{
cocoon.sendPage("forgot/invalid-token");
return;
}
var errors = new Array();
do {
cocoon.sendPageAndWait("forgot/reset", { "email" : email, "errors" : errors.join(',') });
// Get the eperson associated with the password change
var eperson = AccountManager.getEPerson(getDSContext(), token);
// Temporaraly log the user in so that they can update their password.
getDSContext().setCurrentUser(eperson);
errors = updatePassword(eperson);
getDSContext().setCurrentUser(null);
} while (errors.length > 0)
// Log the user in and remove the token.
AuthenticationUtil.logIn(getObjectModel(),eperson);
AccountManager.deleteToken(getDSContext(), token);
getDSContext().commit();
cocoon.sendPage("forgot/finished");
}
}
/**
* Flow function to update a user's profile. This flow will iterate
* over the profile/update form untill the user has provided correct
* data (i.e. filled in the required fields and meet the minimum
* password requirements).
*/
function doUpdateProfile()
{
var retry = false;
// check that the user is logged in.
if (getEPerson() == null)
{
var contextPath = cocoon.request.getContextPath();
cocoon.redirectTo(contextPath + "/login",true);
getDSContext().complete();
cocoon.exit();
}
// Do we allow the user to change their password or does
// it not make sense for their authentication mechanism?
var setPassword = AuthenticationUtil.allowSetPassword(getObjectModel(),getEPerson().getEmail());
// List of errors encountered.
var errors = new Array();
do {
cocoon.sendPageAndWait("profile/update", {"allowSetPassword" : setPassword, "errors" : errors.join(',') } );
if (cocoon.request.get("submit"))
{
// Update the user's info and password.
errors = updateInformation(getEPerson());
if (setPassword)
{
// check if they entered a new password:
var password = cocoon.request.getParameter("password");
if (password != null && !password.equals(""))
{
var passwordErrors = updatePassword(getEPerson());
errors = errors.concat(passwordErrors);
}
}
}
else if (cocoon.request.get("submit_subscriptions_add"))
{
// Add the a new subscription
var collection = Collection.find(getDSContext(),cocoon.request.get("subscriptions"));
if (collection != null)
{
Subscribe.subscribe(getDSContext(),getEPerson(),collection);
getDSContext().commit();
}
}
else if (cocoon.request.get("submit_subscriptions_delete"))
{
// Remove any selected subscriptions
var names = cocoon.request.getParameterValues("subscriptions_selected");
if (names != null)
{
for (var i = 0; i < names.length; i++)
{
var collectionID = cocoon.request.get(names[i]);
var collection = Collection.find(getDSContext(),collectionID);
if (collection != null)
Subscribe.unsubscribe(getDSContext(),getEPerson(),collection);
}
}
getDSContext().commit();
}
} while (errors.length > 0 || !cocoon.request.get("submit"))
cocoon.sendPage("profile/updated");
}
/**
* Update the eperson's profile information. Some fields, such as
* last_name & first_name are required.
*
* Missing or mailformed field names will be returned in an array.
* If the user's profile information was updated successfully then
* an empty array will be returned.
*/
function updateInformation(eperson)
{
if (!(ConfigurationManager.getBooleanProperty("xmlui.user.editmetadata", true)))
{
// We're configured to not allow the user to update their metadata so return with no errors.
return new Array();
}
// Get the parameters from the form
var lastName = cocoon.request.getParameter("last_name");
var firstName = cocoon.request.getParameter("first_name");
var phone = cocoon.request.getParameter("phone");
var language = cocoon.request.getParameter("language");
// first check that each parameter is filled in before seting anything.
var idx = 0;
var errors = new Array();
if (firstName == null || firstName.equals(""))
{
errors[idx++] = "first_name";
}
if (lastName == null || lastName.equals(""))
{
errors[idx++] = "last_name";
}
if (idx > 0)
{
// There were errors
return errors;
}
eperson.setFirstName(firstName);
eperson.setLastName(lastName);
eperson.setMetadata("phone", phone);
eperson.setLanguage(language);
eperson.update();
return new Array();
}
/**
* Update the eperson's password if it meets the minimum password
* requirements.
*
* Any fields that are in error will be returned in an array. If
* the user's password was updated successfull then an empty array
* will be returned.
*/
function updatePassword(eperson)
{
var password = cocoon.request.getParameter("password");
var passwordConfirm = cocoon.request.getParameter("password_confirm");
// No empty passwords
if (password == null)
{
return new Array("password");
}
// No short passwords
if ( password.length() < 6)
{
return new Array("password");
}
// No unconfirmed passwords
if (!password.equals(passwordConfirm))
{
return new Array("password_confirm");
}
eperson.setPassword(password);
eperson.update();
return new Array();
}
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
importClass(Packages.java.lang.Class);
importClass(Packages.java.lang.ClassLoader);
importClass(Packages.org.dspace.app.xmlui.utils.FlowscriptUtils);
importClass(Packages.org.apache.cocoon.environment.http.HttpEnvironment);
importClass(Packages.org.apache.cocoon.servlet.multipart.Part);
importClass(Packages.org.dspace.handle.HandleManager);
importClass(Packages.org.dspace.core.Constants);
importClass(Packages.org.dspace.workflow.WorkflowItem);
importClass(Packages.org.dspace.workflow.WorkflowManager);
importClass(Packages.org.dspace.content.WorkspaceItem);
importClass(Packages.org.dspace.authorize.AuthorizeManager);
importClass(Packages.org.dspace.license.CreativeCommons);
importClass(Packages.org.dspace.app.xmlui.utils.ContextUtil);
importClass(Packages.org.dspace.app.xmlui.cocoon.HttpServletRequestCocoonWrapper);
importClass(Packages.org.dspace.app.xmlui.aspect.submission.FlowUtils);
importClass(Packages.org.dspace.app.xmlui.aspect.submission.StepAndPage);
importClass(Packages.org.dspace.app.util.SubmissionConfig);
importClass(Packages.org.dspace.app.util.SubmissionConfigReader);
importClass(Packages.org.dspace.app.util.SubmissionInfo);
importClass(Packages.org.dspace.submit.AbstractProcessingStep);
/* Global variable which stores a comma-separated list of all fields
* which errored out during processing of the last step.
*/
var ERROR_FIELDS = null;
/**
* Simple access method to access the current cocoon object model.
*/
function getObjectModel()
{
return FlowscriptUtils.getObjectModel(cocoon);
}
/**
* Return the DSpace context for this request since each HTTP request generates
* a new context this object should never be stored and instead always accessed
* through this method so you are ensured that it is the correct one.
*/
function getDSContext()
{
return ContextUtil.obtainContext(getObjectModel());
}
/**
* Return the HTTP Request object for this request
*/
function getHttpRequest()
{
//return getObjectModel().get(HttpEnvironment.HTTP_REQUEST_OBJECT)
// Cocoon's request object handles form encoding, thus if the users enters
// non-ascii characters such as those found in foreign languages they will
// come through corrupted if they are not obtained through the cocoon request
// object. However, since the dspace-api is built to accept only HttpServletRequest
// a wrapper class HttpServletRequestCocoonWrapper has bee built to translate
// the cocoon request back into a servlet request. This is not a fully complete
// translation as some methods are unimplemented. But it is enough for our
// purposes here.
return new HttpServletRequestCocoonWrapper(getObjectModel());
}
/**
* Return the HTTP Response object for the response
* (used for compatibility with DSpace configurable submission system)
*/
function getHttpResponse()
{
return getObjectModel().get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
}
/**
* Return the SubmissionInfo for the current submission
*/
function getSubmissionInfo(workspaceID)
{
return FlowUtils.obtainSubmissionInfo(getObjectModel(), workspaceID);
}
/**
* Return an array of all step and page numbers as StepAndPage objects.
* This returns all steps within the current submission process,
* including non-interactive steps which do not appear in
* the Progress Bar.
*/
function getSubmissionSteps(submissionInfo)
{
return FlowUtils.getListOfAllSteps(getHttpRequest(), submissionInfo);
}
/**
* Send the current page and wait for the flow to be continued. Use this method to add
* a flow=true parameter. This allows the sitemap to filter out all flow related requests
* from non flow related requests.
*/
function sendPageAndWait(uri,bizData)
{
if (bizData == null)
bizData = {};
// just to remember where we came from.
bizData["flow"] = "true";
cocoon.sendPageAndWait(uri,bizData);
}
/**
* Send the given page and DO NOT wait for the flow to be continued. Execution will
* proceed as normal. Use this method to add a flow=true parameter. This allows the
* sitemap to filter out all flow related requests from non flow related requests.
*/
function sendPage(uri,bizData)
{
if (bizData == null)
bizData = {};
// just to remember where we came from.
bizData["flow"] = "true";
cocoon.sendPage(uri,bizData);
}
/**
* Submission starting point.
*
* This is the entry point for all submission related flows, either resuming an old
* submission or starting a new one. If a new submission is being resumed then the
* workspace id should be passed as an HTTP parameter.
*/
function doSubmission()
{
var step = cocoon.request.get("step"); //retrieve step number
var workspaceID = cocoon.request.get("workspaceID");
if (workspaceID == null)
{
var handle = cocoon.parameters["handle"];
if (handle == null)
handle = cocoon.request.get("handle");
var collectionSelected = false;
do {
if (handle != null)
{
var dso = HandleManager.resolveToObject(getDSContext(), handle);
// Check that the dso is a collection
if (dso != null && dso.getType() == Constants.COLLECTION)
{
// Check that the user is able to submit
if (AuthorizeManager.authorizeActionBoolean(getDSContext(), dso, Constants.ADD))
{
// Construct a new workspace for this submission.
var workspace = WorkspaceItem.create(getDSContext(), dso, true);
workspaceID = workspace.getID();
collectionSelected = true;
break; // We don't need to ask them for a collection again.
}
}
}
sendPageAndWait("submit/selectCollectionStep", { "handle" : handle } );
handle = cocoon.request.get("handle");
} while (collectionSelected == false)
// Hand off to the master thingy....
//(specify "S" for submission item, for FlowUtils.findSubmission())
submissionControl(handle,"S"+workspaceID, step);
}
else
{
// Resume a previous submission
var workspace = WorkspaceItem.find(getDSContext(), workspaceID);
// First check that the id is valid.
var submitterID = workspace.getSubmitter().getID()
var currentID = getDSContext().getCurrentUser().getID();
if (submitterID == currentID)
{
// Get the collection handle for this item.
var handle = workspace.getCollection().getHandle();
// Record that this is a submission id, not a workflow id.
//(specify "S" for submission item, for FlowUtils.findSubmission())
workspaceID = "S"+workspaceID;
do {
sendPageAndWait("handle/"+handle+"/submit/resumeStep",
{"id":workspaceID,"step":"0.0"});
if (cocoon.request.get("submit_resume"))
{
submissionControl(handle,workspaceID, step);
}
else if (cocoon.request.get("submit_cancel"))
{
var contextPath = cocoon.request.getContextPath();
cocoon.redirectTo(contextPath+"/submissions",true);
getDSContext().complete();
cocoon.exit();
}
} while (1 == 1)
}
}
}
/**
* This is the master flow control for submissions. This method decides
* which steps are executed in which order. Each step is called and does
* not return until its exit conditions have been met. Then the standard
* navigation buttons are checked and the step is either decreased or
* increased accordingly. Special cases like jumping or saving are also
* handled here.
*
* Parameters:
* collectionHandle - the handle of the collection we are submitting to
* workspaceID - the in progress submission's Workspace ID
* stepAndPage - the Step and Page number to start on (e.g. (1,1))
*/
function submissionControl(collectionHandle, workspaceID, initStepAndPage)
{
//load initial submission information
var submissionInfo = getSubmissionInfo(workspaceID);
//Initialize a Cocoon Local Page to save current state information
//(This lets us handle when users click the browser "back button"
// by caching the state of that previous page, etc.)
var state = cocoon.createPageLocal();
state.progressIterator = 0; //initialize our progress indicator
//this is array of all the steps/pages in current submission process
//it's used to step back and forth between pages!
var stepsInSubmission = getSubmissionSteps(submissionInfo);
//if we didn't have a page passed in, go to first page in process
if(initStepAndPage==null)
state.stepAndPage = stepsInSubmission[0];
else
state.stepAndPage = initStepAndPage;
var response_flag = 0;
do {
// Loop forever, exit cases such as save, remove, or completed
// will call cocoon.exit() stopping execution.
cocoon.log.debug("Current step & page=" + state.stepAndPage, null);
cocoon.log.debug("Current ERROR Fields=" + getErrorFields(), null);
//----------------------------------------------------------
// #1: Actually load the next page in the process
//-----------------------------------------------------------
//split out step and page (e.g. 1.2 is page 2 of step 1)
var step = state.stepAndPage.getStep();
var page = state.stepAndPage.getPage();
//Set the current page we've reached in current step
FlowUtils.setPageReached(getDSContext(),workspaceID, step, page);
//Load this step's configuration
var stepConfig = submissionInfo.getSubmissionConfig().getStep(step);
//Pass it all the info it needs, including any response/error flags
//in case an error occurred
response_flag = doNextPage(collectionHandle, workspaceID, stepConfig, state.stepAndPage, response_flag);
var maxStep = FlowUtils.getMaximumStepReached(getDSContext(),workspaceID);
var maxPage = FlowUtils.getMaximumPageReached(getDSContext(),workspaceID);
var maxStepAndPage = new StepAndPage(maxStep,maxPage);
//----------------------------------------------------------
// #2: Determine which page/step the user should be sent to next
//-----------------------------------------------------------
// User clicked "Next->" button (or a Non-interactive Step - i.e. no UI)
// Only step forward to next page if no errors on this page
if ((cocoon.request.get(AbstractProcessingStep.NEXT_BUTTON) || !stepHasUI(stepConfig)) && (response_flag==AbstractProcessingStep.STATUS_COMPLETE))
{
state.progressIterator++;
var totalSteps = stepsInSubmission.length;
var inWorkflow = submissionInfo.isInWorkflow();
//check if we've completed the submission
if(state.progressIterator >= totalSteps)
{
if(inWorkflow==false)
{
//Submission is completed!
cocoon.log.debug("Submission Completed!");
showCompleteConfirmation(collectionHandle);
}
else
{ //since in Workflow just break out of loop to return to Workflow process
break;
}
}
else
{
state.stepAndPage = stepsInSubmission[state.progressIterator];
cocoon.log.debug("Next Step & Page=" + state.stepAndPage);
}
}//User clicked "<- Previous" button
else if (cocoon.request.get(AbstractProcessingStep.PREVIOUS_BUTTON) &&
(response_flag==AbstractProcessingStep.STATUS_COMPLETE || state.stepAndPage == maxStepAndPage))
{
var stepBack = true;
//Need to find the previous step which HAS a user interface.
while(stepBack)
{
state.progressIterator--;
if(state.progressIterator<0)
stepBack = false;
state.stepAndPage = stepsInSubmission[state.progressIterator];
var prevStep = state.stepAndPage.getStep();
var prevStepConfig = submissionInfo.getSubmissionConfig().getStep(prevStep);
if(!stepHasUI(prevStepConfig))
stepBack = true;
else
stepBack = false;
}
cocoon.log.debug("Previous Step & Page=" + state.stepAndPage);
}
// User clicked "Save/Cancel" Button
else if (cocoon.request.get(AbstractProcessingStep.CANCEL_BUTTON))
{
var inWorkflow = submissionInfo.isInWorkflow();
if (inWorkflow && response_flag==AbstractProcessingStep.STATUS_COMPLETE)
{
var contextPath = cocoon.request.getContextPath();
cocoon.redirectTo(contextPath+"/submissions",true);
coocon.exit();
}
else if (!inWorkflow)
{
submitStepSaveOrRemove(collectionHandle,workspaceID,step,page);
}
}
//User clicked on Progress Bar:
// only check for a 'step_jump' (i.e. click on progress bar)
// if there are no errors to be resolved
if(response_flag==AbstractProcessingStep.STATUS_COMPLETE || state.stepAndPage == maxStepAndPage)
{
var names = cocoon.request.getParameterNames();
while(names.hasMoreElements())
{
var name = names.nextElement();
if (name.startsWith(AbstractProcessingStep.PROGRESS_BAR_PREFIX))
{
var newStepAndPage = name.substring(AbstractProcessingStep.PROGRESS_BAR_PREFIX.length());
newStepAndPage = new StepAndPage(newStepAndPage);
//only allow a jump to a page user has already been to
if (newStepAndPage.isSet() && (newStepAndPage.compareTo(maxStepAndPage) <= 0))
{
state.stepAndPage = newStepAndPage;
cocoon.log.debug("Jump To Step & Page=" + state.stepAndPage);
//reset progress iterator
for(var i=0; i<stepsInSubmission.length; i++)
{
if(state.stepAndPage.equals(stepsInSubmission[i]))
{
state.progressIterator = i;
break;
}
}
}
}//end if submit_jump pressed
}//end while more elements
}//end if no errors
} while ( 1 == 1)
}
/**
* This function actually starts the next page in a step,
* loading it's UI and then doing its processing!
*
* Parameters:
* collectionHandle - the handle of the collection we are submitting to
* workspaceID - the in progress submission's Workspace ID
* stepConfig - the SubmissionStepConfig representing the current step config
* stepAndPage - the current Step and Page number (e.g. "1.1")
* response_flag - any response or errors from previous processing
*/
function doNextPage(collectionHandle, workspaceID, stepConfig, stepAndPage, response_flag)
{
//split out step and page (e.g. 1.2 is page 2 of step 1)
var step = stepAndPage.getStep();
var page = stepAndPage.getPage();
//-------------------------------------
// #1: Check if this step has a UI
//-------------------------------------
//if this step has an XML-UI, then call the generic step transformer
//(otherwise, this is just a processing step)
if(stepHasUI(stepConfig))
{
//prepend URI with the handle of the collection, and go there!
sendPageAndWait("handle/"+collectionHandle+ "/submit/continue",{"id":workspaceID,"step":String(stepAndPage),"transformer":stepConfig.getXMLUIClassName(),"error":String(response_flag),"error_fields":getErrorFields()});
}
//-------------------------------------
// #2: Perform step processing
//-------------------------------------
//perform step processing (this returns null if no errors, otherwise an error string)
response_flag = processPage(workspaceID, stepConfig, page);
return response_flag;
}
/**
* This function calls the step processing code, which will process
* all user inputs for this step, or just perform backend processing
* (for non-interactive steps).
*
* This function returns the response_flag which is returned by the
* step class's doProcessing() method. An error flag of
* AbstractProcessingStep.STATUS_COMPLETE (value = 0) means no errors!
*
* Parameters:
* workspaceID - the in progress submission's Workspace ID
* stepConfig - the SubmissionStepConfig for the current step
* page - the current page number we are on in the step
*/
function processPage(workspaceID, stepConfig, page)
{
//retrieve submission info
//(we cannot pass the submission info to this function, since
// often this processing takes place as part of a new request
// and the DSpace Context is changed on each request)
var submissionInfo = getSubmissionInfo(workspaceID);
var response_flag = null;
//---------------------------------------------
// #1: Get a reference to Step Processing class
//---------------------------------------------
//get name of processing class for this step
var processingClassName = stepConfig.getProcessingClassName();
//retrieve an instance of the processing class
var loader = submissionInfo.getClass().getClassLoader();
var processingClass = loader.loadClass(processingClassName);
// this processing class *must* be a valid AbstractProcessingStep,
// or else we'll have problems very shortly
var stepClass = processingClass.newInstance();
//------------------------------------------------
// #2: Perform step processing & check for errors
//------------------------------------------------
//Check if this request is a file upload
//(if so, Cocoon automatically uploads the file,
// so we need to let the Processing class know that)
var contentType = getHttpRequest().getContentType();
if ((contentType != null)
&& (contentType.indexOf("multipart/form-data") != -1))
{
//load info about uploaded file, so that it can be
//saved properly by the step's doProcessing() method below
loadFileUploadInfo();
}
//before beginning processing, let this step know what page to process
//(this is important for multi-page steps!)
stepClass.setCurrentPage(getHttpRequest(), page);
//call the step's doProcessing() method
response_flag = stepClass.doProcessing(getDSContext(), getHttpRequest(), getHttpResponse(), submissionInfo);
//if this is a non-interactive step,
//we cannot do much with errors/responses other than logging them!
if((!stepHasUI(stepConfig)) && (response_flag!=AbstractProcessingStep.STATUS_COMPLETE))
{
//check to see if there is a description of this response/error in Messages!
var error = stepClass.getErrorMessage(response_flag);
//if no error message defined, create a dummy one
if(error==null)
{
error = "The doProcessing() method for " + processingClass.getName() +
" returned an error flag = " + response_flag + ". " +
"It is recommended to define a custom error message for this error flag using the addErrorMessage() method for this class!";
}
cocoon.log.error(error, null); //log as an error to Cocoon
//clear error flag, so that processing can continue
response_flag = AbstractProcessingStep.STATUS_COMPLETE;
//clear any error fields as well
saveErrorFields(null);
}//else if there is a UI, but still there were errors!
else if(response_flag!=AbstractProcessingStep.STATUS_COMPLETE)
{
//save error fields to global ERROR_FIELDS variable,
//for step-specific post-processing
saveErrorFields(stepClass.getErrorFields(getHttpRequest()));
}
else //otherwise, no errors at all
{
//clear any previously set error fields
saveErrorFields(null);
}
return response_flag;
}
/**
* This function loads information about a file automatically
* uploaded by Cocoon. A file will only be automatically uploaded
* by Cocoon if 'enable-uploads' is set to 'true' in the web.xml
* (which is the default setting for Manakin).
*
* The uploaded files will be added to the Request object as two
* separate attributes: [name]-path and [name]-inputstream. The first
* attribute contains the full path to the uploaded file on the client's
* Operating System. The second attribute contains an inputstream to the
* file. These two attributes will be created for any file uploaded.
*/
function loadFileUploadInfo()
{
//determine the parameter which is the uploaded file
var paramNames = cocoon.request.getParameterNames();
while(paramNames.hasMoreElements())
{
var fileParam = paramNames.nextElement();
var fileObject = cocoon.request.get(fileParam);
//check if this is actually a file
if (!(fileObject instanceof Part))
{
continue;
}
//load uploaded file information
if (fileObject != null && fileObject.getSize() > 0)
{
//Now, save information to HTTP request which
//the step processing class will use to actually
//save the file as a DSpace bitstream object.
//save original filename to request attribute
getHttpRequest().setAttribute(fileParam + "-path", fileObject.getUploadName());
//save inputstream of file contents to request attribute
getHttpRequest().setAttribute(fileParam + "-inputstream", fileObject.getInputStream());
}
}
}
/**
* Save the error fields returned by the last step processed.
*
* The errorFields parameter is the List of strings returned by a
* call to AbstractProcessingStep.getErrorFields()
*/
function saveErrorFields(errorFields)
{
if(errorFields==null || errorFields.size()==0)
{
ERROR_FIELDS=null;
}
else
{
ERROR_FIELDS="";
//iterate through the fields
var i = errorFields.iterator();
//build comma-separated list of error fields
while(i.hasNext())
{
var field = i.next();
if(ERROR_FIELDS==null || ERROR_FIELDS.length==0)
{
ERROR_FIELDS = field;
}
else
{
ERROR_FIELDS = ERROR_FIELDS + "," + field;
}
}
}
}
/**
* Get the error fields returned by the last step processed.
*
* This method returns a comma-separated list of field names
*/
function getErrorFields()
{
return ERROR_FIELDS;
}
/**
* Return whether or not the step (specified by the step configuration)
* has a User Interface.
*
* This method returns true (if step has UI) or false (if no UI / non-interactive step)
* Parameters:
* stepConfig - the SubmissionStepConfig representing the current step config
*/
function stepHasUI(stepConfig)
{
//check if this step has an XML-UI Transformer class specified
var xmlUIClassName = stepConfig.getXMLUIClassName();
//if this step specifies an XMLUI class, then it has a User Interface
if((xmlUIClassName!=null) && (xmlUIClassName.length()>0))
{
return true;
}
else
{
return false;
}
}
/**
* This step is used when ever the user clicks save/cancel during the submission
* processes. We ask them if they would like to save the submission or remove it.
*/
function submitStepSaveOrRemove(collectionHandle,workspaceID,step,page)
{
// we need to update the reached step to prevent smart user to skip file upload
// or keep empty required metadata using the resume
var maxStep = FlowUtils.getMaximumStepReached(getDSContext(),workspaceID);
var maxPage = FlowUtils.getMaximumPageReached(getDSContext(),workspaceID);
var maxStepAndPage = new StepAndPage(maxStep,maxPage);
var currStepAndPage = new StepAndPage(step,page);
if (maxStepAndPage.compareTo(currStepAndPage) > 0)
{
FlowUtils.setBackPageReached(getDSContext(),workspaceID, step, page);
}
sendPageAndWait("handle/"+collectionHandle+"/submit/saveOrRemoveStep",{"id":workspaceID,"step":String(step),"page":String(page)});
FlowUtils.processSaveOrRemove(getDSContext(), workspaceID, cocoon.request);
if (cocoon.request.get("submit_save"))
{
// Already saved...
var contextPath = cocoon.request.getContextPath();
cocoon.redirectTo(contextPath+"/submissions",true);
cocoon.exit();
}
else if (cocoon.request.get("submit_remove"))
{
sendPage("handle/"+collectionHandle+"/submit/removedStep");
cocoon.exit(); // We're done, Stop execution.
}
// go back to submission control and continue.
}
/**
* This method simply displays
* the "submission completed" confirmation page
*/
function showCompleteConfirmation(handle)
{
//forward to completion page & exit cocoon
sendPage("handle/"+handle+"/submit/completedStep",{"handle":handle});
cocoon.exit(); // We're done, Stop execution.
}
/**
* This is the starting point for all workflow tasks. The id of the workflow
* is expected to be passed in as a request parameter. The user will be able
* to view the item and perform the necessary actions on the task such as:
* accept, reject, or edit the item's metadata.
*/
function doWorkflow()
{
var workflowID = cocoon.request.get("workflowID");
if (workflowID == null)
{
throw "Unable to find workflow, no workflow id supplied.";
}
// Get the collection handle for this item.
var handle = WorkflowItem.find(getDSContext(), workflowID).getCollection().getHandle();
// Specify that we are working with workflows.
//(specify "W" for workflow item, for FlowUtils.findSubmission())
workflowID = "W"+workflowID;
do
{
sendPageAndWait("handle/"+handle+"/workflow/performTaskStep",{"id":workflowID,"step":"0"});
if (cocoon.request.get("submit_leave"))
{
// Just exit workflow with out doing anything
var contextPath = cocoon.request.getContextPath();
cocoon.redirectTo(contextPath+"/submissions",true);
getDSContext().complete();
cocoon.exit();
}
else if (cocoon.request.get("submit_approve"))
{
// Approve this task and exit the workflow
var archived = FlowUtils.processApproveTask(getDSContext(),workflowID);
var contextPath = cocoon.request.getContextPath();
cocoon.redirectTo(contextPath+"/submissions",true);
getDSContext().complete();
cocoon.exit();
}
else if (cocoon.request.get("submit_return"))
{
// Return this task to the pool and exit the workflow
FlowUtils.processUnclaimTask(getDSContext(),workflowID);
var contextPath = cocoon.request.getContextPath();
cocoon.redirectTo(contextPath+"/submissions",true);
getDSContext().complete();
cocoon.exit();
}
else if (cocoon.request.get("submit_take_task"))
{
// Take the task and stay on this workflow
FlowUtils.processClaimTask(getDSContext(),workflowID);
}
else if (cocoon.request.get("submit_reject"))
{
var rejected = workflowStepReject(handle,workflowID);
if (rejected == true)
{
// the user really rejected the item
var contextPath = cocoon.request.getContextPath();
cocoon.redirectTo(contextPath+"/submissions",true);
getDSContext().complete();
cocoon.exit();
}
}
else if (cocoon.request.get("submit_edit"))
{
//User is editing this submission:
// Send user through the Submission Control
// (NOTE: The SubmissionInfo object decides which
// steps are able to be edited in a Workflow)
submissionControl(handle, workflowID, null);
}
} while (1==1)
}
/**
* This step is used when the user wants to reject a workflow item, at this step they
* are asked to enter a reason for the rejection.
*/
function workflowStepReject(handle,workflowID)
{
var error_fields;
do {
sendPageAndWait("handle/"+handle+"/workflow/rejectTaskStep",{"id":workflowID, "step":"0", "error_fields":error_fields});
if (cocoon.request.get("submit_reject"))
{
error_fields = FlowUtils.processRejectTask(getDSContext(),workflowID,cocoon.request);
if (error_fields == null)
{
// Only exit if rejection succeeded, otherwise ask for a reason again.
return true;
}
}
else if (cocoon.request.get("submit_cancel"))
{
// just go back to the view workflow screen.
return false;
}
} while (1 == 1)
}
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
importClass(Packages.org.dspace.authorize.AuthorizeManager);
importClass(Packages.org.dspace.core.Constants);
importClass(Packages.org.dspace.content.Bitstream);
importClass(Packages.org.dspace.content.Bundle);
importClass(Packages.org.dspace.content.Item);
importClass(Packages.org.dspace.content.Collection);
importClass(Packages.org.dspace.content.Community);
importClass(Packages.org.dspace.harvest.HarvestedCollection);
importClass(Packages.org.dspace.eperson.EPerson);
importClass(Packages.org.dspace.eperson.Group);
importClass(Packages.org.dspace.app.xmlui.utils.FlowscriptUtils);
importClass(Packages.org.dspace.app.xmlui.utils.ContextUtil);
importClass(Packages.org.dspace.app.xmlui.aspect.administrative.FlowEPersonUtils);
importClass(Packages.org.dspace.app.xmlui.aspect.administrative.FlowGroupUtils);
importClass(Packages.org.dspace.app.xmlui.aspect.administrative.FlowRegistryUtils);
importClass(Packages.org.dspace.app.xmlui.aspect.administrative.FlowItemUtils);
importClass(Packages.org.dspace.app.xmlui.aspect.administrative.FlowMapperUtils);
importClass(Packages.org.dspace.app.xmlui.aspect.administrative.FlowAuthorizationUtils);
importClass(Packages.org.dspace.app.xmlui.aspect.administrative.FlowContainerUtils);
importClass(Packages.org.dspace.app.xmlui.aspect.administrative.FlowMetadataImportUtils);
importClass(Packages.java.lang.System);
/**
* Simple access method to access the current cocoon object model.
*/
function getObjectModel()
{
return FlowscriptUtils.getObjectModel(cocoon);
}
/**
* Return the DSpace context for this request since each HTTP request generates
* a new context this object should never be stored and instead allways accessed
* through this method so you are ensured that it is the correct one.
*/
function getDSContext()
{
return ContextUtil.obtainContext(getObjectModel());
}
/**
* Send the current page and wait for the flow to be continued. This method will
* preform two usefull actions: set the flow parameter & add result information.
*
* The flow parameter is used by the sitemap to seperate requests comming from a
* flow script from just normal urls.
*
* The result object could potentialy contain a notice message and a list of
* errors. If either of these are present then they are added to the sitemap's
* parameters.
*/
function sendPageAndWait(uri,bizData,result)
{
if (bizData == null)
bizData = {};
if (result != null)
{
var outcome = result.getOutcome();
var header = result.getHeader();
var message = result.getMessage();
var characters = result.getCharacters();
if (message != null || characters != null)
{
bizData["notice"] = "true";
bizData["outcome"] = outcome;
bizData["header"] = header;
bizData["message"] = message;
bizData["characters"] = characters;
}
var errors = result.getErrorString();
if (errors != null)
{
bizData["errors"] = errors;
}
}
// just to remember where we came from.
bizData["flow"] = "true";
cocoon.sendPageAndWait(uri,bizData);
}
/**
* Send the given page and DO NOT wait for the flow to be continued. Execution will
* proceed as normal. This method will perform two useful actions: set the flow
* parameter & add result information.
*
* The flow parameter is used by the sitemap to separate requests coming from a
* flow script from just normal urls.
*
* The result object could potentially contain a notice message and a list of
* errors. If either of these are present then they are added to the sitemap's
* parameters.
*/
function sendPage(uri,bizData,result)
{
if (bizData == null)
bizData = {};
if (result != null)
{
var outcome = result.getOutcome();
var header = result.getHeader();
var message = result.getMessage();
var characters = result.getCharacters();
if (message != null || characters != null)
{
bizData["notice"] = "true";
bizData["outcome"] = outcome;
bizData["header"] = header;
bizData["message"] = message;
bizData["characters"] = characters;
}
var errors = result.getErrorString();
if (errors != null)
{
bizData["errors"] = errors;
}
}
// just to remember where we came from.
bizData["flow"] = "true";
cocoon.sendPage(uri,bizData);
}
/*
* This function cycles through the submit parameters until it finds one that starts with "prefix".
* It then returns everything after the prefix for the first match. If none are found, null is returned.
* For example, if one of the submit variables is named "submit_add_2123", calling this function with a
* prefix variable of "submit_add_" will return 2123.
*/
function extractSubmitSuffix(prefix) {
var names = cocoon.request.getParameterNames();
while (names.hasMoreElements())
{
var name = names.nextElement();
if (name.startsWith(prefix))
{
var extractedSuffix = name.substring(prefix.length);
return extractedSuffix;
}
}
return null;
}
/*
* Return wheather the currently authenticated EPerson is authorized to
* preform the given action over/on the the given object.
*/
function isAuthorized(objectType, objectID, action) {
// Note: it's okay to instantiate a DSpace object here because
// under all cases this method will exit and the objects send
// for garbage collecting before and continuations and are used.
var object = null;
switch (objectType) {
case Constants.BITSTREAM:
object = Bitstream.find(getDSContext(),objectID);
break;
case Constants.BUNDLE:
object = Bundle.find(getDSContext(),objectID);
break;
case Constants.ITEM:
object = Item.find(getDSContext(),objectID);
break;
case Constants.COLLECTION:
object = Collection.find(getDSContext(),objectID);
break;
case Constants.COMMUNITY:
object = Community.find(getDSContext(),objectID);
break;
case Constants.GROUP:
object = Group.find(getDSContext(),objectID);
break;
case Constants.EPERSON:
object = EPerson.find(getDSContext(),objectID);
break;
}
// If we couldn't find the object then return false
if (object == null)
return false;
return AuthorizeManager.authorizeActionBoolean(getDSContext(),object,action);
}
/**
* Assert that the currently authenticated eperson is able to preform
* the given action over the given object. If they are not then an
* error page is returned and this function will NEVER return.
*/
function assertAuthorized(objectType, objectID, action) {
if ( ! isAuthorized(objectType, objectID, action)) {
sendPage("admin/not-authorized");
cocoon.exit();
}
}
/**
* Return weather the currently authenticated eperson can edit the identified item.
*/
function canEditItem(itemID)
{
var item = Item.find(getDSContext(),itemID);
return item.canEdit();
}
/**
* Assert that the currently authenticated eperson can edit this item, if they can
* not then this method will never return.
*/
function assertEditItem(itemID) {
if ( ! canEditItem(itemID)) {
sendPage("admin/not-authorized");
cocoon.exit();
}
}
/**
* Return whether the currently authenticated eperson can edit this collection
*/
function canEditCollection(collectionID)
{
var collection = Collection.find(getDSContext(),collectionID);
if (collection == null) {
return isAdministrator();
}
return collection.canEditBoolean();
}
/**
* Assert that the currently authenticated eperson can edit this collection. If they
* can not then this method will never return.
*/
function assertEditCollection(collectionID) {
if ( ! canEditCollection(collectionID)) {
sendPage("admin/not-authorized");
cocoon.exit();
}
}
/**
* Return whether the currently authenticated eperson can administrate this collection
*/
function canAdminCollection(collectionID)
{
var collection = Collection.find(getDSContext(),collectionID);
if (collection == null) {
return isAdministrator();
}
return AuthorizeManager.authorizeActionBoolean(getDSContext(), collection, Constants.ADMIN);
}
/**
* Assert that the currently authenticated eperson can administrate this collection. If they
* can not then this method will never return.
*/
function assertAdminCollection(collectionID) {
if ( ! canAdminCollection(collectionID)) {
sendPage("admin/not-authorized");
cocoon.exit();
}
}
/**
* Return whether the currently authenticated eperson can edit this community.
*/
function canEditCommunity(communityID)
{
if (communityID == -1) {
return isAdministrator();
}
var community = Community.find(getDSContext(),communityID);
if (community == null) {
return isAdministrator();
}
return community.canEditBoolean();
}
/**
* Assert that the currently authenticated eperson can edit this community. If they can
* not then this method will never return.
*/
function assertEditCommunity(communityID) {
if ( ! canEditCommunity(communityID)) {
sendPage("admin/not-authorized");
cocoon.exit();
}
}
/**
* Return whether the currently authenticated eperson can administrate this community
*/
function canAdminCommunity(communityID)
{
var community = Community.find(getDSContext(),communityID);
if (community == null) {
return isAdministrator();
}
return AuthorizeManager.authorizeActionBoolean(getDSContext(), community, Constants.ADMIN);
}
/**
* Assert that the currently authenticated eperson can administrate this community. If they
* can not then this method will never return.
*/
function assertAdminCommunity(communityID) {
if ( ! canAdminCommunity(communityID)) {
sendPage("admin/not-authorized");
cocoon.exit();
}
}
/**
* Assert that the currently authenticated eperson can edit the given group. If they can
* not then this method will never return.
*/
function assertEditGroup(groupID)
{
// Check authorizations
if (groupID == -1)
{
// only system admin can create "top level" group
assertAdministrator();
}
else
{
assertAuthorized(Constants.GROUP, groupID, Constants.WRITE);
}
}
/**
* Return whether the currently authenticated eperson is an
* administrator.
*/
function isAdministrator() {
return AuthorizeManager.isAdmin(getDSContext());
}
/**
* Assert that the currently authenticated eperson is an administrator.
* If they are not then an error page is returned and this function
* will NEVER return.
*/
function assertAdministrator() {
if ( ! isAdministrator()) {
sendPage("admin/not-authorized");
cocoon.exit();
}
}
/*********************
* Entry Point flows
*********************/
/**
* Start managing epeople
*/
function startManageEPeople()
{
assertAdministrator();
doManageEPeople();
// This should never return, but just in case it does then point
// the user to the home page.
cocoon.redirectTo(cocoon.request.getContextPath());
getDSContext().complete();
cocoon.exit();
}
/**
* Start managing groups
*/
function startManageGroups()
{
assertAdministrator();
doManageGroups();
// This should never return, but just in case it does then point
// the user to the home page.
cocoon.redirectTo(cocoon.request.getContextPath());
getDSContext().complete();
cocoon.exit();
}
/**
* Start managing the metadata registry
*/
function startManageMetadataRegistry()
{
assertAdministrator();
doManageMetadataRegistry();
// This should never return, but just in case it does then point
// the user to the home page.
cocoon.redirectTo(cocoon.request.getContextPath());
getDSContext().complete();
cocoon.exit();
}
/**
* Start managing the format registry
*/
function startManageFormatRegistry()
{
assertAdministrator();
doManageFormatRegistry();
// This should never return, but just in case it does then point
// the user to the home page.
cocoon.redirectTo(cocoon.request.getContextPath());
getDSContext().complete();
cocoon.exit();
}
/**
* Start managing items
*/
function startManageItems()
{
assertAdministrator();
doManageItems();
// This should never return, but just in case it does then point
// the user to the home page.
cocoon.redirectTo(cocoon.request.getContextPath());
getDSContext().complete();
cocoon.exit();
}
/**
* Start managing authorizations
*/
function startManageAuthorizations()
{
assertAdministrator();
doManageAuthorizations();
// This should never return, but just in case it does then point
// the user to the home page.
cocoon.redirectTo(cocoon.request.getContextPath());
getDSContext().complete();
cocoon.exit();
}
/**
* Start editing an individual item.
*/
function startEditItem()
{
var itemID = cocoon.request.get("itemID");
assertEditItem(itemID);
doEditItem(itemID);
var item = Item.find(getDSContext(),itemID);
cocoon.redirectTo(cocoon.request.getContextPath()+"/handle/"+item.getHandle(),true);
getDSContext().complete();
item = null;
cocoon.exit();
}
/**
* Start managing items that are mapped to a collection.
*/
function startMapItems()
{
var collectionID = cocoon.request.get("collectionID");
// they can edit the collection they are maping items into.
assertEditCollection(collectionID);
doMapItems(collectionID);
var collection = Collection.find(getDSContext(),collectionID);
cocoon.redirectTo(cocoon.request.getContextPath()+"/handle/"+collection.getHandle(),true);
getDSContext().complete();
collection = null;
cocoon.exit();
}
function startMetadataImport()
{
assertAdministrator();
doMetadataImport();
cocoon.redirectTo(cocoon.request.getContextPath());
getDSContext().complete();
cocoon.exit();
}
/**
* Start creating a new collection.
*/
function startCreateCollection()
{
var communityID = cocoon.request.get("communityID");
assertAuthorized(Constants.COMMUNITY,communityID,Constants.ADD);
doCreateCollection(communityID);
// Root level community, cancel out to the global community list.
cocoon.redirectTo(cocoon.request.getContextPath()+"/community-list",true);
getDSContext().complete();
cocoon.exit();
}
/**
* Start editing an individual collection
*/
function startEditCollection()
{
var collectionID = cocoon.request.get("collectionID");
assertEditCollection(collectionID);
doEditCollection(collectionID);
// Go back to the collection
var collection = Collection.find(getDSContext(),collectionID);
cocoon.redirectTo(cocoon.request.getContextPath()+"/handle/"+collection.getHandle(),true);
getDSContext().complete();
collection = null;
cocoon.exit();
}
/**
* Start creating a new community
*/
function startCreateCommunity()
{
var communityID = cocoon.request.get("communityID");
doCreateCommunity(communityID);
// Root level community, cancel out to the global community list.
cocoon.redirectTo(cocoon.request.getContextPath()+"/community-list",true);
getDSContext().complete();
cocoon.exit();
}
/**
* Start editing an individual community
*/
function startEditCommunity()
{
var communityID = cocoon.request.get("communityID");
assertEditCommunity(communityID);
doEditCommunity(communityID);
// Go back to the community
var community = Community.find(getDSContext(),communityID);
cocoon.redirectTo(cocoon.request.getContextPath()+"/handle/"+community.getHandle(),true);
getDSContext().complete();
community = null;
cocoon.exit();
}
/********************
* EPerson flows
********************/
/**
* Manage epeople, allow users to create new, edit exiting,
* or remove epeople. The user may also search or browse
* for epeople.
*
* The is typically used as an entry point flow.
*/
function doManageEPeople()
{
assertAdministrator();
var query = "";
var page = 0;
var highlightID = -1;
var result;
do {
sendPageAndWait("admin/epeople/main",{"page":page,"query":query,"highlightID":highlightID},result);
result = null;
// Update the page parameter if supplied.
if (cocoon.request.get("page"))
page = cocoon.request.get("page");
if (cocoon.request.get("submit_search"))
{
// Grab the new query and reset the page parameter
query = cocoon.request.get("query");
page = 0
highlightID = -1;
}
else if (cocoon.request.get("submit_add"))
{
// Add a new eperson
assertAdministrator();
result = doAddEPerson();
if (result != null && result.getParameter("epersonID"))
highlightID = result.getParameter("epersonID");
}
else if (cocoon.request.get("submit_edit") && cocoon.request.get("epersonID"))
{
// Edit an exting eperson
assertAdministrator();
var epersonID = cocoon.request.get("epersonID");
result = doEditEPerson(epersonID);
highlightID = epersonID;
}
else if (cocoon.request.get("submit_delete") && cocoon.request.get("select_eperson"))
{
// Delete a set of epeople
assertAdministrator();
var epeopleIDs = cocoon.request.getParameterValues("select_eperson");
result = doDeleteEPeople(epeopleIDs);
highlightID = -1;
}
else if (cocoon.request.get("submit_return"))
{
// Not implemented in the UI, but should be incase someone links to us.
return;
}
} while (true) // only way to exit is to hit the submit_back button.
}
/**
* Add a new eperson, the user is presented with a form to create a new eperson. They will
* repeate this form untill the user has supplied a unique email address, first name, and
* last name.
*/
function doAddEPerson()
{
assertAdministrator();
var result;
do {
sendPageAndWait("admin/epeople/add",{},result);
result = null;
if (cocoon.request.get("submit_save"))
{
// Save the new eperson, assuming they have meet all the requirements.
assertAdministrator();
result = FlowEPersonUtils.processAddEPerson(getDSContext(),cocoon.request,getObjectModel());
}
else if (cocoon.request.get("submit_cancel"))
{
// The user can cancel at any time.
return null;
}
} while (result == null || !result.getContinue())
return result;
}
/**
* Edit an exiting eperson, all standard metadata elements are presented for editing. The same
* validation is required as is in adding a new eperson: unique email, first name, and last name
*/
function doEditEPerson(epersonID)
{
// We can't assert any privleges at this point, the user could be a collection
// admin or a supper admin. Instead we protect each operation.
var result;
do {
sendPageAndWait("admin/epeople/edit",{"epersonID":epersonID},result);
result == null;
if (cocoon.request.get("submit_save"))
{
// Attempt to save the changes.
assertAdministrator();
result = FlowEPersonUtils.processEditEPerson(getDSContext(),cocoon.request,getObjectModel(),epersonID);
}
else if (cocoon.request.get("submit_cancel"))
{
// Cancel out and return to where ever the user came from.
return null;
}
else if (cocoon.request.get("submit_edit_group") && cocoon.request.get("groupID"))
{
// Jump to a group that this user is a member.
assertAdministrator();
var groupID = cocoon.request.get("groupID");
result = doEditGroup(groupID);
// Don't continue after returning from editing a group.
if (result != null)
result.setContinue(false);
}
else if (cocoon.request.get("submit_delete"))
{
// Delete this user
assertAdministrator();
var epeopleIDs = new Array();
epeopleIDs[0] = epersonID;
result = doDeleteEPeople(epeopleIDs);
// No matter what just bail out to the group list.
return null;
}
else if (cocoon.request.get("submit_reset_password"))
{
// Reset the user's password by sending them the forgot password email.
assertAdministrator();
result = FlowEPersonUtils.processResetPassword(getDSContext(),epersonID);
if (result != null)
result.setContinue(false);
}
else if (cocoon.request.get("submit_login_as"))
{
// Login as this user.
assertAdministrator();
result = FlowEPersonUtils.processLoginAs(getDSContext(),getObjectModel(),epersonID);
if (result != null && result.getOutcome().equals("success"))
{
// the user is loged in as another user, we can't let them continue on
// using this flow because they might not have permissions. So forward
// them to the homepage.
cocoon.redirectTo(cocoon.request.getContextPath(),true);
getDSContext().complete();
cocoon.exit();
}
}
} while (result == null || !result.getContinue())
return result;
}
/**
* Confirm and delete the list of given epeople. The user will be presented with a list of selected epeople,
* and if they click the confirm delete button then the epeople will be deleted.
*/
function doDeleteEPeople(epeopleIDs)
{
assertAdministrator();
sendPageAndWait("admin/epeople/delete",{"epeopleIDs":epeopleIDs.join(',')});
if (cocoon.request.get("submit_confirm"))
{
// The user has confirmed, preform the actualy delete.
assertAdministrator();
var result = FlowEPersonUtils.processDeleteEPeople(getDSContext(),epeopleIDs);
return result;
}
return null;
}
/********************
* Group flows
********************/
/**
* Manage groups, allow users to create new, edit exiting,
* or remove groups. The user may also search or browse
* for groups.
*
* The is typicaly used as an entry point flow.
*/
function doManageGroups()
{
assertAdministrator();
var highlightID = -1
var query = "";
var page = 0;
var result;
do {
sendPageAndWait("admin/group/main",{"query":query,"page":page,"highlightID":highlightID},result);
assertAdministrator();
result = null;
// Update the page parameter if supplied.
if (cocoon.request.get("page"))
page = cocoon.request.get("page");
if (cocoon.request.get("submit_search"))
{
// Grab the new query and reset the page parameter
query = cocoon.request.get("query");
page = 0
highlightID = -1
}
else if (cocoon.request.get("submit_add"))
{
// Just create a blank group then pass it to the group editor.
result = doEditGroup(-1);
if (result != null && result.getParameter("groupID"))
highlightID = result.getParameter("groupID");
}
else if (cocoon.request.get("submit_edit") && cocoon.request.get("groupID"))
{
// Edit a specific group
var groupID = cocoon.request.get("groupID");
result = doEditGroup(groupID);
highlightID = groupID;
}
else if (cocoon.request.get("submit_delete") && cocoon.request.get("select_group"))
{
// Delete a set of groups
var groupIDs = cocoon.request.getParameterValues("select_group");
result = doDeleteGroups(groupIDs);
highlightID = -1;
}
else if (cocoon.request.get("submit_return"))
{
// Not implemented in the UI, but should be incase someone links to us.
return;
}
} while (true) // only way to exit is to hit the submit_back button.
}
/**
* This flow allows for the full editing of a group, changing the group's name or
* removing members. Users may also search for epeople / groups to add as members
* to this group.
*/
function doEditGroup(groupID)
{
var groupName = FlowGroupUtils.getName(getDSContext(),groupID);
var memberEPeopleIDs = FlowGroupUtils.getEPeopleMembers(getDSContext(),groupID);
var memberGroupIDs = FlowGroupUtils.getGroupMembers(getDSContext(),groupID);
assertEditGroup(groupID);
var highlightEPersonID;
var highlightGroupID;
var type = "";
var query = "";
var page = 0;
var result = null;
do {
sendPageAndWait("admin/group/edit",{"groupID":groupID,"groupName":groupName,"memberGroupIDs":memberGroupIDs.join(','),"memberEPeopleIDs":memberEPeopleIDs.join(','),"highlightEPersonID":highlightEPersonID,"highlightGroupID":highlightGroupID,"query":query,"page":page,"type":type},result);
assertEditGroup(groupID);
result = null;
highlightEPersonID = null;
highlightGroupID = null;
// Update the groupName
if (cocoon.request.get("group_name"))
groupName = cocoon.request.get("group_name");
if (cocoon.request.get("page"))
page = cocoon.request.get("page");
if (cocoon.request.get("submit_cancel"))
{
// Just return with out saving anything.
return null;
}
else if (cocoon.request.get("submit_save"))
{
result = FlowGroupUtils.processSaveGroup(getDSContext(),groupID,groupName,memberEPeopleIDs,memberGroupIDs);
// Incase a group was created, update our id.
if (result != null && result.getParameter("groupID"))
groupID = result.getParameter("groupID");
}
else if (cocoon.request.get("submit_search_epeople") && cocoon.request.get("query"))
{
// Preform a new search for epeople.
query = cocoon.request.get("query");
page = 0;
type = "eperson";
}
else if (cocoon.request.get("submit_search_groups") && cocoon.request.get("query"))
{
// Prefrom a new search for groups.
query = cocoon.request.get("query");
page = 0;
type = "group";
}
else if (cocoon.request.get("submit_clear"))
{
// Preform a new search for epeople.
query = "";
page = 0;
type = "";
}
else if (cocoon.request.get("submit_edit_eperson") && cocoon.request.get("epersonID"))
{
// Jump to a specific EPerson
var epersonID = cocoon.request.get("epersonID");
result = doEditEPerson(epersonID);
if (result != null)
result.setContinue(false);
}
else if (cocoon.request.get("submit_edit_group") && cocoon.request.get("groupID"))
{
// Jump to another group.
var newGroupID = cocoon.request.get("groupID");
result = doEditGroup(newGroupID); // ahhh recursion!
if (result != null)
result.setContinue(false);
}
// Check if there were any add or delete operations.
var names = cocoon.request.getParameterNames();
while (names.hasMoreElements())
{
var name = names.nextElement();
var match = null;
if ((match = name.match(/submit_add_eperson_(\d+)/)) != null)
{
// Add an eperson
var epersonID = match[1];
memberEPeopleIDs = FlowGroupUtils.addMember(memberEPeopleIDs,epersonID);
highlightEPersonID = epersonID;
}
if ((match = name.match(/submit_add_group_(\d+)/)) != null)
{
// Add a group
var _groupID = match[1];
memberGroupIDs = FlowGroupUtils.addMember(memberGroupIDs,_groupID);
highlightGroupID = _groupID;
}
if ((match = name.match(/submit_remove_eperson_(\d+)/)) != null)
{
// remove an eperson
var epersonID = match[1];
memberEPeopleIDs = FlowGroupUtils.removeMember(memberEPeopleIDs,epersonID);
highlightEPersonID = epersonID;
}
if ((match = name.match(/submit_remove_group_(\d+)/)) != null)
{
// remove a group
var _groupID = match[1];
memberGroupIDs = FlowGroupUtils.removeMember(memberGroupIDs,_groupID);
highlightGroupID = _groupID;
}
}
} while (result == null || !result.getContinue())
return result;
}
/**
* Confirm that the given groupIDs should be deleted, if confirmed they will be deleted.
*/
function doDeleteGroups(groupIDs)
{
assertAdministrator();
sendPageAndWait("admin/group/delete",{"groupIDs":groupIDs.join(',')});
if (cocoon.request.get("submit_confirm"))
{
// The user has confirmed, actualy delete these groups
assertAdministrator();
var result = FlowGroupUtils.processDeleteGroups(getDSContext(),groupIDs);
return result;
}
return null;
}
/**************************
* Registries: Metadata flows
**************************/
/**
* Manage metadata registries, consisting of all metadata fields grouped into
* one or more schemas. This flow will list all available schemas for edit, allow
* the user to add or delete schemas.
*
* This is an entry point flow.
*/
function doManageMetadataRegistry()
{
assertAdministrator();
var result = null;
do {
sendPageAndWait("admin/metadata-registry/main",{},result);
assertAdministrator();
result = null;
if (cocoon.request.get("submit_edit") && cocoon.request.get("schemaID"))
{
// Edit a specific schema
var schemaID = cocoon.request.get("schemaID");
result = doEditMetadataSchema(schemaID)
}
else if (cocoon.request.get("submit_add"))
{
// Add a new schema
var namespace = cocoon.request.get("namespace");
var name = cocoon.request.get("name");
result = FlowRegistryUtils.processAddMetadataSchema(getDSContext(), namespace, name);
}
else if (cocoon.request.get("submit_delete") && cocoon.request.get("select_schema"))
{
// Remove the selected schemas
var schemaIDs = cocoon.request.getParameterValues("select_schema");
result = doDeleteMetadataSchemas(schemaIDs)
}
} while(true)
}
/**
* Edit a particular schema, this will list all fields in the schema. When clicking
* on a field it will be loaded into the top of the page where it can be edited. When
* the top form is not loaded it can be used to add new fields.
*
* The last field operated on is kept as a highlighted field to make it easier to
* find things in the interface.
*/
function doEditMetadataSchema(schemaID)
{
assertAdministrator();
var highlightID = -1 // Field that is highlighted
var updateID = -1; // Field being updated
var result = null;
do {
sendPageAndWait("admin/metadata-registry/edit-schema",{"schemaID":schemaID,"updateID":updateID,"highlightID":highlightID},result);
assertAdministrator();
result = null;
if (cocoon.request.get("submit_return"))
{
// Go back to where ever they came from.
return null;
}
else if (cocoon.request.get("submit_edit") && cocoon.request.get("fieldID"))
{
// select an existing field for editing. This will load it into the
// form for editing.
updateID = cocoon.request.get("fieldID");
highlightID = updateID;
}
else if (cocoon.request.get("submit_add"))
{
// Add a new field
var element = cocoon.request.get("newElement");
var qualifier = cocoon.request.get("newQualifier");
var note = cocoon.request.get("newNote");
// processes adding field
result = FlowRegistryUtils.processAddMetadataField(getDSContext(),schemaID,element,qualifier,note);
highlightID = result.getParameter("fieldID");
}
else if (cocoon.request.get("submit_update") && updateID >= 0)
{
// Update an exiting field
var element = cocoon.request.get("updateElement");
var qualifier = cocoon.request.get("updateQualifier");
var note = cocoon.request.get("updateNote");
result = FlowRegistryUtils.processEditMetadataField(getDSContext(),schemaID,updateID,element,qualifier,note);
if (result != null && result.getContinue())
{
// If the update was successfull then clean the updateID;
highlightID = updateID;
updateID = -1;
}
}
else if (cocoon.request.get("submit_cancel"))
{
// User cancels out of a field update
updateID = -1;
highlightID = -1;
}
else if (cocoon.request.get("submit_delete") && cocoon.request.get("select_field"))
{
// Delete the selected fields
var fieldIDs = cocoon.request.getParameterValues("select_field");
result = doDeleteMetadataFields(fieldIDs);
updateID = -1;
highlightID = -1
}
else if (cocoon.request.get("submit_move") && cocoon.request.get("select_field"))
{
// Attempt to move the selected fields to another schema.
var fieldIDs = cocoon.request.getParameterValues("select_field");
result = doMoveMetadataFields(fieldIDs);
updateID = -1;
highlightID = -1;
}
} while (true)
}
/**
* Confirm the deletition of the listed metadata fields.
*/
function doDeleteMetadataFields(fieldIDs)
{
assertAdministrator();
sendPageAndWait("admin/metadata-registry/delete-fields",{"fieldIDs":fieldIDs.join(',')})
assertAdministrator();
if (cocoon.request.get("submit_confirm"))
{
// Actualy delete the fields
var result = FlowRegistryUtils.processDeleteMetadataField(getDSContext(),fieldIDs);
return result;
}
return null;
}
/**
* Move the listed fields to the target schema. A list of all fields will be
* given a select box to identify the target schema.
*/
function doMoveMetadataFields(fieldIDs)
{
assertAdministrator();
sendPageAndWait("admin/metadata-registry/move-fields",{"fieldIDs":fieldIDs.join(',')});
assertAdministrator();
if (cocoon.request.get("submit_move") && cocoon.request.get("to_schema"))
{
// Actualy move the fields
var schemaID = cocoon.request.get("to_schema");
var result = FlowRegistryUtils.processMoveMetadataField(getDSContext(), schemaID,fieldIDs);
return result;
}
return null;
}
/**
* Confirm the deletition of the listed schema
*/
function doDeleteMetadataSchemas(schemaIDs)
{
assertAdministrator();
sendPageAndWait("admin/metadata-registry/delete-schemas",{"schemaIDs":schemaIDs.join(',')});
assertAdministrator();
if (cocoon.request.get("submit_confirm"))
{
// Actualy delete the schemas
var result = FlowRegistryUtils.processDeleteMetadataSchemas(getDSContext(),schemaIDs)
return result;
}
return null;
}
/**************************
* Registries: Format flows
**************************/
/**
* Manage the set of bitstream formats that are available in the system. A
* list of all available formats is given each one can be editeded or
* deleteed and new ones may be added.
*/
function doManageFormatRegistry()
{
assertAdministrator();
var highlightID = -1 // Field that is highlighted
var updateID = -1; // Field being updated
var result = null;
do {
sendPageAndWait("admin/format-registry/main",{"updateID":updateID,"highlightID":highlightID},result);
assertAdministrator();
result = null;
if (cocoon.request.get("submit_return"))
{
// Go back to where ever they came from.
return null;
}
else if (cocoon.request.get("submit_edit") && cocoon.request.get("formatID"))
{
var formatID = cocoon.request.get("formatID");
result = doEditBitstreamFormat(formatID);
// Highlight the format that was just edited.
if (result != null && result.getParameter("formatID"))
highlightID = result.getParameter("formatID");
else
highlightID = formatID;
}
else if (cocoon.request.get("submit_add"))
{
// Add a new format
result = doEditBitstreamFormat(-1);
// Highlight the format that was just created.
if (result != null && result.getParameter("formatID"))
highlightID = result.getParameter("formatID");
}
else if (cocoon.request.get("submit_delete") && cocoon.request.get("select_format"))
{
// Delete the selected formats
var formatIDs = cocoon.request.getParameterValues("select_format");
result = doDeleteBitstreamFormats(formatIDs);
updateID = -1;
highlightID = -1
}
} while (true)
}
/**
* Edit a single bitstream format specified by formatID. If the formatID is
* -1 then a new bitstream will be added instead.
*/
function doEditBitstreamFormat(formatID)
{
assertAdministrator();
var result = null;
do {
sendPageAndWait("admin/format-registry/edit",{"formatID":formatID},result);
assertAdministrator();
result = null;
if (cocoon.request.get("submit_cancel"))
{
// Go back to where ever they came from.
return null;
}
else if (cocoon.request.get("submit_save"))
{
// Create or update an existing bitstream format
result = FlowRegistryUtils.processEditBitstreamFormat(getDSContext(), formatID, cocoon.request);
}
} while (result == null || !result.getContinue())
return result;
}
/**
* Confirm the deletition of the listed bitstream formats
*/
function doDeleteBitstreamFormats(formatIDs)
{
assertAdministrator();
sendPageAndWait("admin/format-registry/delete",{"formatIDs":formatIDs.join(',')});
assertAdministrator();
if (cocoon.request.get("submit_confirm"))
{
// Actualy delete the formats
var result = FlowRegistryUtils.processDeleteBitstreamFormats(getDSContext(),formatIDs)
return result;
}
return null;
}
/**************************
* Edit Item flows
**************************/
/**
* Manage items, this is a flow entry point allowing the user to search for items by
* their internal id or handle.
*/
function doManageItems()
{
assertAdministrator();
var identifier;
var result;
do {
sendPageAndWait("admin/item/find",{"identifier":identifier},result);
assertAdministrator();
result = null;
if (cocoon.request.get("submit_find") && cocoon.request.get("identifier"))
{
// Search for the identifier
identifier = cocoon.request.get("identifier");
result = FlowItemUtils.resolveItemIdentifier(getDSContext(),identifier);
// If an item was found then allow the user to edit the item.
if (result != null && result.getParameter("itemID"))
{
var itemID = result.getParameter("itemID");
result = doEditItem(itemID);
}
}
} while (true)
}
/**
* Edit a single item. This method allows the user to switch between the
* three sections of editing an item: status, bitstreams, and metadata.
*/
function doEditItem(itemID)
{
// Always go to the status page first
doEditItemStatus(itemID);
do {
if (cocoon.request.get("submit_return"))
{
// go back to where ever we came from.
return null;
}
else if (cocoon.request.get("submit_status"))
{
doEditItemStatus(itemID);
}
else if (cocoon.request.get("submit_bitstreams"))
{
doEditItemBitstreams(itemID);
}
else if (cocoon.request.get("submit_metadata"))
{
doEditItemMetadata(itemID, -1);
}
else if (cocoon.request.get("view_item"))
{
doViewItem(itemID);
}
else if (cocoon.request.get("submit_curate")) {
doCurateItem(itemID, cocoon.request.get("curate_task"));
}
else
{
// This case should never happen but to prevent an infinite loop
// from occuring let's just return null.
return null;
}
} while (true)
}
/**
* Just show the item
*/
function doViewItem(itemID){
do {
sendPageAndWait("admin/item/view_item",{"itemID":itemID},null);
assertEditItem(itemID);
if ( !cocoon.request.get("view_item"))
{
// go back to where ever we came from.
return null;
}
} while (true)
}
/**
* Change the status of an item, withdraw or reinstate, or completely delete it.
*/
function doEditItemStatus(itemID)
{
assertEditItem(itemID);
var result;
do {
sendPageAndWait("admin/item/status",{"itemID":itemID},result);
assertEditItem(itemID);
result = null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_bitstreams") || cocoon.request.get("submit_metadata") || cocoon.request.get("view_item") || cocoon.request.get("submit_curate") )
{
// go back to where ever we came from.
return null;
}
else if (cocoon.request.get("submit_delete"))
{
assertAuthorized(Constants.ITEM, itemID, Constants.DELETE);
// Confirm the item's deletion
result = doDeleteItem(itemID);
// If the user actualy deleted the item the return back
// to the manage items page.
if (result != null)
return result;
}
else if (cocoon.request.get("submit_withdraw"))
{
// Confirm the withdrawl of the item
result = doWithdrawItem(itemID);
}
else if (cocoon.request.get("submit_reinstate"))
{
// Confirm the reinstation of the item
result = doReinstateItem(itemID);
}
else if (cocoon.request.get("submit_move"))
{
// Move this item somewhere else
result = doMoveItem(itemID);
}
else if (cocoon.request.get("submit_authorization"))
{
// Edit the authorizations for this
// authorization check performed by the doAuthorize methods in FlowAuthorizationUtils
// assertAdministrator();
doAuthorizeItem(itemID);
}
} while (true)
}
/**
* Allow the user to manage the item's bitstreams, add, delete, or change a bitstream's metadata.
*/
function doEditItemBitstreams(itemID)
{
assertEditItem(itemID);
var result;
do {
sendPageAndWait("admin/item/bitstreams",{"itemID":itemID}, result);
assertEditItem(itemID);
result = null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_status") || cocoon.request.get("submit_bitstreams") || cocoon.request.get("submit_metadata") || cocoon.request.get("view_item") || cocoon.request.get("submit_curate"))
{
// go back to where ever we came from.
return null;
}
else if (cocoon.request.get("submit_add"))
{
// Upload a new bitstream
assertAuthorized(Constants.ITEM,itemID,Constants.ADD)
result = doAddBitstream(itemID);
}
else if (cocoon.request.get("submit_edit") && cocoon.request.get("bitstreamID"))
{
// Update the bitstream's metadata
var bitstreamID = cocoon.request.get("bitstreamID");
assertAuthorized(Constants.BITSTREAM,bitstreamID,Constants.WRITE)
result = doEditBitstream(itemID, bitstreamID);
}
else if (cocoon.request.get("submit_delete") && cocoon.request.get("remove"))
{
// Delete the bitstream
assertAuthorized(Constants.ITEM,itemID,Constants.REMOVE);
var bitstreamIDs = cocoon.request.getParameterValues("remove");
result = doDeleteBitstreams(itemID,bitstreamIDs)
}
} while (true)
}
/**
* Allow the user to update, remove, and add new metadata to the item.
*/
function doEditItemMetadata(itemID, templateCollectionID)
{
assertEditItem(itemID);
var result;
do {
sendPageAndWait("admin/item/metadata",{"itemID":itemID,
"templateCollectionID":templateCollectionID},result);
assertEditItem(itemID);
result = null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_status") ||
cocoon.request.get("submit_bitstreams") || cocoon.request.get("submit_metadata") ||
cocoon.request.get("view_item") || cocoon.request.get("submit_curate"))
{
// go back to where ever we came from.
return null;
}
else if (cocoon.request.get("submit_add"))
{
// Add a new metadata entry
result = FlowItemUtils.processAddMetadata(getDSContext(),itemID,cocoon.request);
}
else if (cocoon.request.get("submit_update"))
{
// Update the item
result = FlowItemUtils.processEditItem(getDSContext(),itemID,cocoon.request);
}
} while (true)
}
/** Curate
*
*
*/
function doCurateItem(itemID, task) {
var result;
do {
sendPageAndWait("admin/item/curateItem",{"itemID":itemID}, result);
assertEditCommunity(itemID);
result = null;
if (!cocoon.request.get("submit_curate_task") && !cocoon.request.get("submit_queue_task"))
{
return null;
}
else if (cocoon.request.get("submit_curate_task"))
{
result = FlowItemUtils.processCurateItem(getDSContext(), itemID, cocoon.request);
}
else if (cocoon.request.get("submit_queue_task"))
{
result = FlowItemUtils.processQueueItem(getDSContext(), itemID, cocoon.request);
}
} while (true);
}
/**
* Confirm the deletition of this item.
*/
function doDeleteItem(itemID)
{
assertAuthorized(Constants.ITEM, itemID, Constants.DELETE);
sendPageAndWait("admin/item/delete",{"itemID":itemID});
if (cocoon.request.get("submit_confirm"))
{
// It's been confirmed, delete the item.
assertAuthorized(Constants.ITEM, itemID, Constants.DELETE);
var result = FlowItemUtils.processDeleteItem(getDSContext(),itemID);
if (result.getContinue()) {
cocoon.redirectTo(cocoon.request.getContextPath()+"/community-list",true);
getDSContext().complete();
cocoon.exit();
}
return result;
}
return null;
}
/**
* Confirm the withdrawl of this item.
*/
function doWithdrawItem(itemID)
{
// authorization check performed directly by the dspace-api
// assertAdministrator();
sendPageAndWait("admin/item/withdraw",{"itemID":itemID});
if (cocoon.request.get("submit_confirm"))
{
// Actualy withdraw the item
// authorization check performed directly by the dspace-api
// assertAdministrator();
var result = FlowItemUtils.processWithdrawItem(getDSContext(),itemID);
return result;
}
return null;
}
/**
* Confirm the reinstatition of this item
*/
function doReinstateItem(itemID)
{
// authorization check performed directly by the dspace-api
// assertAdministrator();
sendPageAndWait("admin/item/reinstate",{"itemID":itemID});
if (cocoon.request.get("submit_confirm"))
{
// Actually reinstate the item
// authorization check performed directly by the dspace-api
// assertAdministrator();
var result = FlowItemUtils.processReinstateItem(getDSContext(),itemID);
return result;
}
return null;
}
/*
* Move this item to another collection
*/
function doMoveItem(itemID)
{
assertEditItem(itemID);
var result;
do {
sendPageAndWait("admin/item/move",{"itemID":itemID});
result = null;
if (cocoon.request.get("submit_cancel"))
{
return null;
}
else if (cocoon.request.get("submit_move"))
{
var collectionID = cocoon.request.get("collectionID");
if (!collectionID)
{
continue;
}
var inherit = false;
if (cocoon.request.get("inheritPolicies"))
{
inherit = true;
}
// Actually move the item
assertEditItem(itemID);
result = FlowItemUtils.processMoveItem(getDSContext(), itemID, collectionID, inherit);
}
} while (result == null || !result.getContinue());
return result;
}
/**
* Allow the user to upload a new bitstream to this item.
*/
function doAddBitstream(itemID)
{
assertAuthorized(Constants.ITEM,itemID,Constants.ADD);
var result;
do {
sendPageAndWait("admin/item/add-bitstream",{"itemID":itemID},result);
assertAuthorized(Constants.ITEM,itemID,Constants.ADD);
result = null;
if (cocoon.request.get("submit_cancel"))
{
// return to whom ever called us
return null;
}
else if (cocoon.request.get("submit_upload"))
{
// Upload the file
result = FlowItemUtils.processAddBitstream(getDSContext(),itemID,cocoon.request);
}
} while (result == null || ! result.getContinue())
return result;
}
/**
* Allow the user to edit a bitstream's metadata (description & format)
*/
function doEditBitstream(itemID, bitstreamID)
{
assertAuthorized(Constants.BITSTREAM,bitstreamID,Constants.WRITE);
var result;
do {
sendPageAndWait("admin/item/edit-bitstream",{"itemID":itemID,"bitstreamID":bitstreamID},result);
assertAuthorized(Constants.BITSTREAM,bitstreamID,Constants.WRITE);
result = null;
if (cocoon.request.get("submit_cancel"))
{
// return to whom ever called us
return null;
}
else if (cocoon.request.get("submit_save"))
{
// Update the metadata
var primary = cocoon.request.get("primary");
var description = cocoon.request.get("description");
var formatID = cocoon.request.get("formatID");
var userFormat = cocoon.request.get("user_format");
result = FlowItemUtils.processEditBitstream(getDSContext(),itemID,bitstreamID,primary,description,formatID,userFormat);
}
} while (result == null || ! result.getContinue())
return result;
}
/**
* Confirm and delete the given bitstreamIDs
*/
function doDeleteBitstreams(itemID, bitstreamIDs)
{
assertAuthorized(Constants.ITEM,itemID,Constants.REMOVE);
sendPageAndWait("admin/item/delete-bitstreams",{"itemID":itemID,"bitstreamIDs":bitstreamIDs.join(',')});
if (cocoon.request.get("submit_confirm"))
{
// The user has confirmed,
assertAuthorized(Constants.ITEM,itemID,Constants.REMOVE);
var result = FlowItemUtils.processDeleteBitstreams(getDSContext(),itemID,bitstreamIDs);
return result;
}
return null;
}
/**
* Manage mapping items from one collection to another.
*/
function doMapItems(collectionID)
{
assertEditCollection(collectionID);
var result;
do
{
sendPageAndWait("admin/mapper/main",{"collectionID":collectionID},result);
assertEditCollection(collectionID);
result = null;
if (cocoon.request.get("submit_return"))
{
return null;
}
if (cocoon.request.get("submit_author"))
{
// Search for new items to added
assertAuthorized(Constants.COLLECTION,collectionID,Constants.ADD);
result = doMapItemSearch(collectionID);
}
else if (cocoon.request.get("submit_browse"))
{
// Browse existing mapped items
result = doMapItemBrowse(collectionID);
}
} while (true);
}
/**
* Manage batch metadata import
*
*/
function doMetadataImport()
{
var result;
assertAdministrator();
do
{
sendPageAndWait("admin/metadataimport/main",{},result);
result = null;
if (cocoon.request.get("submit_upload"))
{
result = doMetadataImportUpload();
}
} while (true);
}
function doMetadataImportUpload()
{
var result = FlowMetadataImportUtils.processUploadCSV(getDSContext(),cocoon.request);
assertAdministrator();
do
{
sendPageAndWait("admin/metadataimport/upload",{},result);
result = null;
if (cocoon.request.get("submit_return"))
{
return null;
}
else if (cocoon.request.get("submit_confirm"))
{
result = doMetadataImportConfirm();
return result;
}
} while (true);
}
function doMetadataImportConfirm()
{
var result = FlowMetadataImportUtils.processMetadataImport(getDSContext(),cocoon.request);
assertAdministrator();
sendPageAndWait("admin/metadataimport/confirm",{},result);
return null;
}
/**
* Search for new items to map into the collection
*/
function doMapItemSearch(collectionID)
{
assertAuthorized(Constants.COLLECTION,collectionID,Constants.ADD);
var result;
var query = cocoon.request.get("query");
sendPageAndWait("admin/mapper/search",{"collectionID":collectionID,"query":query},result);
assertAuthorized(Constants.COLLECTION,collectionID,Constants.ADD);
if (cocoon.request.get("submit_cancel"))
{
// return back
return null;
}
else if (cocoon.request.get("submit_map") && cocoon.request.get("itemID"))
{
// map the selected items
var itemIDs = cocoon.request.getParameterValues("itemID");
result = FlowMapperUtils.processMapItems(getDSContext(),collectionID,itemIDs);
return result;
}
}
/**
* Browse items that have been mapped into this collection.
*/
function doMapItemBrowse(collectionID)
{
var result;
do {
sendPageAndWait("admin/mapper/browse",{"collectionID":collectionID});
if (cocoon.request.get("submit_return"))
{
// return back to where they came from.
return null;
}
else if (cocoon.request.get("submit_unmap") && cocoon.request.get("itemID"))
{
// Unmap these items.
assertAuthorized(Constants.COLLECTION,collectionID,Constants.REMOVE);
var itemIDs = cocoon.request.getParameterValues("itemID");
result = FlowMapperUtils.processUnmapItems(getDSContext(), collectionID, itemIDs);
}
} while (true);
}
/**
* Authorization Flows
*/
/*
* Current entry point into the authorization flow. Presents the user with form to look up items,
* perform wildcard authorizations, or select a collection/community from the list to edit.
*/
function doManageAuthorizations()
{
// authorization check moved to FlowAuthorizationUtils
// assertAdministrator();
var result = null;
var query = "";
do {
sendPageAndWait("admin/authorize/main",{"query":query},result);
// authorization check moved to FlowAuthorizationUtils
// assertAdministrator();
result = null;
// if an identifier of some sort was entered into the lookup field
if (cocoon.request.get("submit_edit") && cocoon.request.get("identifier"))
{
var identifier = cocoon.request.get("identifier");
query = identifier;
// resolve the identifier to a type, look up its associated object, and act accordingly
result = FlowAuthorizationUtils.resolveItemIdentifier(getDSContext(),identifier);
if (result.getParameter("type") == Constants.ITEM && result.getParameter("itemID"))
{
var itemID = result.getParameter("itemID");
result = doAuthorizeItem(itemID);
}
else if (result.getParameter("type") == Constants.COLLECTION && result.getParameter("collectionID"))
{
var collectionID = result.getParameter("collectionID");
result = doAuthorizeCollection(collectionID);
}
else if (result.getParameter("type") == Constants.COMMUNITY && result.getParameter("communityID"))
{
var communityID = result.getParameter("communityID");
result = doAuthorizeCommunity(communityID);
}
}
// Clicking to edit a collection's authorizations
else if (cocoon.request.get("submit_edit") && cocoon.request.get("collection_id"))
{
var collectionID = cocoon.request.get("collection_id");
result = doAuthorizeCollection(collectionID);
}
// Clicking to edit a community's authorizations
else if (cocoon.request.get("submit_edit") && cocoon.request.get("community_id"))
{
var communityID = cocoon.request.get("community_id");
result = doAuthorizeCommunity(communityID);
}
// Wildcard/advanced authorizations
else if (cocoon.request.get("submit_wildcard"))
{
result = doAdvancedAuthorization();
}
}
while(true);
}
/*
* Wrapper functions for editing authorization policies for collections and communities
*/
function doAuthorizeCollection(collectionID)
{
doAuthorizeContainer(Constants.COLLECTION,collectionID);
}
function doAuthorizeCommunity(communityID)
{
doAuthorizeContainer(Constants.COMMUNITY,communityID);
}
/*
* Editing authorization policies for collections and communities, collectively refered to as "containers"
*/
function doAuthorizeContainer(containerType, containerID)
{
// authorization check moved to FlowAuthorizationUtils
// must be an ADMIN on the container to change its authorizations
// assertAuthorized(containerType, containerID, Constants.ADMIN);
var result;
var highlightID;
do {
sendPageAndWait("admin/authorize/container",{"containerType":containerType,"containerID":containerID,"highlightID":highlightID},result);
// authorization check moved to FlowAuthorizationUtils
// assertAuthorized(containerType, containerID, Constants.ADMIN);
result = null;
// Cancel out the operation
if (cocoon.request.get("submit_return")) {
return null;
}
else if (cocoon.request.get("submit_add")) {
// Create a new policy
result = doEditPolicy(containerType,containerID,-1);
if (result != null && result.getParameter("policyID"))
highlightID = result.getParameter("policyID");
}
else if (cocoon.request.get("submit_edit") && cocoon.request.get("policy_id")) {
// Edit an existing policy
var policyID = cocoon.request.get("policy_id");
result = doEditPolicy(containerType,containerID,policyID);
highlightID = policyID;
}
else if (cocoon.request.get("submit_delete") && cocoon.request.get("select_policy")) {
// Delete existing policies
var policyIDs = cocoon.request.getParameterValues("select_policy");
result = doDeletePolicies(policyIDs);
highlightID = null;
}
else if (cocoon.request.get("submit_edit_group") && cocoon.request.get("group_id")) {
// Edit a group from the authorization screen
var groupID = cocoon.request.get("group_id");
result = doEditGroup(groupID);
}
}
while (true);
}
/*
* Editing authorization policies for items
*/
function doAuthorizeItem(itemID)
{
// authorization check moved to FlowAuthorizationUtils
// assertAdministrator();
var result;
var highlightID;
do {
sendPageAndWait("admin/authorize/item",{"itemID":itemID,"highlightID":highlightID},result);
// authorization check moved to FlowAuthorizationUtils
// assertAdministrator();
result = null;
var bundleID = extractSubmitSuffix("submit_add_bundle_");
var bitstreamID = extractSubmitSuffix("submit_add_bitstream_");
// Cancel out the operation
if (cocoon.request.get("submit_return")) {
return null;
}
else if (bundleID)
{
// Create a new policy for a bundle
result = doEditPolicy(Constants.BUNDLE, bundleID,-1);
if (result != null && result.getParameter("policyID"))
highlightID = result.getParameter("policyID");
}
else if (bitstreamID)
{
// Create a new policy for a bitstream
result = doEditPolicy(Constants.BITSTREAM, bitstreamID,-1);
if (result != null && result.getParameter("policyID"))
highlightID = result.getParameter("policyID");
}
else if (cocoon.request.get("submit_add_item")) {
// Create a new policy for the item
result = doEditPolicy(Constants.ITEM, itemID,-1);
if (result != null && result.getParameter("policyID"))
highlightID = result.getParameter("policyID");
}
else if (cocoon.request.get("submit_edit") && cocoon.request.get("policy_id")
&& cocoon.request.get("object_id") && cocoon.request.get("object_type")) {
// Edit an existing policy
var policyID = cocoon.request.get("policy_id");
var objectID = cocoon.request.get("object_id");
var objectType = cocoon.request.get("object_type");
result = doEditPolicy(objectType,objectID,policyID);
highlightID = policyID;
}
else if (cocoon.request.get("submit_delete") && cocoon.request.get("select_policy")) {
// Delete existing policies
var policyIDs = cocoon.request.getParameterValues("select_policy");
result = doDeletePolicies(policyIDs);
highlightID = null;
}
else if (cocoon.request.get("submit_edit_group") && cocoon.request.get("group_id")) {
// Edit a group from the authorization screen
var groupID = cocoon.request.get("group_id");
result = doEditGroup(groupID);
}
}
while (true);
}
/*
* Advanced or "wildcard" authorizations; presents the user with a list of communities and list of groups,
* together with options for an authorization action and a recepient of that action. The user can select
* multiple collections and multiple groups to create repository-wide authorizations.
*/
function doAdvancedAuthorization()
{
assertAdministrator();
var result;
do {
sendPageAndWait("admin/authorize/advanced",{},result);
assertAdministrator();
result = null;
// For all of the selected groups...
var groupIDs = cocoon.request.getParameterValues("group_id");
// ...grant the ability to perform the following action...
var actionID = cocoon.request.get("action_id");
// ...for all following object types...
var resourceID = cocoon.request.get("resource_id");
// ...across the following collections.
var collectionIDs = cocoon.request.getParameterValues("collection_id");
if (cocoon.request.get("submit_return"))
{
return null;
}
else if (cocoon.request.get("submit_add"))
{
result = FlowAuthorizationUtils.processAdvancedPolicyAdd(getDSContext(),groupIDs,actionID,resourceID,collectionIDs);
}
else if (cocoon.request.get("submit_remove_all"))
{
result = FlowAuthorizationUtils.processAdvancedPolicyDelete(getDSContext(),resourceID,collectionIDs);
}
}
while(result == null || !result.getContinue());
}
/**
* Edit a policy, giving the user a choice of actions and the ability to either browse to a desired group via
* drop-down field, or search for one via search box.
*/
function doEditPolicy(objectType,objectID,policyID)
{
// authorize check moved to FlowAuthorizationUtils.processEditPolicy
// assertAdministrator();
var result;
var query= "-1";
var groupID;
var actionID;
var page = 0;
do {
/* The page recieves parameters for the type and ID of the DSpace object that the policy is assciated with, the
* policy ID, the group search query (if a search was performed), the ID of the currenly associated group, the
* current action and the currently viewed page (if a search returned more than one page of results) */
sendPageAndWait("admin/authorize/edit",{"objectType":objectType,"objectID":objectID,"policyID":policyID,"query":query,"groupID":groupID,"actionID":actionID,"page":page},result);
// authorize check moved to FlowAuthorizationUtils.processEditPolicy
// assertAdministrator();
result = null;
// Figure out which button was pressed on the group search results page
var names = cocoon.request.getParameterNames();
while (names.hasMoreElements())
{
var name = names.nextElement();
var match = null;
if ((match = name.match(/submit_group_id_(\d+)/)) != null)
{
groupID = match[1];
}
if (cocoon.request.get("action_id"))
actionID = cocoon.request.get("action_id");
}
if (cocoon.request.get("page")) {
page = cocoon.request.get("page");
}
// perform a search to set a group
if (cocoon.request.get("submit_search_groups")) {
query = cocoon.request.get("query");
if (cocoon.request.get("action_id"))
actionID = cocoon.request.get("action_id");
page = 0;
}
else if (cocoon.request.get("submit_save"))
{
groupID = cocoon.request.get("group_id");
if (groupID == null) groupID = -1;
actionID = cocoon.request.get("action_id");
if (actionID == null) actionID = -1;
result = FlowAuthorizationUtils.processEditPolicy(getDSContext(),objectType,objectID,policyID,groupID,actionID);
}
else if (cocoon.request.get("submit_cancel"))
{
return null;
}
// TODO; make sure to handle the odd case of the target group getting deleted from inside the authorization flow
else if (cocoon.request.get("submit_edit_group") && cocoon.request.get("group_id"))
{
var editGroupID = cocoon.request.get("group_id");
result = doEditGroup(editGroupID);
if (result != null)
result.setContinue(false);
}
}
while(result == null || !result.getContinue());
return result;
}
/**
* Confirm that the given policies should be deleted; if confirmed they will be deleted.
*/
function doDeletePolicies(policyIDs)
{
// authorization check moved to FlowAuthorizationUtils
// assertAdministrator();
sendPageAndWait("admin/authorize/delete",{"policyIDs":policyIDs.join(',')});
if (cocoon.request.get("submit_confirm"))
{
// The user has confirmed, actualy delete these policies
// authorization check moved to FlowAuthorizationUtils
// assertAdministrator();
var result = FlowAuthorizationUtils.processDeletePolicies(getDSContext(),policyIDs);
return result;
}
return null;
}
/**
* Community/Collection editing
*/
function doEditCollection(collectionID,newCollectionP)
{
assertEditCollection(collectionID);
// If this is a new collection, then go to
// role assignment first, otherwise start with
// the metadata
if (newCollectionP)
doAssignCollectionRoles(collectionID);
else
doEditCollectionMetadata(collectionID);
do {
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_save"))
{
// go back to where ever we came from.
return null;
}
else if (cocoon.request.get("submit_metadata"))
{
// go edit collection metadata
doEditCollectionMetadata(collectionID)
}
else if (cocoon.request.get("submit_roles"))
{
// go assign collection roles
doAssignCollectionRoles(collectionID);
}
else if (cocoon.request.get("submit_harvesting"))
{
// edit collection harvesting settings
doEditCollectionHarvesting(collectionID);
}
else if (cocoon.request.get("submit_curate"))
{
doCurateCollection(collectionID, cocoon.request.get("curate_task"));
}
else
{
// This case should never happen but to prevent an infinite loop
// from occuring let's just return null.
return null;
}
} while (true)
}
/**
* Edit metadata of a collection; presenting the user with a form of standard collection metadata,
* an option add/remove a logo, and set the item template. From here the user can also move on to
* edit roles and authorizations screen
*/
function doEditCollectionMetadata(collectionID)
{
assertEditCollection(collectionID);
var result;
do {
sendPageAndWait("admin/collection/editMetadata",{"collectionID":collectionID},result);
assertEditCollection(collectionID);
result=null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_metadata") ||
cocoon.request.get("submit_roles") || cocoon.request.get("submit_harvesting") ||
cocoon.request.get("submit_curate"))
{
// return to the editCollection function which will determine where to go next.
return null;
}
else if (cocoon.request.get("submit_save"))
{
// Save updates
result = FlowContainerUtils.processEditCollection(getDSContext(), collectionID, false, cocoon.request);
if (result.getContinue())
return null;
}
else if (cocoon.request.get("submit_delete"))
{
// delete collection
assertAdministrator();
result = doDeleteCollection(collectionID);
}
else if (cocoon.request.get("submit_delete_logo"))
{
// Delete the collection's logo
result = FlowContainerUtils.processEditCollection(getDSContext(), collectionID, true, cocoon.request);
}
else if (cocoon.request.get("submit_create_template") || cocoon.request.get("submit_edit_template"))
{
// Create or edit the item's template
var itemID = FlowContainerUtils.getTemplateItemID(getDSContext(), collectionID);
result = doEditItemMetadata(itemID, collectionID);
}
else if (cocoon.request.get("submit_delete_template"))
{
// Delete the item's template
assertEditCollection(collectionID);
result = FlowContainerUtils.processDeleteTemplateItem(getDSContext(), collectionID);
}
}while (true);
}
/**
* Edit the set roles for a collection: admin, workflows, submitters, and default read.
* Returns to the EditCollection page and selected tab if this is a simple navigation,
* not a submit.
*/
function doAssignCollectionRoles(collectionID)
{
assertEditCollection(collectionID);
var result;
do {
sendPageAndWait("admin/collection/assignRoles",{"collectionID":collectionID},result);
assertEditCollection(collectionID);
result = null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_metadata") ||
cocoon.request.get("submit_roles") || cocoon.request.get("submit_harvesting") ||
cocoon.request.get("submit_curate"))
{
return null;
}
else if (cocoon.request.get("submit_authorizations"))
{
// general authorizations
// assertAdminCollection(collectionID);
result = doAuthorizeCollection(collectionID);
}
// ADMIN
else if (cocoon.request.get("submit_edit_admin") || cocoon.request.get("submit_create_admin"))
{
assertEditCollection(collectionID);
var groupID = FlowContainerUtils.getCollectionRole(getDSContext(),collectionID, "ADMIN");
result = doEditGroup(groupID);
}
else if (cocoon.request.get("submit_delete_admin")) {
result = doDeleteCollectionRole(collectionID, "ADMIN");
}
// WORKFLOW STEPS 1-3
else if (cocoon.request.get("submit_edit_wf_step1") || cocoon.request.get("submit_create_wf_step1"))
{
assertEditCollection(collectionID);
var groupID = FlowContainerUtils.getCollectionRole(getDSContext(),collectionID, "WF_STEP1");
result = doEditGroup(groupID);
}
else if (cocoon.request.get("submit_delete_wf_step1"))
{
result = doDeleteCollectionRole(collectionID, "WF_STEP1");
}
else if (cocoon.request.get("submit_edit_wf_step2") || cocoon.request.get("submit_create_wf_step2"))
{
assertEditCollection(collectionID);
var groupID = FlowContainerUtils.getCollectionRole(getDSContext(),collectionID, "WF_STEP2");
result = doEditGroup(groupID);
}
else if (cocoon.request.get("submit_delete_wf_step2"))
{
result = doDeleteCollectionRole(collectionID, "WF_STEP2");
}
else if (cocoon.request.get("submit_edit_wf_step3") || cocoon.request.get("submit_create_wf_step3"))
{
assertEditCollection(collectionID);
var groupID = FlowContainerUtils.getCollectionRole(getDSContext(),collectionID, "WF_STEP3");
result = doEditGroup(groupID);
}
else if (cocoon.request.get("submit_delete_wf_step3"))
{
result = doDeleteCollectionRole(collectionID, "WF_STEP3");
}
// SUBMIT
else if (cocoon.request.get("submit_edit_submit") || cocoon.request.get("submit_create_submit"))
{
assertEditCollection(collectionID);
var groupID = FlowContainerUtils.getCollectionRole(getDSContext(),collectionID, "SUBMIT");
result = doEditGroup(groupID);
}
else if (cocoon.request.get("submit_delete_submit"))
{
result = doDeleteCollectionRole(collectionID, "SUBMIT");
}
// DEFAULT_READ
else if (cocoon.request.get("submit_create_default_read"))
{
assertAdminCollection(collectionID);
var groupID = FlowContainerUtils.createCollectionDefaultReadGroup(getDSContext(), collectionID);
result = doEditGroup(groupID);
}
else if (cocoon.request.get("submit_edit_default_read"))
{
assertEditCollection(collectionID);
var groupID = FlowContainerUtils.getCollectionDefaultRead(getDSContext(), collectionID);
result = doEditGroup(groupID);
}
else if (cocoon.request.get("submit_delete_default_read"))
{
result = doDeleteCollectionRole(collectionID, "DEFAULT_READ");
}
}while(true);
}
/**
* Curate Collection
*
*/
/** Curate
*
*
*/
function doCurateCollection(collectionID, task) {
var result;
do {
sendPageAndWait("admin/collection/curateCollection",{"collectionID":collectionID},result);
assertEditCollection(collectionID);
result = null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_metadata") ||
cocoon.request.get("submit_roles") || cocoon.request.get("submit_harvesting") ||
cocoon.request.get("submit_curate"))
{
//return to the editCollection function which will determine where to go next.
return null;
}
if (cocoon.request.get("submit_curate_task"))
{
result = FlowContainerUtils.processCurateCollection(getDSContext(), collectionID, cocoon.request);
}
else if (cocoon.request.get("submit_queue_task"))
{
result = FlowContainerUtils.processQueueCollection(getDSContext(), collectionID, cocoon.request);
}
}
while (true);
}
/**
* Set up various harvesting options.
* From here the user can also move on to edit roles and edit metadata screen.
*/
function doSetupCollectionHarvesting(collectionID)
{
assertAdminCollection(collectionID);
var result = null;
var oaiProviderValue = null;
var oaiSetAll = null;
var oaiSetIdValue = null;
var metadataFormatValue = null;
var harvestLevelValue = null;
do {
sendPageAndWait("admin/collection/setupHarvesting",{"collectionID":collectionID,"oaiProviderValue":oaiProviderValue,"oaiSetAll":oaiSetAll,"oaiSetIdValue":oaiSetIdValue,"metadataFormatValue":metadataFormatValue,"harvestLevelValue":harvestLevelValue},result);
result = null;
oaiProviderValue = cocoon.request.get("oai_provider");
oaiSetAll = cocoon.request.get("oai-set-setting");
oaiSetIdValue = cocoon.request.get("oai_setid");
metadataFormatValue = cocoon.request.get("metadata_format");
harvestLevelValue = cocoon.request.get("harvest_level");
assertAdminCollection(collectionID);
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_metadata") ||
cocoon.request.get("submit_roles") || cocoon.request.get("submit_harvesting"))
{
// return to the editCollection function which will determine where to go next.
return null;
}
else if (cocoon.request.get("submit_save"))
{
// Save updates
result = FlowContainerUtils.processSetupCollectionHarvesting(getDSContext(), collectionID, cocoon.request);
}
else if (cocoon.request.get("submit_test"))
{
// Ping the OAI server and verify that the address/set/metadata combo is present there
// Can get this either in a single GetRecords OAI request or via two separate ones: ListSets and ListMetadataFormats
result = FlowContainerUtils.testOAISettings(getDSContext(), cocoon.request);
}
} while (!result.getContinue());
}
/**
* Edit existing harvesting options.
* From here the user can also move on to edit roles and edit metadata screen.
*/
function doEditCollectionHarvesting(collectionID)
{
assertAdminCollection(collectionID);
var result = null;
do
{
// If this collection's havresting is not set up properly, redirect to the setup screen
if (HarvestedCollection.find(getDSContext(), collectionID) == null) {
sendPageAndWait("admin/collection/toggleHarvesting",{"collectionID":collectionID},result);
}
else if (!HarvestedCollection.isHarvestable(getDSContext(), collectionID)) {
doSetupCollectionHarvesting(collectionID);
}
else {
sendPageAndWait("admin/collection/editHarvesting",{"collectionID":collectionID},result);
}
result = null;
assertAdminCollection(collectionID);
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_metadata") ||
cocoon.request.get("submit_roles") || cocoon.request.get("submit_harvesting") ||
cocoon.request.get("submit_curate"))
{
// return to the editCollection function which will determine where to go next.
return null;
}
else if (cocoon.request.get("submit_save"))
{
// Save updates
result = FlowContainerUtils.processSetupCollectionHarvesting(getDSContext(), collectionID, cocoon.request);
}
else if (cocoon.request.get("submit_import_now"))
{
// Test the settings and run the import immediately
result = FlowContainerUtils.processRunCollectionHarvest(getDSContext(), collectionID, cocoon.request);
}
else if (cocoon.request.get("submit_reimport"))
{
// Test the settings and run the import immediately
result = FlowContainerUtils.processReimportCollection(getDSContext(), collectionID, cocoon.request);
}
else if (cocoon.request.get("submit_change"))
{
doSetupCollectionHarvesting(collectionID);
}
} while (true);
}
/**
* Delete a specified collection role. Under the current implementation, the only roles this applies to
* directly are the workflow steps. Admin and submitter authorizations cannot be deleted once formed, and
* the default read group is changed to Anonymous instead.
*/
function doDeleteCollectionRole(collectionID,role)
{
assertAdminCollection(collectionID);
var groupID;
if (role == "DEFAULT_READ") {
groupID = FlowContainerUtils.getCollectionDefaultRead(getDSContext(), collectionID);
}
else {
groupID = FlowContainerUtils.getCollectionRole(getDSContext(),collectionID, role);
}
sendPageAndWait("admin/collection/deleteRole",{"collectionID":collectionID,"role":role,"groupID":groupID});
assertAdminCollection(collectionID);
if (cocoon.request.get("submit_confirm") && role == "DEFAULT_READ")
{
// Special case for default_read
var result = FlowContainerUtils.changeCollectionDefaultReadToAnonymous(getDSContext(), collectionID);
return result;
}
else if (cocoon.request.get("submit_confirm"))
{
// All other roles use the standard methods
var result = FlowContainerUtils.processDeleteCollectionRole(getDSContext(),collectionID,role,groupID);
return result;
}
return null;
}
/**
* Delete an entire collection, requesting a confirmation first.
*/
function doDeleteCollection(collectionID)
{
assertAuthorized(Constants.COLLECTION, collectionID, Constants.DELETE);
sendPageAndWait("admin/collection/delete",{"collectionID":collectionID});
assertAuthorized(Constants.COLLECTION, collectionID, Constants.DELETE);
if (cocoon.request.get("submit_confirm"))
{
var result = FlowContainerUtils.processDeleteCollection(getDSContext(),collectionID);
if (result.getContinue()) {
cocoon.redirectTo(cocoon.request.getContextPath()+"/community-list",true);
getDSContext().complete();
cocoon.exit();
}
}
return null;
}
// Creating a new collection, given the ID of its parent community
function doCreateCollection(communityID)
{
assertAuthorized(Constants.COMMUNITY,communityID,Constants.ADD);
var result;
var collectionID;
do {
sendPageAndWait("admin/collection/createCollection",{"communityID":communityID},result);
assertAuthorized(Constants.COMMUNITY,communityID,Constants.ADD);
result=null;
if (cocoon.request.get("submit_save")) {
// create the collection, passing back its ID
result = FlowContainerUtils.processCreateCollection(getDSContext(), communityID, cocoon.request);
// send the user to the authorization screen
if (result.getContinue() && result.getParameter("collectionID")) {
collectionID = result.getParameter("collectionID");
result = doEditCollection(collectionID,true);
// If they return then pass them back to where they came from.
return result;
}
}
else if (cocoon.request.get("submit_cancel")) {
cocoon.redirectTo(cocoon.request.getContextPath()+"/community-list",true);
getDSContext().complete();
cocoon.exit();
}
} while (true);
}
// Creating a new community, given the ID of its parent community or an ID of -1 to designate top-level
function doCreateCommunity(parentCommunityID)
{
var result;
var newCommunityID;
// If we are not passed a communityID from the flow, we assume that is passed in from the sitemap
if (parentCommunityID == null && cocoon.request.getParameter("communityID") != null)
{
parentCommunityID = cocoon.request.getParameter("communityID");
}
else if (parentCommunityID == null)
{
parentCommunityID = -1;
}
assertEditCommunity(parentCommunityID);
do {
sendPageAndWait("admin/community/createCommunity",{"communityID":parentCommunityID},result);
assertEditCommunity(parentCommunityID);
result=null;
if (cocoon.request.get("submit_save")) {
// create the community, passing back its ID
result = FlowContainerUtils.processCreateCommunity(getDSContext(), parentCommunityID, cocoon.request);
// send the user to the newly created community
if (result.getContinue() && result.getParameter("communityID")) {
newCommunityID = result.getParameter("communityID");
result = doEditCommunity(newCommunityID);
return result;
}
}
else if (cocoon.request.get("submit_cancel")) {
cocoon.redirectTo(cocoon.request.getContextPath()+"/community-list",true);
getDSContext().complete();
cocoon.exit();
}
} while (true);
}
/**
* Edit a community.
*/
function doEditCommunity(itemID)
{
// Always go to the status page first
doEditCommunityMetadata(itemID);
do {
if (cocoon.request.get("submit_return"))
{
return null;
}
else if (cocoon.request.get("submit_metadata")) {
doEditCommunityMetadata(itemID);
}
else if (cocoon.request.get("submit_status"))
{
doEditItemStatus(itemID);
}
else if (cocoon.request.get("submit_bitstreams"))
{
doEditItemBitstreams(itemID);
}
else if (cocoon.request.get("submit_save") || cocoon.request.get("submit_delete") || cocoon.request.get("submit_delete_logo"))
{
doEditCommunityMetadata(itemID, -1);
}
else if (cocoon.request.get("submit_authorizations")) {
result = doAuthorizeCommunity(communityID);
}
else if (cocoon.request.get("submit_roles"))
{
doAssignCommunityRoles(itemID);
}
else if (cocoon.request.get("submit_curate")) {
doCurateCommunity(itemID, cocoon.request.get("curate_task"));
}
else
{
// This case should never happen but to prevent an infinite loop
// from occuring let's just return null.
return null;
}
} while (true)
}
/**
* Edit metadata of a community; presenting the user with a form of standard community metadata,
* an option add/remove a logo and a link to the authorizations screen
*/
function doEditCommunityMetadata(communityID)
{
assertEditCommunity(communityID);
var result;
do {
sendPageAndWait("admin/community/editMetadata",{"communityID":communityID},result);
assertEditCommunity(communityID);
result=null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_metadata") || cocoon.request.get("submit_roles") || cocoon.request.get("submit_curate")){
return null;
}
if (cocoon.request.get("submit_save")) {
result = FlowContainerUtils.processEditCommunity(getDSContext(), communityID, false, cocoon.request);
if (result.getContinue())
return null;
} else if (cocoon.request.get("submit_delete")) {
assertAuthorized(Constants.COMMUNITY, communityID, Constants.DELETE);
result = doDeleteCommunity(communityID);
}
else if (cocoon.request.get("submit_delete_logo")) {
result = FlowContainerUtils.processEditCommunity(getDSContext(), communityID, true, cocoon.request);
}
}
while (true);
}
/**
* Delete an entire community, asking for a confirmation first
*/
function doDeleteCommunity(communityID) {
assertAuthorized(Constants.COMMUNITY, communityID, Constants.DELETE);
sendPageAndWait("admin/community/delete",{"communityID":communityID});
assertAuthorized(Constants.COMMUNITY, communityID, Constants.DELETE);
if (cocoon.request.get("submit_confirm"))
{
var result = FlowContainerUtils.processDeleteCommunity(getDSContext(),communityID);
if (result.getContinue()) {
cocoon.redirectTo(cocoon.request.getContextPath()+"/community-list",true);
getDSContext().complete();
cocoon.exit();
}
}
return null;
}
/**
* Edit the administrative role for a community.
*/
function doAssignCommunityRoles(communityID)
{
var result;
do {
sendPageAndWait("admin/community/assignRoles",{"communityID":communityID},result);
assertEditCommunity(communityID);
result = null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_metadata") || cocoon.request.get("submit_roles") || cocoon.request.get("submit_curate") )
{
return null;
}
else if (cocoon.request.get("submit_authorizations"))
{
// authorization check moved to FlowAuthorizationUtils
// assertAdministrator();
result = doAuthorizeCommunity(communityID);
}
// ADMIN
else if (cocoon.request.get("submit_edit_admin") || cocoon.request.get("submit_create_admin"))
{
var groupID = FlowContainerUtils.getCommunityRole(getDSContext(),communityID, "ADMIN");
result = doEditGroup(groupID);
}
else if (cocoon.request.get("submit_delete_admin")) {
result = doDeleteCommunityRole(communityID, "ADMIN");
}
}while (true);
}
/** Curate
*
*
*/
function doCurateCommunity(communityID, task) {
var result;
do {
sendPageAndWait("admin/community/curateCommunity",{"communityID":communityID},result);
assertEditCommunity(communityID);
result = null;
if (cocoon.request.get("submit_return") || cocoon.request.get("submit_metadata") || cocoon.request.get("submit_roles") || cocoon.request.get("submit_curate") )
{
return null;
}
else if (cocoon.request.get("submit_curate_task"))
{
result = FlowContainerUtils.processCurateCommunity(getDSContext(), communityID, cocoon.request);
}
else if (cocoon.request.get("submit_queue_task"))
{
result = FlowContainerUtils.processQueueCommunity(getDSContext(), communityID, cocoon.request);
}
} while (true);
}
/**
* Delete a specified community role. Under the current
* implementation, admin authorizations cannot be deleted once formed,
* and the default read group is changed to Anonymous instead.
*/
function doDeleteCommunityRole(communityID,role)
{
// authorization check performed directly by the dspace-api
// assertAdminCommunity(communityID);
var groupID = FlowContainerUtils.getCommunityRole(getDSContext(), communityID, role);
sendPageAndWait("admin/community/deleteRole",{"communityID":communityID,"role":role,"groupID":groupID});
// authorization check performed directly by the dspace-api
// assertAdminCommunity(communityID);
if (cocoon.request.get("submit_confirm"))
{
// All other roles use the standard methods
var result = FlowContainerUtils.processDeleteCommunityRole(getDSContext(),communityID,role,groupID);
return result;
}
return null;
}
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// script.aculo.us builder.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Builder = {
NODEMAP: {
AREA: 'map',
CAPTION: 'table',
COL: 'table',
COLGROUP: 'table',
LEGEND: 'fieldset',
OPTGROUP: 'select',
OPTION: 'select',
PARAM: 'object',
TBODY: 'table',
TD: 'table',
TFOOT: 'table',
TH: 'table',
THEAD: 'table',
TR: 'table'
},
// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
// due to a Firefox bug
node: function(elementName) {
elementName = elementName.toUpperCase();
// try innerHTML approach
var parentTag = this.NODEMAP[elementName] || 'div';
var parentElement = document.createElement(parentTag);
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
} catch(e) {}
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
if(element && (element.tagName.toUpperCase() != elementName))
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
if(!element) element = document.createElement(elementName);
// abort if nothing could be created
if(!element) return;
// attributes (or text)
if(arguments[1])
if(this._isStringOrNumber(arguments[1]) ||
(arguments[1] instanceof Array) ||
arguments[1].tagName) {
this._children(element, arguments[1]);
} else {
var attrs = this._attributes(arguments[1]);
if(attrs.length) {
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" +elementName + " " +
attrs + "></" + elementName + ">";
} catch(e) {}
element = parentElement.firstChild || null;
// workaround firefox 1.0.X bug
if(!element) {
element = document.createElement(elementName);
for(attr in arguments[1])
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
if(element.tagName.toUpperCase() != elementName)
element = parentElement.getElementsByTagName(elementName)[0];
}
}
// text, or array of children
if(arguments[2])
this._children(element, arguments[2]);
return $(element);
},
_text: function(text) {
return document.createTextNode(text);
},
ATTR_MAP: {
'className': 'class',
'htmlFor': 'for'
},
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
'="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'"') + '"');
return attrs.join(" ");
},
_children: function(element, children) {
if(children.tagName) {
element.appendChild(children);
return;
}
if(typeof children=='object') { // array can hold nodes and text
children.flatten().each( function(e) {
if(typeof e=='object')
element.appendChild(e);
else
if(Builder._isStringOrNumber(e))
element.appendChild(Builder._text(e));
});
} else
if(Builder._isStringOrNumber(children))
element.appendChild(Builder._text(children));
},
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
},
build: function(html) {
var element = this.node('div');
$(element).update(html.strip());
return element.down();
},
dump: function(scope) {
if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
tags.each( function(tag){
scope[tag] = function() {
return Builder.node.apply(Builder, [tag].concat($A(arguments)));
};
});
}
}; | JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// Client-side scripting to support DSpace Choice Control
// IMPORTANT NOTE:
// This code depends on a *MODIFIED* version of the
// script.aculo.us controls v1.8.2, fixed to avoid a bug that
// affects autocomplete in Firefox 3. This code is included in DSpace.
// Entry points:
// 1. DSpaceAutocomplete -- add autocomplete (suggest) to an input field
//
// 2. DSpaceChoiceLookup -- create popup window with authority choices
//
// @Author: Larry Stone <lcs@hulmail.harvard.edu>
// $Revision $
// -------------------- support for Autocomplete (Suggest)
// Autocomplete utility:
// Arguments:
// formID -- ID attribute of form tag
// args properties:
// metadataField -- metadata field e.g. dc_contributor_author
// inputName -- input field name for text input, or base of "Name" pair
// authorityName -- input field name in which to set authority
// containerID -- ID attribute of DIV to hold the menu objects
// indicatorID -- ID attribute of element to use as a "loading" indicator
// confidenceIndicatorID -- ID of element on which to set confidence
// confidenceName - NAME of confidence input (not ID)
// contextPath -- URL path prefix (i.e. webapp contextPath) for DSpace.
// collection -- db ID of dspace collection to serve as context
// isClosed -- true if authority value is required, false = non-auth allowed
// XXX Can't really enforce "isClosed=true" with autocomplete, user can type anything
//
// NOTE: Successful autocomplete always sets confidence to 'accepted' since
// authority value (if any) *was* chosen interactively by a human.
function DSpaceSetupAutocomplete(formID, args)
{
if (args.authorityName == null)
args.authorityName = dspace_makeFieldInput(args.inputName,'_authority');
var form = document.getElementById(formID);
var inputID = form.elements[args.inputName].id;
var authorityID = null;
if (form.elements[args.authorityName] != null)
authorityID = form.elements[args.authorityName].id;
// AJAX menu source, can add &query=TEXT
var choiceURL = args.contextPath+"/choices/"+args.metadataField;
var collID = args.collection == null ? -1 : args.collection;
// field in whcih to store authority value
var options =
{
// class name of spans that contain value in li elements
select: "value",
// make up query args for AJAX callback
parameters: 'collection='+collID+'&format=ul',
callback:
function(inField, querystring) {
return querystring+"&query="+inField.value;
},
// called after target field is updated
afterUpdateElement:
function(ignoreField, li)
{
// NOTE: lookup element late because it might not be in DOM
// at the time we evaluate the function..
var authInput = document.getElementById(authorityID);
var authValue = li == null ? "" : li.getAttribute("authority");
if (authInput != null)
{
authInput.value = authValue;
// update confidence input's value too if available.
if (args.confidenceName != null)
{
var confInput = authInput.form.elements[args.confidenceName];
if (confInput != null)
confInput.value = 'accepted';
}
}
// make indicator blank if no authority value
DSpaceUpdateConfidence(document, args.confidenceIndicatorID,
authValue == null || authValue == '' ? 'blank' :'accepted');
}
};
if (args.indicatorID != null)
options.indicator = args.indicatorID;
// be sure to turn off autocomplete, it absorbs arrow-key events!
form.elements[args.inputName].setAttribute("autocomplete", "off");
new Ajax.Autocompleter(inputID, args.containerID, choiceURL, options);
}
// -------------------- support for Lookup Popup
// Create popup window with authority choices for value of an input field.
// This is intended to be called by onClick of a "Lookup" or "Add" button.
function DSpaceChoiceLookup(url, field, formID, valueInput, authInput,
confIndicatorID, collectionID, isName, isRepeating)
{
// fill in URL
url += '?field='+field+'&formID='+formID+'&valueInput='+valueInput+
'&authorityInput='+authInput+'&collection='+collectionID+
'&isName='+isName+'&isRepeating='+isRepeating+'&confIndicatorID='+confIndicatorID;
// primary input field - for positioning popup.
var inputFieldName = isName ? dspace_makeFieldInput(valueInput,'_last') : valueInput;
var inputField = document.getElementById(formID).elements[inputFieldName];
// scriptactulous magic to figure out true offset:
var cOffset = 0;
if (inputField != null)
cOffset = $(inputField).cumulativeOffset();
var width = 600; // XXX guesses! these should be params, or configured..
var height = 470;
var left; var top;
if (window.screenX == null) {
left = window.screenLeft + cOffset.left - (width/2);
top = window.screenTop + cOffset.top - (height/2);
} else {
left = window.screenX + cOffset.left - (width/2);
top = window.screenY + cOffset.top - (height/2);
}
if (left < 0) left = 0;
if (top < 0) top = 0;
var pw = window.open(url, 'ignoreme',
'width='+width+',height='+height+',left='+left+',top='+top+
',toolbar=no,menubar=no,location=no,status=no,resizable');
if (window.focus) pw.focus();
return false;
}
// Run this as the Lookup page is loaded to initialize DOM objects, load choices
function DSpaceChoicesSetup(form)
{
// find the "LEGEND" in fieldset, which acts as page title,
// and save it as a bogus form element, e.g. elements['statline']
var fieldset = document.getElementById('aspect_general_ChoiceLookupTransformer_list_choicesList');
for (i = 0; i < fieldset.childNodes.length; ++i)
{
if (fieldset.childNodes[i].nodeName == 'LEGEND')
{
form.statline = fieldset.childNodes[i];
form.statline_template = fieldset.childNodes[i].innerHTML;
fieldset.childNodes[i].innerHTML = "Loading...";
break;
}
}
DSpaceChoicesLoad(form);
}
// populate the "select" with options from ajax request
// stash some parameters as properties of the "select" so we can add to
// the last start index to query for next set of results.
function DSpaceChoicesLoad(form)
{
var field = form.elements['paramField'].value;
var value = form.elements['paramValue'].value;
var start = form.elements['paramStart'].value;
var limit = form.elements['paramLimit'].value;
var formID = form.elements['paramFormID'].value;
var collID = form.elements['paramCollection'].value;
var isName = form.elements['paramIsName'].value == 'true';
var isRepeating = form.elements['paramIsRepeating'].value == 'true';
var isClosed = form.elements['paramIsClosed'].value == 'true';
var contextPath = form.elements['contextPath'].value;
var fail = form.elements['paramFail'].value;
var valueInput = form.elements['paramValueInput'].value;
var nonAuthority = "";
if (form.elements['paramNonAuthority'] != null)
nonAuthority = form.elements['paramNonAuthority'].value;
// get value from form inputs in opener if not explicitly supplied
if (value.length == 0)
{
var of = window.opener.document.getElementById(formID);
if (isName)
value = makePersonName(of.elements[dspace_makeFieldInput(valueInput,'_last')].value,
of.elements[dspace_makeFieldInput(valueInput,'_first')].value);
else
value = of.elements[valueInput].value;
// if this is a repeating input, clear the source value so that e.g.
// clicking "Next" on a submit-describe page will not *add* the proposed
// lookup text as a metadata value:
if (isRepeating)
{
if (isName)
{
of.elements[dspace_makeFieldInput(valueInput,'_last')].value = null;
of.elements[dspace_makeFieldInput(valueInput,'_first')].value = null;
}
else
of.elements[valueInput].value = null;
}
}
// start spinner
var indicator = document.getElementById('lookup_indicator_id');
if (indicator != null)
indicator.style.display = "inline";
new Ajax.Request(contextPath+"/choices/"+field,
{
method: "get",
parameters: {query: value, format: 'select', collection: collID,
start: start, limit: limit},
// triggered by any exception, even in success
onException: function(req, e) {
window.alert(fail+" Exception="+e);
if (indicator != null) indicator.style.display = "none";
},
// when http load of choices fails
onFailure: function() {
window.alert(fail+" HTTP error resonse");
if (indicator != null) indicator.style.display = "none";
},
// format is <select><option authority="key" value="val">label</option>...
onSuccess: function(transport) {
var ul = transport.responseXML.documentElement;
var err = ul.getAttributeNode('error');
if (err != null && err.value == 'true')
window.alert(fail+" Server indicates error in response.");
var opts = ul.getElementsByTagName('option');
// update range message and update 'more' button
var oldStart = 1 * ul.getAttributeNode('start').value;
var nextStart = oldStart + opts.length;
var lastTotal = ul.getAttributeNode('total').value;
var resultMore = ul.getAttributeNode('more');
form.elements['more'].disabled = !(resultMore != null && resultMore.value == 'true');
form.elements['paramStart'].value = nextStart;
// clear select first
var select = form.elements['chooser'];
for (var i = select.length-1; i >= 0; --i)
select.remove(i);
// load select and look for default selection
var selectedByValue = -1; // select by value match
var selectedByChoices = -1; // Choice says its selected
for (var i = 0; i < opts.length; ++i)
{
var opt = opts.item(i);
var olabel = "";
for (var j = 0; j < opt.childNodes.length; ++j)
{
var node = opt.childNodes[j];
if (node.nodeName == "#text")
olabel += node.data;
}
var ovalue = opt.getAttributeNode('value').value;
var option = new Option(olabel, ovalue);
option.authority = opt.getAttributeNode('authority').value;
select.add(option, null);
if (value == ovalue)
selectedByValue = select.options.length - 1;
if (opt.getAttributeNode('selected') != null)
selectedByChoices = select.options.length - 1;
}
// add non-authority option if needed.
if (!isClosed)
{
select.add(new Option(dspace_formatMessage(nonAuthority, value), value), null);
}
var defaultSelected = -1;
if (selectedByChoices >= 0)
defaultSelected = selectedByChoices;
else if (selectedByValue >= 0)
defaultSelected = selectedByValue;
else if (select.options.length == 1)
defaultSelected = 0;
// load default-selected value
if (defaultSelected >= 0)
{
select.options[defaultSelected].defaultSelected = true;
var so = select.options[defaultSelected];
if (isName)
{
form.elements['text1'].value = lastNameOf(so.value);
form.elements['text2'].value = firstNameOf(so.value);
}
else
form.elements['text1'].value = so.value;
}
// turn off spinner
if (indicator != null)
indicator.style.display = "none";
// "results" status line
var statLast = nextStart + (isClosed ? 2 : 1);
form.statline.innerHTML =
dspace_formatMessage(form.statline_template,
oldStart+1, statLast, Math.max(lastTotal,statLast), value);
}
});
}
// handler for change event on choice selector - load new values
function DSpaceChoicesSelectOnChange ()
{
// "this" is the window,
var form = document.getElementById('aspect_general_ChoiceLookupTransformer_div_lookup');
var select = form.elements['chooser'];
var so = select.options[select.selectedIndex];
var isName = form.elements['paramIsName'].value == 'true';
if (isName)
{
form.elements['text1'].value = lastNameOf(so.value);
form.elements['text2'].value = firstNameOf(so.value);
}
else
form.elements['text1'].value = so.value;
}
// handler for lookup popup's accept (or add) button
// stuff values back to calling page, force an add if necessary, and close.
function DSpaceChoicesAcceptOnClick ()
{
var select = this.form.elements['chooser'];
var isName = this.form.elements['paramIsName'].value == 'true';
var isRepeating = this.form.elements['paramIsRepeating'].value == 'true';
var valueInput = this.form.elements['paramValueInput'].value;
var authorityInput = this.form.elements['paramAuthorityInput'].value;
var formID = this.form.elements['paramFormID'].value;
var confIndicatorID = this.form.elements['paramConfIndicatorID'] == null?null:this.form.elements['paramConfIndicatorID'].value;
// default the authority input if not supplied.
if (authorityInput.length == 0)
authorityInput = dspace_makeFieldInput(valueInput,'_authority');
// always stuff text fields back into caller's value input(s)
if (valueInput.length > 0)
{
var of = window.opener.document.getElementById(formID);
if (isName)
{
of.elements[dspace_makeFieldInput(valueInput,'_last')].value = this.form.elements['text1'].value;
of.elements[dspace_makeFieldInput(valueInput,'_first')].value = this.form.elements['text2'].value;
}
else
of.elements[valueInput].value = this.form.elements['text1'].value;
if (authorityInput.length > 0 && of.elements[authorityInput] != null)
{
// conf input is auth input, substitute '_confidence' for '_authority'
// if conf fieldname is FIELD_confidence_NUMBER, then '_authority_' => '_confidence_'
var confInput = "";
var ci = authorityInput.lastIndexOf("_authority_");
if (ci < 0)
confInput = authorityInput.substring(0, authorityInput.length-10)+'_confidence';
else
confInput = authorityInput.substring(0, ci)+"_confidence_"+authorityInput.substring(ci+11);
// DEBUG:
// window.alert('Setting fields auth="'+authorityInput+'", conf="'+confInput+'"');
var authValue = null;
if (select.selectedIndex >= 0 && select.options[select.selectedIndex].authority != null)
{
authValue = select.options[select.selectedIndex].authority;
of.elements[authorityInput].value = authValue;
}
if (of.elements[confInput] != null)
of.elements[confInput].value = 'accepted';
// make indicator blank if no authority value
DSpaceUpdateConfidence(window.opener.document, confIndicatorID,
authValue == null || authValue == '' ? 'blank' :'accepted');
}
// force the submit button -- if there is an "add"
if (isRepeating)
{
var add = of.elements["submit_"+valueInput+"_add"];
if (add != null)
add.click();
else
alert('Sanity check: Cannot find button named "submit_'+valueInput+'_add"');
}
}
window.close();
return false;
}
// handler for lookup popup's more button
function DSpaceChoicesMoreOnClick ()
{
DSpaceChoicesLoad(this.form);
}
// handler for lookup popup's cancel button
function DSpaceChoicesCancelOnClick ()
{
window.close();
return false;
}
// -------------------- Utilities
// DSpace person-name conventions, see DCPersonName
function makePersonName(lastName, firstName)
{
return (firstName == null || firstName.length == 0) ? lastName :
lastName+", "+firstName;
}
// DSpace person-name conventions, see DCPersonName
function firstNameOf(personName)
{
var comma = personName.indexOf(",");
return (comma < 0) ? "" : stringTrim(personName.substring(comma+1));
}
// DSpace person-name conventions, see DCPersonName
function lastNameOf(personName)
{
var comma = personName.indexOf(",");
return stringTrim((comma < 0) ? personName : personName.substring(0, comma));
}
// replicate java String.trim()
function stringTrim(str)
{
var start = 0;
var end = str.length;
for (; str.charAt(start) == ' '&& start < end; ++start) ;
for (; end > start && str.charAt(end-1) == ' '; --end) ;
return str.slice(start, end);
}
// format utility - replace @1@, @2@ etc with args 1, 2, 3..
// NOTE params MUST be monotonically increasing
// NOTE we can't use "{1}" like the i18n catalog because it elides them!!
// ...UNLESS maybe it were to be fixed not to when no params...
function dspace_formatMessage()
{
var template = dspace_formatMessage.arguments[0];
var i;
for (i = 1; i < arguments.length; ++i)
{
var pattern = '@'+i+'@';
if (template.search(pattern) >= 0)
template = template.replace(pattern, dspace_formatMessage.arguments[i]);
}
return template;
}
// utility to make sub-field name of input field, e.g. _last, _first, _auth..
// if name ends with _1, _2 etc, put sub-name BEFORE the number
function dspace_makeFieldInput(name, sub)
{
var i = name.search("_[0-9]+$");
if (i < 0)
return name+sub;
else
return name.substr(0, i)+sub+name.substr(i);
}
// update the class value of confidence-indicating element
function DSpaceUpdateConfidence(doc, confIndicatorID, newValue)
{
// sanity checks - need valid ID and a real DOM object
if (confIndicatorID == null || confIndicatorID == "")
return;
var confElt = doc.getElementById(confIndicatorID);
if (confElt == null)
return;
// add or update CSS class with new confidence value, e.g. "cf-accepted".
if (confElt.className == null)
confElt.className = "cf-"+newValue;
else
{
var classes = confElt.className.split(" ");
var newClasses = "";
var found = false;
for (var i = 0; i < classes.length; ++i)
{
if (classes[i].match('^cf-[a-zA-Z0-9]+$'))
{
newClasses += "cf-"+newValue+" ";
found = true;
}
else
newClasses += classes[i]+" ";
}
if (!found)
newClasses += "cf-"+newValue+" ";
confElt.className = newClasses;
}
}
// respond to "onchanged" event on authority input field
// set confidence to 'accepted' if authority was changed by user.
function DSpaceAuthorityOnChange(self, confValueID, confIndicatorID)
{
var confidence = 'accepted';
if (confValueID != null && confValueID != '')
{
var confValueField = document.getElementById(confValueID);
if (confValueField != null)
confValueField.value = confidence;
}
DSpaceUpdateConfidence(document, confIndicatorID, confidence)
return false;
}
// respond to click on the authority-value lock button in Edit Item Metadata:
// "button" is bound to the image input for the lock button, "this"
function DSpaceToggleAuthorityLock(button, authInputID)
{
// sanity checks - need valid ID and a real DOM object
if (authInputID == null || authInputID == '')
return false;
var authInput = document.getElementById(authInputID);
if (authInput == null)
return false;
// look for is-locked or is-unlocked in class list:
var classes = button.className.split(' ');
var newClass = '';
var newLocked = false;
var found = false;
for (var i = 0; i < classes.length; ++i)
{
if (classes[i] == 'is-locked')
{
newLocked = false;
found = true;
}
else if (classes[i] == 'is-unlocked')
{
newLocked = true;
found = true;
}
else
newClass += classes[i]+' ';
}
if (!found)
return false;
// toggle the image, and set readability
button.className = newClass + (newLocked ? 'is-locked' : 'is-unlocked') + ' ';
authInput.readOnly = newLocked;
return false;
}
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// Client-side scripting to support DSpace Choice Control
// IMPORTANT NOTE:
// This version of choice-support.js has been rewritten to use jQuery
// instead of prototype & scriptaculous. The goal was not to change the
// way it works in any way, just to get the prototype dependency out.
// @Author Art Lowel (art.lowel at atmire.com)
// Entry points:
// 1. DSpaceAutocomplete -- add autocomplete (suggest) to an input field
//
// 2. DSpaceChoiceLookup -- create popup window with authority choices
//
// @Author: Larry Stone <lcs@hulmail.harvard.edu>
// $Revision $
// -------------------- support for Autocomplete (Suggest)
// Autocomplete utility:
// Arguments:
// formID -- ID attribute of form tag
// args properties:
// metadataField -- metadata field e.g. dc_contributor_author
// inputName -- input field name for text input, or base of "Name" pair
// authorityName -- input field name in which to set authority
// containerID -- ID attribute of DIV to hold the menu objects
// indicatorID -- ID attribute of element to use as a "loading" indicator
// confidenceIndicatorID -- ID of element on which to set confidence
// confidenceName - NAME of confidence input (not ID)
// contextPath -- URL path prefix (i.e. webapp contextPath) for DSpace.
// collection -- db ID of dspace collection to serve as context
// isClosed -- true if authority value is required, false = non-auth allowed
// XXX Can't really enforce "isClosed=true" with autocomplete, user can type anything
//
// NOTE: Successful autocomplete always sets confidence to 'accepted' since
// authority value (if any) *was* chosen interactively by a human.
function DSpaceSetupAutocomplete(formID, args) {
$(function() {
if (args.authorityName == null)
args.authorityName = dspace_makeFieldInput(args.inputName, '_authority');
var form = $('#' + formID)[0];
var inputID = form.elements[args.inputName].id;
var authorityID = null;
if (form.elements[args.authorityName] != null)
authorityID = form.elements[args.authorityName].id;
// AJAX menu source, can add &query=TEXT
var choiceURL = args.contextPath + "/choices/" + args.metadataField;
var collID = args.collection == null ? -1 : args.collection;
choiceURL += '?collection=' + collID;
var ac = $('#' + inputID);
ac.autocomplete({
source: function(request, response) {
var reqUrl = choiceURL;
if(request && request.term) {
reqUrl += "&query=" + request.term;
}
$.get(reqUrl, function(xmldata) {
var options = [];
var authorities = [];
$(xmldata).find('Choice').each(function() {
// get value
var value = $(this).attr('value') ? $(this).attr('value') : null;
// get label, if empty set it to value
var label = $(this).text() ? $(this).text() : value;
// if value was empty but label was provided, set value to label
if(!value) {
value = label;
}
// if at this point either value or label == null, this means none of both were set and we shouldn't add it to the list of options
if (label != null) {
options.push({
label: label,
value: value
});
authorities['label: ' + label + ', value: ' + value] = $(this).attr('authority') ? $(this).attr('authority') : value;
}
});
ac.data('authorities',authorities);
response(options);
});
},
select: function(event, ui) {
// NOTE: lookup element late because it might not be in DOM
// at the time we evaluate the function..
// var authInput = document.getElementById(authorityID);
// var authValue = li == null ? "" : li.getAttribute("authority");
var authInput = $('#' + authorityID);
if(authInput.length > 0) {
authInput = authInput[0];
}
var authorities = ac.data('authorities');
var authValue = authorities['label: ' + ui.item.label + ', value: ' + ui.item.value];
if (authInput != null) {
authInput.value = authValue;
// update confidence input's value too if available.
if (args.confidenceName != null) {
var confInput = authInput.form.elements[args.confidenceName];
if (confInput != null)
confInput.value = 'accepted';
}
}
// make indicator blank if no authority value
DSpaceUpdateConfidence(document, args.confidenceIndicatorID,
authValue == null || authValue == '' ? 'blank' : 'accepted');
}
});
});
}
// -------------------- support for Lookup Popup
// Create popup window with authority choices for value of an input field.
// This is intended to be called by onClick of a "Lookup" or "Add" button.
function DSpaceChoiceLookup(url, field, formID, valueInput, authInput,
confIndicatorID, collectionID, isName, isRepeating) {
// fill in URL
url += '?field=' + field + '&formID=' + formID + '&valueInput=' + valueInput +
'&authorityInput=' + authInput + '&collection=' + collectionID +
'&isName=' + isName + '&isRepeating=' + isRepeating + '&confIndicatorID=' + confIndicatorID;
// primary input field - for positioning popup.
var inputFieldName = isName ? dspace_makeFieldInput(valueInput, '_last') : valueInput;
var inputField = $('input[name = ' + inputFieldName + ']');
// sometimes a textarea is used, in which case the previous jQuery search delivered no results...
if(inputField.length == 0) {
// so search for a textarea
inputField = $('textarea[name = ' + inputFieldName + ']');
}
var cOffset = 0;
if (inputField != null)
cOffset = inputField.offset();
var width = 600; // XXX guesses! these should be params, or configured..
var height = 470;
var left;
var top;
if (window.screenX == null) {
left = window.screenLeft + cOffset.left - (width / 2);
top = window.screenTop + cOffset.top - (height / 2);
} else {
left = window.screenX + cOffset.left - (width / 2);
top = window.screenY + cOffset.top - (height / 2);
}
if (left < 0) left = 0;
if (top < 0) top = 0;
var pw = window.open(url, 'ignoreme',
'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top +
',toolbar=no,menubar=no,location=no,status=no,resizable');
if (window.focus) pw.focus();
return false;
}
// Run this as the Lookup page is loaded to initialize DOM objects, load choices
function DSpaceChoicesSetup(form) {
// find the "LEGEND" in fieldset, which acts as page title,
var legend = $('#aspect_general_ChoiceLookupTransformer_list_choicesList :header:first');
//save the template as a jQuery data field
legend.data('template', legend.html());
legend.html("Loading...");
DSpaceChoicesLoad(form);
}
// populate the "select" with options from ajax request
// stash some parameters as properties of the "select" so we can add to
// the last start index to query for next set of results.
function DSpaceChoicesLoad(form) {
var field = $('*[name = paramField]').val();
var value = $('*[name = paramValue]').val();
if (!value)
value = '';
var start = $('*[name = paramStart]').val();
var limit = $('*[name = paramLimit]').val();
var formID = $('*[name = paramFormID]').val();
var collID = $('*[name = paramCollection]').val();
var isName = $('*[name = paramIsName]').val() == 'true';
var isRepeating = $('*[name = paramIsRepeating]').val() == 'true';
var isClosed = $('*[name = paramIsClosed]').val() == 'true';
var contextPath = $('*[name = contextPath]').val();
var fail = $('*[name = paramFail]').val();
var valueInput = $('*[name = paramValueInput]').val();
var nonAuthority = "";
var pNAInput = $('*[name = paramNonAuthority]');
if (pNAInput.length > 0)
nonAuthority = pNAInput.val();
// get value from form inputs in opener if not explicitly supplied
if (value.length == 0) {
var of = $(window.opener.document).find('#' + formID);
if (isName)
value = makePersonName(of.find('*[name = ' + dspace_makeFieldInput(valueInput, '_last') + ']').val(),
of.find('*[name = ' + dspace_makeFieldInput(valueInput, '_first') + ']').val());
else
value = of.find('*[name = ' + valueInput + ']').val();
// if this is a repeating input, clear the source value so that e.g.
// clicking "Next" on a submit-describe page will not *add* the proposed
// lookup text as a metadata value:
if (isRepeating) {
if (isName) {
of.find('*[name = ' + dspace_makeFieldInput(valueInput, '_last') + ']').val('');
of.find('*[name = ' + dspace_makeFieldInput(valueInput, '_first') + ']').val('');
}
else
of.find('*[name = ' + valueInput + ']').val(null);
}
}
// start spinner
var indicator = $('#lookup_indicator_id');
indicator.show('fast');
$(window).ajaxError(function(e, xhr, settings, exception) {
window.alert(fail + " Exception=" + e);
if (indicator != null) indicator.style.display = "none";
});
$.ajax({
url: contextPath + "/choices/" + field,
type: "GET",
data: {query: value, collection: collID,
start: start, limit: limit},
error: function() {
window.alert(fail + " HTTP error resonse");
if (indicator != null) indicator.style.display = "none";
},
success: function(data) {
var Choices = $(data).find('Choices');
var err = Choices.attr('error');
if (err != null && err == 'true')
window.alert(fail + " Server indicates error in response.");
var opts = Choices.find('Choice');
// update range message and update 'more' button
var oldStart = 1 * Choices.attr('start');
var nextStart = oldStart + opts.length;
var lastTotal = Choices.attr('total');
var resultMore = Choices.attr('more');
$('*[name = more]').attr('disabled', !(resultMore != null && resultMore == 'true'));
$('*[name = paramStart]').val(nextStart);
// clear select first
var select = $('select[name = chooser]:first');
select.find('option:not(:last)').remove();
var lastOption = select.find('option:last');
var selectedByValue = -1; // select by value match
var selectedByChoices = -1; // Choice says its selected
$.each(opts, function(index) {
// debugger;
var current = $(this);
if (current.attr('value') == value)
selectedByValue = index;
if(current.attr('selected') != undefined)
selectedByChoices = index;
var newOption = $('<option value="' + current.attr('value') + '">' + current.text() + '</option>');
newOption.data('authority', current.attr('authority'));
if (lastOption.length > 0)
lastOption.insertBefore(newOption);
else
select.append(newOption);
});
// add non-authority option if needed.
if (!isClosed) {
select.append(new Option(dspace_formatMessage(nonAuthority, value), value), null);
}
var defaultSelected = -1;
if (selectedByChoices >= 0)
defaultSelected = selectedByChoices;
else if (selectedByValue >= 0)
defaultSelected = selectedByValue;
else if (select[0].options.length == 1)
defaultSelected = 0;
// load default-selected value
if (defaultSelected >= 0) {
select[0].options[defaultSelected].defaultSelected = true;
var so = select[0].options[defaultSelected];
if (isName) {
$('*[name = text1]').val(lastNameOf(so.value));
$('*[name = text2]').val(firstNameOf(so.value));
}
else
$('*[name = text1]').val(so.value);
}
// turn off spinner
indicator.hide('fast');
// "results" status line
var statLast = nextStart + (isClosed ? 2 : 1);
var legend = $('#aspect_general_ChoiceLookupTransformer_list_choicesList :header:first');
legend.html(dspace_formatMessage(legend.data('template'),
oldStart + 1, statLast, Math.max(lastTotal, statLast), value));
}
});
}
// handler for change event on choice selector - load new values
function DSpaceChoicesSelectOnChange() {
// "this" is the window,
var form = $('#aspect_general_ChoiceLookupTransformer_div_lookup');
var select = form.find('*[name = chooser]');
var isName = form.find('*[name = paramIsName]').val() == 'true';
var selectedValue = select.val();
if (isName) {
form.find('*[name = text1]').val(lastNameOf(selectedValue));
form.find('*[name = text2]').val(firstNameOf(selectedValue));
}
else
form.find('*[name = text1]').val(selectedValue);
}
// handler for lookup popup's accept (or add) button
// stuff values back to calling page, force an add if necessary, and close.
function DSpaceChoicesAcceptOnClick() {
var select = $('*[name = chooser]');
var isName = $('*[name = paramIsName]').val() == 'true';
var isRepeating = $('*[name = paramIsRepeating]').val() == 'true';
var valueInput = $('*[name = paramValueInput]').val();
var authorityInput = $('*[name = paramAuthorityInput]').val();
var formID = $('*[name = paramFormID]').val();
var confIndicatorID = $('*[name = paramConfIndicatorID]').length = 0 ? null : $('*[name = paramConfIndicatorID]').val();
// default the authority input if not supplied.
if (authorityInput.length == 0)
authorityInput = dspace_makeFieldInput(valueInput, '_authority');
// always stuff text fields back into caller's value input(s)
if (valueInput.length > 0) {
var of = $(window.opener.document).find('#' + formID);
if (isName) {
of.find('*[name = ' + dspace_makeFieldInput(valueInput, '_last') + ']').val($('*[name = text1]').val());
of.find('*[name = ' + dspace_makeFieldInput(valueInput, '_first') + ']').val($('*[name = text2]').val());
}
else
of.find('*[name = ' + valueInput + ']').val($('*[name = text1]').val());
if (authorityInput.length > 0 && of.find('*[name = ' + authorityInput + ']').length > 0) {
// conf input is auth input, substitute '_confidence' for '_authority'
// if conf fieldname is FIELD_confidence_NUMBER, then '_authority_' => '_confidence_'
var confInput = "";
var ci = authorityInput.lastIndexOf("_authority_");
if (ci < 0)
confInput = authorityInput.substring(0, authorityInput.length - 10) + '_confidence';
else
confInput = authorityInput.substring(0, ci) + "_confidence_" + authorityInput.substring(ci + 11);
// DEBUG:
// window.alert('Setting fields auth="'+authorityInput+'", conf="'+confInput+'"');
var authValue = null;
var selectedOption = select.find(':selected');
if (selectedOption.length >= 0 && selectedOption.data('authority') != null) {
of.find('*[name = ' + authorityInput + ']').val(selectedOption.data('authority'));
}
of.find('*[name = ' + confInput + ']').val('accepted');
// make indicator blank if no authority value
DSpaceUpdateConfidence(window.opener.document, confIndicatorID,
authValue == null || authValue == '' ? 'blank' : 'accepted');
}
// force the submit button -- if there is an "add"
if (isRepeating) {
var add = of.find('*[name = submit_' + valueInput + '_add]');
if (add.length > 0)
add.click();
else
alert('Sanity check: Cannot find button named "submit_' + valueInput + '_add"');
}
}
window.close();
return false;
}
// handler for lookup popup's more button
function DSpaceChoicesMoreOnClick() {
DSpaceChoicesLoad(this.form);
}
// handler for lookup popup's cancel button
function DSpaceChoicesCancelOnClick() {
window.close();
return false;
}
// -------------------- Utilities
// DSpace person-name conventions, see DCPersonName
function makePersonName(lastName, firstName) {
return (firstName == null || firstName.length == 0) ? lastName :
lastName + ", " + firstName;
}
// DSpace person-name conventions, see DCPersonName
function firstNameOf(personName) {
var comma = personName.indexOf(",");
return (comma < 0) ? "" : stringTrim(personName.substring(comma + 1));
}
// DSpace person-name conventions, see DCPersonName
function lastNameOf(personName) {
var comma = personName.indexOf(",");
return stringTrim((comma < 0) ? personName : personName.substring(0, comma));
}
// replicate java String.trim()
function stringTrim(str) {
var start = 0;
var end = str.length;
for (; str.charAt(start) == ' ' && start < end; ++start) ;
for (; end > start && str.charAt(end - 1) == ' '; --end) ;
return str.slice(start, end);
}
// format utility - replace @1@, @2@ etc with args 1, 2, 3..
// NOTE params MUST be monotonically increasing
// NOTE we can't use "{1}" like the i18n catalog because it elides them!!
// ...UNLESS maybe it were to be fixed not to when no params...
function dspace_formatMessage() {
var template = dspace_formatMessage.arguments[0];
var i;
for (i = 1; i < arguments.length; ++i) {
var pattern = '@' + i + '@';
if (template.search(pattern) >= 0)
{
var value = dspace_formatMessage.arguments[i];
if (value == undefined)
value = '';
template = template.replace(pattern, value);
}
}
return template;
}
// utility to make sub-field name of input field, e.g. _last, _first, _auth..
// if name ends with _1, _2 etc, put sub-name BEFORE the number
function dspace_makeFieldInput(name, sub) {
var i = name.search("_[0-9]+$");
if (i < 0)
return name + sub;
else
return name.substr(0, i) + sub + name.substr(i);
}
// update the class value of confidence-indicating element
function DSpaceUpdateConfidence(doc, confIndicatorID, newValue) {
// sanity checks - need valid ID and a real DOM object
if (confIndicatorID == null || confIndicatorID == "")
return;
var confElt = doc.getElementById(confIndicatorID);
if (confElt == null)
return;
// add or update CSS class with new confidence value, e.g. "cf-accepted".
if (confElt.className == null)
confElt.className = "cf-" + newValue;
else {
var classes = confElt.className.split(" ");
var newClasses = "";
var found = false;
for (var i = 0; i < classes.length; ++i) {
if (classes[i].match('^cf-[a-zA-Z0-9]+$')) {
newClasses += "cf-" + newValue + " ";
found = true;
}
else
newClasses += classes[i] + " ";
}
if (!found)
newClasses += "cf-" + newValue + " ";
confElt.className = newClasses;
}
}
// respond to "onchanged" event on authority input field
// set confidence to 'accepted' if authority was changed by user.
function DSpaceAuthorityOnChange(self, confValueID, confIndicatorID) {
var confidence = 'accepted';
if (confValueID != null && confValueID != '') {
var confValueField = document.getElementById(confValueID);
if (confValueField != null)
confValueField.value = confidence;
}
DSpaceUpdateConfidence(document, confIndicatorID, confidence);
return false;
}
// respond to click on the authority-value lock button in Edit Item Metadata:
// "button" is bound to the image input for the lock button, "this"
function DSpaceToggleAuthorityLock(button, authInputID) {
// sanity checks - need valid ID and a real DOM object
if (authInputID == null || authInputID == '')
return false;
var authInput = document.getElementById(authInputID);
if (authInput == null)
return false;
// look for is-locked or is-unlocked in class list:
var classes = button.className.split(' ');
var newClass = '';
var newLocked = false;
var found = false;
for (var i = 0; i < classes.length; ++i) {
if (classes[i] == 'is-locked') {
newLocked = false;
found = true;
}
else if (classes[i] == 'is-unlocked') {
newLocked = true;
found = true;
}
else
newClass += classes[i] + ' ';
}
if (!found)
return false;
// toggle the image, and set readability
button.className = newClass + (newLocked ? 'is-locked' : 'is-unlocked') + ' ';
authInput.readOnly = newLocked;
return false;
}
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
/**
* DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>.
* Author: Drew Diller
* Email: drew.diller@gmail.com
* URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.8a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
**/
/*
PLEASE READ:
Absolutely everything in this script is SILLY. I know this. IE's rendering of certain pixels doesn't make sense, so neither does this code!
*/
var DD_belatedPNG = {
ns: 'DD_belatedPNG',
imgSize: {},
delay: 10,
nodesFixed: 0,
createVmlNameSpace: function () { /* enable VML */
if (document.namespaces && !document.namespaces[this.ns]) {
document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
}
},
createVmlStyleSheet: function () { /* style VML, enable behaviors */
/*
Just in case lots of other developers have added
lots of other stylesheets using document.createStyleSheet
and hit the 31-limit mark, let's not use that method!
further reading: http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx
*/
var screenStyleSheet, printStyleSheet;
screenStyleSheet = document.createElement('style');
screenStyleSheet.setAttribute('media', 'screen');
document.documentElement.firstChild.insertBefore(screenStyleSheet, document.documentElement.firstChild.firstChild);
if (screenStyleSheet.styleSheet) {
screenStyleSheet = screenStyleSheet.styleSheet;
screenStyleSheet.addRule(this.ns + '\\:*', '{behavior:url(#default#VML)}');
screenStyleSheet.addRule(this.ns + '\\:shape', 'position:absolute;');
screenStyleSheet.addRule('img.' + this.ns + '_sizeFinder', 'behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;'); /* large negative top value for avoiding vertical scrollbars for large images, suggested by James O'Brien, http://www.thanatopsic.org/hendrik/ */
this.screenStyleSheet = screenStyleSheet;
/* Add a print-media stylesheet, for preventing VML artifacts from showing up in print (including preview). */
/* Thanks to R�mi Pr�vost for automating this! */
printStyleSheet = document.createElement('style');
printStyleSheet.setAttribute('media', 'print');
document.documentElement.firstChild.insertBefore(printStyleSheet, document.documentElement.firstChild.firstChild);
printStyleSheet = printStyleSheet.styleSheet;
printStyleSheet.addRule(this.ns + '\\:*', '{display: none !important;}');
printStyleSheet.addRule('img.' + this.ns + '_sizeFinder', '{display: none !important;}');
}
},
readPropertyChange: function () {
var el, display, v;
el = event.srcElement;
if (!el.vmlInitiated) {
return;
}
if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
DD_belatedPNG.applyVML(el);
}
if (event.propertyName == 'style.display') {
display = (el.currentStyle.display == 'none') ? 'none' : 'block';
for (v in el.vml) {
if (el.vml.hasOwnProperty(v)) {
el.vml[v].shape.style.display = display;
}
}
}
if (event.propertyName.search('filter') != -1) {
DD_belatedPNG.vmlOpacity(el);
}
},
vmlOpacity: function (el) {
if (el.currentStyle.filter.search('lpha') != -1) {
var trans = el.currentStyle.filter;
trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
el.vml.image.fill.opacity = trans; /* complete guesswork */
}
},
handlePseudoHover: function (el) {
setTimeout(function () { /* wouldn't work as intended without setTimeout */
DD_belatedPNG.applyVML(el);
}, 1);
},
/**
* This is the method to use in a document.
* @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
**/
fix: function (selector) {
if (this.screenStyleSheet) {
var selectors, i;
selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
for (i=0; i<selectors.length; i++) {
this.screenStyleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(this))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
}
}
},
applyVML: function (el) {
el.runtimeStyle.cssText = '';
this.vmlFill(el);
this.vmlOffsets(el);
this.vmlOpacity(el);
if (el.isImg) {
this.copyImageBorders(el);
}
},
attachHandlers: function (el) {
var self, handlers, handler, moreForAs, a, h;
self = this;
handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
if (el.nodeName == 'A') {
moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
for (a in moreForAs) {
if (moreForAs.hasOwnProperty(a)) {
handlers[a] = moreForAs[a];
}
}
}
for (h in handlers) {
if (handlers.hasOwnProperty(h)) {
handler = function () {
self[handlers[h]](el);
};
el.attachEvent('on' + h, handler);
}
}
el.attachEvent('onpropertychange', this.readPropertyChange);
},
giveLayout: function (el) {
el.style.zoom = 1;
if (el.currentStyle.position == 'static') {
el.style.position = 'relative';
}
},
copyImageBorders: function (el) {
var styles, s;
styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
for (s in styles) {
if (styles.hasOwnProperty(s)) {
el.vml.color.shape.style[s] = el.currentStyle[s];
}
}
},
vmlFill: function (el) {
if (!el.currentStyle) {
return;
} else {
var elStyle, noImg, lib, v, img, imgLoaded;
elStyle = el.currentStyle;
}
for (v in el.vml) {
if (el.vml.hasOwnProperty(v)) {
el.vml[v].shape.style.zIndex = elStyle.zIndex;
}
}
el.runtimeStyle.backgroundColor = '';
el.runtimeStyle.backgroundImage = '';
noImg = true;
if (elStyle.backgroundImage != 'none' || el.isImg) {
if (!el.isImg) {
el.vmlBg = elStyle.backgroundImage;
el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
}
else {
el.vmlBg = el.src;
}
lib = this;
if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
img = document.createElement('img');
lib.imgSize[el.vmlBg] = img;
img.className = lib.ns + '_sizeFinder';
img.runtimeStyle.cssText = 'behavior:none; position:absolute; left:-10000px; top:-10000px; border:none; margin:0; padding:0;'; /* make sure to set behavior to none to prevent accidental matching of the helper elements! */
imgLoaded = function () {
this.width = this.offsetWidth; /* weird cache-busting requirement! */
this.height = this.offsetHeight;
lib.vmlOffsets(el);
};
img.attachEvent('onload', imgLoaded);
img.src = el.vmlBg;
img.removeAttribute('width');
img.removeAttribute('height');
document.body.insertBefore(img, document.body.firstChild);
}
el.vml.image.fill.src = el.vmlBg;
noImg = false;
}
el.vml.image.fill.on = !noImg;
el.vml.image.fill.color = 'none';
el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
el.runtimeStyle.backgroundImage = 'none';
el.runtimeStyle.backgroundColor = 'transparent';
},
/* IE can't figure out what do when the offsetLeft and the clientLeft add up to 1, and the VML ends up getting fuzzy... so we have to push/enlarge things by 1 pixel and then clip off the excess */
vmlOffsets: function (el) {
var thisStyle, size, fudge, makeVisible, bg, bgR, dC, altC, b, c, v;
thisStyle = el.currentStyle;
size = {'W':el.clientWidth+1, 'H':el.clientHeight+1, 'w':this.imgSize[el.vmlBg].width, 'h':this.imgSize[el.vmlBg].height, 'L':el.offsetLeft, 'T':el.offsetTop, 'bLW':el.clientLeft, 'bTW':el.clientTop};
fudge = (size.L + size.bLW == 1) ? 1 : 0;
/* vml shape, left, top, width, height, origin */
makeVisible = function (vml, l, t, w, h, o) {
vml.coordsize = w+','+h;
vml.coordorigin = o+','+o;
vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
vml.style.width = w + 'px';
vml.style.height = h + 'px';
vml.style.left = l + 'px';
vml.style.top = t + 'px';
};
makeVisible(el.vml.color.shape, (size.L + (el.isImg ? 0 : size.bLW)), (size.T + (el.isImg ? 0 : size.bTW)), (size.W-1), (size.H-1), 0);
makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1 );
bg = {'X':0, 'Y':0};
if (el.isImg) {
bg.X = parseInt(thisStyle.paddingLeft, 10) + 1;
bg.Y = parseInt(thisStyle.paddingTop, 10) + 1;
}
else {
for (b in bg) {
if (bg.hasOwnProperty(b)) {
this.figurePercentage(bg, size, b, thisStyle['backgroundPosition'+b]);
}
}
}
el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
bgR = thisStyle.backgroundRepeat;
dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
if (bgR != 'repeat' || el.isImg) {
c = {'T':(bg.Y), 'R':(bg.X+size.w), 'B':(bg.Y+size.h), 'L':(bg.X)}; /* these are defaults for no-repeat - clips down to the image location */
if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
v = bgR.split('repeat-')[1].toUpperCase();
c[altC[v].b1] = 1;
c[altC[v].b2] = size[altC[v].d];
}
if (c.B > size.H) {
c.B = size.H;
}
el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
}
else {
el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
}
},
figurePercentage: function (bg, size, axis, position) {
var horizontal, fraction;
fraction = true;
horizontal = (axis == 'X');
switch(position) {
case 'left':
case 'top':
bg[axis] = 0;
break;
case 'center':
bg[axis] = 0.5;
break;
case 'right':
case 'bottom':
bg[axis] = 1;
break;
default:
if (position.search('%') != -1) {
bg[axis] = parseInt(position, 10) / 100;
}
else {
fraction = false;
}
}
bg[axis] = Math.ceil( fraction ? ( (size[horizontal?'W': 'H'] * bg[axis]) - (size[horizontal?'w': 'h'] * bg[axis]) ) : parseInt(position, 10) );
if (bg[axis] % 2 === 0) {
bg[axis]++;
}
return bg[axis];
},
fixPng: function (el) {
el.style.behavior = 'none';
var lib, els, nodeStr, v, e;
if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
return;
}
el.isImg = false;
if (el.nodeName == 'IMG') {
if(el.src.toLowerCase().search(/\.png(\?\d+)?$/) != -1) {
el.isImg = true;
el.style.visibility = 'hidden';
}
else {
return;
}
}
else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
return;
}
lib = DD_belatedPNG;
el.vml = {color: {}, image: {}};
els = {shape: {}, fill: {}};
for (v in el.vml) {
if (el.vml.hasOwnProperty(v)) {
for (e in els) {
if (els.hasOwnProperty(e)) {
nodeStr = lib.ns + ':' + e;
el.vml[v][e] = document.createElement(nodeStr);
}
}
el.vml[v].shape.stroked = false;
el.vml[v].shape.appendChild(el.vml[v].fill);
el.parentNode.insertBefore(el.vml[v].shape, el);
}
}
el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
/* If the height and width attributes are set, then scale to size, if not, display as per usual */
if (el.height && el.width){el.vml.image.fill.type = 'frame';} else {el.vml.image.fill.type = 'tile';}
el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
lib.attachHandlers(el);
lib.giveLayout(el);
lib.giveLayout(el.offsetParent);
el.vmlInitiated = true;
lib.applyVML(el); /* Render! */
}
};
try {
document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
} catch(r) {}
DD_belatedPNG.createVmlNameSpace();
DD_belatedPNG.createVmlStyleSheet(); | JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// jQuery code for the Kubrick theme.
//
// This applies some style that couldn't be achieved with css due to
// poor browser implementations of the W3C standard. Also, this provides
// the interactive sliders that hide and reveal metadata for specific
// items when browsing lists.
$(document).ready(function(){
//alert("Render mode: "+ document.compatMode);
//First, some css that couldn't be achieved with css selectors
$("table:not(.ds-includeSet-metadata-table) tr td:has(span[class=bold])").css({ textAlign:"right", verticalAlign:"top" });
$("table.ds-includeSet-metadata-table tr td:has(span[class=bold])").css({ textAlign:"left", verticalAlign:"top" });
$("fieldset#aspect_submission_StepTransformer_list_submit-describe ol li.odd div.ds-form-content input#aspect_submission_StepTransformer_field_dc_subject ~ input.ds-button-field").css({display: "inline"});
//The metadata sliders for ds-artifact-item-with-popup's
$("div.item_metadata_more").toggle(function(){
$(this).children(".item_more_text").hide();
$(this).children(".item_less_text").show();
$(this).next().slideDown();
},function(){
$(this).children(".item_more_text").show();
$(this).children(".item_less_text").hide();
$(this).next().slideUp();
});
}); | JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// $Id$
/**
* @see http://wiki.apache.org/solr/SolJSON#JSON_specific_parameters
* @class Manager
* @augments AjaxSolr.AbstractManager
*/
AjaxSolr.Manager = AjaxSolr.AbstractManager.extend(
/** @lends AjaxSolr.Manager.prototype */
{
executeRequest: function (servlet) {
var self = this;
if (this.proxyUrl) {
jQuery.post(this.proxyUrl, { query: this.store.string() }, function (data) { self.handleResponse(data); }, 'json');
}
else {
// jQuery.getJSON(this.solrUrl + servlet + '?' + this.store.string() + '&wt=json&json.wrf=?', {}, function (data) { self.handleResponse(data); });
jQuery.getJSON(this.solrUrl + '?' + this.store.string() + '&wt=json&json.wrf=?', {}, function (data) { self.handleResponse(data); });
}
}
});
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
(function ($) {
AjaxSolr.AutocompleteWidget = AjaxSolr.AbstractFacetWidget.extend({
afterRequest: function () {
$(this.target).find("input[type='text']").val('');
var self = this;
var callback = function (response) {
var list = [];
for (var i = 0; i < self.fields.length; i++) {
var field = self.fields[i];
for (var facet in response.facet_counts.facet_fields[field]) {
list.push({
field: field,
value: facet,
text: facet + ' (' + response.facet_counts.facet_fields[field][facet] + ')'
});
}
}
self.requestSent = false;
$(self.target).find("input[type='text']").autocomplete(list, {
formatItem: function(facet) {
return facet.text;
}
}).result(function(e, facet) {
$(this).val(facet.value);
// self.requestSent = true;
// if (self.manager.store.addByValue('fq', facet.field + ':' + facet.value)) {
// self.manager.doRequest(0);
// }
}).bind('keydown', function(e) {
if (self.requestSent === false && e.which == 13) {
var value = $(this).val();
if (value && self.add(value)) {
self.manager.doRequest(0);
}
}
});
}; // end callback
var params = [ 'q=' + query + '&facet=true&facet.limit=-1&facet.sort=count&facet.mincount=1&json.nl=map' ];
for (var i = 0; i < this.fields.length; i++) {
params.push('facet.field=' + this.fields[i]);
}
var fqs = $("input[name='fq']");
for(var j = 0; j < fqs.length; j ++){
params.push('fq=' + $(fqs[j]).val());
}
// jQuery.getJSON(this.manager.solrUrl + 'select?' + params.join('&') + '&wt=json&json.wrf=?', {}, callback);
jQuery.getJSON(this.manager.solrUrl + '?' + params.join('&') + '&wt=json&json.wrf=?', {}, callback);
}
});
})(jQuery);
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// $Id$
/**
* The ParameterStore, as its name suggests, stores Solr parameters. Widgets
* expose some of these parameters to the user. Whenever the user changes the
* values of these parameters, the state of the application changes. In order to
* allow the user to move back and forth between these states with the browser's
* Back and Forward buttons, and to bookmark these states, each state needs to
* be stored. The easiest method is to store the exposed parameters in the URL
* hash (see the <tt>ParameterHashStore</tt> class). However, you may implement
* your own storage method by extending this class.
*
* <p>For a list of possible parameters, please consult the links below.</p>
*
* @see http://wiki.apache.org/solr/CoreQueryParameters
* @see http://wiki.apache.org/solr/CommonQueryParameters
* @see http://wiki.apache.org/solr/SimpleFacetParameters
* @see http://wiki.apache.org/solr/HighlightingParameters
* @see http://wiki.apache.org/solr/MoreLikeThis
* @see http://wiki.apache.org/solr/SpellCheckComponent
* @see http://wiki.apache.org/solr/StatsComponent
* @see http://wiki.apache.org/solr/TermsComponent
* @see http://wiki.apache.org/solr/TermVectorComponent
* @see http://wiki.apache.org/solr/LocalParams
*
* @param properties A map of fields to set. Refer to the list of public fields.
* @class ParameterStore
*/
AjaxSolr.ParameterStore = AjaxSolr.Class.extend(
/** @lends AjaxSolr.ParameterStore.prototype */
{
/**
* The names of the exposed parameters. Any parameters that your widgets
* expose to the user, directly or indirectly, should be listed here.
*
* @field
* @public
* @type String[]
* @default []
*/
exposed: [],
/**
* The Solr parameters.
*
* @field
* @private
* @type Object
* @default {}
*/
params: {},
/**
* A reference to the parameter store's manager. For internal use only.
*
* @field
* @private
* @type AjaxSolr.AbstractManager
*/
manager: null,
/**
* An abstract hook for child implementations.
*
* <p>This method should do any necessary one-time initializations.</p>
*/
init: function () {},
/**
* Some Solr parameters may be specified multiple times. It is easiest to
* hard-code a list of such parameters. You may change the list by passing
* <code>{ multiple: /pattern/ }</code> as an argument to the constructor of
* this class or one of its children, e.g.:
*
* <p><code>new ParameterStore({ multiple: /pattern/ })</code>
*
* @param {String} name The name of the parameter.
* @returns {Boolean} Whether the parameter may be specified multiple times.
*/
isMultiple: function (name) {
return name.match(/^(?:bf|bq|facet\.date|facet\.date\.other|facet\.field|facet\.query|fq|pf|qf)$/);
},
/**
* Returns a parameter. If the parameter doesn't exist, creates it.
*
* @param {String} name The name of the parameter.
* @returns {AjaxSolr.Parameter|AjaxSolr.Parameter[]} The parameter.
*/
get: function (name) {
if (this.params[name] === undefined) {
var param = new AjaxSolr.Parameter({ name: name });
if (this.isMultiple(name)) {
this.params[name] = [ param ];
}
else {
this.params[name] = param;
}
}
return this.params[name];
},
/**
* If the parameter may be specified multiple times, returns the values of
* all identically-named parameters. If the parameter may be specified only
* once, returns the value of that parameter.
*
* @param {String} name The name of the parameter.
* @returns {String[]|Number[]} The value(s) of the parameter.
*/
values: function (name) {
if (this.params[name] !== undefined) {
if (this.isMultiple(name)) {
var values = [];
for (var i = 0, l = this.params[name].length; i < l; i++) {
values.push(this.params[name][i].val());
}
return values;
}
else {
return [ this.params[name].val() ];
}
}
return [];
},
/**
* If the parameter may be specified multiple times, adds the given parameter
* to the list of identically-named parameters, unless one already exists with
* the same value. If it may be specified only once, replaces the parameter.
*
* @param {String} name The name of the parameter.
* @param {AjaxSolr.Parameter} [param] The parameter.
* @returns {AjaxSolr.Parameter|Boolean} The parameter, or false.
*/
add: function (name, param) {
if (param === undefined) {
param = new AjaxSolr.Parameter({ name: name });
}
if (this.isMultiple(name)) {
if (this.params[name] === undefined) {
this.params[name] = [ param ];
}
else {
if (AjaxSolr.inArray(param.val(), this.values(name)) == -1) {
this.params[name].push(param);
}
else {
return false;
}
}
}
else {
this.params[name] = param;
}
return param;
},
/**
* Deletes a parameter.
*
* @param {String} name The name of the parameter.
* @param {Number} [index] The index of the parameter.
*/
remove: function (name, index) {
if (index === undefined) {
delete this.params[name];
}
else {
this.params[name].splice(index, 1);
if (this.params[name].length == 0) {
delete this.params[name];
}
}
},
/**
* Finds all parameters with matching values.
*
* @param {String} name The name of the parameter.
* @param {String|Number|String[]|Number[]|RegExp} value The value.
* @returns {String|Number[]} The indices of the parameters found.
*/
find: function (name, value) {
if (this.params[name] !== undefined) {
if (this.isMultiple(name)) {
var indices = [];
for (var i = 0, l = this.params[name].length; i < l; i++) {
if (AjaxSolr.equals(this.params[name][i].val(), value)) {
indices.push(i);
}
}
return indices.length ? indices : false;
}
else {
if (AjaxSolr.equals(this.params[name].val(), value)) {
return name;
}
}
}
return false;
},
/**
* If the parameter may be specified multiple times, creates a parameter using
* the given name and value, and adds it to the list of identically-named
* parameters, unless one already exists with the same value. If it may be
* specified only once, replaces the parameter.
*
* @param {String} name The name of the parameter.
* @param {String|Number|String[]|Number[]} value The value.
* @returns {AjaxSolr.Parameter|Boolean} The parameter, or false.
*/
addByValue: function (name, value) {
if (this.isMultiple(name) && AjaxSolr.isArray(value)) {
var ret = [];
for (var i = 0, l = value.length; i < l; i++) {
ret.push(this.add(name, new AjaxSolr.Parameter({ name: name, value: value[i] })));
}
return ret;
}
else {
return this.add(name, new AjaxSolr.Parameter({ name: name, value: value }))
}
},
/**
* Deletes any parameter with a matching value.
*
* @param {String} name The name of the parameter.
* @param {String|Number|String[]|Number[]|RegExp} value The value.
* @returns {String|Number[]} The indices deleted.
*/
removeByValue: function (name, value) {
var indices = this.find(name, value);
if (indices) {
if (AjaxSolr.isArray(indices)) {
for (var i = indices.length - 1; i >= 0; i--) {
this.remove(name, indices[i]);
}
}
else {
this.remove(indices);
}
}
return indices;
},
/**
* Returns the Solr parameters as a query string.
*
* <p>IE6 calls the default toString() if you write <tt>store.toString()
* </tt>. So, we need to choose another name for toString().</p>
*/
string: function () {
var params = [];
for (var name in this.params) {
if (this.isMultiple(name)) {
for (var i = 0, l = this.params[name].length; i < l; i++) {
params.push(this.params[name][i].string());
}
}
else {
params.push(this.params[name].string());
}
}
return AjaxSolr.compact(params).join('&');
},
/**
* Parses a query string into Solr parameters.
*
* @param {String} str The string to parse.
*/
parseString: function (str) {
var pairs = str.split('&');
for (var i = 0, l = pairs.length; i < l; i++) {
if (pairs[i]) { // ignore leading, trailing, and consecutive &'s
var param = new AjaxSolr.Parameter();
param.parseString(pairs[i]);
this.add(param.name, param);
}
}
},
/**
* Returns the exposed parameters as a query string.
*
* @returns {String} A string representation of the exposed parameters.
*/
exposedString: function () {
var params = [];
for (var i = 0, l = this.exposed.length; i < l; i++) {
if (this.params[this.exposed[i]] !== undefined) {
if (this.isMultiple(this.exposed[i])) {
for (var j = 0, m = this.params[this.exposed[i]].length; j < m; j++) {
params.push(this.params[this.exposed[i]][j].string());
}
}
else {
params.push(this.params[this.exposed[i]].string());
}
}
}
return AjaxSolr.compact(params).join('&');
},
/**
* Resets the values of the exposed parameters.
*/
exposedReset: function () {
for (var i = 0, l = this.exposed.length; i < l; i++) {
this.remove(this.exposed[i]);
}
},
/**
* Loads the values of exposed parameters from persistent storage. It is
* necessary, in most cases, to reset the values of exposed parameters before
* setting the parameters to the values in storage. This is to ensure that a
* parameter whose name is not present in storage is properly reset.
*
* @param {Boolean} [reset=true] Whether to reset the exposed parameters.
* before loading new values from persistent storage. Default: true.
*/
load: function (reset) {
if (reset === undefined) {
reset = true;
}
if (reset) {
this.exposedReset();
}
this.parseString(this.storedString());
},
/**
* An abstract hook for child implementations.
*
* <p>Stores the values of the exposed parameters in persistent storage. This
* method should usually be called before each Solr request.</p>
*/
save: function () {},
/**
* An abstract hook for child implementations.
*
* <p>Returns the string to parse from persistent storage.</p>
*
* @returns {String} The string from persistent storage.
*/
storedString: function () {
return '';
}
});
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// $Id$
/**
* @namespace A unique namespace for the AJAX Solr library.
*/
AjaxSolr = function () {};
/**
* @namespace Baseclass for all classes
*/
AjaxSolr.Class = function () {};
/**
* A class 'extends' itself into a subclass.
*
* @static
* @param properties The properties of the subclass.
* @returns A function that represents the subclass.
*/
AjaxSolr.Class.extend = function (properties) {
var klass = this; // Safari dislikes 'class'
// The subclass is just a function that when called, instantiates itself.
// Nothing is _actually_ shared between _instances_ of the same class.
var subClass = function (options) {
// 'this' refers to the subclass, which starts life as an empty object.
// Add its parent's properties, its own properties, and any passed options.
AjaxSolr.extend(this, new klass(options), properties, options);
}
// Allow the subclass to extend itself into further subclasses.
subClass.extend = this.extend;
return subClass;
};
/**
* @static
* @param {Object} obj Any object.
* @returns {Number} the number of properties on an object.
* @see http://stackoverflow.com/questions/5223/length-of-javascript-associative-array
*/
AjaxSolr.size = function (obj) {
var size = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
};
/**
* @static
* @param foo A value.
* @param bar A value.
* @returns {Boolean} Whether the two given values are equal.
*/
AjaxSolr.equals = function (foo, bar) {
if (AjaxSolr.isArray(foo) && AjaxSolr.isArray(bar)) {
if (foo.length !== bar.length) {
return false;
}
for (var i = 0, l = foo.length; i < l; i++) {
if (foo[i] !== bar[i]) {
return false;
}
}
return true;
}
else if (AjaxSolr.isRegExp(foo) && AjaxSolr.isString(bar)) {
return bar.match(foo);
}
else if (AjaxSolr.isRegExp(bar) && AjaxSolr.isString(foo)) {
return foo.match(bar);
}
else {
return foo === bar;
}
};
/**
* @static
* @param value A value.
* @param array An array.
* @returns {Boolean} Whether value exists in the array.
*/
AjaxSolr.inArray = function (value, array) {
if (array) {
for (var i = 0, l = array.length; i < l; i++) {
if (AjaxSolr.equals(array[i], value)) {
return i;
}
}
}
return -1;
};
/**
* A copy of MooTools' Array.flatten function.
*
* @static
* @see http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools.js
*/
AjaxSolr.flatten = function(array) {
var ret = [];
for (var i = 0, l = array.length; i < l; i++) {
ret = ret.concat(AjaxSolr.isArray(array[i]) ? AjaxSolr.flatten(array[i]) : array[i]);
}
return ret;
};
/**
* A copy of jQuery's jQuery.grep function.
*
* @static
* @see http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js
*/
AjaxSolr.grep = function(array, callback) {
var ret = [];
for (var i = 0, l = array.length; i < l; i++) {
if (!callback(array[i], i) === false) {
ret.push(array[i]);
}
}
return ret;
}
/**
* Equivalent to Ruby's Array#compact.
*/
AjaxSolr.compact = function(array) {
return AjaxSolr.grep(array, function (item) {
return item.toString();
});
}
/**
* Can't use toString.call(obj) === "[object Array]", as it may return
* "[xpconnect wrapped native prototype]", which is undesirable.
*
* @static
* @see http://thinkweb2.com/projects/prototype/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* @see http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js
*/
AjaxSolr.isArray = function (obj) {
return obj != null && typeof obj == 'object' && 'splice' in obj && 'join' in obj;
};
/**
* @param obj Any object.
* @returns {Boolean} Whether the object is a RegExp object.
*/
AjaxSolr.isRegExp = function (obj) {
return obj != null && (typeof obj == 'object' || typeof obj == 'function') && 'ignoreCase' in obj;
};
/**
* @param obj Any object.
* @returns {Boolean} Whether the object is a String object.
*/
AjaxSolr.isString = function (obj) {
return obj != null && typeof obj == 'string';
};
/**
* Define theme functions to separate, as much as possible, your HTML from your
* JavaScript. Theme functions provided by AJAX Solr are defined in the
* AjaxSolr.theme.prototype namespace, e.g. AjaxSolr.theme.prototype.select_tag.
*
* To override a theme function provided by AJAX Solr, define a function of the
* same name in the AjaxSolr.theme namespace, e.g. AjaxSolr.theme.select_tag.
*
* To retrieve the HTML output by AjaxSolr.theme.prototype.select_tag(...), call
* AjaxSolr.theme('select_tag', ...).
*
* @param {String} func
* The name of the theme function to call.
* @param ...
* Additional arguments to pass along to the theme function.
* @returns
* Any data the theme function returns. This could be a plain HTML string,
* but also a complex object.
*
* @static
* @throws Exception if the theme function is not defined.
* @see http://cvs.drupal.org/viewvc.py/drupal/drupal/misc/drupal.js?revision=1.58
*/
AjaxSolr.theme = function (func) {
for (var i = 1, args = []; i < arguments.length; i++) {
args.push(arguments[i]);
}
try {
return (AjaxSolr.theme[func] || AjaxSolr.theme.prototype[func]).apply(this, args);
}
catch (e) {
if (console && console.log) {
console.log('Theme function "' + func + '" is not defined.');
}
throw e;
}
};
/**
* A simplified version of jQuery's extend function.
*
* @static
* @see http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
*/
AjaxSolr.extend = function () {
var target = arguments[0] || {}, i = 1, length = arguments.length, options;
for (; i < length; i++) {
if ((options = arguments[i]) != null) {
for (var name in options) {
var src = target[name], copy = options[name];
if (target === copy) {
continue;
}
if (copy && typeof copy == 'object' && !copy.nodeType) {
target[name] = AjaxSolr.extend(src || (copy.length != null ? [] : {}), copy);
}
else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// $Id$
/**
* Baseclass for all facet widgets.
*
* @class AbstractFacetWidget
* @augments AjaxSolr.AbstractWidget
*/
AjaxSolr.AbstractFacetWidget = AjaxSolr.AbstractWidget.extend(
/** @lends AjaxSolr.AbstractFacetWidget.prototype */
{
/**
* The field to facet on.
*
* @field
* @public
* @type String
*/
field: null,
/**
* @returns {Boolean} Whether any filter queries have been set using this
* widget's facet field.
*/
isEmpty: function () {
return !this.manager.store.find('fq', new RegExp('^-?' + this.field + ':'));
},
/**
* Adds a filter query.
*
* @returns {Boolean} Whether a filter query was added.
*/
add: function (value) {
return this.changeSelection(function () {
return this.manager.store.addByValue('fq', this.fq(value));
});
},
/**
* Removes a filter query.
*
* @returns {Boolean} Whether a filter query was removed.
*/
remove: function (value) {
return this.changeSelection(function () {
return this.manager.store.removeByValue('fq', this.fq(value));
});
},
/**
* Removes all filter queries using the widget's facet field.
*
* @returns {Boolean} Whether a filter query was removed.
*/
clear: function () {
return this.changeSelection(function () {
return this.manager.store.removeByValue('fq', new RegExp('^-?' + this.field + ':'));
});
},
/**
* Helper for selection functions.
*
* @param {Function} Selection function to call.
* @returns {Boolean} Whether the selection changed.
*/
changeSelection: function (func) {
changed = func.apply(this);
if (changed) {
this.afterChangeSelection();
}
return changed;
},
/**
* An abstract hook for child implementations.
*
* <p>This method is executed after the filter queries change.</p>
*/
afterChangeSelection: function () {},
/**
* @param {String} value The value.
* @returns {Function} Sends a request to Solr if it successfully adds a
* filter query with the given value.
*/
clickHandler: function (value) {
var self = this;
return function () {
if (self.add(value)) {
self.manager.doRequest(0);
}
return false;
}
},
/**
* @param {String} value The value.
* @returns {Function} Sends a request to Solr if it successfully removes a
* filter query with the given value.
*/
unclickHandler: function (value) {
var self = this;
return function () {
if (self.remove(value)) {
self.manager.doRequest(0);
}
return false;
}
},
/**
* @param {String} value The facet value.
* @param {Boolean} exclude Whether to exclude this fq parameter value.
* @returns {String} An fq parameter value.
*/
fq: function (value, exclude) {
// If the field value has a space or a colon in it, wrap it in quotes,
// unless it is a range query.
if (value.match(/[ :]/) && !value.match(/[\[\{]\S+ TO \S+[\]\}]/)) {
value = '"' + value + '"';
}
return (exclude ? '-' : '') + this.field + ':' + value;
}
});
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// $Id$
/**
* Baseclass for all widgets.
*
* Provides abstract hooks for child classes.
*
* @param properties A map of fields to set. May be new or public fields.
* @class AbstractWidget
*/
AjaxSolr.AbstractWidget = AjaxSolr.Class.extend(
/** @lends AjaxSolr.AbstractWidget.prototype */
{
/**
* A unique identifier of this widget.
*
* @field
* @public
* @type String
*/
id: null,
/**
* The CSS selector for this widget's target HTML element, e.g. a specific
* <tt>div</tt> or <tt>ul</tt>. A Widget is usually implemented to perform
* all its UI changes relative to its target HTML element.
*
* @field
* @public
* @type String
*/
target: null,
/**
* A reference to the widget's manager. For internal use only.
*
* @field
* @private
* @type AjaxSolr.AbstractManager
*/
manager: null,
/**
* An abstract hook for child implementations.
*
* <p>This method should do any necessary one-time initializations.</p>
*/
init: function () {},
/**
* An abstract hook for child implementations.
*
* <p>This method is executed before the Solr request is sent.</p>
*/
beforeRequest: function () {},
/**
* An abstract hook for child implementations.
*
* <p>This method is executed after the Solr response is received.</p>
*/
afterRequest: function () {}
});
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// $Id$
/**
* The Manager acts as the controller in a Model-View-Controller framework. All
* public calls should be performed on the manager object.
*
* @param properties A map of fields to set. Refer to the list of public fields.
* @class AbstractManager
*/
AjaxSolr.AbstractManager = AjaxSolr.Class.extend(
/** @lends AjaxSolr.AbstractManager.prototype */
{
/**
* The fully-qualified URL of the Solr application. You must include the
* trailing slash. Do not include the path to any Solr servlet.
*
* @field
* @public
* @type String
* @default "http://localhost:8983/solr/"
*/
solrUrl: 'http://localhost:8983/solr/',
/**
* If we want to proxy queries through a script, rather than send queries
* to Solr directly, set this field to the fully-qualified URL of the script.
*
* @field
* @public
* @type String
*/
proxyUrl: null,
/**
* The default Solr servlet.
*
* @field
* @public
* @type String
* @default "select"
*/
servlet: 'select',
/**
* The most recent response from Solr.
*
* @field
* @private
* @type Object
* @default {}
*/
response: {},
/**
* A collection of all registered widgets. For internal use only.
*
* @field
* @private
* @type Object
* @default {}
*/
widgets: {},
/**
* The parameter store for the manager and its widgets. For internal use only.
*
* @field
* @private
* @type Object
*/
store: null,
/**
* Whether <tt>init()</tt> has been called yet. For internal use only.
*
* @field
* @private
* @type Boolean
* @default false
*/
initialized: false,
/**
* An abstract hook for child implementations.
*
* <p>This method should be called after the store and the widgets have been
* added. It should initialize the widgets and the store, and do any other
* one-time initializations, e.g., perform the first request to Solr.</p>
*
* <p>If no store has been set, it sets the store to the basic <tt>
* AjaxSolr.ParameterStore</tt>.</p>
*/
init: function () {
this.initialized = true;
if (this.store === null) {
this.setStore(new AjaxSolr.ParameterStore());
}
this.store.load(false);
for (var widgetId in this.widgets) {
this.widgets[widgetId].init();
}
this.store.init();
},
/**
* Set the manager's parameter store.
*
* @param {AjaxSolr.ParameterStore} store
*/
setStore: function (store) {
store.manager = this;
this.store = store;
},
/**
* Adds a widget to the manager.
*
* @param {AjaxSolr.AbstractWidget} widget
*/
addWidget: function (widget) {
widget.manager = this;
this.widgets[widget.id] = widget;
},
/**
* Stores the Solr parameters to be sent to Solr and sends a request to Solr.
*
* @param {Boolean} [start] The Solr start offset parameter.
* @param {String} [servlet] The Solr servlet to send the request to.
*/
doRequest: function (start, servlet) {
if (this.initialized === false) {
this.init();
}
// Allow non-pagination widgets to reset the offset parameter.
if (start !== undefined) {
this.store.get('start').val(start);
}
if (servlet === undefined) {
servlet = this.servlet;
}
this.store.save();
for (var widgetId in this.widgets) {
this.widgets[widgetId].beforeRequest();
}
this.executeRequest(servlet);
},
/**
* An abstract hook for child implementations.
*
* <p>Sends the request to Solr, i.e. to <code>this.solrUrl</code> or <code>
* this.proxyUrl</code>, and receives Solr's response. It should send <code>
* this.store.string()</code> as the Solr query, and it should pass Solr's
* response to <code>handleResponse()</code> for handling.</p>
*
* <p>See <tt>managers/Manager.jquery.js</tt> for a jQuery implementation.</p>
*
* @param {String} servlet The Solr servlet to send the request to.
* @throws If not defined in child implementation.
*/
executeRequest: function (servlet) {
throw 'Abstract method executeRequest must be overridden in a subclass.';
},
/**
* This method is executed after the Solr response data arrives. Allows each
* widget to handle Solr's response separately.
*
* @param {Object} data The Solr response.
*/
handleResponse: function (data) {
this.response = data;
for (var widgetId in this.widgets) {
this.widgets[widgetId].afterRequest();
}
}
});
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
// $Id$
/**
* Represents a Solr parameter.
*
* @param properties A map of fields to set. Refer to the list of public fields.
* @class Parameter
*/
AjaxSolr.Parameter = AjaxSolr.Class.extend(
/** @lends AjaxSolr.Parameter.prototype */
{
/**
* The parameter's name.
*
* @field
* @private
* @type String
*/
name: null,
/**
* The parameter's value.
*
* @field
* @private
* @type String
*/
value: null,
/**
* The parameter's local parameters.
*
* @field
* @private
* @type Object
* @default {}
*/
locals: {},
/**
* Returns the value. If called with an argument, sets the value.
*
* @param {String|Number|String[]|Number[]} [value] The value to set.
* @returns The value.
*/
val: function (value) {
if (value === undefined) {
return this.value;
}
else {
this.value = value;
}
},
/**
* Returns the value of a local parameter. If called with a second argument,
* sets the value of a local parameter.
*
* @param {String} name The name of the local parameter.
* @param {String|Number|String[]|Number[]} [value] The value to set.
* @returns The value.
*/
local: function (name, value) {
if (value === undefined) {
return this.locals[name];
}
else {
this.locals[name] = value;
}
},
/**
* Deletes a local parameter.
*
* @param {String} name The name of the local parameter.
*/
remove: function (name) {
delete this.locals[name];
},
/**
* Returns the Solr parameter as a query string key-value pair.
*
* <p>IE6 calls the default toString() if you write <tt>store.toString()
* </tt>. So, we need to choose another name for toString().</p>
*/
string: function () {
var pairs = [];
for (var name in this.locals) {
if (this.locals[name]) {
pairs.push(name + '=' + encodeURIComponent(this.locals[name]));
}
}
var prefix = pairs.length ? '{!' + pairs.join('%20') + '}' : '';
if (this.value) {
return this.name + '=' + prefix + this.valueString(this.value);
}
// For dismax request handlers, if the q parameter has local params, the
// q parameter must be set to a non-empty value. In case the q parameter
// is empty, use the q.alt parameter, which accepts wildcards.
else if (this.name == 'q') {
return 'q.alt=' + prefix + encodeURIComponent('*.*');
}
else {
return '';
}
},
/**
* Parses a string formed by calling string().
*
* @param {String} str The string to parse.
*/
parseString: function (str) {
var param = str.match(/^([^=]+)=(?:\{!([^\}]*)\})?(.*)$/);
if (param) {
var matches;
while (matches = /([^\s=]+)=(\S*)/g.exec(decodeURIComponent(param[2]))) {
this.locals[matches[1]] = decodeURIComponent(matches[2]);
param[2] = param[2].replace(matches[0], ''); // Safari's exec seems not to do this on its own
}
if (param[1] == 'q.alt') {
this.name = 'q';
// if q.alt is present, assume it is because q was empty, as above
}
else {
this.name = param[1];
this.value = this.parseValueString(param[3]);
}
}
},
/**
* Returns the value as a URL-encoded string.
*
* @private
* @param {String|Number|String[]|Number[]} value The value.
* @returns {String} The URL-encoded string.
*/
valueString: function (value) {
value = AjaxSolr.isArray(value) ? value.join(',') : value;
return encodeURIComponent(value);
},
/**
* Parses a URL-encoded string to return the value.
*
* @private
* @param {String} str The URL-encoded string.
* @returns {Array} The value.
*/
parseValueString: function (str) {
str = decodeURIComponent(str);
return str.indexOf(',') == -1 ? str : str.split(',');
}
});
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
var Manager;
var query;
var defaultFacets = new Array();
(function ($) {
$(function () {
var searchUrl = $("input[name='solr-search-url']").val();
Manager = new AjaxSolr.Manager({
solrUrl: searchUrl
});
//Retrieve our filterSelect, which contains all the types to be sorted on
var filterSelect = $("select[id='aspect_discovery_SimpleSearch_field_filtertype']");
//Get our filters
/*
var filterOptions = filterSelect.find('option');
//Get all the
for (var index = 1; index < filterOptions.length; index++){
//We skip the first one (for the moment)
defaultFacets[index - 1] = filterOptions[index].value;
}
*/
//As a default facet we use everything
defaultFacets[0] = 'all_ac';
var widget = Manager.addWidget(new AjaxSolr.AutocompleteWidget({
id: 'text',
target: 'li#aspect_discovery_SimpleSearch_item_search-filter-list',
field: 'allText',
fields: defaultFacets
}));
Manager.init();
query = $('input#aspect_discovery_SimpleSearch_field_query').val();
if(query == '')
query = '*:*';
Manager.store.addByValue('q', query);
//Retrieve our filter queries
var fqs = $("input[name='fq']");
for(var j = 0; j < fqs.length; j ++){
Manager.store.addByValue('fq', $(fqs[j]).val());
}
Manager.store.addByValue('facet.sort', 'count');
var params = {
facet: true,
'facet.field': defaultFacets,
'facet.limit': 20,
'facet.mincount': 1,
'f.topics.facet.limit': 50,
'json.nl': 'map'
};
for (var name in params) {
Manager.store.addByValue(name, params[name]);
}
Manager.doRequest();
filterSelect.change(function() {
// TODO: this is dirty, but with lack of time the best I could do
var oldInput = $('input#aspect_discovery_SimpleSearch_field_filter');
var newInput = oldInput.clone(false);
// newInput.val(oldInput.val());
newInput.appendTo(oldInput.parent());
oldInput.remove();
//Remove any results lists we may still have standing
$("div#discovery_autocomplete_div").remove();
//Put the field in which our facet is going to facet into the widget
var facetFields;
if($(this).val() != '*'){
var facetVal = $(this).val();
//Only facet on autocomplete fields
if(!facetVal.match(/.year$/)){
facetVal += '_ac';
}
facetFields = [facetVal];
} else {
facetFields = defaultFacets;
}
Manager.widgets.text.fields = facetFields;
Manager.initialized = false;
Manager.init();
//TODO: does this need to happen twice ?
Manager.store.addByValue('q', query);
//Retrieve our filter queries
var fqs = $("input[name='fq']");
for(var j = 0; j < fqs.length; j ++){
Manager.store.addByValue('fq', $(fqs[j]).val());
}
Manager.store.addByValue('facet.sort', 'count');
var params = {
facet: true,
'facet.field': facetFields,
'facet.limit': 20,
'facet.mincount': 1,
'f.topics.facet.limit': 50,
'json.nl': 'map'
};
for (var name in params) {
Manager.store.addByValue(name, params[name]);
}
Manager.doRequest();
});
});
})(jQuery);
| JavaScript |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
;(function($) {
$.fn.extend({
autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function(input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;
var v = selected.result;
previousValue = v;
if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator );
}
v += options.multipleSeparator;
}
$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue )
return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value)
return [""];
if (!options.multiple)
return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function(word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
if (words.length == 1)
return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
}
);
}
};
function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultId: "discovery_autocomplete_div",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function(options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){
length++;
}
data[q] = value;
}
function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush(){
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.attr("id", options.resultId)
.css("position", "absolute")
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});
if( options.width > 0 )
element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}
function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available) {
return options.max && options.max < available
? options.max
: available;
}
function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}
return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};
$.fn.selection = function(start, end) {
if (start !== undefined) {
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery);
| JavaScript |
/*
* JQuery zTree core 3.1
* http://code.google.com/p/jquerytree/
*
* Copyright (c) 2010 Hunter.z (baby666.cn)
*
* Licensed same as jquery - MIT License
* http://www.opensource.org/licenses/mit-license.php
*
* email: hunter.z@263.net
* Date: 2012-02-14
*/
(function($){
var settings = {}, roots = {}, caches = {}, zId = 0,
//default consts of core
_consts = {
event: {
NODECREATED: "ztree_nodeCreated",
CLICK: "ztree_click",
EXPAND: "ztree_expand",
COLLAPSE: "ztree_collapse",
ASYNC_SUCCESS: "ztree_async_success",
ASYNC_ERROR: "ztree_async_error"
},
id: {
A: "_a",
ICON: "_ico",
SPAN: "_span",
SWITCH: "_switch",
UL: "_ul"
},
line: {
ROOT: "root",
ROOTS: "roots",
CENTER: "center",
BOTTOM: "bottom",
NOLINE: "noline",
LINE: "line"
},
folder: {
OPEN: "open",
CLOSE: "close",
DOCU: "docu"
},
node: {
CURSELECTED: "curSelectedNode"
}
},
//default setting of core
_setting = {
treeId: "",
treeObj: null,
view: {
addDiyDom: null,
autoCancelSelected: true,
dblClickExpand: true,
expandSpeed: "fast",
fontCss: {},
nameIsHTML: false,
selectedMulti: true,
showIcon: true,
showLine: true,
showTitle: true
},
data: {
key: {
children: "children",
name: "name",
title: ""
},
simpleData: {
enable: false,
idKey: "id",
pIdKey: "pId",
rootPId: null
},
keep: {
parent: false,
leaf: false
}
},
async: {
enable: false,
contentType: "application/x-www-form-urlencoded",
type: "post",
dataType: "text",
url: "",
autoParam: [],
otherParam: [],
dataFilter: null
},
callback: {
beforeAsync:null,
beforeClick:null,
beforeRightClick:null,
beforeMouseDown:null,
beforeMouseUp:null,
beforeExpand:null,
beforeCollapse:null,
onAsyncError:null,
onAsyncSuccess:null,
onNodeCreated:null,
onClick:null,
onRightClick:null,
onMouseDown:null,
onMouseUp:null,
onExpand:null,
onCollapse:null
}
},
//default root of core
//zTree use root to save full data
_initRoot = function (setting) {
var r = data.getRoot(setting);
if (!r) {
r = {};
data.setRoot(setting, r);
}
r.children = [];
r.expandTriggerFlag = false;
r.curSelectedList = [];
r.noSelection = true;
r.createdNodes = [];
},
//default cache of core
_initCache = function(setting) {
var c = data.getCache(setting);
if (!c) {
c = {};
data.setCache(setting, c);
}
c.nodes = [];
c.doms = [];
},
//default bindEvent of core
_bindEvent = function(setting) {
var o = setting.treeObj,
c = consts.event;
o.unbind(c.NODECREATED);
o.bind(c.NODECREATED, function (event, treeId, node) {
tools.apply(setting.callback.onNodeCreated, [event, treeId, node]);
});
o.unbind(c.CLICK);
o.bind(c.CLICK, function (event, treeId, node, clickFlag) {
tools.apply(setting.callback.onClick, [event, treeId, node, clickFlag]);
});
o.unbind(c.EXPAND);
o.bind(c.EXPAND, function (event, treeId, node) {
tools.apply(setting.callback.onExpand, [event, treeId, node]);
});
o.unbind(c.COLLAPSE);
o.bind(c.COLLAPSE, function (event, treeId, node) {
tools.apply(setting.callback.onCollapse, [event, treeId, node]);
});
o.unbind(c.ASYNC_SUCCESS);
o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) {
tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]);
});
o.unbind(c.ASYNC_ERROR);
o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) {
tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]);
});
},
//default event proxy of core
_eventProxy = function(event) {
var target = event.target,
setting = settings[event.data.treeId],
tId = "", node = null,
nodeEventType = "", treeEventType = "",
nodeEventCallback = null, treeEventCallback = null,
tmp = null;
if (tools.eqs(event.type, "mousedown")) {
treeEventType = "mousedown";
} else if (tools.eqs(event.type, "mouseup")) {
treeEventType = "mouseup";
} else if (tools.eqs(event.type, "contextmenu")) {
treeEventType = "contextmenu";
} else if (tools.eqs(event.type, "click")) {
if (tools.eqs(target.tagName, "button")) {
target.blur();
}
if (tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+ consts.id.SWITCH) !== null) {
tId = target.parentNode.id;
nodeEventType = "switchNode";
} else {
tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]);
if (tmp) {
tId = tmp.parentNode.id;
nodeEventType = "clickNode";
}
}
} else if (tools.eqs(event.type, "dblclick")) {
treeEventType = "dblclick";
tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]);
if (tmp) {
tId = tmp.parentNode.id;
nodeEventType = "switchNode";
}
}
if (treeEventType.length > 0 && tId.length == 0) {
tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]);
if (tmp) {tId = tmp.parentNode.id;}
}
// event to node
if (tId.length>0) {
node = data.getNodeCache(setting, tId);
switch (nodeEventType) {
case "switchNode" :
if (!node.isParent) {
nodeEventType = "";
} else if (tools.eqs(event.type, "click")
|| (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) {
nodeEventCallback = handler.onSwitchNode;
} else {
nodeEventType = "";
}
break;
case "clickNode" :
nodeEventCallback = handler.onClickNode;
break;
}
}
// event to zTree
switch (treeEventType) {
case "mousedown" :
treeEventCallback = handler.onZTreeMousedown;
break;
case "mouseup" :
treeEventCallback = handler.onZTreeMouseup;
break;
case "dblclick" :
treeEventCallback = handler.onZTreeDblclick;
break;
case "contextmenu" :
treeEventCallback = handler.onZTreeContextmenu;
break;
}
var proxyResult = {
stop: false,
node: node,
nodeEventType: nodeEventType,
nodeEventCallback: nodeEventCallback,
treeEventType: treeEventType,
treeEventCallback: treeEventCallback
};
return proxyResult
},
//default init node of core
_initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) {
if (!n) return;
var childKey = setting.data.key.children;
n.level = level;
n.tId = setting.treeId + "_" + (++zId);
n.parentTId = parentNode ? parentNode.tId : null;
if (n[childKey] && n[childKey].length > 0) {
if (typeof n.open == "string") n.open = tools.eqs(n.open, "true");
n.open = !!n.open;
n.isParent = true;
n.zAsync = true;
} else {
n.open = false;
if (typeof n.isParent == "string") n.isParent = tools.eqs(n.isParent, "true");
n.isParent = !!n.isParent;
n.zAsync = !n.isParent;
}
n.isFirstNode = isFirstNode;
n.isLastNode = isLastNode;
n.getParentNode = function() {return data.getNodeCache(setting, n.parentTId);};
n.getPreNode = function() {return data.getPreNode(setting, n);};
n.getNextNode = function() {return data.getNextNode(setting, n);};
n.isAjaxing = false;
data.fixPIdKeyValue(setting, n);
},
_init = {
bind: [_bindEvent],
caches: [_initCache],
nodes: [_initNode],
proxys: [_eventProxy],
roots: [_initRoot],
beforeA: [],
afterA: [],
innerBeforeA: [],
innerAfterA: [],
zTreeTools: []
},
//method of operate data
data = {
addNodeCache: function(setting, node) {
data.getCache(setting).nodes[node.tId] = node;
},
addAfterA: function(afterA) {
_init.afterA.push(afterA);
},
addBeforeA: function(beforeA) {
_init.beforeA.push(beforeA);
},
addInnerAfterA: function(innerAfterA) {
_init.innerAfterA.push(innerAfterA);
},
addInnerBeforeA: function(innerBeforeA) {
_init.innerBeforeA.push(innerBeforeA);
},
addInitBind: function(bindEvent) {
_init.bind.push(bindEvent);
},
addInitCache: function(initCache) {
_init.caches.push(initCache);
},
addInitNode: function(initNode) {
_init.nodes.push(initNode);
},
addInitProxy: function(initProxy) {
_init.proxys.push(initProxy);
},
addInitRoot: function(initRoot) {
_init.roots.push(initRoot);
},
addNodesData: function(setting, parentNode, nodes) {
var childKey = setting.data.key.children;
if (!parentNode[childKey]) parentNode[childKey] = [];
if (parentNode[childKey].length > 0) {
parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false;
view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]);
}
parentNode.isParent = true;
parentNode[childKey] = parentNode[childKey].concat(nodes);
},
addSelectedNode: function(setting, node) {
var root = data.getRoot(setting);
if (!data.isSelectedNode(setting, node)) {
root.curSelectedList.push(node);
}
},
addCreatedNode: function(setting, node) {
if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) {
var root = data.getRoot(setting);
root.createdNodes.push(node);
}
},
addZTreeTools: function(zTreeTools) {
_init.zTreeTools.push(zTreeTools);
},
exSetting: function(s) {
$.extend(true, _setting, s);
},
fixPIdKeyValue: function(setting, node) {
if (setting.data.simpleData.enable) {
node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId;
}
},
getAfterA: function(setting, node, array) {
for (var i=0, j=_init.afterA.length; i<j; i++) {
_init.afterA[i].apply(this, arguments);
}
},
getBeforeA: function(setting, node, array) {
for (var i=0, j=_init.beforeA.length; i<j; i++) {
_init.beforeA[i].apply(this, arguments);
}
},
getInnerAfterA: function(setting, node, array) {
for (var i=0, j=_init.innerAfterA.length; i<j; i++) {
_init.innerAfterA[i].apply(this, arguments);
}
},
getInnerBeforeA: function(setting, node, array) {
for (var i=0, j=_init.innerBeforeA.length; i<j; i++) {
_init.innerBeforeA[i].apply(this, arguments);
}
},
getCache: function(setting) {
return caches[setting.treeId];
},
getNextNode: function(setting, node) {
if (!node) return null;
var childKey = setting.data.key.children,
p = node.parentTId ? node.getParentNode() : data.getRoot(setting);
if (node.isLastNode) {
return null;
} else if (node.isFirstNode) {
return p[childKey][1];
} else {
for (var i=1, l=p[childKey].length-1; i<l; i++) {
if (p[childKey][i] === node) {
return p[childKey][i+1];
}
}
}
return null;
},
getNodeByParam: function(setting, nodes, key, value) {
if (!nodes || !key) return null;
var childKey = setting.data.key.children;
for (var i = 0, l = nodes.length; i < l; i++) {
if (nodes[i][key] == value) {
return nodes[i];
}
var tmp = data.getNodeByParam(setting, nodes[i][childKey], key, value);
if (tmp) return tmp;
}
return null;
},
getNodeCache: function(setting, tId) {
if (!tId) return null;
var n = caches[setting.treeId].nodes[tId];
return n ? n : null;
},
getNodes: function(setting) {
return data.getRoot(setting)[setting.data.key.children];
},
getNodesByParam: function(setting, nodes, key, value) {
if (!nodes || !key) return [];
var childKey = setting.data.key.children,
result = [];
for (var i = 0, l = nodes.length; i < l; i++) {
if (nodes[i][key] == value) {
result.push(nodes[i]);
}
result = result.concat(data.getNodesByParam(setting, nodes[i][childKey], key, value));
}
return result;
},
getNodesByParamFuzzy: function(setting, nodes, key, value) {
if (!nodes || !key) return [];
var childKey = setting.data.key.children,
result = [];
for (var i = 0, l = nodes.length; i < l; i++) {
if (typeof nodes[i][key] == "string" && nodes[i][key].indexOf(value)>-1) {
result.push(nodes[i]);
}
result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value));
}
return result;
},
getPreNode: function(setting, node) {
if (!node) return null;
var childKey = setting.data.key.children,
p = node.parentTId ? node.getParentNode() : data.getRoot(setting);
if (node.isFirstNode) {
return null;
} else if (node.isLastNode) {
return p[childKey][p[childKey].length-2];
} else {
for (var i=1, l=p[childKey].length-1; i<l; i++) {
if (p[childKey][i] === node) {
return p[childKey][i-1];
}
}
}
return null;
},
getRoot: function(setting) {
return setting ? roots[setting.treeId] : null;
},
getSetting: function(treeId) {
return settings[treeId];
},
getSettings: function() {
return settings;
},
getTitleKey: function(setting) {
return setting.data.key.title === "" ? setting.data.key.name : setting.data.key.title;
},
getZTreeTools: function(treeId) {
var r = this.getRoot(this.getSetting(treeId));
return r ? r.treeTools : null;
},
initCache: function(setting) {
for (var i=0, j=_init.caches.length; i<j; i++) {
_init.caches[i].apply(this, arguments);
}
},
initNode: function(setting, level, node, parentNode, preNode, nextNode) {
for (var i=0, j=_init.nodes.length; i<j; i++) {
_init.nodes[i].apply(this, arguments);
}
},
initRoot: function(setting) {
for (var i=0, j=_init.roots.length; i<j; i++) {
_init.roots[i].apply(this, arguments);
}
},
isSelectedNode: function(setting, node) {
var root = data.getRoot(setting);
for (var i=0, j=root.curSelectedList.length; i<j; i++) {
if(node === root.curSelectedList[i]) return true;
}
return false;
},
removeNodeCache: function(setting, node) {
var childKey = setting.data.key.children;
if (node[childKey]) {
for (var i=0, l=node[childKey].length; i<l; i++) {
arguments.callee(setting, node[childKey][i]);
}
}
delete data.getCache(setting).nodes[node.tId];
},
removeSelectedNode: function(setting, node) {
var root = data.getRoot(setting);
for (var i=0, j=root.curSelectedList.length; i<j; i++) {
if(node === root.curSelectedList[i] || !data.getNodeCache(setting, root.curSelectedList[i].tId)) {
root.curSelectedList.splice(i, 1);
i--;j--;
}
}
},
setCache: function(setting, cache) {
caches[setting.treeId] = cache;
},
setRoot: function(setting, root) {
roots[setting.treeId] = root;
},
setZTreeTools: function(setting, zTreeTools) {
for (var i=0, j=_init.zTreeTools.length; i<j; i++) {
_init.zTreeTools[i].apply(this, arguments);
}
},
transformToArrayFormat: function (setting, nodes) {
if (!nodes) return [];
var childKey = setting.data.key.children,
r = [];
if (tools.isArray(nodes)) {
for (var i=0, l=nodes.length; i<l; i++) {
r.push(nodes[i]);
if (nodes[i][childKey])
r = r.concat(data.transformToArrayFormat(setting, nodes[i][childKey]));
}
} else {
r.push(nodes);
if (nodes[childKey])
r = r.concat(data.transformToArrayFormat(setting, nodes[childKey]));
}
return r;
},
transformTozTreeFormat: function(setting, sNodes) {
var i,l,
key = setting.data.simpleData.idKey,
parentKey = setting.data.simpleData.pIdKey,
childKey = setting.data.key.children;
if (!key || key=="" || !sNodes) return [];
if (tools.isArray(sNodes)) {
var r = [];
var tmpMap = [];
for (i=0, l=sNodes.length; i<l; i++) {
tmpMap[sNodes[i][key]] = sNodes[i];
}
for (i=0, l=sNodes.length; i<l; i++) {
if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
if (!tmpMap[sNodes[i][parentKey]][childKey])
tmpMap[sNodes[i][parentKey]][childKey] = [];
tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
} else {
r.push(sNodes[i]);
}
}
return r;
}else {
return [sNodes];
}
}
},
//method of event proxy
event = {
bindEvent: function(setting) {
for (var i=0, j=_init.bind.length; i<j; i++) {
_init.bind[i].apply(this, arguments);
}
},
bindTree: function(setting) {
var eventParam = {
treeId: setting.treeId
},
o = setting.treeObj;
o.unbind('click', event.proxy);
o.bind('click', eventParam, event.proxy);
o.unbind('dblclick', event.proxy);
o.bind('dblclick', eventParam, event.proxy);
o.unbind('mouseover', event.proxy);
o.bind('mouseover', eventParam, event.proxy);
o.unbind('mouseout', event.proxy);
o.bind('mouseout', eventParam, event.proxy);
o.unbind('mousedown', event.proxy);
o.bind('mousedown', eventParam, event.proxy);
o.unbind('mouseup', event.proxy);
o.bind('mouseup', eventParam, event.proxy);
o.unbind('contextmenu', event.proxy);
o.bind('contextmenu', eventParam, event.proxy);
},
doProxy: function(e) {
var results = [];
for (var i=0, j=_init.proxys.length; i<j; i++) {
var proxyResult = _init.proxys[i].apply(this, arguments);
results.push(proxyResult);
if (proxyResult.stop) {
break;
}
}
return results;
},
proxy: function(e) {
var setting = data.getSetting(e.data.treeId);
if (!tools.uCanDo(setting, e)) return true;
var results = event.doProxy(e),
r = true, x = false;
for (var i=0, l=results.length; i<l; i++) {
var proxyResult = results[i];
if (proxyResult.nodeEventCallback) {
x = true;
r = proxyResult.nodeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r;
}
if (proxyResult.treeEventCallback) {
x = true;
r = proxyResult.treeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r;
}
}
try{
if (x && $("input:focus").length == 0) {
tools.noSel(setting);
}
} catch(e) {}
return r;
}
},
//method of event handler
handler = {
onSwitchNode: function (event, node) {
var setting = settings[event.data.treeId];
if (node.open) {
if (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false) return true;
data.getRoot(setting).expandTriggerFlag = true;
view.switchNode(setting, node);
} else {
if (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false) return true;
data.getRoot(setting).expandTriggerFlag = true;
view.switchNode(setting, node);
}
return true;
},
onClickNode: function (event, node) {
var setting = settings[event.data.treeId],
clickFlag = ( (setting.view.autoCancelSelected && event.ctrlKey) && data.isSelectedNode(setting, node)) ? 0 : (setting.view.autoCancelSelected && event.ctrlKey && setting.view.selectedMulti) ? 2 : 1;
if (tools.apply(setting.callback.beforeClick, [setting.treeId, node, clickFlag], true) == false) return true;
if (clickFlag === 0) {
view.cancelPreSelectedNode(setting, node);
} else {
view.selectNode(setting, node, clickFlag === 2);
}
setting.treeObj.trigger(consts.event.CLICK, [setting.treeId, node, clickFlag]);
return true;
},
onZTreeMousedown: function(event, node) {
var setting = settings[event.data.treeId];
if (tools.apply(setting.callback.beforeMouseDown, [setting.treeId, node], true)) {
tools.apply(setting.callback.onMouseDown, [event, setting.treeId, node]);
}
return true;
},
onZTreeMouseup: function(event, node) {
var setting = settings[event.data.treeId];
if (tools.apply(setting.callback.beforeMouseUp, [setting.treeId, node], true)) {
tools.apply(setting.callback.onMouseUp, [event, setting.treeId, node]);
}
return true;
},
onZTreeDblclick: function(event, node) {
var setting = settings[event.data.treeId];
if (tools.apply(setting.callback.beforeDblClick, [setting.treeId, node], true)) {
tools.apply(setting.callback.onDblClick, [event, setting.treeId, node]);
}
return true;
},
onZTreeContextmenu: function(event, node) {
var setting = settings[event.data.treeId];
if (tools.apply(setting.callback.beforeRightClick, [setting.treeId, node], true)) {
tools.apply(setting.callback.onRightClick, [event, setting.treeId, node]);
}
return (typeof setting.callback.onRightClick) != "function";
}
},
//method of tools for zTree
tools = {
apply: function(fun, param, defaultValue) {
if ((typeof fun) == "function") {
return fun.apply(zt, param?param:[]);
}
return defaultValue;
},
canAsync: function(setting, node) {
var childKey = setting.data.key.children;
return (node && node.isParent && !(node.zAsync || (node[childKey] && node[childKey].length > 0)));
},
clone: function (jsonObj) {
var buf;
if (jsonObj instanceof Array) {
buf = [];
var i = jsonObj.length;
while (i--) {
buf[i] = arguments.callee(jsonObj[i]);
}
return buf;
}else if (typeof jsonObj == "function"){
return jsonObj;
}else if (jsonObj instanceof Object){
buf = {};
for (var k in jsonObj) {
buf[k] = arguments.callee(jsonObj[k]);
}
return buf;
}else{
return jsonObj;
}
},
eqs: function(str1, str2) {
return str1.toLowerCase() === str2.toLowerCase();
},
isArray: function(arr) {
return Object.prototype.toString.apply(arr) === "[object Array]";
},
getMDom: function (setting, curDom, targetExpr) {
if (!curDom) return null;
while (curDom && curDom.id !== setting.treeId) {
for (var i=0, l=targetExpr.length; curDom.tagName && i<l; i++) {
if (tools.eqs(curDom.tagName, targetExpr[i].tagName) && curDom.getAttribute(targetExpr[i].attrName) !== null) {
return curDom;
}
}
curDom = curDom.parentNode;
}
return null;
},
noSel: function(setting) {
var r = data.getRoot(setting);
if (r.noSelection) {
try {
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
} catch(e){}
}
},
uCanDo: function(setting, e) {
return true;
}
},
//method of operate ztree dom
view = {
addNodes: function(setting, parentNode, newNodes, isSilent) {
if (setting.data.keep.leaf && parentNode && !parentNode.isParent) {
return;
}
if (!tools.isArray(newNodes)) {
newNodes = [newNodes];
}
if (setting.data.simpleData.enable) {
newNodes = data.transformTozTreeFormat(setting, newNodes);
}
if (parentNode) {
var target_switchObj = $("#" + parentNode.tId + consts.id.SWITCH),
target_icoObj = $("#" + parentNode.tId + consts.id.ICON),
target_ulObj = $("#" + parentNode.tId + consts.id.UL);
if (!parentNode.open) {
view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE);
view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE);
parentNode.open = false;
target_ulObj.css({
"display": "none"
});
}
data.addNodesData(setting, parentNode, newNodes);
view.createNodes(setting, parentNode.level + 1, newNodes, parentNode);
if (!isSilent) {
view.expandCollapseParentNode(setting, parentNode, true);
}
} else {
data.addNodesData(setting, data.getRoot(setting), newNodes);
view.createNodes(setting, 0, newNodes, null);
}
},
appendNodes: function(setting, level, nodes, parentNode, initFlag, openFlag) {
if (!nodes) return [];
var html = [],
childKey = setting.data.key.children,
nameKey = setting.data.key.name,
titleKey = data.getTitleKey(setting);
for (var i = 0, l = nodes.length; i < l; i++) {
var node = nodes[i],
tmpPNode = (parentNode) ? parentNode: data.getRoot(setting),
tmpPChild = tmpPNode[childKey],
isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)),
isLastNode = (i == (nodes.length - 1));
if (initFlag) {
data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag);
data.addNodeCache(setting, node);
}
var childHtml = [];
if (node[childKey] && node[childKey].length > 0) {
//make child html first, because checkType
childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open);
}
if (openFlag) {
var url = view.makeNodeUrl(setting, node),
fontcss = view.makeNodeFontCss(setting, node),
fontStyle = [];
for (var f in fontcss) {
fontStyle.push(f, ":", fontcss[f], ";");
}
html.push("<li id='", node.tId, "' class='level", node.level,"' treenode>",
"<button type='button' hidefocus='true'",(node.isParent?"":"disabled")," id='", node.tId, consts.id.SWITCH,
"' title='' class='", view.makeNodeLineClass(setting, node), "' treeNode", consts.id.SWITCH,"></button>");
data.getBeforeA(setting, node, html);
html.push("<a id='", node.tId, consts.id.A, "' class='level", node.level,"' treeNode", consts.id.A," onclick=\"", (node.click || ''),
"\" ", ((url != null && url.length > 0) ? "href='" + url + "'" : ""), " target='",view.makeNodeTarget(node),"' style='", fontStyle.join(''),
"'");
if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && node[titleKey]) {html.push("title='", node[titleKey].replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>'),"'");}
html.push(">");
data.getInnerBeforeA(setting, node, html);
var name = setting.view.nameIsHTML ? node[nameKey] : node[nameKey].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
html.push("<button type='button' hidefocus='true' id='", node.tId, consts.id.ICON,
"' title='' treeNode", consts.id.ICON," class='", view.makeNodeIcoClass(setting, node), "' style='", view.makeNodeIcoStyle(setting, node), "'></button><span id='", node.tId, consts.id.SPAN,
"'>",name,"</span>");
data.getInnerAfterA(setting, node, html);
html.push("</a>");
data.getAfterA(setting, node, html);
if (node.isParent && node.open) {
view.makeUlHtml(setting, node, html, childHtml.join(''));
}
html.push("</li>");
data.addCreatedNode(setting, node);
}
}
return html;
},
appendParentULDom: function(setting, node) {
var html = [],
nObj = $("#" + node.tId),
ulObj = $("#" + node.tId + consts.id.UL),
childKey = setting.data.key.children,
childHtml = view.appendNodes(setting, node.level+1, node[childKey], node, false, true);
view.makeUlHtml(setting, node, html, childHtml.join(''));
if (!nObj.get(0) && !!node.parentTId) {
view.appendParentULDom(setting, node.getParentNode());
nObj = $("#" + node.tId);
}
if (ulObj.get(0)) {
ulObj.remove();
}
nObj.append(html.join(''));
view.createNodeCallback(setting);
},
asyncNode: function(setting, node, isSilent, callback) {
var i, l;
if (node && !node.isParent) {
tools.apply(callback);
return false;
} else if (node && node.isAjaxing) {
return false;
} else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) {
tools.apply(callback);
return false;
}
if (node) {
node.isAjaxing = true;
var icoObj = $("#" + node.tId + consts.id.ICON);
icoObj.attr({"style":"", "class":"ico_loading"});
}
var isJson = (setting.async.contentType == "application/json"), tmpParam = isJson ? "{" : "", jTemp="";
for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) {
var pKey = setting.async.autoParam[i].split("="), spKey = pKey;
if (pKey.length>1) {
spKey = pKey[1];
pKey = pKey[0];
}
if (isJson) {
jTemp = (typeof node[pKey] == "string") ? '"' : '';
tmpParam += '"' + spKey + ('":' + jTemp + node[pKey]).replace(/'/g,'\\\'') + jTemp + ',';
} else {
tmpParam += spKey + ("=" + node[pKey]).replace(/&/g,'%26') + "&";
}
}
if (tools.isArray(setting.async.otherParam)) {
for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) {
if (isJson) {
jTemp = (typeof setting.async.otherParam[i + 1] == "string") ? '"' : '';
tmpParam += '"' + setting.async.otherParam[i] + ('":' + jTemp + setting.async.otherParam[i + 1]).replace(/'/g,'\\\'') + jTemp + ",";
} else {
tmpParam += setting.async.otherParam[i] + ("=" + setting.async.otherParam[i + 1]).replace(/&/g,'%26') + "&";
}
}
} else {
for (var p in setting.async.otherParam) {
if (isJson) {
jTemp = (typeof setting.async.otherParam[p] == "string") ? '"' : '';
tmpParam += '"' + p + ('":' + jTemp + setting.async.otherParam[p]).replace(/'/g,'\\\'') + jTemp + ",";
} else {
tmpParam += p + ("=" + setting.async.otherParam[p]).replace(/&/g,'%26') + "&";
}
}
}
if (tmpParam.length > 1) tmpParam = tmpParam.substring(0, tmpParam.length-1);
if (isJson) tmpParam += "}";
$.ajax({
contentType: setting.async.contentType,
type: setting.async.type,
url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url),
data: tmpParam,
dataType: setting.async.dataType,
success: function(msg) {
var newNodes = [];
try {
if (!msg || msg.length == 0) {
newNodes = [];
} else if (typeof msg == "string") {
newNodes = eval("(" + msg + ")");
} else {
newNodes = msg;
}
} catch(err) {}
if (node) {
node.isAjaxing = null;
node.zAsync = true;
}
view.setNodeLineIcos(setting, node);
if (newNodes && newNodes != "") {
newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes);
view.addNodes(setting, node, tools.clone(newNodes), !!isSilent);
} else {
view.addNodes(setting, node, [], !!isSilent);
}
setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]);
tools.apply(callback);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
view.setNodeLineIcos(setting, node);
if (node) node.isAjaxing = null;
setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]);
}
});
return true;
},
cancelPreSelectedNode: function (setting, node) {
var list = data.getRoot(setting).curSelectedList;
for (var i=0, j=list.length-1; j>=i; j--) {
if (!node || node === list[j]) {
$("#" + list[j].tId + consts.id.A).removeClass(consts.node.CURSELECTED);
view.setNodeName(setting, list[j]);
if (node) {
data.removeSelectedNode(setting, node);
break;
}
}
}
if (!node) data.getRoot(setting).curSelectedList = [];
},
createNodeCallback: function(setting) {
if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) {
var root = data.getRoot(setting);
while (root.createdNodes.length>0) {
var node = root.createdNodes.shift();
tools.apply(setting.view.addDiyDom, [setting.treeId, node]);
if (!!setting.callback.onNodeCreated) {
setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]);
}
}
}
},
createNodes: function(setting, level, nodes, parentNode) {
if (!nodes || nodes.length == 0) return;
var root = data.getRoot(setting),
childKey = setting.data.key.children,
openFlag = !parentNode || parentNode.open || !!$("#" + parentNode[childKey][0].tId).get(0);
root.createdNodes = [];
var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag);
if (!parentNode) {
setting.treeObj.append(zTreeHtml.join(''));
} else {
var ulObj = $("#" + parentNode.tId + consts.id.UL);
if (ulObj.get(0)) {
ulObj.append(zTreeHtml.join(''));
}
}
view.createNodeCallback(setting);
},
expandCollapseNode: function(setting, node, expandFlag, animateFlag, callback) {
var root = data.getRoot(setting),
childKey = setting.data.key.children;
if (!node) {
tools.apply(callback, []);
return;
}
if (root.expandTriggerFlag) {
var _callback = callback;
callback = function(){
if (_callback) _callback();
if (node.open) {
setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]);
} else {
setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]);
}
};
root.expandTriggerFlag = false;
}
if (node.open == expandFlag) {
tools.apply(callback, []);
return;
}
if (!node.open && node.isParent && ((!$("#" + node.tId + consts.id.UL).get(0)) || (node[childKey] && node[childKey].length>0 && !$("#" + node[childKey][0].tId).get(0)))) {
view.appendParentULDom(setting, node);
}
var ulObj = $("#" + node.tId + consts.id.UL),
switchObj = $("#" + node.tId + consts.id.SWITCH),
icoObj = $("#" + node.tId + consts.id.ICON);
if (node.isParent) {
node.open = !node.open;
if (node.iconOpen && node.iconClose) {
icoObj.attr("style", view.makeNodeIcoStyle(setting, node));
}
if (node.open) {
view.replaceSwitchClass(node, switchObj, consts.folder.OPEN);
view.replaceIcoClass(node, icoObj, consts.folder.OPEN);
if (animateFlag == false || setting.view.expandSpeed == "") {
ulObj.show();
tools.apply(callback, []);
} else {
if (node[childKey] && node[childKey].length > 0) {
ulObj.slideDown(setting.view.expandSpeed, callback);
} else {
ulObj.show();
tools.apply(callback, []);
}
}
} else {
view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE);
view.replaceIcoClass(node, icoObj, consts.folder.CLOSE);
if (animateFlag == false || setting.view.expandSpeed == "") {
ulObj.hide();
tools.apply(callback, []);
} else {
ulObj.slideUp(setting.view.expandSpeed, callback);
}
}
} else {
tools.apply(callback, []);
}
},
expandCollapseParentNode: function(setting, node, expandFlag, animateFlag, callback) {
if (!node) return;
if (!node.parentTId) {
view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback);
return;
} else {
view.expandCollapseNode(setting, node, expandFlag, animateFlag);
}
if (node.parentTId) {
view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback);
}
},
expandCollapseSonNode: function(setting, node, expandFlag, animateFlag, callback) {
var root = data.getRoot(setting),
childKey = setting.data.key.children,
treeNodes = (node) ? node[childKey]: root[childKey],
selfAnimateSign = (node) ? false : animateFlag,
expandTriggerFlag = data.getRoot(setting).expandTriggerFlag;
data.getRoot(setting).expandTriggerFlag = false;
if (treeNodes) {
for (var i = 0, l = treeNodes.length; i < l; i++) {
if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign);
}
}
data.getRoot(setting).expandTriggerFlag = expandTriggerFlag;
view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback );
},
makeNodeFontCss: function(setting, node) {
var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss);
return (fontCss && ((typeof fontCss) != "function")) ? fontCss : {};
},
makeNodeIcoClass: function(setting, node) {
var icoCss = ["ico"];
if (!node.isAjaxing) {
icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0];
if (node.isParent) {
icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE);
} else {
icoCss.push(consts.folder.DOCU);
}
}
return icoCss.join('_');
},
makeNodeIcoStyle: function(setting, node) {
var icoStyle = [];
if (!node.isAjaxing) {
var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon;
if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;");
if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) {
icoStyle.push("width:0px;height:0px;");
}
}
return icoStyle.join('');
},
makeNodeLineClass: function(setting, node) {
var lineClass = [];
if (setting.view.showLine) {
if (node.level == 0 && node.isFirstNode && node.isLastNode) {
lineClass.push(consts.line.ROOT);
} else if (node.level == 0 && node.isFirstNode) {
lineClass.push(consts.line.ROOTS);
} else if (node.isLastNode) {
lineClass.push(consts.line.BOTTOM);
} else {
lineClass.push(consts.line.CENTER);
}
} else {
lineClass.push(consts.line.NOLINE);
}
if (node.isParent) {
lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE);
} else {
lineClass.push(consts.folder.DOCU);
}
return view.makeNodeLineClassEx(node) + lineClass.join('_');
},
makeNodeLineClassEx: function(node) {
return "level" + node.level + " switch ";
},
makeNodeTarget: function(node) {
return (node.target || "_blank");
},
makeNodeUrl: function(setting, node) {
return node.url ? node.url : null;
},
makeUlHtml: function(setting, node, html, content) {
html.push("<ul id='", node.tId, consts.id.UL, "' class='level", node.level, " ", view.makeUlLineClass(setting, node), "' style='display:", (node.open ? "block": "none"),"'>");
html.push(content);
html.push("</ul>");
},
makeUlLineClass: function(setting, node) {
return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : "");
},
replaceIcoClass: function(node, obj, newName) {
if (!obj || node.isAjaxing) return;
var tmpName = obj.attr("class");
if (tmpName == undefined) return;
var tmpList = tmpName.split("_");
switch (newName) {
case consts.folder.OPEN:
case consts.folder.CLOSE:
case consts.folder.DOCU:
tmpList[tmpList.length-1] = newName;
break;
}
obj.attr("class", tmpList.join("_"));
},
replaceSwitchClass: function(node, obj, newName) {
if (!obj) return;
var tmpName = obj.attr("class");
if (tmpName == undefined) return;
var tmpList = tmpName.split("_");
switch (newName) {
case consts.line.ROOT:
case consts.line.ROOTS:
case consts.line.CENTER:
case consts.line.BOTTOM:
case consts.line.NOLINE:
tmpList[0] = view.makeNodeLineClassEx(node) + newName;
break;
case consts.folder.OPEN:
case consts.folder.CLOSE:
case consts.folder.DOCU:
tmpList[1] = newName;
break;
}
obj.attr("class", tmpList.join("_"));
if (newName !== consts.folder.DOCU) {
obj.removeAttr("disabled");
} else {
obj.attr("disabled", "disabled");
}
},
selectNode: function(setting, node, addFlag) {
if (!addFlag) {
view.cancelPreSelectedNode(setting);
}
$("#" + node.tId + consts.id.A).addClass(consts.node.CURSELECTED);
data.addSelectedNode(setting, node);
},
setNodeFontCss: function(setting, treeNode) {
var aObj = $("#" + treeNode.tId + consts.id.A),
fontCss = view.makeNodeFontCss(setting, treeNode);
if (fontCss) {
aObj.css(fontCss);
}
},
setNodeLineIcos: function(setting, node) {
if (!node) return;
var switchObj = $("#" + node.tId + consts.id.SWITCH),
ulObj = $("#" + node.tId + consts.id.UL),
icoObj = $("#" + node.tId + consts.id.ICON),
ulLine = view.makeUlLineClass(setting, node);
if (ulLine.length==0) {
ulObj.removeClass(consts.line.LINE);
} else {
ulObj.addClass(ulLine);
}
switchObj.attr("class", view.makeNodeLineClass(setting, node));
if (node.isParent) {
switchObj.removeAttr("disabled");
} else {
switchObj.attr("disabled", "disabled");
}
icoObj.removeAttr("style");
icoObj.attr("style", view.makeNodeIcoStyle(setting, node));
icoObj.attr("class", view.makeNodeIcoClass(setting, node));
},
setNodeName: function(setting, node) {
var nameKey = setting.data.key.name,
titleKey = data.getTitleKey(setting),
nObj = $("#" + node.tId + consts.id.SPAN);
nObj.empty();
if (setting.view.nameIsHTML) {
nObj.html(node[nameKey]);
} else {
nObj.text(node[nameKey]);
}
if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && node[titleKey]) {
var aObj = $("#" + node.tId + consts.id.A);
aObj.attr("title", node[titleKey]);
}
},
setNodeTarget: function(node) {
var aObj = $("#" + node.tId + consts.id.A);
aObj.attr("target", view.makeNodeTarget(node));
},
setNodeUrl: function(setting, node) {
var aObj = $("#" + node.tId + consts.id.A),
url = view.makeNodeUrl(setting, node);
if (url == null || url.length == 0) {
aObj.removeAttr("href");
} else {
aObj.attr("href", url);
}
},
switchNode: function(setting, node) {
if (node.open || !tools.canAsync(setting, node)) {
view.expandCollapseNode(setting, node, !node.open);
} else if (setting.async.enable) {
if (!view.asyncNode(setting, node)) {
view.expandCollapseNode(setting, node, !node.open);
return;
}
} else if (node) {
view.expandCollapseNode(setting, node, !node.open);
}
}
};
// zTree defind
$.fn.zTree = {
consts : _consts,
_z : {
tools: tools,
view: view,
event: event,
data: data
},
getZTreeObj: function(treeId) {
var o = data.getZTreeTools(treeId);
return o ? o : null;
},
init: function(obj, zSetting, zNodes) {
var setting = tools.clone(_setting);
$.extend(true, setting, zSetting);
setting.treeId = obj.attr("id");
setting.treeObj = obj;
setting.treeObj.empty();
settings[setting.treeId] = setting;
if ($.browser.msie && parseInt($.browser.version)<7) {
setting.view.expandSpeed = "";
}
data.initRoot(setting);
var root = data.getRoot(setting),
childKey = setting.data.key.children;
zNodes = zNodes ? tools.clone(tools.isArray(zNodes)? zNodes : [zNodes]) : [];
if (setting.data.simpleData.enable) {
root[childKey] = data.transformTozTreeFormat(setting, zNodes);
} else {
root[childKey] = zNodes;
}
data.initCache(setting);
event.bindTree(setting);
event.bindEvent(setting);
var zTreeTools = {
setting: setting,
cancelSelectedNode : function(node) {
view.cancelPreSelectedNode(this.setting, node);
},
expandAll : function(expandFlag) {
expandFlag = !!expandFlag;
view.expandCollapseSonNode(this.setting, null, expandFlag, true);
return expandFlag;
},
expandNode : function(node, expandFlag, sonSign, focus, callbackFlag) {
if (!node || !node.isParent) return null;
if (expandFlag !== true && expandFlag !== false) {
expandFlag = !node.open;
}
callbackFlag = !!callbackFlag;
if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) {
return null;
} else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) {
return null;
}
if (expandFlag && node.parentTId) {
view.expandCollapseParentNode(this.setting, node.getParentNode(), expandFlag, false);
}
if (expandFlag === node.open && !sonSign) {
return null;
}
data.getRoot(setting).expandTriggerFlag = callbackFlag;
if (sonSign) {
view.expandCollapseSonNode(this.setting, node, expandFlag, true, function() {
if (focus !== false) {$("#" + node.tId + consts.id.ICON).focus().blur();}
});
} else {
node.open = !expandFlag;
view.switchNode(this.setting, node);
if (focus !== false) {$("#" + node.tId + consts.id.ICON).focus().blur();}
}
return expandFlag;
},
getNodes : function() {
return data.getNodes(this.setting);
},
getNodeByParam : function(key, value, parentNode) {
if (!key) return null;
return data.getNodeByParam(this.setting, parentNode?parentNode[this.setting.data.key.children]:data.getNodes(this.setting), key, value);
},
getNodeByTId : function(tId) {
return data.getNodeCache(this.setting, tId);
},
getNodesByParam : function(key, value, parentNode) {
if (!key) return null;
return data.getNodesByParam(this.setting, parentNode?parentNode[this.setting.data.key.children]:data.getNodes(this.setting), key, value);
},
getNodesByParamFuzzy : function(key, value, parentNode) {
if (!key) return null;
return data.getNodesByParamFuzzy(this.setting, parentNode?parentNode[this.setting.data.key.children]:data.getNodes(this.setting), key, value);
},
getNodeIndex : function(node) {
if (!node) return null;
var childKey = setting.data.key.children,
parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(this.setting);
for (var i=0, l = parentNode[childKey].length; i < l; i++) {
if (parentNode[childKey][i] == node) return i;
}
return -1;
},
getSelectedNodes : function() {
var r = [], list = data.getRoot(this.setting).curSelectedList;
for (var i=0, l=list.length; i<l; i++) {
r.push(list[i]);
}
return r;
},
isSelectedNode : function(node) {
return data.isSelectedNode(this.setting, node);
},
reAsyncChildNodes : function(parentNode, reloadType, isSilent) {
if (!this.setting.async.enable) return;
var isRoot = !parentNode;
if (isRoot) {
parentNode = data.getRoot(this.setting);
}
if (reloadType=="refresh") {
parentNode[this.setting.data.key.children] = [];
if (isRoot) {
this.setting.treeObj.empty();
} else {
var ulObj = $("#" + parentNode.tId + consts.id.UL);
ulObj.empty();
}
}
view.asyncNode(this.setting, isRoot? null:parentNode, !!isSilent);
},
refresh : function() {
this.setting.treeObj.empty();
var root = data.getRoot(this.setting),
nodes = root[this.setting.data.key.children]
data.initRoot(this.setting);
root[this.setting.data.key.children] = nodes
data.initCache(this.setting);
view.createNodes(this.setting, 0, root[this.setting.data.key.children]);
},
selectNode : function(node, addFlag) {
if (!node) return;
if (tools.uCanDo(this.setting)) {
addFlag = setting.view.selectedMulti && addFlag;
if (node.parentTId) {
view.expandCollapseParentNode(this.setting, node.getParentNode(), true, false, function() {
$("#" + node.tId + consts.id.ICON).focus().blur();
});
} else {
$("#" + node.tId + consts.id.ICON).focus().blur();
}
view.selectNode(this.setting, node, addFlag);
}
},
transformTozTreeNodes : function(simpleNodes) {
return data.transformTozTreeFormat(this.setting, simpleNodes);
},
transformToArray : function(nodes) {
return data.transformToArrayFormat(this.setting, nodes);
},
updateNode : function(node, checkTypeFlag) {
if (!node) return;
var nObj = $("#" + node.tId);
if (nObj.get(0) && tools.uCanDo(this.setting)) {
view.setNodeName(this.setting, node);
view.setNodeTarget(node);
view.setNodeUrl(this.setting, node);
view.setNodeLineIcos(this.setting, node);
view.setNodeFontCss(this.setting, node);
}
}
}
root.treeTools = zTreeTools;
data.setZTreeTools(setting, zTreeTools);
if (root[childKey] && root[childKey].length > 0) {
view.createNodes(setting, 0, root[childKey]);
} else if (setting.async.enable && setting.async.url && setting.async.url !== '') {
view.asyncNode(setting);
}
return zTreeTools;
}
};
var zt = $.fn.zTree,
consts = zt.consts;
})(jQuery);
/*
* JQuery zTree excheck 3.1
* http://code.google.com/p/jquerytree/
*
* Copyright (c) 2010 Hunter.z (baby666.cn)
*
* Licensed same as jquery - MIT License
* http://www.opensource.org/licenses/mit-license.php
*
* email: hunter.z@263.net
* Date: 2012-02-14
*/
(function($){
//default consts of excheck
var _consts = {
event: {
CHECK: "ztree_check"
},
id: {
CHECK: "_check"
},
checkbox: {
STYLE: "checkbox",
DEFAULT: "chk",
DISABLED: "disable",
FALSE: "false",
TRUE: "true",
FULL: "full",
PART: "part",
FOCUS: "focus"
},
radio: {
STYLE: "radio",
TYPE_ALL: "all",
TYPE_LEVEL: "level"
}
},
//default setting of excheck
_setting = {
check: {
enable: false,
autoCheckTrigger: false,
chkStyle: _consts.checkbox.STYLE,
nocheckInherit: false,
radioType: _consts.radio.TYPE_LEVEL,
chkboxType: {
"Y": "ps",
"N": "ps"
}
},
data: {
key: {
checked: "checked"
}
},
callback: {
beforeCheck:null,
onCheck:null
}
},
//default root of excheck
_initRoot = function (setting) {
var r = data.getRoot(setting);
r.radioCheckedList = [];
},
//default cache of excheck
_initCache = function(treeId) {},
//default bind event of excheck
_bindEvent = function(setting) {
var o = setting.treeObj,
c = consts.event;
o.unbind(c.CHECK);
o.bind(c.CHECK, function (event, treeId, node) {
tools.apply(setting.callback.onCheck, [event, treeId, node]);
});
},
//default event proxy of excheck
_eventProxy = function(e) {
var target = e.target,
setting = data.getSetting(e.data.treeId),
tId = "", node = null,
nodeEventType = "", treeEventType = "",
nodeEventCallback = null, treeEventCallback = null;
if (tools.eqs(e.type, "mouseover")) {
if (setting.check.enable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) {
tId = target.parentNode.id;
nodeEventType = "mouseoverCheck";
}
} else if (tools.eqs(e.type, "mouseout")) {
if (setting.check.enable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) {
tId = target.parentNode.id;
nodeEventType = "mouseoutCheck";
}
} else if (tools.eqs(e.type, "click")) {
if (setting.check.enable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) {
tId = target.parentNode.id;
nodeEventType = "checkNode";
}
}
if (tId.length>0) {
node = data.getNodeCache(setting, tId);
switch (nodeEventType) {
case "checkNode" :
nodeEventCallback = _handler.onCheckNode;
break;
case "mouseoverCheck" :
nodeEventCallback = _handler.onMouseoverCheck;
break;
case "mouseoutCheck" :
nodeEventCallback = _handler.onMouseoutCheck;
break;
}
}
var proxyResult = {
stop: false,
node: node,
nodeEventType: nodeEventType,
nodeEventCallback: nodeEventCallback,
treeEventType: treeEventType,
treeEventCallback: treeEventCallback
};
return proxyResult
},
//default init node of excheck
_initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) {
if (!n) return;
var checkedKey = setting.data.key.checked;
if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true");
n[checkedKey] = !!n[checkedKey];
n.checkedOld = n[checkedKey];
n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck);
n.chkDisabled = !!n.chkDisabled || (parentNode && !!parentNode.chkDisabled);
if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true");
n.halfCheck = !!n.halfCheck;
n.check_Child_State = -1;
n.check_Focus = false;
n.getCheckStatus = function() {return data.getCheckStatus(setting, n);};
if (isLastNode) {
data.makeChkFlag(setting, parentNode);
}
},
//add dom for check
_beforeA = function(setting, node, html) {
var checkedKey = setting.data.key.checked;
if (setting.check.enable) {
data.makeChkFlag(setting, node);
if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && node[checkedKey] ) {
var r = data.getRoot(setting);
r.radioCheckedList.push(node);
}
html.push("<button type='button' ID='", node.tId, consts.id.CHECK, "' class='", view.makeChkClass(setting, node), "' treeNode", consts.id.CHECK," onfocus='this.blur();' ",(node.nocheck === true?"style='display:none;'":""),"></button>");
}
},
//update zTreeObj, add method of check
_zTreeTools = function(setting, zTreeTools) {
zTreeTools.checkNode = function(node, checked, checkTypeFlag, callbackFlag) {
var checkedKey = this.setting.data.key.checked;
if (node.chkDisabled === true) return;
if (checked !== true && checked !== false) {
checked = !node[checkedKey];
}
callbackFlag = !!callbackFlag;
if (node[checkedKey] === checked && !checkTypeFlag) {
return;
} else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) {
return;
}
if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) {
node[checkedKey] = checked;
var checkObj = $("#" + node.tId + consts.id.CHECK);
if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node);
view.setChkClass(this.setting, checkObj, node);
view.repairParentChkClassWithSelf(this.setting, node);
if (callbackFlag) {
setting.treeObj.trigger(consts.event.CHECK, [setting.treeId, node]);
}
}
}
zTreeTools.checkAllNodes = function(checked) {
view.repairAllChk(this.setting, !!checked);
}
zTreeTools.getCheckedNodes = function(checked) {
var childKey = this.setting.data.key.children;
checked = (checked !== false);
return data.getTreeCheckedNodes(this.setting, data.getRoot(setting)[childKey], checked);
}
zTreeTools.getChangeCheckedNodes = function() {
var childKey = this.setting.data.key.children;
return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(setting)[childKey]);
}
zTreeTools.setChkDisabled = function(node, disabled) {
disabled = !!disabled;
view.repairSonChkDisabled(this.setting, node, disabled);
if (!disabled) view.repairParentChkDisabled(this.setting, node, disabled);
}
var _updateNode = zTreeTools.updateNode;
zTreeTools.updateNode = function(node, checkTypeFlag) {
if (_updateNode) _updateNode.apply(zTreeTools, arguments);
if (!node || !this.setting.check.enable) return;
var nObj = $("#" + node.tId);
if (nObj.get(0) && tools.uCanDo(this.setting)) {
var checkObj = $("#" + node.tId + consts.id.CHECK);
if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node);
view.setChkClass(this.setting, checkObj, node);
view.repairParentChkClassWithSelf(this.setting, node);
}
}
},
//method of operate data
_data = {
getRadioCheckedList: function(setting) {
var checkedList = data.getRoot(setting).radioCheckedList;
for (var i=0, j=checkedList.length; i<j; i++) {
if(!data.getNodeCache(setting, checkedList[i].tId)) {
checkedList.splice(i, 1);
i--; j--;
}
}
return checkedList;
},
getCheckStatus: function(setting, node) {
if (!setting.check.enable || node.nocheck) return null;
var checkedKey = setting.data.key.checked,
r = {
checked: node[checkedKey],
half: node.halfCheck ? node.halfCheck : (setting.check.chkStyle == consts.radio.STYLE ? (node.check_Child_State === 2) : (node[checkedKey] ? (node.check_Child_State > -1 && node.check_Child_State < 2) : (node.check_Child_State > 0)))
};
return r;
},
getTreeCheckedNodes: function(setting, nodes, checked, results) {
if (!nodes) return [];
var childKey = setting.data.key.children,
checkedKey = setting.data.key.checked;
results = !results ? [] : results;
for (var i = 0, l = nodes.length; i < l; i++) {
if (nodes[i].nocheck !== true && nodes[i][checkedKey] == checked) {
results.push(nodes[i]);
}
data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results);
}
return results;
},
getTreeChangeCheckedNodes: function(setting, nodes, results) {
if (!nodes) return [];
var childKey = setting.data.key.children,
checkedKey = setting.data.key.checked;
results = !results ? [] : results;
for (var i = 0, l = nodes.length; i < l; i++) {
if (nodes[i].nocheck !== true && nodes[i][checkedKey] != nodes[i].checkedOld) {
results.push(nodes[i]);
}
data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results);
}
return results;
},
makeChkFlag: function(setting, node) {
if (!node) return;
var childKey = setting.data.key.children,
checkedKey = setting.data.key.checked,
chkFlag = -1;
if (node[childKey]) {
var start = false;
for (var i = 0, l = node[childKey].length; i < l; i++) {
var cNode = node[childKey][i];
var tmp = -1;
if (setting.check.chkStyle == consts.radio.STYLE) {
if (cNode.nocheck === true) {
tmp = cNode.check_Child_State;
} else if (cNode.halfCheck === true) {
tmp = 2;
} else if (cNode.nocheck !== true && cNode[checkedKey]) {
tmp = 2;
} else {
tmp = cNode.check_Child_State > 0 ? 2:0;
}
if (tmp == 2) {
chkFlag = 2; break;
} else if (tmp == 0){
chkFlag = 0;
}
} else if (setting.check.chkStyle == consts.checkbox.STYLE) {
if (cNode.nocheck === true) {
tmp = cNode.check_Child_State;
} else if (cNode.halfCheck === true) {
tmp = 1;
} else if (cNode.nocheck !== true && cNode[checkedKey] ) {
tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1;
} else {
tmp = (cNode.check_Child_State > 0) ? 1 : 0;
}
if (tmp === 1) {
chkFlag = 1; break;
} else if (tmp === 2 && start && tmp !== chkFlag) {
chkFlag = 1; break;
} else if (chkFlag === 2 && tmp > -1 && tmp < 2) {
chkFlag = 1; break;
} else if (tmp > -1) {
chkFlag = tmp;
}
if (!start) start = (cNode.nocheck !== true);
}
}
}
node.check_Child_State = chkFlag;
}
},
//method of event proxy
_event = {
},
//method of event handler
_handler = {
onCheckNode: function (event, node) {
if (node.chkDisabled === true) return false;
var setting = data.getSetting(event.data.treeId),
checkedKey = setting.data.key.checked;
if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true;
node[checkedKey] = !node[checkedKey];
view.checkNodeRelation(setting, node);
var checkObj = $("#" + node.tId + consts.id.CHECK);
view.setChkClass(setting, checkObj, node);
view.repairParentChkClassWithSelf(setting, node);
setting.treeObj.trigger(consts.event.CHECK, [setting.treeId, node]);
return true;
},
onMouseoverCheck: function(event, node) {
if (node.chkDisabled === true) return false;
var setting = data.getSetting(event.data.treeId),
checkObj = $("#" + node.tId + consts.id.CHECK);
node.check_Focus = true;
view.setChkClass(setting, checkObj, node);
return true;
},
onMouseoutCheck: function(event, node) {
if (node.chkDisabled === true) return false;
var setting = data.getSetting(event.data.treeId),
checkObj = $("#" + node.tId + consts.id.CHECK);
node.check_Focus = false;
view.setChkClass(setting, checkObj, node);
return true;
}
},
//method of tools for zTree
_tools = {
},
//method of operate ztree dom
_view = {
checkNodeRelation: function(setting, node) {
var pNode, i, l,
childKey = setting.data.key.children,
checkedKey = setting.data.key.checked,
r = consts.radio;
if (setting.check.chkStyle == r.STYLE) {
var checkedList = data.getRadioCheckedList(setting);
if (node[checkedKey]) {
if (setting.check.radioType == r.TYPE_ALL) {
for (i = checkedList.length-1; i >= 0; i--) {
pNode = checkedList[i];
pNode[checkedKey] = false;
checkedList.splice(i, 1);
view.setChkClass(setting, $("#" + pNode.tId + consts.id.CHECK), pNode);
if (pNode.parentTId != node.parentTId) {
view.repairParentChkClassWithSelf(setting, pNode);
}
}
checkedList.push(node);
} else {
var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting);
for (i = 0, l = parentNode[childKey].length; i < l; i++) {
pNode = parentNode[childKey][i];
if (pNode[checkedKey] && pNode != node) {
pNode[checkedKey] = false;
view.setChkClass(setting, $("#" + pNode.tId + consts.id.CHECK), pNode);
}
}
}
} else if (setting.check.radioType == r.TYPE_ALL) {
for (i = 0, l = checkedList.length; i < l; i++) {
if (node == checkedList[i]) {
checkedList.splice(i, 1);
break;
}
}
}
} else {
if (node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.Y.indexOf("s") > -1)) {
view.setSonNodeCheckBox(setting, node, true);
}
if (!node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.N.indexOf("s") > -1)) {
view.setSonNodeCheckBox(setting, node, false);
}
if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) {
view.setParentNodeCheckBox(setting, node, true);
}
if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) {
view.setParentNodeCheckBox(setting, node, false);
}
}
},
makeChkClass: function(setting, node) {
var checkedKey = setting.data.key.checked,
c = consts.checkbox, r = consts.radio,
fullStyle = "";
if (node.chkDisabled === true) {
fullStyle = c.DISABLED;
} else if (node.halfCheck) {
fullStyle = c.PART;
} else if (setting.check.chkStyle == r.STYLE) {
fullStyle = (node.check_Child_State < 1)? c.FULL:c.PART;
} else {
fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL:c.PART) : ((node.check_Child_State < 1)? c.FULL:c.PART);
}
var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle;
chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName;
return c.DEFAULT + " " + chkName;
},
repairAllChk: function(setting, checked) {
if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) {
var checkedKey = setting.data.key.checked,
childKey = setting.data.key.children,
root = data.getRoot(setting);
for (var i = 0, l = root[childKey].length; i<l ; i++) {
var node = root[childKey][i];
if (node.nocheck !== true) {
node[checkedKey] = checked;
}
view.setSonNodeCheckBox(setting, node, checked);
}
}
},
repairChkClass: function(setting, node) {
if (!node) return;
data.makeChkFlag(setting, node);
var checkObj = $("#" + node.tId + consts.id.CHECK);
view.setChkClass(setting, checkObj, node);
},
repairParentChkClass: function(setting, node) {
if (!node || !node.parentTId) return;
var pNode = node.getParentNode();
view.repairChkClass(setting, pNode);
view.repairParentChkClass(setting, pNode);
},
repairParentChkClassWithSelf: function(setting, node) {
if (!node) return;
var childKey = setting.data.key.children;
if (node[childKey] && node[childKey].length > 0) {
view.repairParentChkClass(setting, node[childKey][0]);
} else {
view.repairParentChkClass(setting, node);
}
},
repairSonChkDisabled: function(setting, node, chkDisabled) {
if (!node) return;
var childKey = setting.data.key.children;
if (node.chkDisabled != chkDisabled) {
node.chkDisabled = chkDisabled;
if (node.nocheck !== true) view.repairChkClass(setting, node);
}
if (node[childKey]) {
for (var i = 0, l = node[childKey].length; i < l; i++) {
var sNode = node[childKey][i];
view.repairSonChkDisabled(setting, sNode, chkDisabled);
}
}
},
repairParentChkDisabled: function(setting, node, chkDisabled) {
if (!node) return;
if (node.chkDisabled != chkDisabled) {
node.chkDisabled = chkDisabled;
if (node.nocheck !== true) view.repairChkClass(setting, node);
}
view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled);
},
setChkClass: function(setting, obj, node) {
if (!obj) return;
if (node.nocheck === true) {
obj.hide();
} else {
obj.show();
}
obj.removeClass();
obj.addClass(view.makeChkClass(setting, node));
},
setParentNodeCheckBox: function(setting, node, value, srcNode) {
var childKey = setting.data.key.children,
checkedKey = setting.data.key.checked,
checkObj = $("#" + node.tId + consts.id.CHECK);
if (!srcNode) srcNode = node;
data.makeChkFlag(setting, node);
if (node.nocheck !== true && node.chkDisabled !== true) {
node[checkedKey] = value;
view.setChkClass(setting, checkObj, node);
if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true) {
setting.treeObj.trigger(consts.event.CHECK, [setting.treeId, node]);
}
}
if (node.parentTId) {
var pSign = true;
if (!value) {
var pNodes = node.getParentNode()[childKey];
for (var i = 0, l = pNodes.length; i < l; i++) {
if ((pNodes[i].nocheck !== true && pNodes[i][checkedKey])
|| (pNodes[i].nocheck === true && pNodes[i].check_Child_State > 0)) {
pSign = false;
break;
}
}
}
if (pSign) {
view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode);
}
}
},
setSonNodeCheckBox: function(setting, node, value, srcNode) {
if (!node) return;
var childKey = setting.data.key.children,
checkedKey = setting.data.key.checked,
checkObj = $("#" + node.tId + consts.id.CHECK);
if (!srcNode) srcNode = node;
var hasDisable = false;
if (node[childKey]) {
for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) {
var sNode = node[childKey][i];
view.setSonNodeCheckBox(setting, sNode, value, srcNode);
if (sNode.chkDisabled === true) hasDisable = true;
}
}
if (node != data.getRoot(setting) && node.chkDisabled !== true) {
if (hasDisable && node.nocheck !== true) {
data.makeChkFlag(setting, node);
}
if (node.nocheck !== true) {
node[checkedKey] = value;
if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1;
} else {
node.check_Child_State = -1;
}
view.setChkClass(setting, checkObj, node);
if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true) {
setting.treeObj.trigger(consts.event.CHECK, [setting.treeId, node]);
}
}
}
},
_z = {
tools: _tools,
view: _view,
event: _event,
data: _data
};
$.extend(true, $.fn.zTree.consts, _consts);
$.extend(true, $.fn.zTree._z, _z);
var zt = $.fn.zTree,
tools = zt._z.tools,
consts = zt.consts,
view = zt._z.view,
data = zt._z.data,
event = zt._z.event;
data.exSetting(_setting);
data.addInitBind(_bindEvent);
data.addInitCache(_initCache);
data.addInitNode(_initNode);
data.addInitProxy(_eventProxy);
data.addInitRoot(_initRoot);
data.addBeforeA(_beforeA);
data.addZTreeTools(_zTreeTools);
var _createNodes = view.createNodes;
view.createNodes = function(setting, level, nodes, parentNode) {
if (_createNodes) _createNodes.apply(view, arguments);
if (!nodes) return;
view.repairParentChkClassWithSelf(setting, parentNode);
}
})(jQuery);
/*
* JQuery zTree exedit 3.1
* http://code.google.com/p/jquerytree/
*
* Copyright (c) 2010 Hunter.z (baby666.cn)
*
* Licensed same as jquery - MIT License
* http://www.opensource.org/licenses/mit-license.php
*
* email: hunter.z@263.net
* Date: 2012-02-14
*/
(function($){
//default consts of exedit
var _consts = {
event: {
DRAG: "ztree_drag",
DROP: "ztree_drop",
REMOVE: "ztree_remove",
RENAME: "ztree_rename"
},
id: {
EDIT: "_edit",
INPUT: "_input",
REMOVE: "_remove"
},
move: {
TYPE_INNER: "inner",
TYPE_PREV: "prev",
TYPE_NEXT: "next"
},
node: {
CURSELECTED_EDIT: "curSelectedNode_Edit",
TMPTARGET_TREE: "tmpTargetzTree",
TMPTARGET_NODE: "tmpTargetNode"
}
},
//default setting of exedit
_setting = {
edit: {
enable: false,
editNameSelectAll: false,
showRemoveBtn: true,
showRenameBtn: true,
removeTitle: "remove",
renameTitle: "rename",
drag: {
autoExpandTrigger: false,
isCopy: true,
isMove: true,
prev: true,
next: true,
inner: true,
minMoveSize: 5,
borderMax: 10,
borderMin: -5,
maxShowNodeNum: 5,
autoOpenTime: 500
}
},
view: {
addHoverDom: null,
removeHoverDom: null
},
callback: {
beforeDrag:null,
beforeDragOpen:null,
beforeDrop:null,
beforeEditName:null,
beforeRemove:null,
beforeRename:null,
onDrag:null,
onDrop:null,
onRemove:null,
onRename:null
}
},
//default root of exedit
_initRoot = function (setting) {
var r = data.getRoot(setting);
r.curEditNode = null;
r.curEditInput = null;
r.curHoverNode = null;
r.dragFlag = 0;
r.dragNodeShowBefore = [];
r.dragMaskList = new Array();
r.showHoverDom = true;
},
//default cache of exedit
_initCache = function(treeId) {},
//default bind event of exedit
_bindEvent = function(setting) {
var o = setting.treeObj;
var c = consts.event;
o.unbind(c.RENAME);
o.bind(c.RENAME, function (event, treeId, treeNode) {
tools.apply(setting.callback.onRename, [event, treeId, treeNode]);
});
o.unbind(c.REMOVE);
o.bind(c.REMOVE, function (event, treeId, treeNode) {
tools.apply(setting.callback.onRemove, [event, treeId, treeNode]);
});
o.unbind(c.DRAG);
o.bind(c.DRAG, function (event, treeId, treeNodes) {
tools.apply(setting.callback.onDrag, [event, treeId, treeNodes]);
});
o.unbind(c.DROP);
o.bind(c.DROP, function (event, treeId, treeNodes, targetNode, moveType) {
tools.apply(setting.callback.onDrop, [event, treeId, treeNodes, targetNode, moveType]);
});
},
//default event proxy of exedit
_eventProxy = function(e) {
var target = e.target,
setting = data.getSetting(e.data.treeId),
relatedTarget = e.relatedTarget,
tId = "", node = null,
nodeEventType = "", treeEventType = "",
nodeEventCallback = null, treeEventCallback = null,
tmp = null;
if (tools.eqs(e.type, "mouseover")) {
tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]);
if (tmp) {
tId = tmp.parentNode.id;
nodeEventType = "hoverOverNode";
}
} else if (tools.eqs(e.type, "mouseout")) {
tmp = tools.getMDom(setting, relatedTarget, [{tagName:"a", attrName:"treeNode"+consts.id.A}]);
if (!tmp) {
tId = "remove";
nodeEventType = "hoverOutNode";
}
} else if (tools.eqs(e.type, "mousedown")) {
tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]);
if (tmp) {
tId = tmp.parentNode.id;
nodeEventType = "mousedownNode";
}
}
if (tId.length>0) {
node = data.getNodeCache(setting, tId);
switch (nodeEventType) {
case "mousedownNode" :
nodeEventCallback = _handler.onMousedownNode;
break;
case "hoverOverNode" :
nodeEventCallback = _handler.onHoverOverNode;
break;
case "hoverOutNode" :
nodeEventCallback = _handler.onHoverOutNode;
break;
}
}
var proxyResult = {
stop: false,
node: node,
nodeEventType: nodeEventType,
nodeEventCallback: nodeEventCallback,
treeEventType: treeEventType,
treeEventCallback: treeEventCallback
};
return proxyResult
},
//default init node of exedit
_initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) {
if (!n) return;
n.isHover = false;
n.editNameFlag = false;
},
//update zTreeObj, add method of edit
_zTreeTools = function(setting, zTreeTools) {
zTreeTools.addNodes = function(parentNode, newNodes, isSilent) {
if (!newNodes) return null;
if (!parentNode) parentNode = null;
if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null;
var xNewNodes = tools.clone(tools.isArray(newNodes)? newNodes: [newNodes]);
function addCallback() {
view.addNodes(setting, parentNode, xNewNodes, (isSilent==true));
}
if (setting.async.enable && tools.canAsync(setting, parentNode)) {
view.asyncNode(setting, parentNode, isSilent, addCallback);
} else {
addCallback();
}
return xNewNodes;
}
zTreeTools.cancelEditName = function(newName) {
var root = data.getRoot(setting),
nameKey = setting.data.key.name,
node = root.curEditNode;
if (!root.curEditNode) return;
view.cancelCurEditNode(setting, newName?newName:node[nameKey]);
}
zTreeTools.copyNode = function(targetNode, node, moveType, isSilent) {
if (!node) return null;
if (targetNode && !targetNode.isParent && setting.data.keep.leaf && moveType === consts.move.TYPE_INNER) return null;
var newNode = tools.clone(node);
if (!targetNode) {
targetNode = null;
moveType = consts.move.TYPE_INNER;
}
if (moveType == consts.move.TYPE_INNER) {
function copyCallback() {
view.addNodes(setting, targetNode, [newNode], isSilent);
}
if (setting.async.enable && tools.canAsync(setting, targetNode)) {
view.asyncNode(setting, targetNode, isSilent, copyCallback);
} else {
copyCallback();
}
} else {
view.addNodes(setting, targetNode.parentNode, [newNode], isSilent);
view.moveNode(setting, targetNode, newNode, moveType, false, isSilent);
}
return newNode;
}
zTreeTools.editName = function(node) {
if (!node || !node.tId || node !== data.getNodeCache(setting, node.tId)) return;
if (node.parentTId) view.expandCollapseParentNode(setting, node.getParentNode(), true);
view.editNode(setting, node)
}
zTreeTools.moveNode = function(targetNode, node, moveType, isSilent) {
if (!node) return node;
if (targetNode && !targetNode.isParent && setting.data.keep.leaf && moveType === consts.move.TYPE_INNER) {
return null;
} else if (targetNode && ((node.parentTId == targetNode.tId && moveType == consts.move.TYPE_INNER) || $("#" + node.tId).find("#" + targetNode.tId).length > 0)) {
return null;
} else if (!targetNode) {
targetNode = null;
}
function moveCallback() {
view.moveNode(setting, targetNode, node, moveType, false, isSilent);
}
if (setting.async.enable && tools.canAsync(setting, targetNode)) {
view.asyncNode(setting, targetNode, isSilent, moveCallback);
} else {
moveCallback();
}
return node;
}
zTreeTools.removeNode = function(node, callbackFlag) {
if (!node) return;
callbackFlag = !!callbackFlag;
if (callbackFlag && tools.apply(setting.callback.beforeRemove, [setting.treeId, node], true) == false) return;
view.removeNode(setting, node);
if (callbackFlag) {
this.setting.treeObj.trigger(consts.event.REMOVE, [setting.treeId, node]);
}
}
zTreeTools.removeChildNodes = function(node) {
if (!node) return null;
var childKey = setting.data.key.children,
nodes = node[childKey];
view.removeChildNodes(setting, node);
return nodes ? nodes : null;
}
zTreeTools.setEditable = function(editable) {
setting.edit.enable = editable;
return this.refresh();
}
},
//method of operate data
_data = {
setSonNodeLevel: function(setting, parentNode, node) {
if (!node) return;
var childKey = setting.data.key.children;
node.level = (parentNode)? parentNode.level + 1 : 0;
if (!node[childKey]) return;
for (var i = 0, l = node[childKey].length; i < l; i++) {
if (node[childKey][i]) data.setSonNodeLevel(setting, node, node[childKey][i]);
}
}
},
//method of event proxy
_event = {
},
//method of event handler
_handler = {
onHoverOverNode: function(event, node) {
var setting = data.getSetting(event.data.treeId),
root = data.getRoot(setting);
if (root.curHoverNode != node) {
_handler.onHoverOutNode(event);
}
root.curHoverNode = node;
view.addHoverDom(setting, node);
},
onHoverOutNode: function(event, node) {
var setting = data.getSetting(event.data.treeId),
root = data.getRoot(setting);
if (root.curHoverNode && !data.isSelectedNode(setting, root.curHoverNode)) {
view.removeTreeDom(setting, root.curHoverNode);
root.curHoverNode = null;
}
},
onMousedownNode: function(eventMouseDown, _node) {
var i,l,
setting = data.getSetting(eventMouseDown.data.treeId),
root = data.getRoot(setting);
//right click can't drag & drop
if (eventMouseDown.button == 2 || !setting.edit.enable || (!setting.edit.drag.isCopy && !setting.edit.drag.isMove)) return true;
//input of edit node name can't drag & drop
var target = eventMouseDown.target,
_nodes = data.getRoot(setting).curSelectedList,
nodes = [];
if (!data.isSelectedNode(setting, _node)) {
nodes = [_node];
} else {
for (i=0, l=_nodes.length; i<l; i++) {
if (_nodes[i].editNameFlag && tools.eqs(target.tagName, "input") && target.getAttribute("treeNode"+consts.id.INPUT) !== null) {
return true;
}
nodes.push(_nodes[i]);
if (nodes[0].parentTId !== _nodes[i].parentTId) {
nodes = [_node];
break;
}
}
}
view.editNodeBlur = true;
view.cancelCurEditNode(setting, null, true);
var doc = $(document), curNode, tmpArrow, tmpTarget,
isOtherTree = false,
targetSetting = setting,
preNode, nextNode,
preTmpTargetNodeId = null,
preTmpMoveType = null,
tmpTargetNodeId = null,
moveType = consts.move.TYPE_INNER,
mouseDownX = eventMouseDown.clientX,
mouseDownY = eventMouseDown.clientY,
startTime = (new Date()).getTime();
if (tools.uCanDo(setting)) {
doc.bind("mousemove", _docMouseMove);
}
function _docMouseMove(event) {
//avoid start drag after click node
if (root.dragFlag == 0 && Math.abs(mouseDownX - event.clientX) < setting.edit.drag.minMoveSize
&& Math.abs(mouseDownY - event.clientY) < setting.edit.drag.minMoveSize) {
return true;
}
var i, l, tmpNode, tmpDom, tmpNodes,
childKey = setting.data.key.children;
tools.noSel(setting);
$("body").css("cursor", "pointer");
if (root.dragFlag == 0) {
if (tools.apply(setting.callback.beforeDrag, [setting.treeId, nodes], true) == false) {
_docMouseUp(event);
return true;
}
for (i=0, l=nodes.length; i<l; i++) {
if (i==0) {
root.dragNodeShowBefore = [];
}
tmpNode = nodes[i];
if (tmpNode.isParent && tmpNode.open) {
view.expandCollapseNode(setting, tmpNode, !tmpNode.open);
root.dragNodeShowBefore[tmpNode.tId] = true;
} else {
root.dragNodeShowBefore[tmpNode.tId] = false;
}
}
root.dragFlag = 1;
root.showHoverDom = false;
tools.showIfameMask(setting, true);
//sort
var isOrder = true, lastIndex = -1;
if (nodes.length>1) {
var pNodes = nodes[0].parentTId ? nodes[0].getParentNode()[childKey] : data.getNodes(setting);
tmpNodes = [];
for (i=0, l=pNodes.length; i<l; i++) {
if (root.dragNodeShowBefore[pNodes[i].tId] !== undefined) {
if (isOrder && lastIndex > -1 && (lastIndex+1) !== i) {
isOrder = false;
}
tmpNodes.push(pNodes[i]);
lastIndex = i;
}
if (nodes.length === tmpNodes.length) {
nodes = tmpNodes;
break;
}
}
}
if (isOrder) {
preNode = nodes[0].getPreNode();
nextNode = nodes[nodes.length-1].getNextNode();
}
//set node in selected
curNode = $("<ul class='zTreeDragUL'></ul>");
for (i=0, l=nodes.length; i<l; i++) {
tmpNode = nodes[i];
tmpNode.editNameFlag = false;
view.selectNode(setting, tmpNode, i>0);
view.removeTreeDom(setting, tmpNode);
tmpDom = $("<li id='"+ tmpNode.tId +"_tmp'></li>");
tmpDom.append($("#" + tmpNode.tId + consts.id.A).clone());
tmpDom.css("padding", "0");
tmpDom.children("#" + tmpNode.tId + consts.id.A).removeClass(consts.node.CURSELECTED);
curNode.append(tmpDom);
if (i == setting.edit.drag.maxShowNodeNum-1) {
tmpDom = $("<li id='"+ tmpNode.tId +"_moretmp'><a> ... </a></li>");
curNode.append(tmpDom);
break;
}
}
curNode.attr("id", nodes[0].tId + consts.id.UL + "_tmp");
curNode.addClass(setting.treeObj.attr("class"));
curNode.appendTo("body");
tmpArrow = $("<button class='tmpzTreeMove_arrow'></button>");
tmpArrow.attr("id", "zTreeMove_arrow_tmp");
tmpArrow.appendTo("body");
setting.treeObj.trigger(consts.event.DRAG, [setting.treeId, nodes]);
}
if (root.dragFlag == 1 && tmpArrow.attr("id") != event.target.id) {
if (tmpTarget) {
tmpTarget.removeClass(consts.node.TMPTARGET_TREE);
if (tmpTargetNodeId) $("#" + tmpTargetNodeId + consts.id.A, tmpTarget).removeClass(consts.node.TMPTARGET_NODE);
}
tmpTarget = null;
tmpTargetNodeId = null;
//judge drag & drop in multi ztree
isOtherTree = false;
targetSetting = setting;
var settings = data.getSettings();
for (var s in settings) {
if (settings[s].treeId && settings[s].edit.enable && settings[s].treeId != setting.treeId
&& (event.target.id == settings[s].treeId || $(event.target).parents("#" + settings[s].treeId).length>0)) {
isOtherTree = true;
targetSetting = settings[s];
}
}
var docScrollTop = doc.scrollTop(),
docScrollLeft = doc.scrollLeft(),
treeOffset = targetSetting.treeObj.offset(),
scrollHeight = targetSetting.treeObj.get(0).scrollHeight,
scrollWidth = targetSetting.treeObj.get(0).scrollWidth,
dTop = (event.clientY + docScrollTop - treeOffset.top),
dBottom = (targetSetting.treeObj.height() + treeOffset.top - event.clientY - docScrollTop),
dLeft = (event.clientX + docScrollLeft - treeOffset.left),
dRight = (targetSetting.treeObj.width() + treeOffset.left - event.clientX - docScrollLeft),
isTop = (dTop < setting.edit.drag.borderMax && dTop > setting.edit.drag.borderMin),
isBottom = (dBottom < setting.edit.drag.borderMax && dBottom > setting.edit.drag.borderMin),
isLeft = (dLeft < setting.edit.drag.borderMax && dLeft > setting.edit.drag.borderMin),
isRight = (dRight < setting.edit.drag.borderMax && dRight > setting.edit.drag.borderMin),
isTreeInner = dTop > setting.edit.drag.borderMin && dBottom > setting.edit.drag.borderMin && dLeft > setting.edit.drag.borderMin && dRight > setting.edit.drag.borderMin,
isTreeTop = (isTop && targetSetting.treeObj.scrollTop() <= 0),
isTreeBottom = (isBottom && (targetSetting.treeObj.scrollTop() + targetSetting.treeObj.height()+10) >= scrollHeight),
isTreeLeft = (isLeft && targetSetting.treeObj.scrollLeft() <= 0),
isTreeRight = (isRight && (targetSetting.treeObj.scrollLeft() + targetSetting.treeObj.width()+10) >= scrollWidth);
if (event.target.id && targetSetting.treeObj.find("#" + event.target.id).length > 0) {
//get node <li> dom
var targetObj = event.target;
while (targetObj && targetObj.tagName && !tools.eqs(targetObj.tagName, "li") && targetObj.id != targetSetting.treeId) {
targetObj = targetObj.parentNode;
}
var canMove = true;
//don't move to self or children of self
for (i=0, l=nodes.length; i<l; i++) {
tmpNode = nodes[i];
if (targetObj.id === tmpNode.tId) {
canMove = false;
break;
} else if ($("#" + tmpNode.tId).find("#" + targetObj.id).length > 0) {
canMove = false;
break;
}
}
if (canMove) {
if (event.target.id &&
(event.target.id == (targetObj.id + consts.id.A) || $(event.target).parents("#" + targetObj.id + consts.id.A).length > 0)) {
tmpTarget = $(targetObj);
tmpTargetNodeId = targetObj.id;
}
}
}
//the mouse must be in zTree
tmpNode = nodes[0];
if (isTreeInner && (event.target.id == targetSetting.treeId || $(event.target).parents("#" + targetSetting.treeId).length>0)) {
//judge mouse move in root of ztree
if (!tmpTarget && (event.target.id == targetSetting.treeId || isTreeTop || isTreeBottom || isTreeLeft || isTreeRight) && (isOtherTree || (!isOtherTree && tmpNode.parentTId))) {
tmpTarget = targetSetting.treeObj;
}
//auto scroll top
if (isTop) {
targetSetting.treeObj.scrollTop(targetSetting.treeObj.scrollTop()-10);
} else if (isBottom) {
targetSetting.treeObj.scrollTop(targetSetting.treeObj.scrollTop()+10);
}
if (isLeft) {
targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()-10);
} else if (isRight) {
targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()+10);
}
//auto scroll left
if (tmpTarget && tmpTarget != targetSetting.treeObj && tmpTarget.offset().left < targetSetting.treeObj.offset().left) {
targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()+ tmpTarget.offset().left - targetSetting.treeObj.offset().left);
}
}
curNode.css({
"top": (event.clientY + docScrollTop + 3) + "px",
"left": (event.clientX + docScrollLeft + 3) + "px"
});
var dX = 0;
var dY = 0;
if (tmpTarget && tmpTarget.attr("id")!=targetSetting.treeId) {
var tmpTargetNode = tmpTargetNodeId == null ? null: data.getNodeCache(targetSetting, tmpTargetNodeId),
isCopy = (event.ctrlKey && setting.edit.drag.isMove && setting.edit.drag.isCopy) || (!setting.edit.drag.isMove && setting.edit.drag.isCopy),
isPrev = !!(preNode && tmpTargetNodeId === preNode.tId),
isNext = !!(nextNode && tmpTargetNodeId === nextNode.tId),
isInner = (tmpNode.parentTId && tmpNode.parentTId == tmpTargetNodeId),
canPrev = (isCopy || !isNext) && tools.apply(targetSetting.edit.drag.prev, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.prev),
canNext = (isCopy || !isPrev) && tools.apply(targetSetting.edit.drag.next, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.next),
canInner = (isCopy || !isInner) && !(targetSetting.data.keep.leaf && !tmpTargetNode.isParent) && tools.apply(targetSetting.edit.drag.inner, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.inner);
if (!canPrev && !canNext && !canInner) {
tmpTarget = null;
tmpTargetNodeId = "";
moveType = consts.move.TYPE_INNER;
tmpArrow.css({
"display":"none"
});
if (window.zTreeMoveTimer) {
clearTimeout(window.zTreeMoveTimer);
window.zTreeMoveTargetNodeTId = null
}
} else {
var tmpTargetA = $("#" + tmpTargetNodeId + consts.id.A, tmpTarget);
tmpTargetA.addClass(consts.node.TMPTARGET_NODE);
var prevPercent = canPrev ? (canInner ? 0.25 : (canNext ? 0.5 : 1) ) : -1,
nextPercent = canNext ? (canInner ? 0.75 : (canPrev ? 0.5 : 0) ) : -1,
dY_percent = (event.clientY + docScrollTop - tmpTargetA.offset().top)/tmpTargetA.height();
if ((prevPercent==1 ||dY_percent<=prevPercent && dY_percent>=-.2) && canPrev) {
dX = 1 - tmpArrow.width();
dY = 0 - tmpArrow.height()/2;
moveType = consts.move.TYPE_PREV;
} else if ((nextPercent==0 || dY_percent>=nextPercent && dY_percent<=1.2) && canNext) {
dX = 1 - tmpArrow.width();
dY = tmpTargetA.height() - tmpArrow.height()/2;
moveType = consts.move.TYPE_NEXT;
}else {
dX = 5 - tmpArrow.width();
dY = 0;
moveType = consts.move.TYPE_INNER;
}
tmpArrow.css({
"display":"block",
"top": (tmpTargetA.offset().top + dY) + "px",
"left": (tmpTargetA.offset().left + dX) + "px"
});
if (preTmpTargetNodeId != tmpTargetNodeId || preTmpMoveType != moveType) {
startTime = (new Date()).getTime();
}
if (tmpTargetNode && tmpTargetNode.isParent && moveType == consts.move.TYPE_INNER) {
var startTimer = true;
if (window.zTreeMoveTimer && window.zTreeMoveTargetNodeTId !== tmpTargetNode.tId) {
clearTimeout(window.zTreeMoveTimer);
window.zTreeMoveTargetNodeTId = null;
} else if (window.zTreeMoveTimer && window.zTreeMoveTargetNodeTId === tmpTargetNode.tId) {
startTimer = false;
}
if (startTimer) {
window.zTreeMoveTimer = setTimeout(function() {
if (moveType != consts.move.TYPE_INNER) return;
if (tmpTargetNode && tmpTargetNode.isParent && !tmpTargetNode.open && (new Date()).getTime() - startTime > targetSetting.edit.drag.autoOpenTime
&& tools.apply(targetSetting.callback.beforeDragOpen, [targetSetting.treeId, tmpTargetNode], true)) {
view.switchNode(targetSetting, tmpTargetNode);
if (targetSetting.edit.drag.autoExpandTrigger) {
targetSetting.treeObj.trigger(consts.event.EXPAND, [targetSetting.treeId, tmpTargetNode]);
}
}
}, targetSetting.edit.drag.autoOpenTime+50);
window.zTreeMoveTargetNodeTId = tmpTargetNode.tId;
}
}
}
} else {
moveType = consts.move.TYPE_INNER;
if (tmpTarget && tools.apply(targetSetting.edit.drag.inner, [targetSetting.treeId, nodes, null], !!targetSetting.edit.drag.inner)) {
tmpTarget.addClass(consts.node.TMPTARGET_TREE);
} else {
tmpTarget = null;
}
tmpArrow.css({
"display":"none"
});
if (window.zTreeMoveTimer) {
clearTimeout(window.zTreeMoveTimer);
window.zTreeMoveTargetNodeTId = null;
}
}
preTmpTargetNodeId = tmpTargetNodeId;
preTmpMoveType = moveType;
}
return false;
}
doc.bind("mouseup", _docMouseUp);
function _docMouseUp(event) {
if (window.zTreeMoveTimer) {
clearTimeout(window.zTreeMoveTimer);
window.zTreeMoveTargetNodeTId = null;
}
preTmpTargetNodeId = null;
preTmpMoveType = null;
doc.unbind("mousemove", _docMouseMove);
doc.unbind("mouseup", _docMouseUp);
doc.unbind("selectstart", _docSelect);
$("body").css("cursor", "auto");
if (tmpTarget) {
tmpTarget.removeClass(consts.node.TMPTARGET_TREE);
if (tmpTargetNodeId) $("#" + tmpTargetNodeId + consts.id.A, tmpTarget).removeClass(consts.node.TMPTARGET_NODE);
}
tools.showIfameMask(setting, false);
root.showHoverDom = true;
if (root.dragFlag == 0) return;
root.dragFlag = 0;
var i, l, tmpNode,
childKey = setting.data.key.children;
for (i=0, l=nodes.length; i<l; i++) {
tmpNode = nodes[i];
if (tmpNode.isParent && root.dragNodeShowBefore[tmpNode.tId] && !tmpNode.open) {
view.expandCollapseNode(setting, tmpNode, !tmpNode.open);
delete root.dragNodeShowBefore[tmpNode.tId];
}
}
if (curNode) curNode.remove();
if (tmpArrow) tmpArrow.remove();
var isCopy = (event.ctrlKey && setting.edit.drag.isMove && setting.edit.drag.isCopy) || (!setting.edit.drag.isMove && setting.edit.drag.isCopy);
if (!isCopy && tmpTarget && tmpTargetNodeId && nodes[0].parentTId && tmpTargetNodeId==nodes[0].parentTId && moveType == consts.move.TYPE_INNER) {
tmpTarget = null;
}
if (tmpTarget) {
var dragTargetNode = tmpTargetNodeId == null ? null: data.getNodeCache(targetSetting, tmpTargetNodeId);
if (tools.apply(setting.callback.beforeDrop, [targetSetting.treeId, nodes, dragTargetNode, moveType], true) == false) return;
var newNodes = isCopy ? tools.clone(nodes) : nodes;
function dropCallback() {
if (isOtherTree) {
if (!isCopy) {
for(var i=0, l=nodes.length; i<l; i++) {
view.removeNode(setting, nodes[i]);
}
}
if (moveType == consts.move.TYPE_INNER) {
view.addNodes(targetSetting, dragTargetNode, newNodes);
} else {
view.addNodes(targetSetting, dragTargetNode.getParentNode(), newNodes);
if (moveType == consts.move.TYPE_PREV) {
for (i=0, l=newNodes.length; i<l; i++) {
view.moveNode(targetSetting, dragTargetNode, newNodes[i], moveType, false);
}
} else {
for (i=-1, l=newNodes.length-1; i<l; l--) {
view.moveNode(targetSetting, dragTargetNode, newNodes[l], moveType, false);
}
}
}
} else {
if (isCopy && moveType == consts.move.TYPE_INNER) {
view.addNodes(targetSetting, dragTargetNode, newNodes);
} else {
if (isCopy) {
view.addNodes(targetSetting, dragTargetNode.getParentNode(), newNodes);
}
if (moveType == consts.move.TYPE_PREV) {
for (i=0, l=newNodes.length; i<l; i++) {
view.moveNode(targetSetting, dragTargetNode, newNodes[i], moveType, false);
}
} else {
for (i=-1, l=newNodes.length-1; i<l; l--) {
view.moveNode(targetSetting, dragTargetNode, newNodes[l], moveType, false);
}
}
}
}
for (i=0, l=newNodes.length; i<l; i++) {
view.selectNode(targetSetting, newNodes[i], i>0);
}
$("#" + newNodes[0].tId + consts.id.ICON).focus().blur();
}
if (moveType == consts.move.TYPE_INNER && tools.canAsync(targetSetting, dragTargetNode)) {
view.asyncNode(targetSetting, dragTargetNode, false, dropCallback);
} else {
dropCallback();
}
setting.treeObj.trigger(consts.event.DROP, [targetSetting.treeId, newNodes, dragTargetNode, moveType]);
} else {
for (i=0, l=nodes.length; i<l; i++) {
view.selectNode(targetSetting, nodes[i], i>0);
}
setting.treeObj.trigger(consts.event.DROP, [setting.treeId, null, null, null]);
}
}
doc.bind("selectstart", _docSelect);
function _docSelect() {
return false;
}
//Avoid FireFox's Bug
//If zTree Div CSS set 'overflow', so drag node outside of zTree, and event.target is error.
if(eventMouseDown.preventDefault) {
eventMouseDown.preventDefault();
}
return true;
}
},
//method of tools for zTree
_tools = {
getAbs: function (obj) {
var oRect = obj.getBoundingClientRect();
return [oRect.left,oRect.top]
},
inputFocus: function(inputObj) {
if (inputObj.get(0)) {
inputObj.focus();
tools.setCursorPosition(inputObj.get(0), inputObj.val().length);
}
},
inputSelect: function(inputObj) {
if (inputObj.get(0)) {
inputObj.focus();
inputObj.select();
}
},
setCursorPosition: function(obj, pos){
if(obj.setSelectionRange) {
obj.focus();
obj.setSelectionRange(pos,pos);
} else if (obj.createTextRange) {
var range = obj.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
},
showIfameMask: function(setting, showSign) {
var root = data.getRoot(setting);
//clear full mask
while (root.dragMaskList.length > 0) {
root.dragMaskList[0].remove();
root.dragMaskList.shift();
}
if (showSign) {
//show mask
var iframeList = $("iframe");
for (var i = 0, l = iframeList.length; i < l; i++) {
var obj = iframeList.get(i),
r = tools.getAbs(obj),
dragMask = $("<div id='zTreeMask_" + i + "' class='zTreeMask' style='background-color:yellow;opacity: 0.3;filter: alpha(opacity=30); top:" + r[1] + "px; left:" + r[0] + "px; width:" + obj.offsetWidth + "px; height:" + obj.offsetHeight + "px;'></div>");
dragMask.appendTo("body");
root.dragMaskList.push(dragMask);
}
}
}
},
//method of operate ztree dom
_view = {
addEditBtn: function(setting, node) {
if (node.editNameFlag || $("#" + node.tId + consts.id.EDIT).length > 0) {
return;
}
if (!tools.apply(setting.edit.showRenameBtn, [setting.treeId, node], setting.edit.showRenameBtn)) {
return;
}
var aObj = $("#" + node.tId + consts.id.A),
editStr = "<button type='button' class='edit' id='" + node.tId + consts.id.EDIT + "' title='"+tools.apply(setting.edit.renameTitle, [setting.treeId, node], setting.edit.renameTitle)+"' treeNode"+consts.id.EDIT+" onfocus='this.blur();' style='display:none;'></button>";
aObj.append(editStr);
$("#" + node.tId + consts.id.EDIT).bind('click',
function() {
if (!tools.uCanDo(setting) || tools.apply(setting.callback.beforeEditName, [setting.treeId, node], true) == false) return true;
view.editNode(setting, node);
return false;
}
).show();
},
addRemoveBtn: function(setting, node) {
if (node.editNameFlag || $("#" + node.tId + consts.id.REMOVE).length > 0) {
return;
}
if (!tools.apply(setting.edit.showRemoveBtn, [setting.treeId, node], setting.edit.showRemoveBtn)) {
return;
}
var aObj = $("#" + node.tId + consts.id.A),
removeStr = "<button type='button' class='remove' id='" + node.tId + consts.id.REMOVE + "' title='"+tools.apply(setting.edit.removeTitle, [setting.treeId, node], setting.edit.removeTitle)+"' treeNode"+consts.id.REMOVE+" onfocus='this.blur();' style='display:none;'></button>";
aObj.append(removeStr);
$("#" + node.tId + consts.id.REMOVE).bind('click',
function() {
if (!tools.uCanDo(setting) || tools.apply(setting.callback.beforeRemove, [setting.treeId, node], true) == false) return true;
view.removeNode(setting, node);
setting.treeObj.trigger(consts.event.REMOVE, [setting.treeId, node]);
return false;
}
).bind('mousedown',
function(eventMouseDown) {
return true;
}
).show();
},
addHoverDom: function(setting, node) {
if (data.getRoot(setting).showHoverDom) {
node.isHover = true;
if (setting.edit.enable) {
view.addEditBtn(setting, node);
view.addRemoveBtn(setting, node);
}
tools.apply(setting.view.addHoverDom, [setting.treeId, node]);
}
},
cancelCurEditNode: function (setting, forceName, isKey) {
var root = data.getRoot(setting),
nameKey = setting.data.key.name,
node = root.curEditNode;
if (node) {
var inputObj = root.curEditInput;
var newName = forceName ? forceName:inputObj.val();
if (!forceName && tools.apply(setting.callback.beforeRename, [setting.treeId, node, newName], true) === false) {
node.editNameFlag = true;
return false;
} else {
node[nameKey] = newName ? newName:inputObj.val();
if (!forceName) {
setting.treeObj.trigger(consts.event.RENAME, [setting.treeId, node]);
}
}
var aObj = $("#" + node.tId + consts.id.A);
aObj.removeClass(consts.node.CURSELECTED_EDIT);
inputObj.unbind();
view.setNodeName(setting, node);
node.editNameFlag = false;
root.curEditNode = null;
root.curEditInput = null;
view.selectNode(setting, node, false);
}
root.noSelection = true;
return true;
},
editNode: function(setting, node) {
var root = data.getRoot(setting);
view.editNodeBlur = false;
if (data.isSelectedNode(setting, node) && root.curEditNode == node && node.editNameFlag) {
setTimeout(function() {tools.inputFocus(root.curEditInput);}, 0);
return;
}
var nameKey = setting.data.key.name;
node.editNameFlag = true;
view.removeTreeDom(setting, node);
view.cancelCurEditNode(setting);
view.selectNode(setting, node, false);
$("#" + node.tId + consts.id.SPAN).html("<input type=text class='rename' id='" + node.tId + consts.id.INPUT + "' treeNode" + consts.id.INPUT + " >");
var inputObj = $("#" + node.tId + consts.id.INPUT);
inputObj.attr("value", node[nameKey]);
if (setting.edit.editNameSelectAll) {
tools.inputSelect(inputObj);
} else {
tools.inputFocus(inputObj);
}
inputObj.bind('blur', function(event) {
if (!view.editNodeBlur) {
view.cancelCurEditNode(setting);
}
}).bind('keydown', function(event) {
if (event.keyCode=="13") {
view.editNodeBlur = true;
view.cancelCurEditNode(setting, null, true);
} else if (event.keyCode=="27") {
view.cancelCurEditNode(setting, node[nameKey]);
}
}).bind('click', function(event) {
return false;
}).bind('dblclick', function(event) {
return false;
});
$("#" + node.tId + consts.id.A).addClass(consts.node.CURSELECTED_EDIT);
root.curEditInput = inputObj;
root.noSelection = false;
root.curEditNode = node;
},
moveNode: function(setting, targetNode, node, moveType, animateFlag, isSilent) {
var root = data.getRoot(setting),
childKey = setting.data.key.children;
if (targetNode == node) return;
if (setting.data.keep.leaf && targetNode && !targetNode.isParent && moveType == consts.move.TYPE_INNER) return;
var oldParentNode = (node.parentTId ? node.getParentNode(): root),
targetNodeIsRoot = (targetNode === null || targetNode == root);
if (targetNodeIsRoot && targetNode === null) targetNode = root;
if (targetNodeIsRoot) moveType = consts.move.TYPE_INNER;
var targetParentNode = (targetNode.parentTId ? targetNode.getParentNode() : root);
if (moveType != consts.move.TYPE_PREV && moveType != consts.move.TYPE_NEXT) {
moveType = consts.move.TYPE_INNER;
}
//move node Dom
var targetObj, target_ulObj;
if (targetNodeIsRoot) {
targetObj = setting.treeObj;
target_ulObj = targetObj;
} else if (!isSilent) {
if (moveType == consts.move.TYPE_INNER) {
view.expandCollapseNode(setting, targetNode, true, false);
} else {
view.expandCollapseNode(setting, targetNode.getParentNode(), true, false);
}
targetObj = $("#" + targetNode.tId);
target_ulObj = $("#" + targetNode.tId + consts.id.UL);
}
var nodeDom = $("#" + node.tId).remove();
if (target_ulObj && moveType == consts.move.TYPE_INNER) {
target_ulObj.append(nodeDom);
} else if (targetObj && moveType == consts.move.TYPE_PREV) {
targetObj.before(nodeDom);
} else if (targetObj && moveType == consts.move.TYPE_NEXT) {
targetObj.after(nodeDom);
}
//repair the data after move
var i,l,
tmpSrcIndex = -1,
tmpTargetIndex = 0,
oldNeighbor = null,
newNeighbor = null,
oldLevel = node.level;
if (node.isFirstNode) {
tmpSrcIndex = 0;
if (oldParentNode[childKey].length > 1 ) {
oldNeighbor = oldParentNode[childKey][1];
oldNeighbor.isFirstNode = true;
}
} else if (node.isLastNode) {
tmpSrcIndex = oldParentNode[childKey].length -1;
oldNeighbor = oldParentNode[childKey][tmpSrcIndex - 1];
oldNeighbor.isLastNode = true;
} else {
for (i = 0, l = oldParentNode[childKey].length; i < l; i++) {
if (oldParentNode[childKey][i].tId == node.tId) {
tmpSrcIndex = i;
break;
}
}
}
if (tmpSrcIndex >= 0) {
oldParentNode[childKey].splice(tmpSrcIndex, 1);
}
if (moveType != consts.move.TYPE_INNER) {
for (i = 0, l = targetParentNode[childKey].length; i < l; i++) {
if (targetParentNode[childKey][i].tId == targetNode.tId) tmpTargetIndex = i;
}
}
if (moveType == consts.move.TYPE_INNER) {
if (targetNodeIsRoot) {
//parentTId of root node is null
node.parentTId = null;
} else {
targetNode.isParent = true;
targetNode.open = false;
node.parentTId = targetNode.tId;
}
if (!targetNode[childKey]) targetNode[childKey] = new Array();
if (targetNode[childKey].length > 0) {
newNeighbor = targetNode[childKey][targetNode[childKey].length - 1];
newNeighbor.isLastNode = false;
}
targetNode[childKey].splice(targetNode[childKey].length, 0, node);
node.isLastNode = true;
node.isFirstNode = (targetNode[childKey].length == 1);
} else if (targetNode.isFirstNode && moveType == consts.move.TYPE_PREV) {
targetParentNode[childKey].splice(tmpTargetIndex, 0, node);
newNeighbor = targetNode;
newNeighbor.isFirstNode = false;
node.parentTId = targetNode.parentTId;
node.isFirstNode = true;
node.isLastNode = false;
} else if (targetNode.isLastNode && moveType == consts.move.TYPE_NEXT) {
targetParentNode[childKey].splice(tmpTargetIndex + 1, 0, node);
newNeighbor = targetNode;
newNeighbor.isLastNode = false;
node.parentTId = targetNode.parentTId;
node.isFirstNode = false;
node.isLastNode = true;
} else {
if (moveType == consts.move.TYPE_PREV) {
targetParentNode[childKey].splice(tmpTargetIndex, 0, node);
} else {
targetParentNode[childKey].splice(tmpTargetIndex + 1, 0, node);
}
node.parentTId = targetNode.parentTId;
node.isFirstNode = false;
node.isLastNode = false;
}
data.fixPIdKeyValue(setting, node);
data.setSonNodeLevel(setting, node.getParentNode(), node);
//repair node what been moved
view.setNodeLineIcos(setting, node);
view.repairNodeLevelClass(setting, node, oldLevel)
//repair node's old parentNode dom
if (!setting.data.keep.parent && oldParentNode[childKey].length < 1) {
//old parentNode has no child nodes
oldParentNode.isParent = false;
oldParentNode.open = false;
var tmp_ulObj = $("#" + oldParentNode.tId + consts.id.UL),
tmp_switchObj = $("#" + oldParentNode.tId + consts.id.SWITCH),
tmp_icoObj = $("#" + oldParentNode.tId + consts.id.ICON);
view.replaceSwitchClass(oldParentNode, tmp_switchObj, consts.folder.DOCU);
view.replaceIcoClass(oldParentNode, tmp_icoObj, consts.folder.DOCU);
tmp_ulObj.css("display", "none");
} else if (oldNeighbor) {
//old neigbor node
view.setNodeLineIcos(setting, oldNeighbor);
}
//new neigbor node
if (newNeighbor) {
view.setNodeLineIcos(setting, newNeighbor);
}
//repair checkbox / radio
if (setting.check.enable && view.repairChkClass) {
view.repairChkClass(setting, oldParentNode);
view.repairParentChkClassWithSelf(setting, oldParentNode);
if (oldParentNode != node.parent)
view.repairParentChkClassWithSelf(setting, node);
}
//expand parents after move
if (!isSilent) {
view.expandCollapseParentNode(setting, node.getParentNode(), true, animateFlag);
}
},
removeChildNodes: function(setting, node) {
if (!node) return;
var childKey = setting.data.key.children,
nodes = node[childKey];
if (!nodes) return;
$("#" + node.tId + consts.id.UL).remove();
for (var i = 0, l = nodes.length; i < l; i++) {
data.removeNodeCache(setting, nodes[i]);
}
data.removeSelectedNode(setting);
delete node[childKey];
if (!setting.data.keep.parent) {
node.isParent = false;
node.open = false;
var tmp_switchObj = $("#" + node.tId + consts.id.SWITCH),
tmp_icoObj = $("#" + node.tId + consts.id.ICON);
view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU);
view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU);
}
},
removeEditBtn: function(node) {
$("#" + node.tId + consts.id.EDIT).unbind().remove();
},
removeNode: function(setting, node) {
var root = data.getRoot(setting),
childKey = setting.data.key.children,
parentNode = (node.parentTId) ? node.getParentNode() : root;
if (root.curEditNode === node) root.curEditNode = null;
node.isFirstNode = false;
node.isLastNode = false;
node.getPreNode = function() {return null;};
node.getNextNode = function() {return null;};
$("#" + node.tId).remove();
data.removeNodeCache(setting, node);
data.removeSelectedNode(setting, node);
for (var i = 0, l = parentNode[childKey].length; i < l; i++) {
if (parentNode[childKey][i].tId == node.tId) {
parentNode[childKey].splice(i, 1);
break;
}
}
var tmp_ulObj,tmp_switchObj,tmp_icoObj;
//repair nodes old parent
if (!setting.data.keep.parent && parentNode[childKey].length < 1) {
//old parentNode has no child nodes
parentNode.isParent = false;
parentNode.open = false;
tmp_ulObj = $("#" + parentNode.tId + consts.id.UL);
tmp_switchObj = $("#" + parentNode.tId + consts.id.SWITCH);
tmp_icoObj = $("#" + parentNode.tId + consts.id.ICON);
view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU);
view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU);
tmp_ulObj.css("display", "none");
} else if (setting.view.showLine && parentNode[childKey].length > 0) {
//old parentNode has child nodes
var newLast = parentNode[childKey][parentNode[childKey].length - 1];
newLast.isLastNode = true;
newLast.isFirstNode = (parentNode[childKey].length == 1);
tmp_ulObj = $("#" + newLast.tId + consts.id.UL);
tmp_switchObj = $("#" + newLast.tId + consts.id.SWITCH);
tmp_icoObj = $("#" + newLast.tId + consts.id.ICON);
if (parentNode == root) {
if (parentNode[childKey].length == 1) {
//node was root, and ztree has only one root after move node
view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT);
} else {
var tmp_first_switchObj = $("#" + parentNode[childKey][0].tId + consts.id.SWITCH);
view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS);
view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM);
}
} else {
view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM);
}
tmp_ulObj.removeClass(consts.line.LINE);
}
},
removeRemoveBtn: function(node) {
$("#" + node.tId + consts.id.REMOVE).unbind().remove();
},
removeTreeDom: function(setting, node) {
node.isHover = false;
view.removeEditBtn(node);
view.removeRemoveBtn(node);
tools.apply(setting.view.removeHoverDom, [setting.treeId, node]);
},
repairNodeLevelClass: function(setting, node, oldLevel) {
if (oldLevel === node.level) return;
var liObj = $("#" + node.tId),
aObj = $("#" + node.tId + consts.id.A),
ulObj = $("#" + node.tId + consts.id.UL),
oldClass = "level" + oldLevel,
newClass = "level" + node.level;
liObj.removeClass(oldClass);
liObj.addClass(newClass);
aObj.removeClass(oldClass);
aObj.addClass(newClass);
ulObj.removeClass(oldClass);
ulObj.addClass(newClass);
}
},
_z = {
tools: _tools,
view: _view,
event: event,
data: _data
};
$.extend(true, $.fn.zTree.consts, _consts);
$.extend(true, $.fn.zTree._z, _z);
var zt = $.fn.zTree,
tools = zt._z.tools,
consts = zt.consts,
view = zt._z.view,
data = zt._z.data,
event = zt._z.event;
data.exSetting(_setting);
data.addInitBind(_bindEvent);
data.addInitCache(_initCache);
data.addInitNode(_initNode);
data.addInitProxy(_eventProxy);
data.addInitRoot(_initRoot);
data.addZTreeTools(_zTreeTools);
var _cancelPreSelectedNode = view.cancelPreSelectedNode;
view.cancelPreSelectedNode = function (setting, node) {
var list = data.getRoot(setting).curSelectedList;
for (var i=0, j=list.length; i<j; i++) {
if (!node || node === list[i]) {
view.removeTreeDom(setting, list[i]);
if (node) break;
}
}
if (_cancelPreSelectedNode) _cancelPreSelectedNode.apply(view, arguments);
}
var _createNodes = view.createNodes;
view.createNodes = function(setting, level, nodes, parentNode) {
if (_createNodes) {
_createNodes.apply(view, arguments);
}
if (!nodes) return;
if (view.repairParentChkClassWithSelf) {
view.repairParentChkClassWithSelf(setting, parentNode);
}
}
view.makeNodeUrl = function(setting, node) {
return (node.url && !setting.edit.enable) ? node.url : null;
}
var _selectNode = view.selectNode;
view.selectNode = function(setting, node, addFlag) {
var root = data.getRoot(setting);
if (data.isSelectedNode(setting, node) && root.curEditNode == node && node.editNameFlag) {
return false;
}
if (_selectNode) _selectNode.apply(view, arguments);
view.addHoverDom(setting, node);
return true;
}
var _uCanDo = tools.uCanDo;
tools.uCanDo = function(setting, e) {
var root = data.getRoot(setting);
if (e && (tools.eqs(e.type, "mouseover") || tools.eqs(e.type, "mouseout") || tools.eqs(e.type, "mousedown") || tools.eqs(e.type, "mouseup"))) {
return true;
}
return (!root.curEditNode) && (_uCanDo ? _uCanDo.apply(view, arguments) : true);
}
})(jQuery);
| JavaScript |
/**
* .select2Buttons - Convert standard html select into button like elements
*
* Version: 1.0.1
* Updated: 2011-04-14
*
* Provides an alternative look and feel for HTML select buttons, inspired by threadless.com
*
* Author: Sam Cavenagh (cavenaghweb@hotmail.com)
* Doco and Source: https://github.com/o-sam-o/jquery.select2Buttons
*
* Licensed under the MIT
**/
jQuery.fn.select2Buttons = function(options) {
return this.each(function(){
var select = $(this);
select.hide();
var selectid = select.attr("id");
if(document.getElementById(selectid+"_bus")){
return;
}
var buttonsHtml = $('<div class="select2Buttons" id="'+selectid+'_bus"></div>');
var selectIndex = 0;
var addOptGroup = function(optGroup){
if (optGroup.attr('label')){
buttonsHtml.append('<strong>' + optGroup.attr('label') + '</strong>');
}
var ulHtml = $('<ul class="select-buttons">');
optGroup.children('option').each(function(){
var liHtml = $('<li></li>');
if ($(this).attr('disabled') || select.attr('disabled')){
liHtml.addClass('disabled');
liHtml.append('<span>' + $(this).html() + '</span>');
}else{
liHtml.append('<a href="#" data-select-index="' + selectIndex + '">' + $(this).html() + '</a>');
}
// Mark current selection as "picked"
if((!options || !options.noDefault) && select.attr("selectedIndex") == selectIndex){
liHtml.children('a, span').addClass('picked');
}
ulHtml.append(liHtml);
selectIndex++;
});
buttonsHtml.append(ulHtml);
}
var optGroups = select.children('optgroup');
if (optGroups.length == 0) {
addOptGroup(select);
}else{
optGroups.each(function(){
addOptGroup($(this));
});
}
select.after(buttonsHtml);
buttonsHtml.find('a').click(function(e){
e.preventDefault();
buttonsHtml.find('a, span').removeClass('picked');
$(this).addClass('picked');
$(select.find('option')[$(this).attr('data-select-index')]).attr('selected', 'selected');
select.trigger('change');
});
});
}; | JavaScript |
/*
PIE: CSS3 rendering for IE
Version 1.0.0
http://css3pie.com
Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2.
*/
(function(){
var doc = document;var PIE = window['PIE'];
if( !PIE ) {
PIE = window['PIE'] = {
CSS_PREFIX: '-pie-',
STYLE_PREFIX: 'Pie',
CLASS_PREFIX: 'pie_',
tableCellTags: {
'TD': 1,
'TH': 1
},
/**
* Lookup table of elements which cannot take custom children.
*/
childlessElements: {
'TABLE':1,
'THEAD':1,
'TBODY':1,
'TFOOT':1,
'TR':1,
'INPUT':1,
'TEXTAREA':1,
'SELECT':1,
'OPTION':1,
'IMG':1,
'HR':1
},
/**
* Elements that can receive user focus
*/
focusableElements: {
'A':1,
'INPUT':1,
'TEXTAREA':1,
'SELECT':1,
'BUTTON':1
},
/**
* Values of the type attribute for input elements displayed as buttons
*/
inputButtonTypes: {
'submit':1,
'button':1,
'reset':1
},
emptyFn: function() {}
};
// Force the background cache to be used. No reason it shouldn't be.
try {
doc.execCommand( 'BackgroundImageCache', false, true );
} catch(e) {}
(function() {
/*
* IE version detection approach by James Padolsey, with modifications -- from
* http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
*/
var ieVersion = 4,
div = doc.createElement('div'),
all = div.getElementsByTagName('i'),
shape;
while (
div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->',
all[0]
) {}
PIE.ieVersion = ieVersion;
// Detect IE6
if( ieVersion === 6 ) {
// IE6 can't access properties with leading dash, but can without it.
PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' );
}
PIE.ieDocMode = doc.documentMode || PIE.ieVersion;
// Detect VML support (a small number of IE installs don't have a working VML engine)
div.innerHTML = '<v:shape adj="1"/>';
shape = div.firstChild;
shape.style['behavior'] = 'url(#default#VML)';
PIE.supportsVML = (typeof shape['adj'] === "object");
}());
/**
* Utility functions
*/
(function() {
var vmlCreatorDoc,
idNum = 0,
imageSizes = {};
PIE.Util = {
/**
* To create a VML element, it must be created by a Document which has the VML
* namespace set. Unfortunately, if you try to add the namespace programatically
* into the main document, you will get an "Unspecified error" when trying to
* access document.namespaces before the document is finished loading. To get
* around this, we create a DocumentFragment, which in IE land is apparently a
* full-fledged Document. It allows adding namespaces immediately, so we add the
* namespace there and then have it create the VML element.
* @param {string} tag The tag name for the VML element
* @return {Element} The new VML element
*/
createVmlElement: function( tag ) {
var vmlPrefix = 'css3vml';
if( !vmlCreatorDoc ) {
vmlCreatorDoc = doc.createDocumentFragment();
vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' );
}
return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag );
},
/**
* Generate and return a unique ID for a given object. The generated ID is stored
* as a property of the object for future reuse.
* @param {Object} obj
*/
getUID: function( obj ) {
return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum );
},
/**
* Simple utility for merging objects
* @param {Object} obj1 The main object into which all others will be merged
* @param {...Object} var_args Other objects which will be merged into the first, in order
*/
merge: function( obj1 ) {
var i, len, p, objN, args = arguments;
for( i = 1, len = args.length; i < len; i++ ) {
objN = args[i];
for( p in objN ) {
if( objN.hasOwnProperty( p ) ) {
obj1[ p ] = objN[ p ];
}
}
}
return obj1;
},
/**
* Execute a callback function, passing it the dimensions of a given image once
* they are known.
* @param {string} src The source URL of the image
* @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known
* @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function
*/
withImageSize: function( src, func, ctx ) {
var size = imageSizes[ src ], img, queue;
if( size ) {
// If we have a queue, add to it
if( Object.prototype.toString.call( size ) === '[object Array]' ) {
size.push( [ func, ctx ] );
}
// Already have the size cached, call func right away
else {
func.call( ctx, size );
}
} else {
queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue
img = new Image();
img.onload = function() {
size = imageSizes[ src ] = { w: img.width, h: img.height };
for( var i = 0, len = queue.length; i < len; i++ ) {
queue[ i ][ 0 ].call( queue[ i ][ 1 ], size );
}
img.onload = null;
};
img.src = src;
}
}
};
})();/**
* Utility functions for handling gradients
*/
PIE.GradientUtil = {
getGradientMetrics: function( el, width, height, gradientInfo ) {
var angle = gradientInfo.angle,
startPos = gradientInfo.gradientStart,
startX, startY,
endX, endY,
startCornerX, startCornerY,
endCornerX, endCornerY,
deltaX, deltaY,
p, UNDEF;
// Find the "start" and "end" corners; these are the corners furthest along the gradient line.
// This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding
// the total length of the VML rendered gradient-line corner to corner.
function findCorners() {
startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0;
startCornerY = angle < 180 ? height : 0;
endCornerX = width - startCornerX;
endCornerY = height - startCornerY;
}
// Normalize the angle to a value between [0, 360)
function normalizeAngle() {
while( angle < 0 ) {
angle += 360;
}
angle = angle % 360;
}
// Find the start and end points of the gradient
if( startPos ) {
startPos = startPos.coords( el, width, height );
startX = startPos.x;
startY = startPos.y;
}
if( angle ) {
angle = angle.degrees();
normalizeAngle();
findCorners();
// If no start position was specified, then choose a corner as the starting point.
if( !startPos ) {
startX = startCornerX;
startY = startCornerY;
}
// Find the end position by extending a perpendicular line from the gradient-line which
// intersects the corner opposite from the starting corner.
p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY );
endX = p[0];
endY = p[1];
}
else if( startPos ) {
// Start position but no angle specified: find the end point by rotating 180deg around the center
endX = width - startX;
endY = height - startY;
}
else {
// Neither position nor angle specified; create vertical gradient from top to bottom
startX = startY = endX = 0;
endY = height;
}
deltaX = endX - startX;
deltaY = endY - startY;
if( angle === UNDEF ) {
// Get the angle based on the change in x/y from start to end point. Checks first for horizontal
// or vertical angles so they get exact whole numbers rather than what atan2 gives.
angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) :
( !deltaY ? ( deltaX < 0 ? 180 : 0 ) :
-Math.atan2( deltaY, deltaX ) / Math.PI * 180
)
);
normalizeAngle();
findCorners();
}
return {
angle: angle,
startX: startX,
startY: startY,
endX: endX,
endY: endY,
startCornerX: startCornerX,
startCornerY: startCornerY,
endCornerX: endCornerX,
endCornerY: endCornerY,
deltaX: deltaX,
deltaY: deltaY,
lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
}
},
/**
* Find the point along a given line (defined by a starting point and an angle), at which
* that line is intersected by a perpendicular line extending through another point.
* @param x1 - x coord of the starting point
* @param y1 - y coord of the starting point
* @param angle - angle of the line extending from the starting point (in degrees)
* @param x2 - x coord of point along the perpendicular line
* @param y2 - y coord of point along the perpendicular line
* @return [ x, y ]
*/
perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
// Handle straight vertical and horizontal angles, for performance and to avoid
// divide-by-zero errors.
if( angle === 0 || angle === 180 ) {
return [ x2, y1 ];
}
else if( angle === 90 || angle === 270 ) {
return [ x1, y2 ];
}
else {
// General approach: determine the Ax+By=C formula for each line (the slope of the second
// line is the negative inverse of the first) and then solve for where both formulas have
// the same x/y values.
var a1 = Math.tan( -angle * Math.PI / 180 ),
c1 = a1 * x1 - y1,
a2 = -1 / a1,
c2 = a2 * x2 - y2,
d = a2 - a1,
endX = ( c2 - c1 ) / d,
endY = ( a1 * c2 - a2 * c1 ) / d;
return [ endX, endY ];
}
},
/**
* Find the distance between two points
* @param {Number} p1x
* @param {Number} p1y
* @param {Number} p2x
* @param {Number} p2y
* @return {Number} the distance
*/
distance: function( p1x, p1y, p2x, p2y ) {
var dx = p2x - p1x,
dy = p2y - p1y;
return Math.abs(
dx === 0 ? dy :
dy === 0 ? dx :
Math.sqrt( dx * dx + dy * dy )
);
}
};/**
*
*/
PIE.Observable = function() {
/**
* List of registered observer functions
*/
this.observers = [];
/**
* Hash of function ids to their position in the observers list, for fast lookup
*/
this.indexes = {};
};
PIE.Observable.prototype = {
observe: function( fn ) {
var id = PIE.Util.getUID( fn ),
indexes = this.indexes,
observers = this.observers;
if( !( id in indexes ) ) {
indexes[ id ] = observers.length;
observers.push( fn );
}
},
unobserve: function( fn ) {
var id = PIE.Util.getUID( fn ),
indexes = this.indexes;
if( id && id in indexes ) {
delete this.observers[ indexes[ id ] ];
delete indexes[ id ];
}
},
fire: function() {
var o = this.observers,
i = o.length;
while( i-- ) {
o[ i ] && o[ i ]();
}
}
};/*
* Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not
* always firing the onmove and onresize events when elements are moved or resized. We check a few
* times every second to make sure the elements have the correct position and size. See Element.js
* which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9
* and false elsewhere.
*/
PIE.Heartbeat = new PIE.Observable();
PIE.Heartbeat.run = function() {
var me = this,
interval;
if( !me.running ) {
interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250;
(function beat() {
me.fire();
setTimeout(beat, interval);
})();
me.running = 1;
}
};
/**
* Create an observable listener for the onunload event
*/
(function() {
PIE.OnUnload = new PIE.Observable();
function handleUnload() {
PIE.OnUnload.fire();
window.detachEvent( 'onunload', handleUnload );
window[ 'PIE' ] = null;
}
window.attachEvent( 'onunload', handleUnload );
/**
* Attach an event which automatically gets detached onunload
*/
PIE.OnUnload.attachManagedEvent = function( target, name, handler ) {
target.attachEvent( name, handler );
this.observe( function() {
target.detachEvent( name, handler );
} );
};
})()/**
* Create a single observable listener for window resize events.
*/
PIE.OnResize = new PIE.Observable();
PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } );
/**
* Create a single observable listener for scroll events. Used for lazy loading based
* on the viewport, and for fixed position backgrounds.
*/
(function() {
PIE.OnScroll = new PIE.Observable();
function scrolled() {
PIE.OnScroll.fire();
}
PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled );
PIE.OnResize.observe( scrolled );
})();
/**
* Listen for printing events, destroy all active PIE instances when printing, and
* restore them afterward.
*/
(function() {
var elements;
function beforePrint() {
elements = PIE.Element.destroyAll();
}
function afterPrint() {
if( elements ) {
for( var i = 0, len = elements.length; i < len; i++ ) {
PIE[ 'attach' ]( elements[i] );
}
elements = 0;
}
}
if( PIE.ieDocMode < 9 ) {
PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint );
PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint );
}
})();/**
* Create a single observable listener for document mouseup events.
*/
PIE.OnMouseup = new PIE.Observable();
PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } );
/**
* Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique
* value is returned from PIE.getLength() - always use that instead of instantiating directly.
* @constructor
* @param {string} val The CSS string representing the length. It is assumed that this will already have
* been validated as a valid length or percentage syntax.
*/
PIE.Length = (function() {
var lengthCalcEl = doc.createElement( 'length-calc' ),
parent = doc.body || doc.documentElement,
s = lengthCalcEl.style,
conversions = {},
units = [ 'mm', 'cm', 'in', 'pt', 'pc' ],
i = units.length,
instances = {};
s.position = 'absolute';
s.top = s.left = '-9999px';
parent.appendChild( lengthCalcEl );
while( i-- ) {
s.width = '100' + units[i];
conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100;
}
parent.removeChild( lengthCalcEl );
// All calcs from here on will use 1em
s.width = '1em';
function Length( val ) {
this.val = val;
}
Length.prototype = {
/**
* Regular expression for matching the length unit
* @private
*/
unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/,
/**
* Get the numeric value of the length
* @return {number} The value
*/
getNumber: function() {
var num = this.num,
UNDEF;
if( num === UNDEF ) {
num = this.num = parseFloat( this.val );
}
return num;
},
/**
* Get the unit of the length
* @return {string} The unit
*/
getUnit: function() {
var unit = this.unit,
m;
if( !unit ) {
m = this.val.match( this.unitRE );
unit = this.unit = ( m && m[0] ) || 'px';
}
return unit;
},
/**
* Determine whether this is a percentage length value
* @return {boolean}
*/
isPercentage: function() {
return this.getUnit() === '%';
},
/**
* Resolve this length into a number of pixels.
* @param {Element} el - the context element, used to resolve font-relative values
* @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a
* function which will be called to return the number.
*/
pixels: function( el, pct100 ) {
var num = this.getNumber(),
unit = this.getUnit();
switch( unit ) {
case "px":
return num;
case "%":
return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100;
case "em":
return num * this.getEmPixels( el );
case "ex":
return num * this.getEmPixels( el ) / 2;
default:
return num * conversions[ unit ];
}
},
/**
* The em and ex units are relative to the font-size of the current element,
* however if the font-size is set using non-pixel units then we get that value
* rather than a pixel conversion. To get around this, we keep a floating element
* with width:1em which we insert into the target element and then read its offsetWidth.
* For elements that won't accept a child we insert into the parent node and perform
* additional calculation. If the font-size *is* specified in pixels, then we use that
* directly to avoid the expensive DOM manipulation.
* @param {Element} el
* @return {number}
*/
getEmPixels: function( el ) {
var fs = el.currentStyle.fontSize,
px, parent, me;
if( fs.indexOf( 'px' ) > 0 ) {
return parseFloat( fs );
}
else if( el.tagName in PIE.childlessElements ) {
me = this;
parent = el.parentNode;
return PIE.getLength( fs ).pixels( parent, function() {
return me.getEmPixels( parent );
} );
}
else {
el.appendChild( lengthCalcEl );
px = lengthCalcEl.offsetWidth;
if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is
el.removeChild( lengthCalcEl );
}
return px;
}
}
};
/**
* Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value.
* @param {string} val The CSS string representing the length. It is assumed that this will already have
* been validated as a valid length or percentage syntax.
*/
PIE.getLength = function( val ) {
return instances[ val ] || ( instances[ val ] = new Length( val ) );
};
return Length;
})();
/**
* Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages.
* @constructor
* @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value.
*/
PIE.BgPosition = (function() {
var length_fifty = PIE.getLength( '50%' ),
vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 },
horiz_idents = { 'left': 1, 'center': 1, 'right': 1 };
function BgPosition( tokens ) {
this.tokens = tokens;
}
BgPosition.prototype = {
/**
* Normalize the values into the form:
* [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ]
* where: xOffsetSide is either 'left' or 'right',
* yOffsetSide is either 'top' or 'bottom',
* and x/yOffsetLength are both PIE.Length objects.
* @return {Array}
*/
getValues: function() {
if( !this._values ) {
var tokens = this.tokens,
len = tokens.length,
Tokenizer = PIE.Tokenizer,
identType = Tokenizer.Type,
length_zero = PIE.getLength( '0' ),
type_ident = identType.IDENT,
type_length = identType.LENGTH,
type_percent = identType.PERCENT,
type, value,
vals = [ 'left', length_zero, 'top', length_zero ];
// If only one value, the second is assumed to be 'center'
if( len === 1 ) {
tokens.push( new Tokenizer.Token( type_ident, 'center' ) );
len++;
}
// Two values - CSS2
if( len === 2 ) {
// If both idents, they can appear in either order, so switch them if needed
if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) &&
tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) {
tokens.push( tokens.shift() );
}
if( tokens[0].tokenType & type_ident ) {
if( tokens[0].tokenValue === 'center' ) {
vals[1] = length_fifty;
} else {
vals[0] = tokens[0].tokenValue;
}
}
else if( tokens[0].isLengthOrPercent() ) {
vals[1] = PIE.getLength( tokens[0].tokenValue );
}
if( tokens[1].tokenType & type_ident ) {
if( tokens[1].tokenValue === 'center' ) {
vals[3] = length_fifty;
} else {
vals[2] = tokens[1].tokenValue;
}
}
else if( tokens[1].isLengthOrPercent() ) {
vals[3] = PIE.getLength( tokens[1].tokenValue );
}
}
// Three or four values - CSS3
else {
// TODO
}
this._values = vals;
}
return this._values;
},
/**
* Find the coordinates of the background image from the upper-left corner of the background area.
* Note that these coordinate values are not rounded.
* @param {Element} el
* @param {number} width - the width for percentages (background area width minus image width)
* @param {number} height - the height for percentages (background area height minus image height)
* @return {Object} { x: Number, y: Number }
*/
coords: function( el, width, height ) {
var vals = this.getValues(),
pxX = vals[1].pixels( el, width ),
pxY = vals[3].pixels( el, height );
return {
x: vals[0] === 'right' ? width - pxX : pxX,
y: vals[2] === 'bottom' ? height - pxY : pxY
};
}
};
return BgPosition;
})();
/**
* Wrapper for a CSS3 background-size value.
* @constructor
* @param {String|PIE.Length} w The width parameter
* @param {String|PIE.Length} h The height parameter, if any
*/
PIE.BgSize = (function() {
var CONTAIN = 'contain',
COVER = 'cover',
AUTO = 'auto';
function BgSize( w, h ) {
this.w = w;
this.h = h;
}
BgSize.prototype = {
pixels: function( el, areaW, areaH, imgW, imgH ) {
var me = this,
w = me.w,
h = me.h,
areaRatio = areaW / areaH,
imgRatio = imgW / imgH;
if ( w === CONTAIN ) {
w = imgRatio > areaRatio ? areaW : areaH * imgRatio;
h = imgRatio > areaRatio ? areaW / imgRatio : areaH;
}
else if ( w === COVER ) {
w = imgRatio < areaRatio ? areaW : areaH * imgRatio;
h = imgRatio < areaRatio ? areaW / imgRatio : areaH;
}
else if ( w === AUTO ) {
h = ( h === AUTO ? imgH : h.pixels( el, areaH ) );
w = h * imgRatio;
}
else {
w = w.pixels( el, areaW );
h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) );
}
return { w: w, h: h };
}
};
BgSize.DEFAULT = new BgSize( AUTO, AUTO );
return BgSize;
})();
/**
* Wrapper for angle values; handles conversion to degrees from all allowed angle units
* @constructor
* @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated.
*/
PIE.Angle = (function() {
function Angle( val ) {
this.val = val;
}
Angle.prototype = {
unitRE: /[a-z]+$/i,
/**
* @return {string} The unit of the angle value
*/
getUnit: function() {
return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() );
},
/**
* Get the numeric value of the angle in degrees.
* @return {number} The degrees value
*/
degrees: function() {
var deg = this._deg, u, n;
if( deg === undefined ) {
u = this.getUnit();
n = parseFloat( this.val, 10 );
deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 );
}
return deg;
}
};
return Angle;
})();/**
* Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique
* value is returned from PIE.getColor() - always use that instead of instantiating directly.
* @constructor
* @param {string} val The raw CSS string value for the color
*/
PIE.Color = (function() {
var instances = {};
function Color( val ) {
this.val = val;
}
/**
* Regular expression for matching rgba colors and extracting their components
* @type {RegExp}
*/
Color.rgbaRE = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/;
Color.names = {
"aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF",
"aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC",
"bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD",
"blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A",
"burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00",
"chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED",
"cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF",
"darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B",
"darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B",
"darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00",
"darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A",
"darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F",
"darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493",
"deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF",
"firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22",
"fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF",
"gold":"FFD700", "goldenrod":"DAA520", "gray":"808080",
"green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0",
"hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082",
"ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA",
"lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD",
"lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF",
"lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3",
"lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA",
"lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE",
"lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32",
"linen":"FAF0E6", "magenta":"F0F", "maroon":"800000",
"mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3",
"mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE",
"mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585",
"midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1",
"moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080",
"oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23",
"orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6",
"palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE",
"palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9",
"peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD",
"powderblue":"B0E0E6", "purple":"800080", "red":"F00",
"rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513",
"salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57",
"seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0",
"skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090",
"snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4",
"tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8",
"tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE",
"wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5",
"yellow":"FF0", "yellowgreen":"9ACD32"
};
Color.prototype = {
/**
* @private
*/
parse: function() {
if( !this._color ) {
var me = this,
v = me.val,
vLower,
m = v.match( Color.rgbaRE );
if( m ) {
me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')';
me._alpha = parseFloat( m[4] );
}
else {
if( ( vLower = v.toLowerCase() ) in Color.names ) {
v = '#' + Color.names[vLower];
}
me._color = v;
me._alpha = ( v === 'transparent' ? 0 : 1 );
}
}
},
/**
* Retrieve the value of the color in a format usable by IE natively. This will be the same as
* the raw input value, except for rgba values which will be converted to an rgb value.
* @param {Element} el The context element, used to get 'currentColor' keyword value.
* @return {string} Color value
*/
colorValue: function( el ) {
this.parse();
return this._color === 'currentColor' ? el.currentStyle.color : this._color;
},
/**
* Retrieve the alpha value of the color. Will be 1 for all values except for rgba values
* with an alpha component.
* @return {number} The alpha value, from 0 to 1.
*/
alpha: function() {
this.parse();
return this._alpha;
}
};
/**
* Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value.
* @param {string} val The CSS string representing the color. It is assumed that this will already have
* been validated as a valid color syntax.
*/
PIE.getColor = function(val) {
return instances[ val ] || ( instances[ val ] = new Color( val ) );
};
return Color;
})();/**
* A tokenizer for CSS value strings.
* @constructor
* @param {string} css The CSS value string
*/
PIE.Tokenizer = (function() {
function Tokenizer( css ) {
this.css = css;
this.ch = 0;
this.tokens = [];
this.tokenIndex = 0;
}
/**
* Enumeration of token type constants.
* @enum {number}
*/
var Type = Tokenizer.Type = {
ANGLE: 1,
CHARACTER: 2,
COLOR: 4,
DIMEN: 8,
FUNCTION: 16,
IDENT: 32,
LENGTH: 64,
NUMBER: 128,
OPERATOR: 256,
PERCENT: 512,
STRING: 1024,
URL: 2048
};
/**
* A single token
* @constructor
* @param {number} type The type of the token - see PIE.Tokenizer.Type
* @param {string} value The value of the token
*/
Tokenizer.Token = function( type, value ) {
this.tokenType = type;
this.tokenValue = value;
};
Tokenizer.Token.prototype = {
isLength: function() {
return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' );
},
isLengthOrPercent: function() {
return this.isLength() || this.tokenType & Type.PERCENT;
}
};
Tokenizer.prototype = {
whitespace: /\s/,
number: /^[\+\-]?(\d*\.)?\d+/,
url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i,
ident: /^\-?[_a-z][\w-]*/i,
string: /^("([^"]*)"|'([^']*)')/,
operator: /^[\/,]/,
hash: /^#[\w]+/,
hashColor: /^#([\da-f]{6}|[\da-f]{3})/i,
unitTypes: {
'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH,
'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH,
'pt': Type.LENGTH, 'pc': Type.LENGTH,
'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE
},
colorFunctions: {
'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1
},
/**
* Advance to and return the next token in the CSS string. If the end of the CSS string has
* been reached, null will be returned.
* @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev().
* @return {PIE.Tokenizer.Token}
*/
next: function( forget ) {
var css, ch, firstChar, match, val,
me = this;
function newToken( type, value ) {
var tok = new Tokenizer.Token( type, value );
if( !forget ) {
me.tokens.push( tok );
me.tokenIndex++;
}
return tok;
}
function failure() {
me.tokenIndex++;
return null;
}
// In case we previously backed up, return the stored token in the next slot
if( this.tokenIndex < this.tokens.length ) {
return this.tokens[ this.tokenIndex++ ];
}
// Move past leading whitespace characters
while( this.whitespace.test( this.css.charAt( this.ch ) ) ) {
this.ch++;
}
if( this.ch >= this.css.length ) {
return failure();
}
ch = this.ch;
css = this.css.substring( this.ch );
firstChar = css.charAt( 0 );
switch( firstChar ) {
case '#':
if( match = css.match( this.hashColor ) ) {
this.ch += match[0].length;
return newToken( Type.COLOR, match[0] );
}
break;
case '"':
case "'":
if( match = css.match( this.string ) ) {
this.ch += match[0].length;
return newToken( Type.STRING, match[2] || match[3] || '' );
}
break;
case "/":
case ",":
this.ch++;
return newToken( Type.OPERATOR, firstChar );
case 'u':
if( match = css.match( this.url ) ) {
this.ch += match[0].length;
return newToken( Type.URL, match[2] || match[3] || match[4] || '' );
}
}
// Numbers and values starting with numbers
if( match = css.match( this.number ) ) {
val = match[0];
this.ch += val.length;
// Check if it is followed by a unit
if( css.charAt( val.length ) === '%' ) {
this.ch++;
return newToken( Type.PERCENT, val + '%' );
}
if( match = css.substring( val.length ).match( this.ident ) ) {
val += match[0];
this.ch += match[0].length;
return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val );
}
// Plain ol' number
return newToken( Type.NUMBER, val );
}
// Identifiers
if( match = css.match( this.ident ) ) {
val = match[0];
this.ch += val.length;
// Named colors
if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) {
return newToken( Type.COLOR, val );
}
// Functions
if( css.charAt( val.length ) === '(' ) {
this.ch++;
// Color values in function format: rgb, rgba, hsl, hsla
if( val.toLowerCase() in this.colorFunctions ) {
function isNum( tok ) {
return tok && tok.tokenType & Type.NUMBER;
}
function isNumOrPct( tok ) {
return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) );
}
function isValue( tok, val ) {
return tok && tok.tokenValue === val;
}
function next() {
return me.next( 1 );
}
if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) &&
isValue( next(), ',' ) &&
isNumOrPct( next() ) &&
isValue( next(), ',' ) &&
isNumOrPct( next() ) &&
( val === 'rgb' || val === 'hsa' || (
isValue( next(), ',' ) &&
isNum( next() )
) ) &&
isValue( next(), ')' ) ) {
return newToken( Type.COLOR, this.css.substring( ch, this.ch ) );
}
return failure();
}
return newToken( Type.FUNCTION, val );
}
// Other identifier
return newToken( Type.IDENT, val );
}
// Standalone character
this.ch++;
return newToken( Type.CHARACTER, firstChar );
},
/**
* Determine whether there is another token
* @return {boolean}
*/
hasNext: function() {
var next = this.next();
this.prev();
return !!next;
},
/**
* Back up and return the previous token
* @return {PIE.Tokenizer.Token}
*/
prev: function() {
return this.tokens[ this.tokenIndex-- - 2 ];
},
/**
* Retrieve all the tokens in the CSS string
* @return {Array.<PIE.Tokenizer.Token>}
*/
all: function() {
while( this.next() ) {}
return this.tokens;
},
/**
* Return a list of tokens from the current position until the given function returns
* true. The final token will not be included in the list.
* @param {function():boolean} func - test function
* @param {boolean} require - if true, then if the end of the CSS string is reached
* before the test function returns true, null will be returned instead of the
* tokens that have been found so far.
* @return {Array.<PIE.Tokenizer.Token>}
*/
until: function( func, require ) {
var list = [], t, hit;
while( t = this.next() ) {
if( func( t ) ) {
hit = true;
this.prev();
break;
}
list.push( t );
}
return require && !hit ? null : list;
}
};
return Tokenizer;
})();/**
* Handles calculating, caching, and detecting changes to size and position of the element.
* @constructor
* @param {Element} el the target element
*/
PIE.BoundsInfo = function( el ) {
this.targetElement = el;
};
PIE.BoundsInfo.prototype = {
_locked: 0,
positionChanged: function() {
var last = this._lastBounds,
bounds;
return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) );
},
sizeChanged: function() {
var last = this._lastBounds,
bounds;
return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) );
},
getLiveBounds: function() {
var el = this.targetElement,
rect = el.getBoundingClientRect(),
isIE9 = PIE.ieDocMode === 9,
isIE7 = PIE.ieVersion === 7,
width = rect.right - rect.left;
return {
x: rect.left,
y: rect.top,
// In some cases scrolling the page will cause IE9 to report incorrect dimensions
// in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height
// instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements
// so we must calculate the ratio and use it in certain places as a position adjustment.
w: isIE9 || isIE7 ? el.offsetWidth : width,
h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top,
logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1
};
},
getBounds: function() {
return this._locked ?
( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) :
this.getLiveBounds();
},
hasBeenQueried: function() {
return !!this._lastBounds;
},
lock: function() {
++this._locked;
},
unlock: function() {
if( !--this._locked ) {
if( this._lockedBounds ) this._lastBounds = this._lockedBounds;
this._lockedBounds = null;
}
}
};
(function() {
function cacheWhenLocked( fn ) {
var uid = PIE.Util.getUID( fn );
return function() {
if( this._locked ) {
var cache = this._lockedValues || ( this._lockedValues = {} );
return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) );
} else {
return fn.call( this );
}
}
}
PIE.StyleInfoBase = {
_locked: 0,
/**
* Create a new StyleInfo class, with the standard constructor, and augmented by
* the StyleInfoBase's members.
* @param proto
*/
newStyleInfo: function( proto ) {
function StyleInfo( el ) {
this.targetElement = el;
this._lastCss = this.getCss();
}
PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto );
StyleInfo._propsCache = {};
return StyleInfo;
},
/**
* Get an object representation of the target CSS style, caching it for each unique
* CSS value string.
* @return {Object}
*/
getProps: function() {
var css = this.getCss(),
cache = this.constructor._propsCache;
return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null;
},
/**
* Get the raw CSS value for the target style
* @return {string}
*/
getCss: cacheWhenLocked( function() {
var el = this.targetElement,
ctor = this.constructor,
s = el.style,
cs = el.currentStyle,
cssProp = this.cssProperty,
styleProp = this.styleProperty,
prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ),
prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) );
return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp );
} ),
/**
* Determine whether the target CSS style is active.
* @return {boolean}
*/
isActive: cacheWhenLocked( function() {
return !!this.getProps();
} ),
/**
* Determine whether the target CSS style has changed since the last time it was used.
* @return {boolean}
*/
changed: cacheWhenLocked( function() {
var currentCss = this.getCss(),
changed = currentCss !== this._lastCss;
this._lastCss = currentCss;
return changed;
} ),
cacheWhenLocked: cacheWhenLocked,
lock: function() {
++this._locked;
},
unlock: function() {
if( !--this._locked ) {
delete this._lockedValues;
}
}
};
})();/**
* Handles parsing, caching, and detecting changes to background (and -pie-background) CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: PIE.CSS_PREFIX + 'background',
styleProperty: PIE.STYLE_PREFIX + 'Background',
attachIdents: { 'scroll':1, 'fixed':1, 'local':1 },
repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 },
originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 },
positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 },
sizeIdents: { 'contain':1, 'cover':1 },
propertyNames: {
CLIP: 'backgroundClip',
COLOR: 'backgroundColor',
IMAGE: 'backgroundImage',
ORIGIN: 'backgroundOrigin',
POSITION: 'backgroundPosition',
REPEAT: 'backgroundRepeat',
SIZE: 'backgroundSize'
},
/**
* For background styles, we support the -pie-background property but fall back to the standard
* backround* properties. The reason we have to use the prefixed version is that IE natively
* parses the standard properties and if it sees something it doesn't know how to parse, for example
* multiple values or gradient definitions, it will throw that away and not make it available through
* currentStyle.
*
* Format of return object:
* {
* color: <PIE.Color>,
* bgImages: [
* {
* imgType: 'image',
* imgUrl: 'image.png',
* imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>,
* bgPosition: <PIE.BgPosition>,
* bgAttachment: <'scroll' | 'fixed' | 'local'>,
* bgOrigin: <'border-box' | 'padding-box' | 'content-box'>,
* bgClip: <'border-box' | 'padding-box'>,
* bgSize: <PIE.BgSize>,
* origString: 'url(img.png) no-repeat top left'
* },
* {
* imgType: 'linear-gradient',
* gradientStart: <PIE.BgPosition>,
* angle: <PIE.Angle>,
* stops: [
* { color: <PIE.Color>, offset: <PIE.Length> },
* { color: <PIE.Color>, offset: <PIE.Length> }, ...
* ]
* }
* ]
* }
* @param {String} css
* @override
*/
parseCss: function( css ) {
var el = this.targetElement,
cs = el.currentStyle,
tokenizer, token, image,
tok_type = PIE.Tokenizer.Type,
type_operator = tok_type.OPERATOR,
type_ident = tok_type.IDENT,
type_color = tok_type.COLOR,
tokType, tokVal,
beginCharIndex = 0,
positionIdents = this.positionIdents,
gradient, stop, width, height,
props = { bgImages: [] };
function isBgPosToken( token ) {
return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents );
}
function sizeToken( token ) {
return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) );
}
// If the CSS3-specific -pie-background property is present, parse it
if( this.getCss3() ) {
tokenizer = new PIE.Tokenizer( css );
image = {};
while( token = tokenizer.next() ) {
tokType = token.tokenType;
tokVal = token.tokenValue;
if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) {
gradient = { stops: [], imgType: tokVal };
stop = {};
while( token = tokenizer.next() ) {
tokType = token.tokenType;
tokVal = token.tokenValue;
// If we reached the end of the function and had at least 2 stops, flush the info
if( tokType & tok_type.CHARACTER && tokVal === ')' ) {
if( stop.color ) {
gradient.stops.push( stop );
}
if( gradient.stops.length > 1 ) {
PIE.Util.merge( image, gradient );
}
break;
}
// Color stop - must start with color
if( tokType & type_color ) {
// if we already have an angle/position, make sure that the previous token was a comma
if( gradient.angle || gradient.gradientStart ) {
token = tokenizer.prev();
if( token.tokenType !== type_operator ) {
break; //fail
}
tokenizer.next();
}
stop = {
color: PIE.getColor( tokVal )
};
// check for offset following color
token = tokenizer.next();
if( token.isLengthOrPercent() ) {
stop.offset = PIE.getLength( token.tokenValue );
} else {
tokenizer.prev();
}
}
// Angle - can only appear in first spot
else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) {
gradient.angle = new PIE.Angle( token.tokenValue );
}
else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) {
tokenizer.prev();
gradient.gradientStart = new PIE.BgPosition(
tokenizer.until( function( t ) {
return !isBgPosToken( t );
}, false )
);
}
else if( tokType & type_operator && tokVal === ',' ) {
if( stop.color ) {
gradient.stops.push( stop );
stop = {};
}
}
else {
// Found something we didn't recognize; fail without adding image
break;
}
}
}
else if( !image.imgType && tokType & tok_type.URL ) {
image.imgUrl = tokVal;
image.imgType = 'image';
}
else if( isBgPosToken( token ) && !image.bgPosition ) {
tokenizer.prev();
image.bgPosition = new PIE.BgPosition(
tokenizer.until( function( t ) {
return !isBgPosToken( t );
}, false )
);
}
else if( tokType & type_ident ) {
if( tokVal in this.repeatIdents && !image.imgRepeat ) {
image.imgRepeat = tokVal;
}
else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) {
image.bgOrigin = tokVal;
if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) &&
token.tokenValue in this.originAndClipIdents ) {
image.bgClip = token.tokenValue;
} else {
image.bgClip = tokVal;
tokenizer.prev();
}
}
else if( tokVal in this.attachIdents && !image.bgAttachment ) {
image.bgAttachment = tokVal;
}
else {
return null;
}
}
else if( tokType & type_color && !props.color ) {
props.color = PIE.getColor( tokVal );
}
else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) {
// background size
token = tokenizer.next();
if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) {
image.bgSize = new PIE.BgSize( token.tokenValue );
}
else if( width = sizeToken( token ) ) {
height = sizeToken( tokenizer.next() );
if ( !height ) {
height = width;
tokenizer.prev();
}
image.bgSize = new PIE.BgSize( width, height );
}
else {
return null;
}
}
// new layer
else if( tokType & type_operator && tokVal === ',' && image.imgType ) {
image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 );
beginCharIndex = tokenizer.ch;
props.bgImages.push( image );
image = {};
}
else {
// Found something unrecognized; chuck everything
return null;
}
}
// leftovers
if( image.imgType ) {
image.origString = css.substring( beginCharIndex );
props.bgImages.push( image );
}
}
// Otherwise, use the standard background properties; let IE give us the values rather than parsing them
else {
this.withActualBg( PIE.ieDocMode < 9 ?
function() {
var propNames = this.propertyNames,
posX = cs[propNames.POSITION + 'X'],
posY = cs[propNames.POSITION + 'Y'],
img = cs[propNames.IMAGE],
color = cs[propNames.COLOR];
if( color !== 'transparent' ) {
props.color = PIE.getColor( color )
}
if( img !== 'none' ) {
props.bgImages = [ {
imgType: 'image',
imgUrl: new PIE.Tokenizer( img ).next().tokenValue,
imgRepeat: cs[propNames.REPEAT],
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() )
} ];
}
} :
function() {
var propNames = this.propertyNames,
splitter = /\s*,\s*/,
images = cs[propNames.IMAGE].split( splitter ),
color = cs[propNames.COLOR],
repeats, positions, origins, clips, sizes, i, len, image, sizeParts;
if( color !== 'transparent' ) {
props.color = PIE.getColor( color )
}
len = images.length;
if( len && images[0] !== 'none' ) {
repeats = cs[propNames.REPEAT].split( splitter );
positions = cs[propNames.POSITION].split( splitter );
origins = cs[propNames.ORIGIN].split( splitter );
clips = cs[propNames.CLIP].split( splitter );
sizes = cs[propNames.SIZE].split( splitter );
props.bgImages = [];
for( i = 0; i < len; i++ ) {
image = images[ i ];
if( image && image !== 'none' ) {
sizeParts = sizes[i].split( ' ' );
props.bgImages.push( {
origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' +
origins[ i ] + ' ' + clips[ i ],
imgType: 'image',
imgUrl: new PIE.Tokenizer( image ).next().tokenValue,
imgRepeat: repeats[ i ],
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ),
bgOrigin: origins[ i ],
bgClip: clips[ i ],
bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] )
} );
}
}
}
}
);
}
return ( props.color || props.bgImages[0] ) ? props : null;
},
/**
* Execute a function with the actual background styles (not overridden with runtimeStyle
* properties set by the renderers) available via currentStyle.
* @param fn
*/
withActualBg: function( fn ) {
var isIE9 = PIE.ieDocMode > 8,
propNames = this.propertyNames,
rs = this.targetElement.runtimeStyle,
rsImage = rs[propNames.IMAGE],
rsColor = rs[propNames.COLOR],
rsRepeat = rs[propNames.REPEAT],
rsClip, rsOrigin, rsSize, rsPosition, ret;
if( rsImage ) rs[propNames.IMAGE] = '';
if( rsColor ) rs[propNames.COLOR] = '';
if( rsRepeat ) rs[propNames.REPEAT] = '';
if( isIE9 ) {
rsClip = rs[propNames.CLIP];
rsOrigin = rs[propNames.ORIGIN];
rsPosition = rs[propNames.POSITION];
rsSize = rs[propNames.SIZE];
if( rsClip ) rs[propNames.CLIP] = '';
if( rsOrigin ) rs[propNames.ORIGIN] = '';
if( rsPosition ) rs[propNames.POSITION] = '';
if( rsSize ) rs[propNames.SIZE] = '';
}
ret = fn.call( this );
if( rsImage ) rs[propNames.IMAGE] = rsImage;
if( rsColor ) rs[propNames.COLOR] = rsColor;
if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat;
if( isIE9 ) {
if( rsClip ) rs[propNames.CLIP] = rsClip;
if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin;
if( rsPosition ) rs[propNames.POSITION] = rsPosition;
if( rsSize ) rs[propNames.SIZE] = rsSize;
}
return ret;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
return this.getCss3() ||
this.withActualBg( function() {
var cs = this.targetElement.currentStyle,
propNames = this.propertyNames;
return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' +
cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y'];
} );
} ),
getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement;
return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty );
} ),
/**
* Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6.
*/
isPngFix: function() {
var val = 0, el;
if( PIE.ieVersion < 7 ) {
el = this.targetElement;
val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' );
}
return val;
},
/**
* The isActive logic is slightly different, because getProps() always returns an object
* even if it is just falling back to the native background properties. But we only want
* to report is as being "active" if either the -pie-background override property is present
* and parses successfully or '-pie-png-fix' is set to true in IE6.
*/
isActive: PIE.StyleInfoBase.cacheWhenLocked( function() {
return (this.getCss3() || this.isPngFix()) && !!this.getProps();
} )
} );/**
* Handles parsing, caching, and detecting changes to border CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
sides: [ 'Top', 'Right', 'Bottom', 'Left' ],
namedWidths: {
'thin': '1px',
'medium': '3px',
'thick': '5px'
},
parseCss: function( css ) {
var w = {},
s = {},
c = {},
active = false,
colorsSame = true,
stylesSame = true,
widthsSame = true;
this.withActualBorder( function() {
var el = this.targetElement,
cs = el.currentStyle,
i = 0,
style, color, width, lastStyle, lastColor, lastWidth, side, ltr;
for( ; i < 4; i++ ) {
side = this.sides[ i ];
ltr = side.charAt(0).toLowerCase();
style = s[ ltr ] = cs[ 'border' + side + 'Style' ];
color = cs[ 'border' + side + 'Color' ];
width = cs[ 'border' + side + 'Width' ];
if( i > 0 ) {
if( style !== lastStyle ) { stylesSame = false; }
if( color !== lastColor ) { colorsSame = false; }
if( width !== lastWidth ) { widthsSame = false; }
}
lastStyle = style;
lastColor = color;
lastWidth = width;
c[ ltr ] = PIE.getColor( color );
width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) );
if( width.pixels( this.targetElement ) > 0 ) {
active = true;
}
}
} );
return active ? {
widths: w,
styles: s,
colors: c,
widthsSame: widthsSame,
colorsSame: colorsSame,
stylesSame: stylesSame
} : null;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement,
cs = el.currentStyle,
css;
// Don't redraw or hide borders for cells in border-collapse:collapse tables
if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) {
this.withActualBorder( function() {
css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor;
} );
}
return css;
} ),
/**
* Execute a function with the actual border styles (not overridden with runtimeStyle
* properties set by the renderers) available via currentStyle.
* @param fn
*/
withActualBorder: function( fn ) {
var rs = this.targetElement.runtimeStyle,
rsWidth = rs.borderWidth,
rsColor = rs.borderColor,
ret;
if( rsWidth ) rs.borderWidth = '';
if( rsColor ) rs.borderColor = '';
ret = fn.call( this );
if( rsWidth ) rs.borderWidth = rsWidth;
if( rsColor ) rs.borderColor = rsColor;
return ret;
}
} );
/**
* Handles parsing, caching, and detecting changes to border-radius CSS
* @constructor
* @param {Element} el the target element
*/
(function() {
PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'border-radius',
styleProperty: 'borderRadius',
parseCss: function( css ) {
var p = null, x, y,
tokenizer, token, length,
hasNonZero = false;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
function collectLengths() {
var arr = [], num;
while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
length = PIE.getLength( token.tokenValue );
num = length.getNumber();
if( num < 0 ) {
return null;
}
if( num > 0 ) {
hasNonZero = true;
}
arr.push( length );
}
return arr.length > 0 && arr.length < 5 ? {
'tl': arr[0],
'tr': arr[1] || arr[0],
'br': arr[2] || arr[0],
'bl': arr[3] || arr[1] || arr[0]
} : null;
}
// Grab the initial sequence of lengths
if( x = collectLengths() ) {
// See if there is a slash followed by more lengths, for the y-axis radii
if( token ) {
if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) {
y = collectLengths();
}
} else {
y = x;
}
// Treat all-zero values the same as no value
if( hasNonZero && x && y ) {
p = { x: x, y : y };
}
}
}
return p;
}
} );
var zero = PIE.getLength( '0' ),
zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero };
PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros };
})();/**
* Handles parsing, caching, and detecting changes to border-image CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'border-image',
styleProperty: 'borderImage',
repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 },
parseCss: function( css ) {
var p = null, tokenizer, token, type, value,
slices, widths, outsets,
slashCount = 0,
Type = PIE.Tokenizer.Type,
IDENT = Type.IDENT,
NUMBER = Type.NUMBER,
PERCENT = Type.PERCENT;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
p = {};
function isSlash( token ) {
return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' );
}
function isFillIdent( token ) {
return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' );
}
function collectSlicesEtc() {
slices = tokenizer.until( function( tok ) {
return !( tok.tokenType & ( NUMBER | PERCENT ) );
} );
if( isFillIdent( tokenizer.next() ) && !p.fill ) {
p.fill = true;
} else {
tokenizer.prev();
}
if( isSlash( tokenizer.next() ) ) {
slashCount++;
widths = tokenizer.until( function( token ) {
return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' );
} );
if( isSlash( tokenizer.next() ) ) {
slashCount++;
outsets = tokenizer.until( function( token ) {
return !token.isLength();
} );
}
} else {
tokenizer.prev();
}
}
while( token = tokenizer.next() ) {
type = token.tokenType;
value = token.tokenValue;
// Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values
if( type & ( NUMBER | PERCENT ) && !slices ) {
tokenizer.prev();
collectSlicesEtc();
}
else if( isFillIdent( token ) && !p.fill ) {
p.fill = true;
collectSlicesEtc();
}
// Idents: one or values for 'repeat'
else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) {
p.repeat = { h: value };
if( token = tokenizer.next() ) {
if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) {
p.repeat.v = token.tokenValue;
} else {
tokenizer.prev();
}
}
}
// URL of the image
else if( ( type & Type.URL ) && !p.src ) {
p.src = value;
}
// Found something unrecognized; exit.
else {
return null;
}
}
// Validate what we collected
if( !p.src || !slices || slices.length < 1 || slices.length > 4 ||
( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) ||
( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) {
return null;
}
// Fill in missing values
if( !p.repeat ) {
p.repeat = { h: 'stretch' };
}
if( !p.repeat.v ) {
p.repeat.v = p.repeat.h;
}
function distributeSides( tokens, convertFn ) {
return {
't': convertFn( tokens[0] ),
'r': convertFn( tokens[1] || tokens[0] ),
'b': convertFn( tokens[2] || tokens[0] ),
'l': convertFn( tokens[3] || tokens[1] || tokens[0] )
};
}
p.slice = distributeSides( slices, function( tok ) {
return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue );
} );
if( widths && widths[0] ) {
p.widths = distributeSides( widths, function( tok ) {
return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
} );
}
if( outsets && outsets[0] ) {
p.outset = distributeSides( outsets, function( tok ) {
return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
} );
}
}
return p;
}
} );/**
* Handles parsing, caching, and detecting changes to box-shadow CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'box-shadow',
styleProperty: 'boxShadow',
parseCss: function( css ) {
var props,
getLength = PIE.getLength,
Type = PIE.Tokenizer.Type,
tokenizer;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
props = { outset: [], inset: [] };
function parseItem() {
var token, type, value, color, lengths, inset, len;
while( token = tokenizer.next() ) {
value = token.tokenValue;
type = token.tokenType;
if( type & Type.OPERATOR && value === ',' ) {
break;
}
else if( token.isLength() && !lengths ) {
tokenizer.prev();
lengths = tokenizer.until( function( token ) {
return !token.isLength();
} );
}
else if( type & Type.COLOR && !color ) {
color = value;
}
else if( type & Type.IDENT && value === 'inset' && !inset ) {
inset = true;
}
else { //encountered an unrecognized token; fail.
return false;
}
}
len = lengths && lengths.length;
if( len > 1 && len < 5 ) {
( inset ? props.inset : props.outset ).push( {
xOffset: getLength( lengths[0].tokenValue ),
yOffset: getLength( lengths[1].tokenValue ),
blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ),
spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ),
color: PIE.getColor( color || 'currentColor' )
} );
return true;
}
return false;
}
while( parseItem() ) {}
}
return props && ( props.inset.length || props.outset.length ) ? props : null;
}
} );
/**
* Retrieves the state of the element's visibility and display
* @constructor
* @param {Element} el the target element
*/
PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var cs = this.targetElement.currentStyle;
return cs.visibility + '|' + cs.display;
} ),
parseCss: function() {
var el = this.targetElement,
rs = el.runtimeStyle,
cs = el.currentStyle,
rsVis = rs.visibility,
csVis;
rs.visibility = '';
csVis = cs.visibility;
rs.visibility = rsVis;
return {
visible: csVis !== 'hidden',
displayed: cs.display !== 'none'
}
},
/**
* Always return false for isActive, since this property alone will not trigger
* a renderer to do anything.
*/
isActive: function() {
return false;
}
} );
PIE.RendererBase = {
/**
* Create a new Renderer class, with the standard constructor, and augmented by
* the RendererBase's members.
* @param proto
*/
newRenderer: function( proto ) {
function Renderer( el, boundsInfo, styleInfos, parent ) {
this.targetElement = el;
this.boundsInfo = boundsInfo;
this.styleInfos = styleInfos;
this.parent = parent;
}
PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto );
return Renderer;
},
/**
* Flag indicating the element has already been positioned at least once.
* @type {boolean}
*/
isPositioned: false,
/**
* Determine if the renderer needs to be updated
* @return {boolean}
*/
needsUpdate: function() {
return false;
},
/**
* Run any preparation logic that would affect the main update logic of this
* renderer or any of the other renderers, e.g. things that might affect the
* element's size or style properties.
*/
prepareUpdate: PIE.emptyFn,
/**
* Tell the renderer to update based on modified properties
*/
updateProps: function() {
this.destroy();
if( this.isActive() ) {
this.draw();
}
},
/**
* Tell the renderer to update based on modified element position
*/
updatePos: function() {
this.isPositioned = true;
},
/**
* Tell the renderer to update based on modified element dimensions
*/
updateSize: function() {
if( this.isActive() ) {
this.draw();
} else {
this.destroy();
}
},
/**
* Add a layer element, with the given z-order index, to the renderer's main box element. We can't use
* z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode.
* So instead we make sure they are inserted into the DOM in the correct order.
* @param {number} index
* @param {Element} el
*/
addLayer: function( index, el ) {
this.removeLayer( index );
for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) {
layer = layers[i];
if( layer ) {
break;
}
}
layers[index] = el;
this.getBox().insertBefore( el, layer || null );
},
/**
* Retrieve a layer element by its index, or null if not present
* @param {number} index
* @return {Element}
*/
getLayer: function( index ) {
var layers = this._layers;
return layers && layers[index] || null;
},
/**
* Remove a layer element by its index
* @param {number} index
*/
removeLayer: function( index ) {
var layer = this.getLayer( index ),
box = this._box;
if( layer && box ) {
box.removeChild( layer );
this._layers[index] = null;
}
},
/**
* Get a VML shape by name, creating it if necessary.
* @param {string} name A name identifying the element
* @param {string=} subElName If specified a subelement of the shape will be created with this tag name
* @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified
* @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered
* using container elements in the correct order, to get correct z stacking without z-index.
*/
getShape: function( name, subElName, parent, group ) {
var shapes = this._shapes || ( this._shapes = {} ),
shape = shapes[ name ],
s;
if( !shape ) {
shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' );
if( subElName ) {
shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) );
}
if( group ) {
parent = this.getLayer( group );
if( !parent ) {
this.addLayer( group, doc.createElement( 'group' + group ) );
parent = this.getLayer( group );
}
}
parent.appendChild( shape );
s = shape.style;
s.position = 'absolute';
s.left = s.top = 0;
s['behavior'] = 'url(#default#VML)';
}
return shape;
},
/**
* Delete a named shape which was created by getShape(). Returns true if a shape with the
* given name was found and deleted, or false if there was no shape of that name.
* @param {string} name
* @return {boolean}
*/
deleteShape: function( name ) {
var shapes = this._shapes,
shape = shapes && shapes[ name ];
if( shape ) {
shape.parentNode.removeChild( shape );
delete shapes[ name ];
}
return !!shape;
},
/**
* For a given set of border radius length/percentage values, convert them to concrete pixel
* values based on the current size of the target element.
* @param {Object} radii
* @return {Object}
*/
getRadiiPixels: function( radii ) {
var el = this.targetElement,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
tlX, tlY, trX, trY, brX, brY, blX, blY, f;
tlX = radii.x['tl'].pixels( el, w );
tlY = radii.y['tl'].pixels( el, h );
trX = radii.x['tr'].pixels( el, w );
trY = radii.y['tr'].pixels( el, h );
brX = radii.x['br'].pixels( el, w );
brY = radii.y['br'].pixels( el, h );
blX = radii.x['bl'].pixels( el, w );
blY = radii.y['bl'].pixels( el, h );
// If any corner ellipses overlap, reduce them all by the appropriate factor. This formula
// is taken straight from the CSS3 Backgrounds and Borders spec.
f = Math.min(
w / ( tlX + trX ),
h / ( trY + brY ),
w / ( blX + brX ),
h / ( tlY + blY )
);
if( f < 1 ) {
tlX *= f;
tlY *= f;
trX *= f;
trY *= f;
brX *= f;
brY *= f;
blX *= f;
blY *= f;
}
return {
x: {
'tl': tlX,
'tr': trX,
'br': brX,
'bl': blX
},
y: {
'tl': tlY,
'tr': trY,
'br': brY,
'bl': blY
}
}
},
/**
* Return the VML path string for the element's background box, with corners rounded.
* @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of
* pixels to shrink the box path inward from the element's four sides.
* @param {number=} mult If specified, all coordinates will be multiplied by this number
* @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
* from this renderer's borderRadiusInfo object.
* @return {string} the VML path
*/
getBoxPath: function( shrink, mult, radii ) {
mult = mult || 1;
var r, str,
bounds = this.boundsInfo.getBounds(),
w = bounds.w * mult,
h = bounds.h * mult,
radInfo = this.styleInfos.borderRadiusInfo,
floor = Math.floor, ceil = Math.ceil,
shrinkT = shrink ? shrink.t * mult : 0,
shrinkR = shrink ? shrink.r * mult : 0,
shrinkB = shrink ? shrink.b * mult : 0,
shrinkL = shrink ? shrink.l * mult : 0,
tlX, tlY, trX, trY, brX, brY, blX, blY;
if( radii || radInfo.isActive() ) {
r = this.getRadiiPixels( radii || radInfo.getProps() );
tlX = r.x['tl'] * mult;
tlY = r.y['tl'] * mult;
trX = r.x['tr'] * mult;
trY = r.y['tr'] * mult;
brX = r.x['br'] * mult;
brY = r.y['br'] * mult;
blX = r.x['bl'] * mult;
blY = r.y['bl'] * mult;
str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) +
'qy' + floor( tlX ) + ',' + floor( shrinkT ) +
'l' + ceil( w - trX ) + ',' + floor( shrinkT ) +
'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) +
'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) +
'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) +
'l' + floor( blX ) + ',' + ceil( h - shrinkB ) +
'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e';
} else {
// simplified path for non-rounded box
str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) +
'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) +
'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) +
'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) +
'xe';
}
return str;
},
/**
* Get the container element for the shapes, creating it if necessary.
*/
getBox: function() {
var box = this.parent.getLayer( this.boxZIndex ), s;
if( !box ) {
box = doc.createElement( this.boxName );
s = box.style;
s.position = 'absolute';
s.top = s.left = 0;
this.parent.addLayer( this.boxZIndex, box );
}
return box;
},
/**
* Hide the actual border of the element. In IE7 and up we can just set its color to transparent;
* however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements
* like form buttons require removing the border width altogether, so for those we increase the padding
* by the border size.
*/
hideBorder: function() {
var el = this.targetElement,
cs = el.currentStyle,
rs = el.runtimeStyle,
tag = el.tagName,
isIE6 = PIE.ieVersion === 6,
sides, side, i;
if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) ||
tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) {
rs.borderWidth = '';
sides = this.styleInfos.borderInfo.sides;
for( i = sides.length; i--; ) {
side = sides[ i ];
rs[ 'padding' + side ] = '';
rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) +
( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) +
( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away
}
rs.borderWidth = 0;
}
else if( isIE6 ) {
// Wrap all the element's children in a custom element, set the element to visiblity:hidden,
// and set the wrapper element to visiblity:visible. This hides the outer element's decorations
// (background and border) but displays all the contents.
// TODO find a better way to do this that doesn't mess up the DOM parent-child relationship,
// as this can interfere with other author scripts which add/modify/delete children. Also, this
// won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into
// using a compositor filter or some other filter which masks the border.
if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) {
var cont = doc.createElement( 'ie6-mask' ),
s = cont.style, child;
s.visibility = 'visible';
s.zoom = 1;
while( child = el.firstChild ) {
cont.appendChild( child );
}
el.appendChild( cont );
rs.visibility = 'hidden';
}
}
else {
rs.borderColor = 'transparent';
}
},
unhideBorder: function() {
},
/**
* Destroy the rendered objects. This is a base implementation which handles common renderer
* structures, but individual renderers may override as necessary.
*/
destroy: function() {
this.parent.removeLayer( this.boxZIndex );
delete this._shapes;
delete this._layers;
}
};
/**
* Root renderer; creates the outermost container element and handles keeping it aligned
* with the target element's size and position.
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.RootRenderer = PIE.RendererBase.newRenderer( {
isActive: function() {
var children = this.childRenderers;
for( var i in children ) {
if( children.hasOwnProperty( i ) && children[ i ].isActive() ) {
return true;
}
}
return false;
},
needsUpdate: function() {
return this.styleInfos.visibilityInfo.changed();
},
updatePos: function() {
if( this.isActive() ) {
var el = this.getPositioningElement(),
par = el,
docEl,
parRect,
tgtCS = el.currentStyle,
tgtPos = tgtCS.position,
boxPos,
s = this.getBox().style, cs,
x = 0, y = 0,
elBounds = this.boundsInfo.getBounds(),
logicalZoomRatio = elBounds.logicalZoomRatio;
if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) {
x = elBounds.x * logicalZoomRatio;
y = elBounds.y * logicalZoomRatio;
boxPos = tgtPos;
} else {
// Get the element's offsets from its nearest positioned ancestor. Uses
// getBoundingClientRect for accuracy and speed.
do {
par = par.offsetParent;
} while( par && ( par.currentStyle.position === 'static' ) );
if( par ) {
parRect = par.getBoundingClientRect();
cs = par.currentStyle;
x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 );
y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 );
} else {
docEl = doc.documentElement;
x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio;
y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio;
}
boxPos = 'absolute';
}
s.position = boxPos;
s.left = x;
s.top = y;
s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex;
this.isPositioned = true;
}
},
updateSize: PIE.emptyFn,
updateVisibility: function() {
var vis = this.styleInfos.visibilityInfo.getProps();
this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none';
},
updateProps: function() {
if( this.isActive() ) {
this.updateVisibility();
} else {
this.destroy();
}
},
getPositioningElement: function() {
var el = this.targetElement;
return el.tagName in PIE.tableCellTags ? el.offsetParent : el;
},
getBox: function() {
var box = this._box, el;
if( !box ) {
el = this.getPositioningElement();
box = this._box = doc.createElement( 'css3-container' );
box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments
this.updateVisibility();
el.parentNode.insertBefore( box, el );
}
return box;
},
finishUpdate: PIE.emptyFn,
destroy: function() {
var box = this._box, par;
if( box && ( par = box.parentNode ) ) {
par.removeChild( box );
}
delete this._box;
delete this._layers;
}
} );
/**
* Renderer for element backgrounds.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 2,
boxName: 'background',
needsUpdate: function() {
var si = this.styleInfos;
return si.backgroundInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderImageInfo.isActive() ||
si.borderRadiusInfo.isActive() ||
si.backgroundInfo.isActive() ||
( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset );
},
/**
* Draw the shapes
*/
draw: function() {
var bounds = this.boundsInfo.getBounds();
if( bounds.w && bounds.h ) {
this.drawBgColor();
this.drawBgImages();
}
},
/**
* Draw the background color shape
*/
drawBgColor: function() {
var props = this.styleInfos.backgroundInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
el = this.targetElement,
color = props && props.color,
shape, w, h, s, alpha;
if( color && color.alpha() > 0 ) {
this.hideBackground();
shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 );
w = bounds.w;
h = bounds.h;
shape.stroked = false;
shape.coordsize = w * 2 + ',' + h * 2;
shape.coordorigin = '1,1';
shape.path = this.getBoxPath( null, 2 );
s = shape.style;
s.width = w;
s.height = h;
shape.fill.color = color.colorValue( el );
alpha = color.alpha();
if( alpha < 1 ) {
shape.fill.opacity = alpha;
}
} else {
this.deleteShape( 'bgColor' );
}
},
/**
* Draw all the background image layers
*/
drawBgImages: function() {
var props = this.styleInfos.backgroundInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
images = props && props.bgImages,
img, shape, w, h, s, i;
if( images ) {
this.hideBackground();
w = bounds.w;
h = bounds.h;
i = images.length;
while( i-- ) {
img = images[i];
shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 );
shape.stroked = false;
shape.fill.type = 'tile';
shape.fillcolor = 'none';
shape.coordsize = w * 2 + ',' + h * 2;
shape.coordorigin = '1,1';
shape.path = this.getBoxPath( 0, 2 );
s = shape.style;
s.width = w;
s.height = h;
if( img.imgType === 'linear-gradient' ) {
this.addLinearGradient( shape, img );
}
else {
shape.fill.src = img.imgUrl;
this.positionBgImage( shape, i );
}
}
}
// Delete any bgImage shapes previously created which weren't used above
i = images ? images.length : 0;
while( this.deleteShape( 'bgImage' + i++ ) ) {}
},
/**
* Set the position and clipping of the background image for a layer
* @param {Element} shape
* @param {number} index
*/
positionBgImage: function( shape, index ) {
var me = this;
PIE.Util.withImageSize( shape.fill.src, function( size ) {
var el = me.targetElement,
bounds = me.boundsInfo.getBounds(),
elW = bounds.w,
elH = bounds.h;
// It's possible that the element dimensions are zero now but weren't when the original
// update executed, make sure that's not the case to avoid divide-by-zero error
if( elW && elH ) {
var fill = shape.fill,
si = me.styleInfos,
border = si.borderInfo.getProps(),
bw = border && border.widths,
bwT = bw ? bw['t'].pixels( el ) : 0,
bwR = bw ? bw['r'].pixels( el ) : 0,
bwB = bw ? bw['b'].pixels( el ) : 0,
bwL = bw ? bw['l'].pixels( el ) : 0,
bg = si.backgroundInfo.getProps().bgImages[ index ],
bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 },
repeat = bg.imgRepeat,
pxX, pxY,
clipT = 0, clipL = 0,
clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel)
clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region
// Positioning - find the pixel offset from the top/left and convert to a ratio
// The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is
// needed to fix antialiasing but makes the bg image fuzzy.
pxX = Math.round( bgPos.x ) + bwL + 0.5;
pxY = Math.round( bgPos.y ) + bwT + 0.5;
fill.position = ( pxX / elW ) + ',' + ( pxY / elH );
// Set the size of the image. We have to actually set it to px values otherwise it will not honor
// the user's browser zoom level and always display at its natural screen size.
fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird!
fill['size'] = size.w + 'px,' + size.h + 'px';
// Repeating - clip the image shape
if( repeat && repeat !== 'repeat' ) {
if( repeat === 'repeat-x' || repeat === 'no-repeat' ) {
clipT = pxY + 1;
clipB = pxY + size.h + clipAdjust;
}
if( repeat === 'repeat-y' || repeat === 'no-repeat' ) {
clipL = pxX + 1;
clipR = pxX + size.w + clipAdjust;
}
shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)';
}
}
} );
},
/**
* Draw the linear gradient for a gradient layer
* @param {Element} shape
* @param {Object} info The object holding the information about the gradient
*/
addLinearGradient: function( shape, info ) {
var el = this.targetElement,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
fill = shape.fill,
stops = info.stops,
stopCount = stops.length,
PI = Math.PI,
GradientUtil = PIE.GradientUtil,
perpendicularIntersect = GradientUtil.perpendicularIntersect,
distance = GradientUtil.distance,
metrics = GradientUtil.getGradientMetrics( el, w, h, info ),
angle = metrics.angle,
startX = metrics.startX,
startY = metrics.startY,
startCornerX = metrics.startCornerX,
startCornerY = metrics.startCornerY,
endCornerX = metrics.endCornerX,
endCornerY = metrics.endCornerY,
deltaX = metrics.deltaX,
deltaY = metrics.deltaY,
lineLength = metrics.lineLength,
vmlAngle, vmlGradientLength, vmlColors,
stopPx, vmlOffsetPct,
p, i, j, before, after;
// In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's
// bounding box; for example specifying a 45 deg angle actually results in a gradient
// drawn diagonally from one corner to its opposite corner, which will only appear to the
// viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas
// between the start and end points, multiply one of them by the shape's aspect ratio,
// and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly
// horizontal or vertical then we don't need to do this conversion.
vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 );
// VML angles are 180 degrees offset from CSS angles
vmlAngle += 180;
vmlAngle = vmlAngle % 360;
// Add all the stops to the VML 'colors' list, including the first and last stops.
// For each, we find its pixel offset along the gradient-line; if the offset of a stop is less
// than that of its predecessor we increase it to be equal. We then map that pixel offset to a
// percentage along the VML gradient-line, which runs from shape corner to corner.
p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY );
vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] );
vmlColors = [];
p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY );
vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100;
// Find the pixel offsets along the CSS3 gradient-line for each stop.
stopPx = [];
for( i = 0; i < stopCount; i++ ) {
stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) :
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
}
// Fill in gaps with evenly-spaced offsets
for( i = 1; i < stopCount; i++ ) {
if( stopPx[ i ] === null ) {
before = stopPx[ i - 1 ];
j = i;
do {
after = stopPx[ ++j ];
} while( after === null );
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
}
// Make sure each stop's offset is no less than the one before it
stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] );
}
// Convert to percentage along the VML gradient line and add to the VML 'colors' value
for( i = 0; i < stopCount; i++ ) {
vmlColors.push(
( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el )
);
}
// Now, finally, we're ready to render the gradient fill. Set the start and end colors to
// the first and last stop colors; this just sets outer bounds for the gradient.
fill['angle'] = vmlAngle;
fill['type'] = 'gradient';
fill['method'] = 'sigma';
fill['color'] = stops[0].color.colorValue( el );
fill['color2'] = stops[stopCount - 1].color.colorValue( el );
if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?)
fill['colors'].value = vmlColors.join( ',' );
} else {
fill['colors'] = vmlColors.join( ',' );
}
},
/**
* Hide the actual background image and color of the element.
*/
hideBackground: function() {
var rs = this.targetElement.runtimeStyle;
rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events
rs.backgroundColor = 'transparent';
},
destroy: function() {
PIE.RendererBase.destroy.call( this );
var rs = this.targetElement.runtimeStyle;
rs.backgroundImage = rs.backgroundColor = '';
}
} );
/**
* Renderer for element borders.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BorderRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 4,
boxName: 'border',
needsUpdate: function() {
var si = this.styleInfos;
return si.borderInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderRadiusInfo.isActive() &&
!si.borderImageInfo.isActive() &&
si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive
},
/**
* Draw the border shape(s)
*/
draw: function() {
var el = this.targetElement,
props = this.styleInfos.borderInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
shape, stroke, s,
segments, seg, i, len;
if( props ) {
this.hideBorder();
segments = this.getBorderSegments( 2 );
for( i = 0, len = segments.length; i < len; i++) {
seg = segments[i];
shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() );
shape.coordsize = w * 2 + ',' + h * 2;
shape.coordorigin = '1,1';
shape.path = seg.path;
s = shape.style;
s.width = w;
s.height = h;
shape.filled = !!seg.fill;
shape.stroked = !!seg.stroke;
if( seg.stroke ) {
stroke = shape.stroke;
stroke['weight'] = seg.weight + 'px';
stroke.color = seg.color.colorValue( el );
stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid';
stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single';
} else {
shape.fill.color = seg.fill.colorValue( el );
}
}
// remove any previously-created border shapes which didn't get used above
while( this.deleteShape( 'borderPiece' + i++ ) ) {}
}
},
/**
* Get the VML path definitions for the border segment(s).
* @param {number=} mult If specified, all coordinates will be multiplied by this number
* @return {Array.<string>}
*/
getBorderSegments: function( mult ) {
var el = this.targetElement,
bounds, elW, elH,
borderInfo = this.styleInfos.borderInfo,
segments = [],
floor, ceil, wT, wR, wB, wL,
round = Math.round,
borderProps, radiusInfo, radii, widths, styles, colors;
if( borderInfo.isActive() ) {
borderProps = borderInfo.getProps();
widths = borderProps.widths;
styles = borderProps.styles;
colors = borderProps.colors;
if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) {
if( colors['t'].alpha() > 0 ) {
// shortcut for identical border on all sides - only need 1 stroked shape
wT = widths['t'].pixels( el ); //thickness
wR = wT / 2; //shrink
segments.push( {
path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ),
stroke: styles['t'],
color: colors['t'],
weight: wT
} );
}
}
else {
mult = mult || 1;
bounds = this.boundsInfo.getBounds();
elW = bounds.w;
elH = bounds.h;
wT = round( widths['t'].pixels( el ) );
wR = round( widths['r'].pixels( el ) );
wB = round( widths['b'].pixels( el ) );
wL = round( widths['l'].pixels( el ) );
var pxWidths = {
't': wT,
'r': wR,
'b': wB,
'l': wL
};
radiusInfo = this.styleInfos.borderRadiusInfo;
if( radiusInfo.isActive() ) {
radii = this.getRadiiPixels( radiusInfo.getProps() );
}
floor = Math.floor;
ceil = Math.ceil;
function radius( xy, corner ) {
return radii ? radii[ xy ][ corner ] : 0;
}
function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) {
var rx = radius( 'x', corner),
ry = radius( 'y', corner),
deg = 65535,
isRight = corner.charAt( 1 ) === 'r',
isBottom = corner.charAt( 0 ) === 'b';
return ( rx > 0 && ry > 0 ) ?
( doMove ? 'al' : 'ae' ) +
( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x
( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y
( floor( rx ) - shrinkX ) * mult + ',' + // width
( floor( ry ) - shrinkY ) * mult + ',' + // height
( startAngle * deg ) + ',' + // start angle
( 45 * deg * ( ccw ? 1 : -1 ) // angle change
) : (
( doMove ? 'm' : 'l' ) +
( isRight ? elW - shrinkX : shrinkX ) * mult + ',' +
( isBottom ? elH - shrinkY : shrinkY ) * mult
);
}
function line( side, shrink, ccw, doMove ) {
var
start = (
side === 't' ?
floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult :
side === 'r' ?
ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult :
side === 'b' ?
ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult :
// side === 'l' ?
floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult
),
end = (
side === 't' ?
ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult :
side === 'r' ?
ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult :
side === 'b' ?
floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult :
// side === 'l' ?
floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult
);
return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start :
( doMove ? 'm' + start : '' ) + 'l' + end;
}
function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) {
var vert = side === 'l' || side === 'r',
sideW = pxWidths[ side ],
beforeX, beforeY, afterX, afterY;
if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) {
beforeX = pxWidths[ vert ? side : sideBefore ];
beforeY = pxWidths[ vert ? sideBefore : side ];
afterX = pxWidths[ vert ? side : sideAfter ];
afterY = pxWidths[ vert ? sideAfter : side ];
if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) {
segments.push( {
path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
fill: colors[ side ]
} );
segments.push( {
path: line( side, sideW / 2, 0, 1 ),
stroke: styles[ side ],
weight: sideW,
color: colors[ side ]
} );
segments.push( {
path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) +
curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ),
fill: colors[ side ]
} );
}
else {
segments.push( {
path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
line( side, sideW, 0, 0 ) +
curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) +
( styles[ side ] === 'double' && sideW > 2 ?
curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) +
line( side, ceil( sideW / 3 * 2 ), 1, 0 ) +
curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) +
'x ' +
curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) +
line( side, floor( sideW / 3 ), 1, 0 ) +
curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 )
: '' ) +
curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) +
line( side, 0, 1, 0 ) +
curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
fill: colors[ side ]
} );
}
}
}
addSide( 't', 'l', 'r', 'tl', 'tr', 90 );
addSide( 'r', 't', 'b', 'tr', 'br', 0 );
addSide( 'b', 'r', 'l', 'br', 'bl', -90 );
addSide( 'l', 'b', 't', 'bl', 'tl', -180 );
}
}
return segments;
},
destroy: function() {
var me = this;
if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) {
me.targetElement.runtimeStyle.borderColor = '';
}
PIE.RendererBase.destroy.call( me );
}
} );
/**
* Renderer for border-image
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 5,
pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ],
needsUpdate: function() {
return this.styleInfos.borderImageInfo.changed();
},
isActive: function() {
return this.styleInfos.borderImageInfo.isActive();
},
draw: function() {
this.getBox(); //make sure pieces are created
var props = this.styleInfos.borderImageInfo.getProps(),
borderProps = this.styleInfos.borderInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
el = this.targetElement,
pieces = this.pieces;
PIE.Util.withImageSize( props.src, function( imgSize ) {
var elW = bounds.w,
elH = bounds.h,
zero = PIE.getLength( '0' ),
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
widthT = widths['t'].pixels( el ),
widthR = widths['r'].pixels( el ),
widthB = widths['b'].pixels( el ),
widthL = widths['l'].pixels( el ),
slices = props.slice,
sliceT = slices['t'].pixels( el ),
sliceR = slices['r'].pixels( el ),
sliceB = slices['b'].pixels( el ),
sliceL = slices['l'].pixels( el );
// Piece positions and sizes
function setSizeAndPos( piece, w, h, x, y ) {
var s = pieces[piece].style,
max = Math.max;
s.width = max(w, 0);
s.height = max(h, 0);
s.left = x;
s.top = y;
}
setSizeAndPos( 'tl', widthL, widthT, 0, 0 );
setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 );
setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 );
setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT );
setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB );
setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB );
setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB );
setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT );
setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT );
// image croppings
function setCrops( sides, crop, val ) {
for( var i=0, len=sides.length; i < len; i++ ) {
pieces[ sides[i] ]['imagedata'][ crop ] = val;
}
}
// corners
setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h );
setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w );
setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h );
setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w );
// edges and center
// TODO right now this treats everything like 'stretch', need to support other schemes
//if( props.repeat.v === 'stretch' ) {
setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h );
setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h );
//}
//if( props.repeat.h === 'stretch' ) {
setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w );
setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w );
//}
// center fill
pieces['c'].style.display = props.fill ? '' : 'none';
}, this );
},
getBox: function() {
var box = this.parent.getLayer( this.boxZIndex ),
s, piece, i,
pieceNames = this.pieceNames,
len = pieceNames.length;
if( !box ) {
box = doc.createElement( 'border-image' );
s = box.style;
s.position = 'absolute';
this.pieces = {};
for( i = 0; i < len; i++ ) {
piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' );
piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) );
s = piece.style;
s['behavior'] = 'url(#default#VML)';
s.position = "absolute";
s.top = s.left = 0;
piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src;
piece.stroked = false;
piece.filled = false;
box.appendChild( piece );
}
this.parent.addLayer( this.boxZIndex, box );
}
return box;
},
prepareUpdate: function() {
if (this.isActive()) {
var me = this,
el = me.targetElement,
rs = el.runtimeStyle,
widths = me.styleInfos.borderImageInfo.getProps().widths;
// Force border-style to solid so it doesn't collapse
rs.borderStyle = 'solid';
// If widths specified in border-image shorthand, override border-width
// NOTE px units needed here as this gets used by the IE9 renderer too
if ( widths ) {
rs.borderTopWidth = widths['t'].pixels( el ) + 'px';
rs.borderRightWidth = widths['r'].pixels( el ) + 'px';
rs.borderBottomWidth = widths['b'].pixels( el ) + 'px';
rs.borderLeftWidth = widths['l'].pixels( el ) + 'px';
}
// Make the border transparent
me.hideBorder();
}
},
destroy: function() {
var me = this,
rs = me.targetElement.runtimeStyle;
rs.borderStyle = '';
if (me.finalized || !me.styleInfos.borderInfo.isActive()) {
rs.borderColor = rs.borderWidth = '';
}
PIE.RendererBase.destroy.call( this );
}
} );
/**
* Renderer for outset box-shadows
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 1,
boxName: 'outset-box-shadow',
needsUpdate: function() {
var si = this.styleInfos;
return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var boxShadowInfo = this.styleInfos.boxShadowInfo;
return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0];
},
draw: function() {
var me = this,
el = this.targetElement,
box = this.getBox(),
styleInfos = this.styleInfos,
shadowInfos = styleInfos.boxShadowInfo.getProps().outset,
radii = styleInfos.borderRadiusInfo.getProps(),
len = shadowInfos.length,
i = len, j,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px
corners = [ 'tl', 'tr', 'br', 'bl' ], corner,
shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path,
totalW, totalH, focusX, focusY, isBottom, isRight;
function getShadowShape( index, corner, xOff, yOff, color, blur, path ) {
var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ),
fill = shape.fill;
// Position and size
shape['coordsize'] = w * 2 + ',' + h * 2;
shape['coordorigin'] = '1,1';
// Color and opacity
shape['stroked'] = false;
shape['filled'] = true;
fill.color = color.colorValue( el );
if( blur ) {
fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?!
fill['color2'] = fill.color;
fill['opacity'] = 0;
}
// Path
shape.path = path;
// This needs to go last for some reason, to prevent rendering at incorrect size
ss = shape.style;
ss.left = xOff;
ss.top = yOff;
ss.width = w;
ss.height = h;
return shape;
}
while( i-- ) {
shadowInfo = shadowInfos[ i ];
xOff = shadowInfo.xOffset.pixels( el );
yOff = shadowInfo.yOffset.pixels( el );
spread = shadowInfo.spread.pixels( el );
blur = shadowInfo.blur.pixels( el );
color = shadowInfo.color;
// Shape path
shrink = -spread - blur;
if( !radii && blur ) {
// If blurring, use a non-null border radius info object so that getBoxPath will
// round the corners of the expanded shadow shape rather than squaring them off.
radii = PIE.BorderRadiusStyleInfo.ALL_ZERO;
}
path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii );
if( blur ) {
totalW = ( spread + blur ) * 2 + w;
totalH = ( spread + blur ) * 2 + h;
focusX = totalW ? blur * 2 / totalW : 0;
focusY = totalH ? blur * 2 / totalH : 0;
if( blur - spread > w / 2 || blur - spread > h / 2 ) {
// If the blur is larger than half the element's narrowest dimension, we cannot do
// this with a single shape gradient, because its focussize would have to be less than
// zero which results in ugly artifacts. Instead we create four shapes, each with its
// gradient focus past center, and then clip them so each only shows the quadrant
// opposite the focus.
for( j = 4; j--; ) {
corner = corners[j];
isBottom = corner.charAt( 0 ) === 'b';
isRight = corner.charAt( 1 ) === 'r';
shape = getShadowShape( i, corner, xOff, yOff, color, blur, path );
fill = shape.fill;
fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' +
( isBottom ? 1 - focusY : focusY );
fill['focussize'] = '0,0';
// Clip to show only the appropriate quadrant. Add 1px to the top/left clip values
// in IE8 to prevent a bug where IE8 displays one pixel outside the clip region.
shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' +
( isRight ? totalW : totalW / 2 ) + 'px,' +
( isBottom ? totalH : totalH / 2 ) + 'px,' +
( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)';
}
} else {
// TODO delete old quadrant shapes if resizing expands past the barrier
shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
fill = shape.fill;
fill['focusposition'] = focusX + ',' + focusY;
fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 );
}
} else {
shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
alpha = color.alpha();
if( alpha < 1 ) {
// shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')';
// ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha ) + ')';
shape.fill.opacity = alpha;
}
}
}
}
} );
/**
* Renderer for re-rendering img elements using VML. Kicks in if the img has
* a border-radius applied, or if the -pie-png-fix flag is set.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.ImgRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 6,
boxName: 'imgEl',
needsUpdate: function() {
var si = this.styleInfos;
return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix();
},
draw: function() {
this._lastSrc = src;
this.hideActualImg();
var shape = this.getShape( 'img', 'fill', this.getBox() ),
fill = shape.fill,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
borderProps = this.styleInfos.borderInfo.getProps(),
borderWidths = borderProps && borderProps.widths,
el = this.targetElement,
src = el.src,
round = Math.round,
cs = el.currentStyle,
getLength = PIE.getLength,
s, zero;
// In IE6, the BorderRenderer will have hidden the border by moving the border-width to
// the padding; therefore we want to pretend the borders have no width so they aren't doubled
// when adding in the current padding value below.
if( !borderWidths || PIE.ieVersion < 7 ) {
zero = PIE.getLength( '0' );
borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero };
}
shape.stroked = false;
fill.type = 'frame';
fill.src = src;
fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0);
shape.coordsize = w * 2 + ',' + h * 2;
shape.coordorigin = '1,1';
shape.path = this.getBoxPath( {
t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ),
r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ),
b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ),
l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) )
}, 2 );
s = shape.style;
s.width = w;
s.height = h;
},
hideActualImg: function() {
this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)';
},
destroy: function() {
PIE.RendererBase.destroy.call( this );
this.targetElement.runtimeStyle.filter = '';
}
} );
/**
* Root renderer for IE9; manages the rendering layers in the element's background
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( {
updatePos: PIE.emptyFn,
updateSize: PIE.emptyFn,
updateVisibility: PIE.emptyFn,
updateProps: PIE.emptyFn,
outerCommasRE: /^,+|,+$/g,
innerCommasRE: /,+/g,
setBackgroundLayer: function(zIndex, bg) {
var me = this,
bgLayers = me._bgLayers || ( me._bgLayers = [] ),
undef;
bgLayers[zIndex] = bg || undef;
},
finishUpdate: function() {
var me = this,
bgLayers = me._bgLayers,
bg;
if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) {
me._lastBg = me.targetElement.runtimeStyle.background = bg;
}
},
destroy: function() {
this.targetElement.runtimeStyle.background = '';
delete this._bgLayers;
}
} );
/**
* Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients
* to an equivalent SVG data URI.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( {
bgLayerZIndex: 1,
needsUpdate: function() {
var si = this.styleInfos;
return si.backgroundInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.backgroundInfo.isActive() || si.borderImageInfo.isActive();
},
draw: function() {
var me = this,
props = me.styleInfos.backgroundInfo.getProps(),
bg, images, i = 0, img, bgAreaSize, bgSize;
if ( props ) {
bg = [];
images = props.bgImages;
if ( images ) {
while( img = images[ i++ ] ) {
if (img.imgType === 'linear-gradient' ) {
bgAreaSize = me.getBgAreaSize( img.bgOrigin );
bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels(
me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h
),
bg.push(
'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' +
me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' +
( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' )
);
} else {
bg.push( img.origString );
}
}
}
if ( props.color ) {
bg.push( props.color.val );
}
me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(','));
}
},
bgPositionToString: function( bgPosition ) {
return bgPosition ? bgPosition.tokens.map(function(token) {
return token.tokenValue;
}).join(' ') : '0 0';
},
getBgAreaSize: function( bgOrigin ) {
var me = this,
el = me.targetElement,
bounds = me.boundsInfo.getBounds(),
elW = bounds.w,
elH = bounds.h,
w = elW,
h = elH,
borders, getLength, cs;
if( bgOrigin !== 'border-box' ) {
borders = me.styleInfos.borderInfo.getProps();
if( borders && ( borders = borders.widths ) ) {
w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el );
h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el );
}
}
if ( bgOrigin === 'content-box' ) {
getLength = PIE.getLength;
cs = el.currentStyle;
w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el );
h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el );
}
return { w: w, h: h };
},
getGradientSvg: function( info, bgWidth, bgHeight ) {
var el = this.targetElement,
stopsInfo = info.stops,
stopCount = stopsInfo.length,
metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ),
startX = metrics.startX,
startY = metrics.startY,
endX = metrics.endX,
endY = metrics.endY,
lineLength = metrics.lineLength,
stopPx,
i, j, before, after,
svg;
// Find the pixel offsets along the CSS3 gradient-line for each stop.
stopPx = [];
for( i = 0; i < stopCount; i++ ) {
stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) :
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
}
// Fill in gaps with evenly-spaced offsets
for( i = 1; i < stopCount; i++ ) {
if( stopPx[ i ] === null ) {
before = stopPx[ i - 1 ];
j = i;
do {
after = stopPx[ ++j ];
} while( after === null );
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
}
}
svg = [
'<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' +
'<defs>' +
'<linearGradient id="g" gradientUnits="userSpaceOnUse"' +
' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">'
];
// Convert to percentage along the SVG gradient line and add to the stops list
for( i = 0; i < stopCount; i++ ) {
svg.push(
'<stop offset="' + ( stopPx[ i ] / lineLength ) +
'" stop-color="' + stopsInfo[i].color.colorValue( el ) +
'" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>'
);
}
svg.push(
'</linearGradient>' +
'</defs>' +
'<rect width="100%" height="100%" fill="url(#g)"/>' +
'</svg>'
);
return svg.join( '' );
},
destroy: function() {
this.parent.setBackgroundLayer( this.bgLayerZIndex );
}
} );
/**
* Renderer for border-image
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( {
REPEAT: 'repeat',
STRETCH: 'stretch',
ROUND: 'round',
bgLayerZIndex: 0,
needsUpdate: function() {
return this.styleInfos.borderImageInfo.changed();
},
isActive: function() {
return this.styleInfos.borderImageInfo.isActive();
},
draw: function() {
var me = this,
props = me.styleInfos.borderImageInfo.getProps(),
borderProps = me.styleInfos.borderInfo.getProps(),
bounds = me.boundsInfo.getBounds(),
repeat = props.repeat,
repeatH = repeat.h,
repeatV = repeat.v,
el = me.targetElement,
isAsync = 0;
PIE.Util.withImageSize( props.src, function( imgSize ) {
var elW = bounds.w,
elH = bounds.h,
imgW = imgSize.w,
imgH = imgSize.h,
// The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange
// security exception (perhaps due to cross-origin policy within data URIs?) Therefore we
// work around this by converting the image data into a data URI itself using a transient
// canvas. This unfortunately requires the border-image src to be within the same domain,
// which isn't a limitation in true border-image, so we need to try and find a better fix.
imgSrc = me.imageToDataURI( props.src, imgW, imgH ),
REPEAT = me.REPEAT,
STRETCH = me.STRETCH,
ROUND = me.ROUND,
ceil = Math.ceil,
zero = PIE.getLength( '0' ),
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
widthT = widths['t'].pixels( el ),
widthR = widths['r'].pixels( el ),
widthB = widths['b'].pixels( el ),
widthL = widths['l'].pixels( el ),
slices = props.slice,
sliceT = slices['t'].pixels( el ),
sliceR = slices['r'].pixels( el ),
sliceB = slices['b'].pixels( el ),
sliceL = slices['l'].pixels( el ),
centerW = elW - widthL - widthR,
middleH = elH - widthT - widthB,
imgCenterW = imgW - sliceL - sliceR,
imgMiddleH = imgH - sliceT - sliceB,
// Determine the size of each tile - 'round' is handled below
tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT,
tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR,
tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB,
tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL,
svg,
patterns = [],
rects = [],
i = 0;
// For 'round', subtract from each tile's size enough so that they fill the space a whole number of times
if (repeatH === ROUND) {
tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT);
tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB);
}
if (repeatV === ROUND) {
tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR);
tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL);
}
// Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched
// or repeated as the fill of a rect of appropriate size.
svg = [
'<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
];
function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) {
patterns.push(
'<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' +
'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' +
'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' +
'width="' + tileW + '" height="' + tileH + '">' +
'<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' +
'<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' +
'</svg>' +
'</pattern>'
);
rects.push(
'<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />'
);
i++;
}
addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left
addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center
addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right
addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left
if ( props.fill ) { // center fill
addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH,
tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH );
}
addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right
addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left
addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center
addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right
svg.push(
'<defs>' +
patterns.join('\n') +
'</defs>' +
rects.join('\n') +
'</svg>'
);
me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' );
// If the border-image's src wasn't immediately available, the SVG for its background layer
// will have been created asynchronously after the main element's update has finished; we'll
// therefore need to force the root renderer to sync to the final background once finished.
if( isAsync ) {
me.parent.finishUpdate();
}
}, me );
isAsync = 1;
},
/**
* Convert a given image to a data URI
*/
imageToDataURI: (function() {
var uris = {};
return function( src, width, height ) {
var uri = uris[ src ],
image, canvas;
if ( !uri ) {
image = new Image();
canvas = doc.createElement( 'canvas' );
image.src = src;
canvas.width = width;
canvas.height = height;
canvas.getContext( '2d' ).drawImage( image, 0, 0 );
uri = uris[ src ] = canvas.toDataURL();
}
return uri;
}
})(),
prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate,
destroy: function() {
var me = this,
rs = me.targetElement.runtimeStyle;
me.parent.setBackgroundLayer( me.bgLayerZIndex );
rs.borderColor = rs.borderStyle = rs.borderWidth = '';
}
} );
PIE.Element = (function() {
var wrappers = {},
lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init',
pollCssProp = PIE.CSS_PREFIX + 'poll',
trackActiveCssProp = PIE.CSS_PREFIX + 'track-active',
trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover',
hoverClass = PIE.CLASS_PREFIX + 'hover',
activeClass = PIE.CLASS_PREFIX + 'active',
focusClass = PIE.CLASS_PREFIX + 'focus',
firstChildClass = PIE.CLASS_PREFIX + 'first-child',
ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 },
classNameRegExes = {},
dummyArray = [];
function addClass( el, className ) {
el.className += ' ' + className;
}
function removeClass( el, className ) {
var re = classNameRegExes[ className ] ||
( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) );
el.className = el.className.replace( re, '' );
}
function delayAddClass( el, className /*, className2*/ ) {
var classes = dummyArray.slice.call( arguments, 1 ),
i = classes.length;
setTimeout( function() {
if( el ) {
while( i-- ) {
addClass( el, classes[ i ] );
}
}
}, 0 );
}
function delayRemoveClass( el, className /*, className2*/ ) {
var classes = dummyArray.slice.call( arguments, 1 ),
i = classes.length;
setTimeout( function() {
if( el ) {
while( i-- ) {
removeClass( el, classes[ i ] );
}
}
}, 0 );
}
function Element( el ) {
var renderers,
rootRenderer,
boundsInfo = new PIE.BoundsInfo( el ),
styleInfos,
styleInfosArr,
initializing,
initialized,
eventsAttached,
eventListeners = [],
delayed,
destroyed,
poll;
/**
* Initialize PIE for this element.
*/
function init() {
if( !initialized ) {
var docEl,
bounds,
ieDocMode = PIE.ieDocMode,
cs = el.currentStyle,
lazy = cs.getAttribute( lazyInitCssProp ) === 'true',
trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false',
trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false',
childRenderers;
// Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll
poll = cs.getAttribute( pollCssProp );
poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true';
// Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes
// after load, but make sure it only gets called the first time through to avoid recursive calls to init().
if( !initializing ) {
initializing = 1;
el.runtimeStyle.zoom = 1;
initFirstChildPseudoClass();
}
boundsInfo.lock();
// If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization
if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) &&
( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) {
if( !delayed ) {
delayed = 1;
PIE.OnScroll.observe( init );
}
} else {
initialized = 1;
delayed = initializing = 0;
PIE.OnScroll.unobserve( init );
// Create the style infos and renderers
if ( ieDocMode === 9 ) {
styleInfos = {
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
borderInfo: new PIE.BorderStyleInfo( el )
};
styleInfosArr = [
styleInfos.backgroundInfo,
styleInfos.borderImageInfo
];
rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos );
childRenderers = [
new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
];
} else {
styleInfos = {
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
borderInfo: new PIE.BorderStyleInfo( el ),
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ),
boxShadowInfo: new PIE.BoxShadowStyleInfo( el ),
visibilityInfo: new PIE.VisibilityStyleInfo( el )
};
styleInfosArr = [
styleInfos.backgroundInfo,
styleInfos.borderInfo,
styleInfos.borderImageInfo,
styleInfos.borderRadiusInfo,
styleInfos.boxShadowInfo,
styleInfos.visibilityInfo
];
rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos );
childRenderers = [
new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
//new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
];
if( el.tagName === 'IMG' ) {
childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) );
}
rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way?
}
renderers = [ rootRenderer ].concat( childRenderers );
// Add property change listeners to ancestors if requested
initAncestorEventListeners();
// Add to list of polled elements in IE8
if( poll ) {
PIE.Heartbeat.observe( update );
PIE.Heartbeat.run();
}
// Trigger rendering
update( 1 );
}
if( !eventsAttached ) {
eventsAttached = 1;
if( ieDocMode < 9 ) {
addListener( el, 'onmove', handleMoveOrResize );
}
addListener( el, 'onresize', handleMoveOrResize );
addListener( el, 'onpropertychange', propChanged );
if( trackHover ) {
addListener( el, 'onmouseenter', mouseEntered );
}
if( trackHover || trackActive ) {
addListener( el, 'onmouseleave', mouseLeft );
}
if( trackActive ) {
addListener( el, 'onmousedown', mousePressed );
}
if( el.tagName in PIE.focusableElements ) {
addListener( el, 'onfocus', focused );
addListener( el, 'onblur', blurred );
}
PIE.OnResize.observe( handleMoveOrResize );
PIE.OnUnload.observe( removeEventListeners );
}
boundsInfo.unlock();
}
}
/**
* Event handler for onmove and onresize events. Invokes update() only if the element's
* bounds have previously been calculated, to prevent multiple runs during page load when
* the element has no initial CSS3 properties.
*/
function handleMoveOrResize() {
if( boundsInfo && boundsInfo.hasBeenQueried() ) {
update();
}
}
/**
* Update position and/or size as necessary. Both move and resize events call
* this rather than the updatePos/Size functions because sometimes, particularly
* during page load, one will fire but the other won't.
*/
function update( force ) {
if( !destroyed ) {
if( initialized ) {
var i, len = renderers.length;
lockAll();
for( i = 0; i < len; i++ ) {
renderers[i].prepareUpdate();
}
if( force || boundsInfo.positionChanged() ) {
/* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting
position changes may not always be accurate; it's possible that
an element will actually move relative to its positioning parent, but its position
relative to the viewport will stay the same. Need to come up with a better way to
track movement. The most accurate would be the same logic used in RootRenderer.updatePos()
but that is a more expensive operation since it does some DOM walking, and we want this
check to be as fast as possible. */
for( i = 0; i < len; i++ ) {
renderers[i].updatePos();
}
}
if( force || boundsInfo.sizeChanged() ) {
for( i = 0; i < len; i++ ) {
renderers[i].updateSize();
}
}
rootRenderer.finishUpdate();
unlockAll();
}
else if( !initializing ) {
init();
}
}
}
/**
* Handle property changes to trigger update when appropriate.
*/
function propChanged() {
var i, len = renderers.length,
renderer,
e = event;
// Some elements like <table> fire onpropertychange events for old-school background properties
// ('background', 'bgColor') when runtimeStyle background properties are changed, which
// results in an infinite loop; therefore we filter out those property names. Also, 'display'
// is ignored because size calculations don't work correctly immediately when its onpropertychange
// event fires, and because it will trigger an onresize event anyway.
if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) {
if( initialized ) {
lockAll();
for( i = 0; i < len; i++ ) {
renderers[i].prepareUpdate();
}
for( i = 0; i < len; i++ ) {
renderer = renderers[i];
// Make sure position is synced if the element hasn't already been rendered.
// TODO this feels sloppy - look into merging propChanged and update functions
if( !renderer.isPositioned ) {
renderer.updatePos();
}
if( renderer.needsUpdate() ) {
renderer.updateProps();
}
}
rootRenderer.finishUpdate();
unlockAll();
}
else if( !initializing ) {
init();
}
}
}
/**
* Handle mouseenter events. Adds a custom class to the element to allow IE6 to add
* hover styles to non-link elements, and to trigger a propertychange update.
*/
function mouseEntered() {
//must delay this because the mouseenter event fires before the :hover styles are added.
delayAddClass( el, hoverClass );
}
/**
* Handle mouseleave events
*/
function mouseLeft() {
//must delay this because the mouseleave event fires before the :hover styles are removed.
delayRemoveClass( el, hoverClass, activeClass );
}
/**
* Handle mousedown events. Adds a custom class to the element to allow IE6 to add
* active styles to non-link elements, and to trigger a propertychange update.
*/
function mousePressed() {
//must delay this because the mousedown event fires before the :active styles are added.
delayAddClass( el, activeClass );
// listen for mouseups on the document; can't just be on the element because the user might
// have dragged out of the element while the mouse button was held down
PIE.OnMouseup.observe( mouseReleased );
}
/**
* Handle mouseup events
*/
function mouseReleased() {
//must delay this because the mouseup event fires before the :active styles are removed.
delayRemoveClass( el, activeClass );
PIE.OnMouseup.unobserve( mouseReleased );
}
/**
* Handle focus events. Adds a custom class to the element to trigger a propertychange update.
*/
function focused() {
//must delay this because the focus event fires before the :focus styles are added.
delayAddClass( el, focusClass );
}
/**
* Handle blur events
*/
function blurred() {
//must delay this because the blur event fires before the :focus styles are removed.
delayRemoveClass( el, focusClass );
}
/**
* Handle property changes on ancestors of the element; see initAncestorEventListeners()
* which adds these listeners as requested with the -pie-watch-ancestors CSS property.
*/
function ancestorPropChanged() {
var name = event.propertyName;
if( name === 'className' || name === 'id' ) {
propChanged();
}
}
function lockAll() {
boundsInfo.lock();
for( var i = styleInfosArr.length; i--; ) {
styleInfosArr[i].lock();
}
}
function unlockAll() {
for( var i = styleInfosArr.length; i--; ) {
styleInfosArr[i].unlock();
}
boundsInfo.unlock();
}
function addListener( targetEl, type, handler ) {
targetEl.attachEvent( type, handler );
eventListeners.push( [ targetEl, type, handler ] );
}
/**
* Remove all event listeners from the element and any monitored ancestors.
*/
function removeEventListeners() {
if (eventsAttached) {
var i = eventListeners.length,
listener;
while( i-- ) {
listener = eventListeners[ i ];
listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] );
}
PIE.OnUnload.unobserve( removeEventListeners );
eventsAttached = 0;
eventListeners = [];
}
}
/**
* Clean everything up when the behavior is removed from the element, or the element
* is manually destroyed.
*/
function destroy() {
if( !destroyed ) {
var i, len;
removeEventListeners();
destroyed = 1;
// destroy any active renderers
if( renderers ) {
for( i = 0, len = renderers.length; i < len; i++ ) {
renderers[i].finalized = 1;
renderers[i].destroy();
}
}
// Remove from list of polled elements in IE8
if( poll ) {
PIE.Heartbeat.unobserve( update );
}
// Stop onresize listening
PIE.OnResize.unobserve( update );
// Kill references
renderers = boundsInfo = styleInfos = styleInfosArr = el = null;
}
}
/**
* If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and
* other event listeners to ancestor(s) of the element so we can pick up style changes
* based on CSS rules using descendant selectors.
*/
function initAncestorEventListeners() {
var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),
i, a;
if( watch ) {
watch = parseInt( watch, 10 );
i = 0;
a = el.parentNode;
while( a && ( watch === 'NaN' || i++ < watch ) ) {
addListener( a, 'onpropertychange', ancestorPropChanged );
addListener( a, 'onmouseenter', mouseEntered );
addListener( a, 'onmouseleave', mouseLeft );
addListener( a, 'onmousedown', mousePressed );
if( a.tagName in PIE.focusableElements ) {
addListener( a, 'onfocus', focused );
addListener( a, 'onblur', blurred );
}
a = a.parentNode;
}
}
}
/**
* If the target element is a first child, add a pie_first-child class to it. This allows using
* the added class as a workaround for the fact that PIE's rendering element breaks the :first-child
* pseudo-class selector.
*/
function initFirstChildPseudoClass() {
var tmpEl = el,
isFirst = 1;
while( tmpEl = tmpEl.previousSibling ) {
if( tmpEl.nodeType === 1 ) {
isFirst = 0;
break;
}
}
if( isFirst ) {
addClass( el, firstChildClass );
}
}
// These methods are all already bound to this instance so there's no need to wrap them
// in a closure to maintain the 'this' scope object when calling them.
this.init = init;
this.update = update;
this.destroy = destroy;
this.el = el;
}
Element.getInstance = function( el ) {
var id = PIE.Util.getUID( el );
return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) );
};
Element.destroy = function( el ) {
var id = PIE.Util.getUID( el ),
wrapper = wrappers[ id ];
if( wrapper ) {
wrapper.destroy();
delete wrappers[ id ];
}
};
Element.destroyAll = function() {
var els = [], wrapper;
if( wrappers ) {
for( var w in wrappers ) {
if( wrappers.hasOwnProperty( w ) ) {
wrapper = wrappers[ w ];
els.push( wrapper.el );
wrapper.destroy();
}
}
wrappers = {};
}
return els;
};
return Element;
})();
/*
* This file exposes the public API for invoking PIE.
*/
/**
* @property supportsVML
* True if the current IE browser environment has a functioning VML engine. Should be true
* in most IEs, but in rare cases may be false. If false, PIE will exit immediately when
* attached to an element; this property may be used for debugging or by external scripts
* to perform some special action when VML support is absent.
* @type {boolean}
*/
PIE[ 'supportsVML' ] = PIE.supportsVML;
/**
* Programatically attach PIE to a single element.
* @param {Element} el
*/
PIE[ 'attach' ] = function( el ) {
if (PIE.ieDocMode < 10 && PIE.supportsVML) {
PIE.Element.getInstance( el ).init();
}
};
/**
* Programatically detach PIE from a single element.
* @param {Element} el
*/
PIE[ 'detach' ] = function( el ) {
PIE.Element.destroy( el );
};
} // if( !PIE )
})(); | JavaScript |
/*
* jqModal - Minimalist Modaling with jQuery
* (http://dev.iceburg.net/jquery/jqModal/)
*
* Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* $Version: 03/01/2009 +r14
*/
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};
$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};
$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
if(c.modal) {if(!A[0])L('bind');A.push(s);}
else if(c.overlay > 0)h.w.jqmAddClose(o);
else o=F;
h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}
if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
else if(cc)h.w.jqmAddClose($(cc,h.w));
if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);
(c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
if(A[0]){A.pop();if(!A[0])L('unbind');}
if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery); | JavaScript |
$(document).ready(function () {
var that = this;
var taskArr = ['checkin', 'invite', 'sendStory'];
var $singleTaskModal = null,
$singleTaskModalContent = null,
$singleTaskModalBtn = null,
currentSingleTask = null;
var $taskModal;
var userId = $(document.body).attr('data-userid');
var taskFunctionMap = {
// follow: '关注我们空间可再获100积分。',
invite: function (next) {
fusion2.dialog.invite({
msg: "一起来选购吧~",
source: userId,
onSuccess: function (opt) {
invite(opt.invitees.length, function () {
/*next && setTimeout(function () {
goToNextTask();
}, 500);*/
});
},
onCancel: function (opt) {
next && goToNextTask();
},
onClose: function (opt) {
next && goToNextTask();
}
});
},
sendStory: function (next) {
fusion2.dialog.sendStory({
title: "亲爱的,我发现一条超美的裙子!",
img: "./icons/ap.png",
summary: "2013最流行的搭配推荐!姐妹们每天打扮用来参考的秘密武器!衣衣、裙子、包包、美鞋,你一定会喜欢的!",
msg: "一起来选购吧",
source: userId,
onSuccess: function (opt) {
next && sendStory(opt.invitees.length, function () {
/*setTimeout(function () {
goToNextTask();
}, 500);*/
});
},
onCancel: function (opt) {
next && goToNextTask();
},
onClose: function (opt) {
next && goToNextTask();
}
});
}
};
$('#do-tasks').click(function (ev) {
ev.preventDefault();
// 弹出做任务界面
showTaskBoard();
});
// 领取积分按钮
var $checkInBtn = $('#checkin-btn');
$checkInBtn.click(function (ev) {
ev.preventDefault();
if (!$(ev.target).hasClass('disabled')) {
checkIn(function () {
$checkInBtn.addClass('disabled');
$('#task-checkin .task-btn').addClass('task-btn-disabled');
hideAlert();
showTaskBoard();
});
}
});
// 喜欢、收藏
$('.item-like, .item-collect').each(function (index) {
var $target = $(this),
$link = $target.find('a'),
$item = $target.parents('.item'),
paramArr = [];
$.each({
url: location.href,
desc: getRidOfSpace($item.find('.item-desc').text()),
title: getRidOfSpace($item.find('.item-hd').text()),
pics: $item.find('.item-pic img').prop('src'),
summary: ' '
}, function (key, value) {
paramArr.push(key + '=' + encodeURIComponent(value));
});
$.each(paramArr, function (index, el) {
console.log(decodeURIComponent(el));
});
$link.click(function (ev) {
ev.preventDefault();
window.open('http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?' + paramArr.join('&'), '_blank', 'scrollbars=no,width=600,height=560,left=175,top=70,status=no,resizable=yes');
if ($target.hasClass('item-like')) {
like($item.attr('data-id'), function (data) {
$link.next('.count').html(data.count);
});
} else if ($target.hasClass('item-collect')) {
collect($item.attr('data-id'), function (data) {
$link.next('.count').html(data.count);
});
}
});
});
// 购买链接
$('.item-pic a, .item-buy a, #search-bar a').click(function (ev) {
ev.preventDefault();
ev.stopPropagation();
openLink(this.href);
});
// 积分兑换按钮
$('#exchange-gifts').click(function (ev) {
ev.preventDefault();
alertInfo('敬请期待!');
});
function initializeSingleTaskModal () {
if ($singleTaskModal) {
return;
}
$singleTaskModal = $('#single-task-modal');
$singleTaskModal.jqm({
closeClass: 'modal-close',
modal: true
});
$singleTaskModalContent = $singleTaskModal.find('.modal-bd-content');
$singleTaskModalBtn = $singleTaskModal.find('.modal-ft a');
$singleTaskModalBtn.click(function (ev) {
ev.preventDefault();
currentSingleTask && currentSingleTask();
});
}
function checkIn (callback) {
// 调用签到接口
$.ajax({
url: './abtainPoints.htm?task_id=3&userid=' + userId,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
// 领取成功
if (data) {
alertSuccess('签到成功,成功获取' + data.points + '积分!');
callback();
}
},
error: function (jqXHR, textStatus, errorThrown) {
// 领取失败
alertError(textStatus);
},
complete: function (jqXHR, textStatus) {
}
});
}
function like (itemId, callback) {
// 喜欢任务
$.ajax({
url: './abtainPoints.htm?task_id=1&userid=' + userId + '&item_id=' + itemId,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
// 成功
callback && callback(data);
},
error: function (jqXHR, textStatus, errorThrown) {
// 失败
alertError(textStatus);
},
complete: function (jqXHR, textStatus) {
}
});
}
function collect (itemId, callback) {
// 收藏任务
$.ajax({
url: './abtainPoints.htm?task_id=2&userid=' + userId + '&item_id=' + itemId,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
// 成功
callback && callback(data);
},
error: function (jqXHR, textStatus, errorThrown) {
// 失败
alertError(textStatus);
},
complete: function (jqXHR, textStatus) {
}
});
}
function invite (num, callback) {
// 邀请任务
$.ajax({
url: './abtainPoints.htm?task_id=7&userid=' + userId + '&num=' + count,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
// 领取成功
alertSuccess('邀请' + num + '人成功,成功获取' + data.points + '积分!');
callback && callback();
},
error: function (jqXHR, textStatus, errorThrown) {
// 领取失败
alertError(textStatus);
},
complete: function (jqXHR, textStatus) {
}
});
}
function sendStory (callback) {
// 分享应用任务
$.ajax({
url: './abtainPoints.htm?task_id=8&userid=' + userId,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
// 领取成功
if (data.success) {
alertSuccess('分享应用成功,成功获取' + data.points + '积分!');
callback && callback();
}
},
error: function (jqXHR, textStatus, errorThrown) {
// 领取失败
alertError(textStatus);
},
complete: function (jqXHR, textStatus) {
}
});
}
function saveBlog (title, content, onSuccess) {
fusion2.dialog.saveBlog({
title: title,
content: content,
context: "",
onSuccess: function (opt) {
onSuccess && onSuccess();
goToNextTask();
},
onCancel: function (opt) {
},
onClose: function (opt) {
}
});
}
function goToNextTask () {
// TODO
// 调用查看下一个任务
// var taskName = 'invite';
var taskName = 'sendStory';
hideAlert();
initializeSingleTaskModal();
$singleTaskModalContent.html(window.taskContentMap[taskName]);
currentSingleTask = taskFunctionMap[taskName];
$singleTaskModal.jqmShow();
}
function alertSuccess (msg) {
fusion2.ui.showMsgbox({
type: 2,
msg: msg,
timeout: 50000
});
}
function alertError (msg) {
fusion2.ui.showMsgbox({
type: 3,
msg: msg,
timeout: 50000
});
}
function alertLoading () {
fusion2.ui.showMsgbox({
type: 4,
msg: '请稍候...',
timeout: 50000
});
}
function alertInfo (msg) {
fusion2.ui.showMsgbox({
type: 1,
msg: msg,
timeout: 2000
});
}
function hideAlert () {
fusion2.ui.hideMsgbox();
}
function getRidOfSpace (str) {
return str.replace(/\s/g, '');
}
function openLink (url) {
fusion2.nav.open({
url: url
});
}
function showTaskBoard () {
if (!$taskModal) {
$taskModal = $('#multi-tasks-modal');
$taskModal.jqm({
trigger: $('#do-tasks'),
closeClass: 'modal-close',
modal: true
});
$('#task-checkin .task-btn').click(function (ev) {
var $target;
ev.preventDefault();
$target = $(ev.target);
if (!$target.hasClass('task-btn-disabled')) {
checkIn(function () {
$target.addClass('task-btn-disabled');
$checkInBtn.addClass('disabled');
setTimeout(function () {
hideAlert();
}, 500);
});
}
});
$('#task-invite .task-btn').click(function (ev) {
var $target;
ev.preventDefault();
$target = $(ev.target);
if (!$target.hasClass('task-btn-disabled')) {
taskFunctionMap.invite(function () {
$target.addClass('task-btn-disabled');
});
}
});
$('#task-sendstory .task-btn').click(function (ev) {
var $target;
ev.preventDefault();
$target = $(ev.target);
if (!$target.hasClass('task-btn-disabled')) {
taskFunctionMap.sendStory(function () {
$target.addClass('task-btn-disabled');
});
}
});
}
$taskModal.jqmShow();
}
}); | JavaScript |
$(function () {
// $.support.cors = true;
// var STR_HOST = 'http://42.121.52.125';
var STR_HOST = 'http://www.100msm.com';
var currTag = '';
STR_URLBASE_VOTE = STR_HOST + '/item/aysnProcessSelected.htm',
STR_URLBASE_GET_CANDIDATES = STR_HOST + '/item/selectCompareItems.htm',
STR_URLBASE_GET_TOPS = STR_HOST + '/100msm/item/topItemsList.htm',
NUM_MAX_DESC = 140;
/**
* @func 计算单字节字数,双字节算两个字
* @param {String} str
* @return {Number}
*/
function countSingleByteWords(str) {
var arr1, arr2, re;
if (typeof str === 'string') {
arr1 = str.match(/[x00-xff]/g) || [];
arr2 = str.match(/[^x00-xff]/g) || [];
re = arr1.length + arr2.length * 2;
} else {
re = 0;
}
return re;
}
/**
* @func 截断字符串,返回x个单字节数的内容
* @param {String} str
* @param {Number} numberOfSingleByteWords
* @return {String}
*/
function cutWordsOff(str, numberOfSingleByteWords) {
var re, count, index;
if (typeof str === 'string') {
if (typeof numberOfSingleByteWords === 'number') {
count = numberOfSingleByteWords;
index = 0;
for (var len = str.length; index < len && count > 1; index++) {
if (/[x00-xff]/.test(str.charAt(index))) {
// 单字节
count = count - 1;
} else if (/[^x00-xff]/.test(str.charAt(index))) {
// 双字节
count = count - 2;
}
}
if (count != 1 || !/[x00-xff]/.test(str[index])) {
index--;
}
re = str.substring(0, index + 1);
} else {
re = str;
}
} else {
re = '';
}
return re;
}
var voteWrapper = $('#vote');
var voteCandidates = $('#vote .item');
voteCandidates.each(function (index, domNode) {
var voteCandidate = $(domNode),
// onHover = voteCandidate.find('.item-onhover'),
btn = voteCandidate.find('.item-btn a'),
// 宝贝描述
itemDesc = voteCandidate.find('.item-description p'),
itemDescStr = itemDesc.html();
// 截断宝贝描述
if (countSingleByteWords(itemDescStr) > NUM_MAX_DESC) {
itemDesc.prop('title', itemDescStr);
itemDesc.html(cutWordsOff(itemDescStr, NUM_MAX_DESC) + '...');
}
voteCandidate.hover(function () {
voteCandidate.addClass('active');
}, function () {
voteCandidate.removeClass('active');
});
voteCandidate.click(function (ev) {
var target = $(ev.target);
if (!target.hasClass('btn-buy') && !target.hasClass('btn-collect')) {
var arr = voteWrapper.attr('data-id').split(','),
url = STR_URLBASE_VOTE + '?winnerItemId=' + arr[0] + '&loserItemId=' + arr[1],
hxr;
ev.preventDefault();
hxr = $.getJSON(url).success(function (data) {
if (!data.success) {
throw new Error('fail to vote...')
}
// 请求新的投票对象
var hxr2 = $.ajax({
url: STR_URLBASE_GET_CANDIDATES + (currTag ? '?tag=' + currTag : ''),
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
var arr = data.result;
voteWrapper.attr('data-id', arr[0].id + ',' + arr[1].id);
voteCandidates.each(function (index, domNode) {
var voteCandidate = $(domNode),
itemDesc = voteCandidate.find('.item-description p'),
itemDescStr = arr[index].description;
// 描述
if (countSingleByteWords(itemDescStr) > NUM_MAX_DESC) {
itemDesc.prop('title', itemDescStr);
itemDesc.html(cutWordsOff(itemDescStr, NUM_MAX_DESC) + '...');
} else {
itemDesc.html(itemDescStr);
}
// 标题
voteCandidate.find('.item-title .item-title-wrapper').html(arr[index].title);
// 价格
voteCandidate.find('.item-price .price-figure').html(arr[index].price);
// 图片
voteCandidate.find('.item-pic img').prop('src', arr[index].image + '_310x310.jpg');
// 地址
voteCandidate.find('.btn-buy').prop('href', arr[index].url);
});
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
});
}
});
});
$('#skip').click(function (ev) {
ev.preventDefault();
var arr = voteWrapper.attr('data-id').split(',');
// 请求新的投票对象
$.ajax({
url: STR_URLBASE_GET_CANDIDATES + (currTag ? '?tag=' + currTag : ''),
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
var arr = data.result;
voteWrapper.attr('data-id', arr[0].id + ',' + arr[1].id);
voteCandidates.each(function (index, domNode) {
var voteCandidate = $(domNode),
itemDesc = voteCandidate.find('.item-description p'),
itemDescStr = arr[index].description;
// 描述
if (countSingleByteWords(itemDescStr) > NUM_MAX_DESC) {
itemDesc.prop('title', itemDescStr);
itemDesc.html(cutWordsOff(itemDescStr, NUM_MAX_DESC) + '...');
} else {
itemDesc.html(itemDescStr);
}
// 标题
voteCandidate.find('.item-title .item-title-wrapper').html(arr[index].title);
// 价格
voteCandidate.find('.item-price .price-figure').html(arr[index].price);
// 图片
voteCandidate.find('.item-pic img').prop('src', arr[index].image + '_310x310.jpg');
// 地址
voteCandidate.find('.btn-buy').prop('href', arr[index].url);
});
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
});
var hxr3 = $.ajax({
url: STR_URLBASE_GET_TOPS,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
var htmlStr = '';
$.each(data.result, function (index, item) {
if (index == data.result.length - 1) {
htmlStr += '<li class="last">';
} else {
htmlStr += '<li>';
}
htmlStr += '<div class="item">';
htmlStr += '<div class="item-pic"><a href="' + item.url + '" target="_blank"><img src="' + item.image + '_170x170.jpg"/></a></div>';
htmlStr += '<p class="item-title" title="' + item.title + '">' + item.title + '</p>';
htmlStr += '<p class="item-count">已得票:' + item.vote + '</p>';
htmlStr += '</div>';
htmlStr += '</li>';
});
$('#tops ul').html(htmlStr);
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
// 标签
var currTagEl = $('#vote-tags .active a');
$('#vote-tags a').click(function (ev) {
var target = ev.target,
targetEl = $(target),
id = targetEl.attr('data-id') || '';
ev.preventDefault();
if (id != currTagEl.attr('data-id')) {
currTagEl.parent().removeClass('active');
currTagEl = targetEl;
currTag = id;
currTagEl.parent().addClass('active');
// ajax
var arr = voteWrapper.attr('data-id').split(',');
// 请求新的投票对象
$.ajax({
url: STR_URLBASE_GET_CANDIDATES + (currTag ? '?tag=' + currTag : ''),
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
var arr = data.result;
voteWrapper.attr('data-id', arr[0].id + ',' + arr[1].id);
voteCandidates.each(function (index, domNode) {
var voteCandidate = $(domNode),
itemDesc = voteCandidate.find('.item-description p'),
itemDescStr = arr[index].description;
// 描述
if (countSingleByteWords(itemDescStr) > NUM_MAX_DESC) {
itemDesc.prop('title', itemDescStr);
itemDesc.html(cutWordsOff(itemDescStr, NUM_MAX_DESC) + '...');
} else {
itemDesc.html(itemDescStr);
}
// 标题
voteCandidate.find('.item-title .item-title-wrapper').html(arr[index].title);
// 价格
voteCandidate.find('.item-price .price-figure').html(arr[index].price);
// 图片
voteCandidate.find('.item-pic img').prop('src', arr[index].image + '_310x310.jpg');
// 地址
voteCandidate.find('.btn-buy').prop('href', arr[index].url);
});
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
}
});
// toplist
$('#top-list li').hover(function () {
$(this).addClass('active');
},function () {
$(this).removeClass('active');
}).click(function (ev) {
if (ev.target.nodeName != 'A') {
window.open($(this).find('.btn-buy').prop('href'));
}
});
});
| JavaScript |
var jsp = require('uglify-js').parser;
var pro = require('uglify-js').uglify;
var fs = require('fs');
var less = require('less');
var baseDir = '/Users/tiny_moo/Workspace/100kymsm/svn_webapp/assets';
var srcDir = baseDir + '/src';
var buildDir = baseDir + '/build/20130304';
var fileNameArr = ['meili'];
// 编译web_game_fp.less
fileNameArr.forEach(function (fileName) {
console.log('input-fileName: ' + srcDir + '/' + fileName + '.less');
fs.exists(srcDir + '/' + fileName + '.less', function (exists) {
if (exists) {
fs.readFile(srcDir + '/' + fileName + '.less', 'utf-8', function (err, data) {
var parser;
if (err) throw err;
parser = new(less.Parser)({
paths: ['./src']
});
parser.parse(data, function (err, tree) {
/*
fs.writeFile(buildDir + '/' + fileName + '.css', tree.toCSS(), function (err) {
if (err) throw err;
console.log('output-fileName: ' + buildDir + '/' + fileName + '.css');
});
*/
fs.writeFile(buildDir + '/' + fileName + '-min.css', tree.toCSS({
compress: true
}), function (err) {
if (err) throw err;
console.log('output-fileName: ' + buildDir + '/' + fileName + '-min.css');
});
});
});
} else {
console.error('cannot find the file');
}
});
});
/*
fs.exists(srcDir + '/home.js', function (exists) {
if (exists) {
fs.readFile(srcDir + '/home.js', 'utf-8', function (err, data) {
var ast, code1, code2;
if (err) throw err;
console.log('get the content of this file');
console.log('get the original ast');
ast = jsp.parse(data);
console.log('ascii the combined code');
code1 = pro.gen_code(ast, {
ascii_only: true,
beautify: true
});
ast = pro.ast_mangle(ast);
ast = pro.ast_squeeze(ast);
console.log('get the compression code');
code2 = pro.gen_code(ast, {
ascii_only: true
});
fs.writeFile(buildDir + '/home-min.js', code2, function (err) {
if (err) throw err;
console.log('get compressed file');
});
});
} else {
console.error('cannot find the file');
}
});
*/
fs.exists(srcDir + '/meili.js', function (exists) {
if (exists) {
fs.readFile(srcDir + '/meili.js', 'utf-8', function (err, data) {
var ast, code1, code2;
if (err) throw err;
console.log('get the content of this file');
console.log('get the original ast');
ast = jsp.parse(data);
console.log('ascii the combined code');
code1 = pro.gen_code(ast, {
ascii_only: true,
beautify: true
});
ast = pro.ast_mangle(ast);
ast = pro.ast_squeeze(ast);
console.log('get the compression code');
code2 = pro.gen_code(ast, {
ascii_only: true
});
fs.writeFile(buildDir + '/meili-min.js', code2, function (err) {
if (err) throw err;
console.log('get compressed file');
});
});
} else {
console.error('cannot find the file');
}
}); | JavaScript |
// Header:
const Name = "Vimperator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/commandline-handler.js'
*/
// Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const name = Name.toLowerCase();
function CommandLineHandler() {
this.wrappedJSObject = this;
}
CommandLineHandler.prototype = {
classDescription: Name + " Command-line Handler",
classID: Components.ID("{16dc34f7-6d22-4aa4-a67f-2921fb5dcb69}"),
contractID: "@mozilla.org/commandlinehandler/general-startup;1?type=" + name,
_xpcom_categories: [{
category: "command-line-handler",
entry: "m-" + name
}],
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsICommandLineHandler]),
handle: function (commandLine) {
// TODO: handle remote launches differently?
try {
this.optionValue = commandLine.handleFlagWithParam(name, false);
}
catch (e) {
dump(name + ": option '-" + name + "' requires an argument\n");
}
}
};
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory([CommandLineHandler]);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([CommandLineHandler]);
// vim: set ft=javascript fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2008-2009 Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/* Adds support for data: URIs with chrome privileges
* and fragment identifiers.
*
* "chrome-data:" <content-type> [; <flag>]* "," [<data>]
*
* By Kris Maglione, ideas from Ed Anuff's nsChromeExtensionHandler.
*/
const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "convert", function () {
var obj = new Object;
Cu.import("resource://liberator/template.js", obj);
return obj.convert;
});
const NS_BINDING_ABORTED = 0x804b0002;
const nsIProtocolHandler = Ci.nsIProtocolHandler;
const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
let channel = Components.classesByID["{61ba33c0-3031-11d3-8cd0-0060b0fc14a3}"]
.getService(Ci.nsIProtocolHandler)
.newChannel(ioService.newURI("chrome://liberator/content/data", null, null))
.QueryInterface(Ci.nsIRequest);
const systemPrincipal = channel.owner;
channel.cancel(NS_BINDING_ABORTED);
delete channel;
function dataURL(type, data) "data:" + (type || "application/xml;encoding=UTF-8") + "," + encodeURIComponent(data);
function makeChannel(url, orig) {
if (typeof url == "function")
url = dataURL.apply(null, url());
let uri = ioService.newURI(url, null, null);
let channel = ioService.newChannelFromURI(uri);
channel.owner = systemPrincipal;
channel.originalURI = orig;
return channel;
}
function fakeChannel(orig) makeChannel("chrome://liberator/content/does/not/exist", orig);
function redirect(to, orig) {
//xxx: escape
let html = '<html><head><meta http-equiv="Refresh" content="' + ("0;" + to).replace(/"/g, """) + '"/></head></html>';
return makeChannel(dataURL('text/html', html), ioService.newURI(to, null, null));
}
XPCOMUtils.defineLazyGetter(this, "cache", function () {
var dir = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
dir.append("liberatorCache");
if (!dir.exists()) {
dir.create(dir.DIRECTORY_TYPE, -1);
}
return dir;
});
XPCOMUtils.defineLazyGetter(this, "version", function () {
return Services.appinfo.version;
});
function ChromeData() {}
ChromeData.prototype = {
contractID: "@mozilla.org/network/protocol;1?name=chrome-data",
classID: Components.ID("{c1b67a07-18f7-4e13-b361-2edcc35a5a0d}"),
classDescription: "Data URIs with chrome privileges",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),
_xpcom_factory: {
createInstance: function (outer, iid) {
if (!ChromeData.instance)
ChromeData.instance = new ChromeData();
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return ChromeData.instance.QueryInterface(iid);
}
},
scheme: "chrome-data",
defaultPort: -1,
allowPort: function (port, scheme) false,
protocolFlags: nsIProtocolHandler.URI_NORELATIVE
| nsIProtocolHandler.URI_NOAUTH
| nsIProtocolHandler.URI_IS_UI_RESOURCE,
newURI: function (spec, charset, baseURI) {
var uri = Cc["@mozilla.org/network/standard-url;1"]
.createInstance(Ci.nsIStandardURL)
.QueryInterface(Ci.nsIURI);
uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, null);
return uri;
},
newChannel: function (uri) {
try {
if (uri.scheme == this.scheme)
return makeChannel(uri.spec.replace(/^.*?:\/*(.*)(?:#.*)?/, "data:$1"), uri);
}
catch (e) {}
return fakeChannel();
}
};
function Liberator() {
this.wrappedJSObject = this;
const self = this;
this.HELP_TAGS = {};
this.FILE_MAP = {};
this.OVERLAY_MAP = {};
}
Liberator.prototype = {
contractID: "@mozilla.org/network/protocol;1?name=liberator",
classID: Components.ID("{9c8f2530-51c8-4d41-b356-319e0b155c44}"),
classDescription: "Liberator utility protocol",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),
_xpcom_factory: {
createInstance: function (outer, iid) {
if (!Liberator.instance)
Liberator.instance = new Liberator();
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return Liberator.instance.QueryInterface(iid);
}
},
init: function (obj) {
for each (let prop in ["HELP_TAGS", "FILE_MAP", "OVERLAY_MAP"]) {
this[prop] = this[prop].constructor();
for (let [k, v] in Iterator(obj[prop] || {}))
this[prop][k] = v
}
},
scheme: "liberator",
defaultPort: -1,
allowPort: function (port, scheme) false,
protocolFlags: 0
| nsIProtocolHandler.URI_IS_UI_RESOURCE
| nsIProtocolHandler.URI_IS_LOCAL_RESOURCE,
newURI: function (spec, charset, baseURI) {
var uri = Cc["@mozilla.org/network/standard-url;1"]
.createInstance(Ci.nsIStandardURL)
.QueryInterface(Ci.nsIURI);
uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, baseURI);
if (uri.host !== "template") return uri;
try {
spec = uri.spec;
//uri.init(uri.URLTYPE_STANDARD, this.defaultPort, uri.path.substr(1), charset, null);
// xxx:
uri = ioService.newURI(uri.path.replace(new RegExp("^/+"), ""), charset, null);
// recursible when override
while (uri.scheme === "chrome") {
uri = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIChromeRegistry)
.convertChromeURL(uri);
}
var nest = Cc["@mozilla.org/network/util;1"].getService(Ci.nsINetUtil).newSimpleNestedURI(uri);
nest.spec = spec;
} catch (ex) { Cu.reportError(ex); }
return nest;
},
newChannel: function (uri) {
try {
if ((uri instanceof Ci.nsINestedURI)) {
var m = (new RegExp("^/{2,}([^/]+)/([^?]+)")).exec(uri.path);
if (m) {
var host = m[1];
var path = m[2];
switch (host) {
case "template":
try {
var nest = ioService.newURI(path, uri.charset, null);
var channel = ioService.newChannelFromURI(nest);
// xxx: support template
if (0) return channel;
// xxx: NG: Firefox 16, 17
// NG: Cu.import
if (parseFloat(version) < 17) {
var stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
var cstream = channel.open();
stream.init(cstream);
var text = stream.read(-1);
stream.close();
cstream.close();
stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
stream.setData(convert(text), -1);
var channel = Cc["@mozilla.org/network/input-stream-channel;1"]
.createInstance(Ci.nsIInputStreamChannel);
channel.contentStream = stream;
channel.QueryInterface(Ci.nsIChannel);
channel.setURI(uri);
return channel;
}
var innerURI = uri.innerURI;
var temp = cache.clone();
var path = nest.spec.replace(/[:\/]/g, "_");
var lastModifiedTime;
if (innerURI.scheme === "resource") {
innerURI = Cc["@mozilla.org/network/protocol;1?name=resource"]
.getService(Ci.nsIResProtocolHandler).resolveURI(innerURI);
innerURI = ioService.newURI(innerURI, null, null);
}
if (innerURI.scheme === "jar") {
innerURI = innerURI.QueryInterface(Ci.nsIJARURI).JARFile;
}
if (innerURI.scheme === "file") {
lastModifiedTime = innerURI.QueryInterface(Ci.nsIFileURL).file.lastModifiedTime;
} else {
Cu.reportError("do not support:" + innerURI.spec);
}
temp.append(path);
if (!temp.exists()
|| temp.lastModifiedTime !== lastModifiedTime) {
var stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
var cstream = channel.open();
stream.init(cstream);
var text = stream.read(-1);
stream.close();
cstream.close();
text = convert(text);
var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
Services.console.logStringMessage("create:" + temp.leafName);
stream.init(temp, 0x2 | 0x8 | 0x20, 0644, 0);
stream.write(text, text.length);
stream.close();
temp.lastModifiedTime = lastModifiedTime;
} else { Services.console.logStringMessage("use cache:" + uri.spec); }
return ioService.newChannelFromURI(ioService.newFileURI(temp));
} catch (ex) { Cu.reportError(ex); }
}
}
return fakeChannel(uri);
}
switch(uri.host) {
case "help":
let url = this.FILE_MAP[uri.path.replace(/^\/|#.*/g, "")];
return makeChannel(url, uri);
case "help-overlay":
url = this.OVERLAY_MAP[uri.path.replace(/^\/|#.*/g, "")];
return makeChannel(url, uri);
case "help-tag":
let tag = uri.path.substr(1);
if (tag in this.HELP_TAGS)
return redirect("liberator://help/" + this.HELP_TAGS[tag] + "#" + tag, uri);
}
}
catch (e) { Cu.reportError(e); }
return fakeChannel(uri);
}
};
var components = [ChromeData, Liberator];
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule(components);
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Name = "Vimperator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/about-handler.js'
*/
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
const name = Name.toLowerCase();
function AboutHandler() {}
AboutHandler.prototype = {
classDescription: "About " + Name + " Page",
classID: Components.ID("81495d80-89ee-4c36-a88d-ea7c4e5ac63f"),
contractID: "@mozilla.org/network/protocol/about;1?what=" + name,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
newChannel: function (uri) {
let channel = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
.newChannel("chrome://" + name + "/content/about.html", null, null);
channel.originalURI = uri;
return channel;
},
getURIFlags: function (uri) Ci.nsIAboutModule.ALLOW_SCRIPT
};
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory([AboutHandler]);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([AboutHandler]);
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Config = Module("config", ConfigBase, {
init: function () {
},
/*** required options, no checks done if they really exist, so be careful ***/
name: "Vimperator",
hostApplication: "Firefox",
features: new Set(["bookmarks", "hints", "history", "marks", "quickmarks", "sanitizer", "session", "tabs", "tabs_undo", "windows", "tabgroup", "privatebrowsing"]),
/*** optional options, there are checked for existence and a fallback provided ***/
autocommands: [["BookmarkAdd", "Triggered after a page is bookmarked"],
["ColorScheme", "Triggered after a color scheme has been loaded"],
["DOMLoad", "Triggered when a page's DOM content has fully loaded"],
["DownloadPost", "Triggered when a download has completed"],
["Fullscreen", "Triggered when the browser's fullscreen state changes"],
["LocationChange", "Triggered when changing tabs or when navigation to a new location"],
["PageLoadPre", "Triggered after a page load is initiated"],
["PageLoad", "Triggered when a page gets (re)loaded/opened"],
// TODO: remove when FF ESR's version is over 20
["PrivateMode", "Triggered when private mode is activated or deactivated"],
["Sanitize", "Triggered when a sanitizeable item is cleared"],
["ShellCmdPost", "Triggered after executing a shell command with :!cmd"],
["VimperatorEnter", "Triggered after Firefox starts"],
["VimperatorLeavePre", "Triggered before exiting Firefox, just before destroying each module"],
["VimperatorLeave", "Triggered before exiting Firefox"]],
defaults: {
complete: "slf",
titlestring: "Vimperator"
},
dialogs: [
["about", "About Firefox",
function () { window.openDialog("chrome://browser/content/aboutDialog.xul", "_blank", "chrome,dialog,modal,centerscreen"); }],
["addbookmark", "Add bookmark for the current page",
function () { PlacesCommandHook.bookmarkCurrentPage(true, PlacesUtils.bookmarksRootId); }],
["addons", "Manage Add-ons",
function () { window.toOpenWindowByType("Addons:Manager", "about:addons", "chrome,centerscreen,resizable,dialog=no,width=700,height=600"); }],
["bookmarks", "List your bookmarks",
function () { window.openDialog("chrome://browser/content/bookmarks/bookmarksPanel.xul", "Bookmarks", "dialog,centerscreen,width=600,height=600"); }],
["checkupdates", "Check for updates", // show the About dialog which includes the Check For Updates button
function () { window.openDialog("chrome://browser/content/aboutDialog.xul", "_blank", "chrome,dialog,modal,centerscreen"); }],
/*function () { window.checkForUpdates(); }],*/
["cleardata", "Clear private data",
function () { Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIBrowserGlue).sanitize(window || null); }],
["cookies", "List your cookies",
function () { window.toOpenWindowByType("Browser:Cookies", "chrome://browser/content/preferences/cookies.xul", "chrome,dialog=no,resizable"); }],
["console", "JavaScript console",
function () { window.toJavaScriptConsole(); }],
["customizetoolbar", "Customize the Toolbar",
function () { window.BrowserCustomizeToolbar(); }],
["dominspector", "DOM Inspector",
function () { try { window.inspectDOMDocument(content.document); } catch (e) { liberator.echoerr("DOM Inspector extension not installed"); } }],
["downloads", "Manage Downloads",
function () { window.toOpenWindowByType("Download:Manager", "chrome://mozapps/content/downloads/downloads.xul", "chrome,dialog=no,resizable"); }],
["history", "List your history",
function () { window.openDialog("chrome://browser/content/history/history-panel.xul", "History", "dialog,centerscreen,width=600,height=600"); }],
["import", "Import Preferences, Bookmarks, History, etc. from other browsers",
function () { var tmp = {}; Cu.import("resource://app/modules/MigrationUtils.jsm", tmp); tmp.MigrationUtils.showMigrationWizard(window); } ],
["openfile", "Open the file selector dialog",
function () { window.BrowserOpenFileWindow(); }],
["pageinfo", "Show information about the current page",
function () { window.BrowserPageInfo(); }],
["pagesource", "View page source",
function () { window.BrowserViewSourceOfDocument(content.document); }],
["passwords", "Show passwords window",
function () { window.openDialog("chrome://passwordmgr/content/passwordManager.xul"); }],
["places", "Places Organizer: Manage your bookmarks and history",
function () { PlacesCommandHook.showPlacesOrganizer(ORGANIZER_ROOT_BOOKMARKS); }],
["preferences", "Show Firefox preferences dialog",
function () {
var features = "chrome,titlebar,toolbar,centerscreen," +
(options.getPref("browser.preferences.instantApply", false) ? "dialog=no" : "modal");
window.toOpenWindowByType("Browser:Preferences", "chrome://browser/content/preferences/preferences.xul", features);
}],
["printpreview", "Preview the page before printing",
function () { PrintUtils.printPreview(PrintPreviewListener); }],
["printsetup", "Setup the page size and orientation before printing",
function () { PrintUtils.showPageSetup(); }],
["print", "Show print dialog",
function () { PrintUtils.print(); }],
["saveframe", "Save frame to disk",
function () { window.saveFrameDocument(); }],
["savepage", "Save page to disk",
function () { window.saveDocument(window.content.document); }],
["searchengines", "Manage installed search engines",
function () { window.openDialog("chrome://browser/content/search/engineManager.xul", "_blank", "chrome,dialog,modal,centerscreen"); }],
["selectionsource", "View selection source",
function () { buffer.viewSelectionSource(); }]
],
hasTabbrowser: true,
ignoreKeys: {},
get mainToolbar() document.getElementById("nav-bar"),
scripts: [
"browser.js",
"bookmarks.js",
"history.js",
"ignorekeys.js",
"quickmarks.js",
"sanitizer.js",
"tabs.js",
"tabgroup.js",
],
styleableChrome: ["chrome://browser/content/browser.xul"],
get tempFile() {
let prefix = this.name.toLowerCase();
try {
prefix += "-" + window.content.document.location.hostname;
}
catch (e) {}
return prefix + ".tmp";
},
toolbars: {
addons: [["addon-bar"], "Add-on bar. By default, only visible if you have addons installed."],
bookmarks: [["PersonalToolbar"], "Bookmarks Toolbar"],
menu: [["toolbar-menubar"], "Menu Bar"],
navigation: [["nav-bar"], "Main toolbar with back/forward buttons location box"],
tabs: [["TabsToolbar"], "Tab bar"]
},
get visualbellWindow() getBrowser().mPanelContainer,
updateTitlebar: function () {
config.tabbrowser.updateTitlebar();
},
}, {
}, {
commands: function () {
commands.add(["winon[ly]"],
"Close all other windows",
function () {
liberator.windows.forEach(function (win) {
if (win != window)
win.close();
});
},
{ argCount: "0" });
commands.add(["pref[erences]", "prefs"],
"Show " + config.hostApplication + " preferences",
function (args) {
if (args.bang) { // open Firefox settings GUI dialog
liberator.open("about:config",
(options["newtab"] && options.get("newtab").has("all", "prefs"))
? liberator.NEW_TAB : liberator.CURRENT_TAB);
}
else
window.openPreferences();
},
{
argCount: "0",
bang: true
});
commands.add(["sbcl[ose]"],
"Close the sidebar window",
function () {
if (!document.getElementById("sidebar-box").hidden)
window.toggleSidebar();
},
{ argCount: "0" });
commands.add(["sideb[ar]", "sb[ar]", "sbope[n]"],
"Open the sidebar window",
function (args) {
let arg = args.literalArg;
function compare(a, b) util.compareIgnoreCase(a, b) == 0
// focus if the requested sidebar is already open
if (compare(document.getElementById("sidebar-title").value, arg)) {
document.getElementById("sidebar-box").focus();
return;
}
let menu = document.getElementById("viewSidebarMenu");
for (let [, panel] in Iterator(menu.childNodes)) {
if (compare(panel.label, arg)) {
panel.doCommand();
return;
}
}
liberator.echoerr("No such sidebar: " + arg);
},
{
argCount: "1",
completer: function (context) {
context.ignoreCase = true;
return completion.sidebar(context);
},
literal: 0
});
commands.add(["wind[ow]"],
"Execute a command and tell it to output in a new window",
function (args) {
var prop = args["-private"] ? "forceNewPrivateWindow" : "forceNewWindow";
try {
liberator[prop] = true;
liberator.execute(args.literalArg, null, true);
}
finally {
liberator[prop] = false;
}
},
{
argCount: "+",
options: [
[["-private", "-p"], commands.OPTION_NOARG],
],
completer: function (context) completion.ex(context),
literal: 0
});
commands.add(["winc[lose]", "wc[lose]"],
"Close window",
function () { window.close(); },
{ argCount: "0" });
commands.add(["wino[pen]", "wo[pen]"],
"Open one or more URLs in a new window",
function (args) {
var where = args["-private"] ? liberator.NEW_PRIVATE_WINDOW : liberator.NEW_WINDOW;
args = args.literalArg;
if (args)
liberator.open(args, where);
else
liberator.open("", where);
},
{
options: [
[["-private", "-p"], commands.OPTION_NOARG],
],
completer: function (context) completion.url(context),
literal: 0,
privateData: true
});
},
completion: function () {
completion.location = function location(context) {
if (!services.get("autoCompleteSearch"))
return;
context.anchored = false;
context.title = ["Smart Completions"];
context.keys.icon = 2;
context.incomplete = true;
context.hasItems = context.completions.length > 0; // XXX
context.filterFunc = null;
context.cancel = function () { services.get("autoCompleteSearch").stopSearch(); context.completions = []; };
context.compare = CompletionContext.Sort.unsorted;
services.get("autoCompleteSearch").stopSearch(); // just to make sure we cancel old running completions
let timer = new Timer(50, 100, function (result) {
context.incomplete = result.searchResult >= result.RESULT_NOMATCH_ONGOING;
context.completions = [
[result.getValueAt(i), result.getCommentAt(i), result.getImageAt(i)]
for (i in util.range(0, result.matchCount))
];
});
services.get("autoCompleteSearch").startSearch(context.filter, "", context.result, {
onSearchResult: function onSearchResult(search, result) {
timer.tell(result);
if (result.searchResult <= result.RESULT_SUCCESS) {
timer.flush();
}
}
});
};
completion.sidebar = function sidebar(context) {
let menu = document.getElementById("viewSidebarMenu");
context.title = ["Sidebar Panel"];
context.completions = Array.map(menu.childNodes, function (n) [n.label, ""]);
};
completion.addUrlCompleter("l",
"Firefox location bar entries (bookmarks and history sorted in an intelligent way)",
completion.location);
},
modes: function () {
this.ignoreKeys = {
"<Return>": modes.NORMAL | modes.INSERT,
"<Space>": modes.NORMAL | modes.INSERT,
"<Up>": modes.NORMAL | modes.INSERT,
"<Down>": modes.NORMAL | modes.INSERT
};
},
options: function () {
options.add(["online"],
"Set the 'work offline' option",
"boolean", true,
{
setter: function (value) {
const ioService = services.get("io");
if (ioService.offline == value)
BrowserOffline.toggleOfflineStatus();
return value;
},
getter: function () !services.get("io").offline
});
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2012 by Martin Stubenschrott <stubenschrott AT vimperator>
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const IgnoreKeys = Module("ignoreKeys", {
requires: ["config", "storage"],
init: function init() {
this._ignoredKeys = storage.newMap("ignored-keys", { store: true, privateData: true });
},
add: function add(filter, exceptions) {
if (!exceptions)
exceptions = [];
// TODO: Add a regular expression cache somewhere?
this._ignoredKeys.set(filter, exceptions);
},
get: function get(filter) {
let filtered = [];
for (let [page, exceptions] in this._ignoredKeys) {
if (!filter || page.indexOf(filter) >= 0)
filtered.push([page, exceptions]);
}
return filtered;
},
hasIgnoredKeys: function isKeyIgnored(url) {
for (let [page, exceptions] in this._ignoredKeys) {
let re = RegExp(page);
if (re.test(url))
return exceptions;
}
return null;
},
isKeyIgnored: function isKeyIgnored(url, key) {
// Don't cripple Vimperator ;) Later this will be part of a new "unignorekeys" option
if (key == ":")
return false;
for (let [page, exceptions] in this._ignoredKeys) {
let re = RegExp(page);
if (re.test(url) && exceptions.indexOf(key) < 0)
return true;
}
return false;
},
remove: function remove(filter) {
if (!filter) {
liberator.echoerr("Invalid filter");
return;
}
for (let [page, ] in this._ignoredKeys) {
if (filter == page)
this._ignoredKeys.remove(page);
}
},
clear: function clear() {
this._ignoredKeys.clear();
}
}, {
}, {
mappings: function () {
mappings.add([modes.NORMAL], ["I"],
"Open an :ignorekeys prompt for the current domain or URL",
function (count) {
commandline.open("", "ignorekeys add ", modes.EX);
},
{ count: false });
},
commands: function () {
commands.add(["ignore[keys]"],
"Ignore all (or most) " + config.name + " keys for certain URLs",
function (args) {
// Without argument, list current pages with ignored keys
completion.listCompleter("ignorekeys");
}, {
subCommands: [
new Command(["add"], "Add an URL filter to the list of ignored keys",
function (args) { ignoreKeys.add(args[0], args["-except"] || []); },
{
argCount: "1",
options: [
[["-except", "-e"], commands.OPTION_LIST, null, null],
],
completer: function (context, args) {
let completions = [];
if (args.completeArg == 0) {
if (buffer.URL)
completions.unshift([util.escapeRegex(buffer.URL), "Current URL"]);
if (content.document && content.document.domain)
completions.unshift([util.escapeRegex(content.document.domain), "Current domain"]);
}
context.compare = CompletionContext.Sort.unsorted;
context.completions = completions;
}
}),
new Command(["clear"], "Clear all ignored pages",
function (args) { ignoreKeys.clear(); },
{ argCount: 0 }),
new Command(["list", "ls"], "List pages with ignored keys",
function (args) {
let res = ignoreKeys.get(args.literalArg || "");
if (res.length == undefined || res.length == 0) {
if (!args.literalArg)
liberator.echomsg("No ignored keys");
else
liberator.echomsg("No ignored keys for pages matching " + args.literalArg);
return;
}
completion.listCompleter("ignorekeys", args.literalArg || "");
},
{
argCount: "?",
literal: 0
}),
new Command(["remove", "rm"], "Remove an URL filter from the list of ignored keys",
function (args) { ignoreKeys.remove(args.literalArg || ""); },
{
argCount: 1,
literal: 0,
completer: function (context, args) completion.ignorekeys(context, args.literalArg || ""),
})
]
});
},
completion: function () {
completion.ignorekeys = function (context) {
context.title = ["URL filter", "Ignored keys"];
context.anchored = false; // match the filter anywhere
context.completions = ignoreKeys.get();
};
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2011-2012 by teramako <teramako at Gmail>
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
// TODO: many methods do not work with Thunderbird correctly yet
/**
* @instance tabgroup
*/
const TabGroup = Module("tabGroup", {
requires: ["config", "tabs"],
TV: window.TabView,
get tabView () {
const TV = window.TabView;
if (!TV)
return null;
if (!TV._window || !TV._window.GroupItems) {
let waiting = true;
TV._initFrame(function() { waiting = false; });
while (waiting)
liberator.threadYield(false, true);
}
delete this.tabView;
return this.tabView = TV._window;
},
get appTabs () {
var apps = [];
for (let tab of config.tabbrowser.tabs) {
if (tab.pinned)
apps.push(tab);
else
break;
}
return apps;
},
/**
* @param {string|number} name
* @param {number} count
* @return {GroupItem}
*/
getGroup: function getGroup (name, count) {
let i = 0;
if (!count)
count = 1;
let test;
if (typeof name == "number")
test = function (g) g.id == name;
else {
name = name.toLowerCase();
let id;
let matches = name.match(/^(\d+)(?::(?:\s+(.*))?)?$/);
if (matches)
[, id, name] = matches;
if (id) {
id = parseInt(id, 10);
test = function (g) g.id == id;
}
else
test = function (g) g.getTitle().toLowerCase() == name;
}
for (let group of this.tabView.GroupItems.groupItems) {
if (test(group)) {
i++;
if (i == count)
return group;
}
}
return null;
},
/**
* switch to a group or an orphaned tab
* @param {String|Number} spec
* @param {Boolean} wrap
*/
switchTo: function (spec, wrap) {
const GI = tabGroup.tabView.GroupItems;
let current = GI.getActiveGroupItem() || GI.getActiveOrphanTab();
let groups = GI.groupItems;
let offset = 1, relative = false, index;
if (typeof spec === "number")
index = parseInt(spec, 10);
else if (/^[+-]\d+$/.test(spec)) {
let buf = parseInt(spec, 10);
index = groups.indexOf(current) + buf;
offset = buf >= 0 ? 1 : -1;
relative = true;
}
else if (spec != "") {
let targetGroup = tabGroup.getGroup(spec);
if (targetGroup)
index = groups.indexOf(targetGroup);
else {
liberator.echoerr("No such tab group: " + spec);
return;
}
} else
return;
let length = groups.length;
let apps = tabGroup.appTabs;
function groupSwitch (index, wrap) {
if (index > length - 1)
index = wrap ? index % length : length - 1;
else if (index < 0)
index = wrap ? index % length + length : 0;
let target = groups[index], group = null;
if (target instanceof tabGroup.tabView.GroupItem) {
group = target;
target = target.getActiveTab() || target.getChild(0);
}
if (target)
gBrowser.mTabContainer.selectedItem = target.tab;
// for empty group
else if (group) {
if (apps.length === 0)
group.newTab();
else {
GI.setActiveGroupItem(group);
tabGroup.tabView.UI.goToTab(tabs.getTab(0));
}
}
else if (relative)
groupSwitch(index + offset, true);
else
{
liberator.echoerr("Cannot switch to tab group: " + spec);
return;
}
}
groupSwitch(index, wrap);
},
/**
* @param {string} name Group Name
* @param {boolean} shouldSwitch switch to the created group if true
* @param {element} tab
* @return {GroupItem} created GroupItem instance
*/
createGroup: function createGroup (name, shouldSwitch, tab) {
let pageBounds = tabGroup.tabView.Items.getPageBounds();
pageBounds.inset(20, 20);
let box = new tabGroup.tabView.Rect(pageBounds);
box.width = 125;
box.height = 110;
let group = new tabGroup.tabView.GroupItem([], { bounds: box, title: name });
if (tab && !tab.pinned)
tabGroup.TV.moveTabTo(tab, group.id);
if (shouldSwitch) {
let appTabs = tabGroup.appTabs,
child = group.getChild(0);
if (child) {
tabGroup.tabView.GroupItems.setActiveGroupItem(group);
tabGroup.tabView.UI.goToTab(child.tab);
}
else if (appTabs.length == 0)
group.newTab();
else {
tabGroup.tabView.GroupItems.setActiveGroupItem(group);
tabGroup.tabView.UI.goToTab(appTabs[appTabs.length - 1]);
}
}
return group;
},
/**
* @param {element} tab element
* @param {GroupItem||string} group See {@link tabGroup.getGroup}.
* @param {boolean} create Create a new group named {group}
* if {group} doesn't exist.
*/
moveTab: function moveTabToGroup (tab, group, shouldSwitch) {
liberator.assert(tab && !tab.pinned, "Cannot move an AppTab");
let groupItem = (group instanceof tabGroup.tabView.GroupItem) ? group : tabGroup.getGroup(group);
liberator.assert(groupItem, "No such group: " + group);
if (groupItem) {
tabGroup.TV.moveTabTo(tab, groupItem.id);
if (shouldSwitch)
tabGroup.tabView.UI.goToTab(tab);
}
},
/**
* close all tabs in the {groupName}'s or current group
* @param {string} groupName
*/
remove: function removeGroup (groupName) {
const GI = tabGroup.tabView.GroupItems;
let activeGroup = GI.getActiveGroupItem();
let group = groupName ? tabGroup.getGroup(groupName) : activeGroup;
liberator.assert(group, "No such group: " + groupName);
if (group === activeGroup) {
let gb = config.tabbrowser;
let vTabs = gb.visibleTabs;
if (vTabs.length < gb.tabs.length)
tabGroup.switchTo("+1", true);
else {
let appTabs = tabGroup.appTabs;
if (appTabs.length == 0)
gb.loadOnTab(window.BROWSER_NEW_TAB_URL || "about:blank", { inBackground: false, relatedToCurrent: false });
else
gb.mTabContainer.selectedIndex = appTabs.length - 1;
for (let i = vTabs.length - 1, tab; (tab = vTabs[i]) && !tab.pinned; i--)
gb.removeTab(tab);
return;
}
}
group.closeAll();
}
}, {
}, {
mappings: function () {
mappings.add([modes.NORMAL], ["g@"],
"Go to an AppTab",
function (count) {
let appTabs = tabGroup.appTabs;
let i = 0;
if (count != null)
i = count - 1;
else {
let currentTab = tabs.getTab();
if (currentTab.pinned)
i = appTabs.indexOf(currentTab) + 1;
i %= appTabs.length;
}
if (appTabs[i])
config.tabbrowser.mTabContainer.selectedIndex = i;
},
{ count: true });
mappings.add([modes.NORMAL], ["<C-S-n>", "<C-S-PageDown>"],
"Switch to next tab group",
function (count) { tabGroup.switchTo("+" + (count || 1), true); },
{ count: true });
mappings.add([modes.NORMAL], ["<C-S-p>", "<C-S-PageUp>"],
"Switch to previous tab group",
function (count) { tabGroup.switchTo("-" + (count || 1), true); },
{ count: true });
},
commands: function () {
let panoramaSubCommands = [
/**
* Panorama SubCommand add
* make a group and switch to the group.
* take up the current tab to the group if bang(!) specified.
*/
new Command(["add"], "Create a new tab group",
function (args) { tabGroup.createGroup(args.literalArg, true, args.bang ? tabs.getTab() : null); },
{ bang: true, literal: 0 }),
/**
* Panorama SubCommand list
* list current tab groups
*/
new Command(["list", "ls"], "List current tab groups",
function (args) { completion.listCompleter("tabgroup"); },
{ bang: false, argCount: 0 }),
/**
* Panorama SubCommad pullTab
* pull the other group's tab
*/
new Command(["pull[tab]"], "Pull a tab from another group",
function (args) {
let activeGroup = tabGroup.tabView.GroupItems.getActiveGroupItem();
if (!activeGroup) {
liberator.echoerr("Cannot pull tab to the current group");
return;
}
let buffer = args.literalArg;
if (!buffer)
return;
let tabItems = tabs.getTabsFromBuffer(buffer);
if (tabItems.length == 0) {
liberator.echoerr("No matching buffer for: " + buffer);
return;
} else if (tabItems.length > 1) {
liberator.echoerr("More than one match for: " + buffer);
return;
}
tabGroup.moveTab(tabItems[0], activeGroup, args.bang);
}, {
bang: true,
literal: 0,
completer: function (context) completion.buffer(context),
}),
/**
* Panorama SubCommand pushTab
* stash the current tab to the {group}
* create {group} and stash if bang(!) specified and {group} doesn't exists.
*/
new Command(["push[tab]", "stash"], "Move the current tab to another group",
function (args) {
let currentTab = tabs.getTab();
if (currentTab.pinned) {
liberator.echoerr("Cannot move an App Tab");
return;
}
let groupName = args.literalArg;
let group = tabGroup.getGroup(groupName);
if (!group) {
if (args.bang)
group = tabGroup.createGroup(groupName);
else {
liberator.echoerr("No such group: " + groupName.quote() + ". Add \"!\" if you want to create it.");
return;
}
}
tabGroup.moveTab(currentTab, group);
}, {
bang: true,
literal: 0,
completer: function (context) completion.tabgroup(context, true),
}),
/**
* Panorama SubCommand remove
* remove {group}.
* remove the current group if {group} is ommited.
*/
new Command(["remove", "rm"], "Close the tab group (including all tabs!)",
function (args) { tabGroup.remove(args.literalArg); },
{
literal: 0,
completer: function (context) completion.tabgroup(context, false),
}),
/**
* Panorama SubCommand switch
* switch to the {group}.
* switch to {count}th next group if {count} specified.
*/
new Command(["switch"], "Switch to another group",
function (args) {
if (args.count > 0)
tabGroup.switchTo("+" + args.count, true);
else
tabGroup.switchTo(args.literalArg);
}, {
count: true,
literal: 0,
completer: function (context) completion.tabgroup(context, true),
}),
];
commands.add(["tabgroups", "panorama"],
"Manage tab groups",
function (args) {
// Without argument, list current groups
completion.listCompleter("tabgroup");
}, {
subCommands: panoramaSubCommands
});
},
completion: function () {
completion.tabgroup = function TabGroupCompleter (context, excludeActiveGroup) {
const GI = tabGroup.tabView.GroupItems;
let groupItems = GI.groupItems;
if (excludeActiveGroup) {
let activeGroup = GI.getActiveGroupItem();
if (activeGroup)
groupItems = groupItems.filter(function(group) group.id != activeGroup.id);
}
context.title = ["Tab Group"];
context.anchored = false;
context.completions = groupItems.map(function(group) {
let title = group.id + ": " + (group.getTitle() || "(Untitled)");
let desc = "Tabs: " + group.getChildren().length;
return [title, desc];
});
};
},
options: function () {
options.add(["apptab", "app"],
"Pin the current tab as App Tab",
"boolean", false,
{
scope: Option.SCOPE_LOCAL,
setter: function (value) {
config.tabbrowser[value ? "pinTab" : "unpinTab"](tabs.getTab());
return value;
},
getter: function () {
return tabs.getTab().pinned;
}
});
},
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
// Script to find regressions
//
// It should use as few liberator methods as possible, but fall back to standard mozilla/DOM methods
// The reason is, we don't want to find regressions in the regressions script, and it should survive
// massive changes in the internal liberator API, but just test for functionality of
// user-visible commands/mappings
//
// NOTE: It is preferable to run this script in a clean profile or at least do NOT use
// :mkvimperatorrc afterwards, as it can remove commands/mappings, etc.
//
// Usage: :[count]regr[essions]
// When [count] is given, just run this test. TODO: move to :regressions [spec]?
// all tests
var skipTests = [":bmarks", "gg"];
/////////////////////////////////////////////////////////////////////////////////////////
// Put definitions here which might change due to internal liberator refactoring
/////////////////////////////////////////////////////////////////////////////////////////
var doc; // document where we output status messages
var multilineOutput = document.getElementById("liberator-multiline-output");
var singlelineOutput = document.getElementById("liberator-message");
/////////////////////////////////////////////////////////////////////////////////////////
// TESTS
//
// They are run in order, so you can specify commands which expect side effects of a
// previous command
/////////////////////////////////////////////////////////////////////////////////////////
// A series of Ex commands or mappings, each with a
// function checking whether the command succeeded
// If the string starts with a ":" it is executed as an Ex command, otherwise as a mapping
// You can also mix commands and mappings
let tests = [
{ cmds: [":!dir"],
verify: function () getMultilineOutput().length > 10 },
{ cmds: [":abbr VIMP vimperator labs", ":abbr"],
verify: function () getOutput().indexOf("vimperator labs") >= 0 },
{ cmds: [":unabbr VIMP", ":abbr"],
verify: function () getOutput().indexOf("vimperator labs") == -1 },
{ cmds: [":bmarks"],
verify: function () getMultilineOutput().length > 100 },
{ cmds: [":echo \"test\""],
verify: function () getSinglelineOutput() == "test" },
{ cmds: [":qmark V http://test.vimperator.org", ":qmarks"],
verify: function () getMultilineOutput().indexOf("test.vimperator.org") >= 0 },
{ cmds: [":javascript liberator.echo('test', commandline.FORCE_MULTILINE)"],
verify: function () getMultilineOutput() == "test" },
// { cmds: [":echomsg \"testmsg\""],
// verify: function () getOutput() == "testmsg" },
// { cmds: [":echoerr \"testerr\""],
// verify: function () getOutput() == "testerr" },
{ cmds: ["gg", "<C-f>"], // NOTE: does not work when there is no page to scroll, we should load a large page before doing these tests
verify: function () this._initialPos.y != getBufferPosition().y,
init: function () this._initialPos = getBufferPosition() }
// testing tab behavior
];
// these functions highly depend on the liberator API, so use Ex command tests whenever possible
let functions = [
function () { return bookmarks.get("").length > 0 }, // will fail for people without bookmarks :( Might want to add one before
function () { return history.get("").length > 0 }
];
/////////////////////////////////////////////////////////////////////////////////////////
// functions below should be as generic as possible, and not require being rewritten
// even after doing major Vimperator refactoring
/////////////////////////////////////////////////////////////////////////////////////////
function resetEnvironment() {
multilineOutput.contentDocument.body.innerHTML = "";
singlelineOutput.value = "";
commandline.close();
modes.reset();
}
function getOutput() multilineOutput.contentDocument.body.textContent || singlelineOutput.value;
function getMultilineOutput() multilineOutput.contentDocument.body.textContent;
function getSinglelineOutput() singlelineOutput.value;
function getTabIndex() getBrowser().mTabContainer.selectedIndex;
function getTabCount() getBrowser().mTabs.length;
function getBufferPosition() {
let win = window.content;
return { x: win.scrollMaxX ? win.pageXOffset / win.scrollMaxX : 0,
y: win.scrollMaxY ? win.pageYOffset / win.scrollMaxY : 0 }
};
function getLocation() window.content.document.location.href;
function echoLine(str, group) {
if (!doc)
return;
doc.body.appendChild(util.xmlToDom(
<div highlight={group} style="border: 1px solid gray; white-space: pre; height: 1.5em; line-height: 1.5em;">{str}</div>,
doc));
}
function echoMulti(str, group) {
if (!doc)
return;
doc.body.appendChild(util.xmlToDom(<div class="ex-command-output"
style="white-space: nowrap; border: 1px solid black; min-height: 1.5em;"
highlight={group}>{template.maybeXML(str)}</div>,
doc));
}
commands.addUserCommand(["regr[essions]"],
"Run regression tests",
function (args) {
// TODO: might need to increase the 'messages' option temporarily
// TODO: count (better even range) support to just run test 34 of 102
// TODO: bang support to either: a) run commands like deleting bookmarks which
// should only be done in a clean profile or b) run functions and not
// just Ex command tests; Yet to be decided
let updateOutputHeight = null;
function init() {
liberator.registerObserver("echoLine", echoLine);
liberator.registerObserver("echoMultiline", echoMulti);
liberator.open("chrome://liberator/content/buffer.xhtml", liberator.NEW_TAB);
events.waitForPageLoad();
doc = content.document;
doc.body.setAttributeNS(NS.uri, "highlight", "CmdLine");
updateOutputHeight = commandline.updateOutputHeight;
commandline.updateOutputHeight = function (open) {
let elem = document.getElementById("liberator-multiline-output");
if (open)
elem.collapsed = false;
elem.height = 0;
};
}
function cleanup() {
liberator.unregisterObserver("echoLine", echoLine);
liberator.unregisterObserver("echoMultiline", echoMulti);
commandline.updateOutputHeight = updateOutputHeight;
}
function run() {
let now = Date.now();
let totalTests = tests.length + functions.length;
let successfulTests = 0;
let skippedTests = 0;
let currentTest = 0;
init();
// TODO: might want to unify 'tests' and 'functions' handling
// 1.) run commands and mappings tests
outer:
for (let [, test] in Iterator(tests)) {
currentTest++;
if (args.count >= 1 && currentTest != args.count)
continue;
let testDescription = util.clip(test.cmds.join(" -> "), 80);
for (let [, cmd] in Iterator(test.cmds)) {
if (skipTests.indexOf(cmd) != -1) {
skippedTests++;
liberator.echomsg("Skipping test " + currentTest + " of " + totalTests + ": " + testDescription);
continue outer;
}
};
commandline.echo("Running test " + currentTest + " of " + totalTests + ": " + testDescription, "Filter", commandline.APPEND_TO_MESSAGES);
resetEnvironment();
if ("init" in test)
test.init();
test.cmds.forEach(function (cmd) {
if (cmd[0] == ":")
liberator.execute(cmd);
else
events.feedkeys(cmd);
});
if (!test.verify())
liberator.echoerr("Test " + currentTest + " failed: " + testDescription);
else
successfulTests++;
}
// 2.) Run function tests
for (let [, func] in Iterator(functions)) {
currentTest++;
if (args.count >= 1 && currentTest != args.count)
continue;
commandline.echo("Running test " + currentTest + " of " + totalTests + ": " + util.clip(func.toString().replace(/[\s\n]+/gm, " "), 80), "Filter", commandline.APPEND_TO_MESSAGES);
resetEnvironment();
if (!func())
liberator.echoerr("Test " + currentTest + " failed!");
else
successfulTests++;
}
cleanup();
let runTests = (args.count >= 1 ? 1 : totalTests) - skippedTests;
XML.ignoreWhitespace = false;
liberator.echomsg(<e4x>
<span style="font-weight: bold">{successfulTests}</span> of <span style="font-weight: bold">{runTests}</span>
tests successfully completed (<span style="font-weight: bold">{skippedTests}</span> tests skipped) in
<span class="time-total">{((Date.now() - now) / 1000.0)}</span> msec
</e4x>.*);
liberator.execute(":messages");
}
if (!args.bang) {
liberator.echo(<e4x>
<span style="font-weight: bold">Running tests should always be done in a new profile.</span><br/>
It should not do any harm to your profile, but your current settings like options,
abbreviations or mappings might not be in the same state as before running the tests.
Just make sure, you don't :mkvimperatorrc, after running the tests.<br/><br/>
<!--' vim. -->
Use :regressions! to skip this prompt.
</e4x>.*);
commandline.input("Type 'yes' to run the tests: ", function (res) { if (res == "yes") run(); } );
return;
}
run();
},
{
bang: true,
argCount: "0",
count: true
});
// vim: set et sts=4 sw=4 :
| JavaScript |
// Header:
const Name = "Muttator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/commandline-handler.js'
*/
// Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const name = Name.toLowerCase();
function CommandLineHandler() {
this.wrappedJSObject = this;
}
CommandLineHandler.prototype = {
classDescription: Name + " Command-line Handler",
classID: Components.ID("{16dc34f7-6d22-4aa4-a67f-2921fb5dcb69}"),
contractID: "@mozilla.org/commandlinehandler/general-startup;1?type=" + name,
_xpcom_categories: [{
category: "command-line-handler",
entry: "m-" + name
}],
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsICommandLineHandler]),
handle: function (commandLine) {
// TODO: handle remote launches differently?
try {
this.optionValue = commandLine.handleFlagWithParam(name, false);
}
catch (e) {
dump(name + ": option '-" + name + "' requires an argument\n");
}
}
};
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory([CommandLineHandler]);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([CommandLineHandler]);
// vim: set ft=javascript fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2008-2009 Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/* Adds support for data: URIs with chrome privileges
* and fragment identifiers.
*
* "chrome-data:" <content-type> [; <flag>]* "," [<data>]
*
* By Kris Maglione, ideas from Ed Anuff's nsChromeExtensionHandler.
*/
const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "convert", function () {
var obj = new Object;
Cu.import("resource://liberator/template.js", obj);
return obj.convert;
});
const NS_BINDING_ABORTED = 0x804b0002;
const nsIProtocolHandler = Ci.nsIProtocolHandler;
const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
let channel = Components.classesByID["{61ba33c0-3031-11d3-8cd0-0060b0fc14a3}"]
.getService(Ci.nsIProtocolHandler)
.newChannel(ioService.newURI("chrome://liberator/content/data", null, null))
.QueryInterface(Ci.nsIRequest);
const systemPrincipal = channel.owner;
channel.cancel(NS_BINDING_ABORTED);
delete channel;
function dataURL(type, data) "data:" + (type || "application/xml;encoding=UTF-8") + "," + encodeURIComponent(data);
function makeChannel(url, orig) {
if (typeof url == "function")
url = dataURL.apply(null, url());
let uri = ioService.newURI(url, null, null);
let channel = ioService.newChannelFromURI(uri);
channel.owner = systemPrincipal;
channel.originalURI = orig;
return channel;
}
function fakeChannel(orig) makeChannel("chrome://liberator/content/does/not/exist", orig);
function redirect(to, orig) {
//xxx: escape
let html = '<html><head><meta http-equiv="Refresh" content="' + ("0;" + to).replace(/"/g, """) + '"/></head></html>';
return makeChannel(dataURL('text/html', html), ioService.newURI(to, null, null));
}
XPCOMUtils.defineLazyGetter(this, "cache", function () {
var dir = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
dir.append("liberatorCache");
if (!dir.exists()) {
dir.create(dir.DIRECTORY_TYPE, -1);
}
return dir;
});
XPCOMUtils.defineLazyGetter(this, "version", function () {
return Services.appinfo.version;
});
function ChromeData() {}
ChromeData.prototype = {
contractID: "@mozilla.org/network/protocol;1?name=chrome-data",
classID: Components.ID("{c1b67a07-18f7-4e13-b361-2edcc35a5a0d}"),
classDescription: "Data URIs with chrome privileges",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),
_xpcom_factory: {
createInstance: function (outer, iid) {
if (!ChromeData.instance)
ChromeData.instance = new ChromeData();
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return ChromeData.instance.QueryInterface(iid);
}
},
scheme: "chrome-data",
defaultPort: -1,
allowPort: function (port, scheme) false,
protocolFlags: nsIProtocolHandler.URI_NORELATIVE
| nsIProtocolHandler.URI_NOAUTH
| nsIProtocolHandler.URI_IS_UI_RESOURCE,
newURI: function (spec, charset, baseURI) {
var uri = Cc["@mozilla.org/network/standard-url;1"]
.createInstance(Ci.nsIStandardURL)
.QueryInterface(Ci.nsIURI);
uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, null);
return uri;
},
newChannel: function (uri) {
try {
if (uri.scheme == this.scheme)
return makeChannel(uri.spec.replace(/^.*?:\/*(.*)(?:#.*)?/, "data:$1"), uri);
}
catch (e) {}
return fakeChannel();
}
};
function Liberator() {
this.wrappedJSObject = this;
const self = this;
this.HELP_TAGS = {};
this.FILE_MAP = {};
this.OVERLAY_MAP = {};
}
Liberator.prototype = {
contractID: "@mozilla.org/network/protocol;1?name=liberator",
classID: Components.ID("{9c8f2530-51c8-4d41-b356-319e0b155c44}"),
classDescription: "Liberator utility protocol",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),
_xpcom_factory: {
createInstance: function (outer, iid) {
if (!Liberator.instance)
Liberator.instance = new Liberator();
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return Liberator.instance.QueryInterface(iid);
}
},
init: function (obj) {
for each (let prop in ["HELP_TAGS", "FILE_MAP", "OVERLAY_MAP"]) {
this[prop] = this[prop].constructor();
for (let [k, v] in Iterator(obj[prop] || {}))
this[prop][k] = v
}
},
scheme: "liberator",
defaultPort: -1,
allowPort: function (port, scheme) false,
protocolFlags: 0
| nsIProtocolHandler.URI_IS_UI_RESOURCE
| nsIProtocolHandler.URI_IS_LOCAL_RESOURCE,
newURI: function (spec, charset, baseURI) {
var uri = Cc["@mozilla.org/network/standard-url;1"]
.createInstance(Ci.nsIStandardURL)
.QueryInterface(Ci.nsIURI);
uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, baseURI);
if (uri.host !== "template") return uri;
try {
spec = uri.spec;
//uri.init(uri.URLTYPE_STANDARD, this.defaultPort, uri.path.substr(1), charset, null);
// xxx:
uri = ioService.newURI(uri.path.replace(new RegExp("^/+"), ""), charset, null);
// recursible when override
while (uri.scheme === "chrome") {
uri = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIChromeRegistry)
.convertChromeURL(uri);
}
var nest = Cc["@mozilla.org/network/util;1"].getService(Ci.nsINetUtil).newSimpleNestedURI(uri);
nest.spec = spec;
} catch (ex) { Cu.reportError(ex); }
return nest;
},
newChannel: function (uri) {
try {
if ((uri instanceof Ci.nsINestedURI)) {
var m = (new RegExp("^/{2,}([^/]+)/([^?]+)")).exec(uri.path);
if (m) {
var host = m[1];
var path = m[2];
switch (host) {
case "template":
try {
var nest = ioService.newURI(path, uri.charset, null);
var channel = ioService.newChannelFromURI(nest);
// xxx: support template
if (0) return channel;
// xxx: NG: Firefox 16, 17
// NG: Cu.import
if (parseFloat(version) < 17) {
var stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
var cstream = channel.open();
stream.init(cstream);
var text = stream.read(-1);
stream.close();
cstream.close();
stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
stream.setData(convert(text), -1);
var channel = Cc["@mozilla.org/network/input-stream-channel;1"]
.createInstance(Ci.nsIInputStreamChannel);
channel.contentStream = stream;
channel.QueryInterface(Ci.nsIChannel);
channel.setURI(uri);
return channel;
}
var innerURI = uri.innerURI;
var temp = cache.clone();
var path = nest.spec.replace(/[:\/]/g, "_");
var lastModifiedTime;
if (innerURI.scheme === "resource") {
innerURI = Cc["@mozilla.org/network/protocol;1?name=resource"]
.getService(Ci.nsIResProtocolHandler).resolveURI(innerURI);
innerURI = ioService.newURI(innerURI, null, null);
}
if (innerURI.scheme === "jar") {
innerURI = innerURI.QueryInterface(Ci.nsIJARURI).JARFile;
}
if (innerURI.scheme === "file") {
lastModifiedTime = innerURI.QueryInterface(Ci.nsIFileURL).file.lastModifiedTime;
} else {
Cu.reportError("do not support:" + innerURI.spec);
}
temp.append(path);
if (!temp.exists()
|| temp.lastModifiedTime !== lastModifiedTime) {
var stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
var cstream = channel.open();
stream.init(cstream);
var text = stream.read(-1);
stream.close();
cstream.close();
text = convert(text);
var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
Services.console.logStringMessage("create:" + temp.leafName);
stream.init(temp, 0x2 | 0x8 | 0x20, 0644, 0);
stream.write(text, text.length);
stream.close();
temp.lastModifiedTime = lastModifiedTime;
} else { Services.console.logStringMessage("use cache:" + uri.spec); }
return ioService.newChannelFromURI(ioService.newFileURI(temp));
} catch (ex) { Cu.reportError(ex); }
}
}
return fakeChannel(uri);
}
switch(uri.host) {
case "help":
let url = this.FILE_MAP[uri.path.replace(/^\/|#.*/g, "")];
return makeChannel(url, uri);
case "help-overlay":
url = this.OVERLAY_MAP[uri.path.replace(/^\/|#.*/g, "")];
return makeChannel(url, uri);
case "help-tag":
let tag = uri.path.substr(1);
if (tag in this.HELP_TAGS)
return redirect("liberator://help/" + this.HELP_TAGS[tag] + "#" + tag, uri);
}
}
catch (e) { Cu.reportError(e); }
return fakeChannel(uri);
}
};
var components = [ChromeData, Liberator];
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule(components);
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Name = "Muttator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/about-handler.js'
*/
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
const name = Name.toLowerCase();
function AboutHandler() {}
AboutHandler.prototype = {
classDescription: "About " + Name + " Page",
classID: Components.ID("81495d80-89ee-4c36-a88d-ea7c4e5ac63f"),
contractID: "@mozilla.org/network/protocol/about;1?what=" + name,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
newChannel: function (uri) {
let channel = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
.newChannel("chrome://" + name + "/content/about.html", null, null);
channel.originalURI = uri;
return channel;
},
getURIFlags: function (uri) Ci.nsIAboutModule.ALLOW_SCRIPT
};
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory([AboutHandler]);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([AboutHandler]);
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const DEFAULT_FAVICON = "chrome://global/skin/icons/Portrait.png";
const Config = Module("config", ConfigBase, {
init: function () {
// don't wait too long when selecting new messages
// GetThreadTree()._selectDelay = 300; // TODO: make configurable
},
/*** required options, no checks done if they really exist, so be careful ***/
name: "Muttator",
hostApplication: "Thunderbird",
get mainWindowId() this.isComposeWindow ? "msgcomposeWindow" : "messengerWindow",
/*** optional options, there are checked for existence and a fallback provided ***/
get features() {
Object.defineProperty(this, "features", {
value: new Set(this.isComposeWindow ? ["addressbook"] : ["hints", "mail", "marks", "addressbook", "tabs"]),
});
return this.features;
},
defaults: {
titlestring: "Muttator"
},
toolbars: {
composition: [["composeToolbar2"], "Composition toolbar"],
folderlist: [["folderPaneBox", "folderpane_splitter"], "Folder list"],
mail: [["mail-bar3"], "Main toolbar for getting mail and composing new ones."],
menu: [["mail-toolbar-menubar2", "compose-toolbar-menubar2"], "Menu Bar"],
tabs: [["tabs-toolbar"], "Tab bar"],
status: [["status-bar"], "Status Bar"]
},
//get isComposeWindow() window.wintype == "msgcompose",
get isComposeWindow() window.document.location == "chrome://messenger/content/messengercompose/messengercompose.xul",
get browserModes() [modes.MESSAGE],
get mailModes() [modes.NORMAL],
// focusContent() focuses this widget
get mainWidget() this.isComposeWindow ? document.getElementById("content-frame") : GetThreadTree(),
get mainToolbar() document.getElementById(this.isComposeWindow ? "compose-toolbar-menubar2" : "mail-bar3"),
get visualbellWindow() document.getElementById(this.mainWindowId),
styleableChrome: ["chrome://messenger/content/messenger.xul",
"chrome://messenger/content/messengercompose/messengercompose.xul"],
autocommands: [["DOMLoad", "Triggered when a page's DOM content has fully loaded"],
["FolderLoad", "Triggered after switching folders in Thunderbird"],
["PageLoadPre", "Triggered after a page load is initiated"],
["PageLoad", "Triggered when a page gets (re)loaded/opened"],
["MuttatorEnter", "Triggered after Thunderbird starts"],
["MuttatorLeave", "Triggered before exiting Thunderbird"],
["MuttatorLeavePre", "Triggered before exiting Thunderbird"]],
dialogs: [
["about", "About Thunderbird",
function () { window.openAboutDialog(); }],
["addons", "Manage Add-ons",
function () { window.toOpenWindowByType("Addons:Manager", "about:addons", "chrome,centerscreen,resizable,dialog=no,width=700,height=600"); }],
["addressbook", "Address book",
function () { window.toAddressBook(); }],
["accounts", "Account Manager",
function () { MsgAccountManager(); }],
["checkupdates", "Check for updates",
function () { window.checkForUpdates(); }],
/*["cleardata", "Clear private data",
function () { Cc[GLUE_CID].getService(Ci.nsIBrowserGlue).sanitize(window || null); }],*/
["console", "JavaScript console",
function () { window.toJavaScriptConsole(); }],
/*["customizetoolbar", "Customize the Toolbar",
function () { BrowserCustomizeToolbar(); }],*/
["dominspector", "DOM Inspector",
function () { window.inspectDOMDocument(content.document); }],
["downloads", "Manage Downloads",
function () { window.toOpenWindowByType('Download:Manager', 'chrome://mozapps/content/downloads/downloads.xul', 'chrome,dialog=no,resizable'); }],
/*["import", "Import Preferences, Bookmarks, History, etc. from other browsers",
function () { BrowserImport(); }],
["openfile", "Open the file selector dialog",
function () { BrowserOpenFileWindow(); }],
["pageinfo", "Show information about the current page",
function () { BrowserPageInfo(); }],
["pagesource", "View page source",
function () { BrowserViewSourceOfDocument(content.document); }],*/
["preferences", "Show Thunderbird preferences dialog",
function () { openOptionsDialog(); }],
/*["printpreview", "Preview the page before printing",
function () { PrintUtils.printPreview(onEnterPrintPreview, onExitPrintPreview); }],*/
["printsetup", "Setup the page size and orientation before printing",
function () { PrintUtils.showPageSetup(); }],
["print", "Show print dialog",
function () { PrintUtils.print(); }],
["saveframe", "Save frame to disk",
function () { window.saveFrameDocument(); }],
["savepage", "Save page to disk",
function () { window.saveDocument(window.content.document); }],
/*["searchengines", "Manage installed search engines",
function () { openDialog("chrome://browser/content/search/engineManager.xul", "_blank", "chrome,dialog,modal,centerscreen"); }],
["selectionsource", "View selection source",
function () { buffer.viewSelectionSource(); }]*/
],
get hasTabbrowser() !this.isComposeWindow,
/*focusChange: function (win) {
// we switch to -- MESSAGE -- mode for Muttator, when the main HTML widget gets focus
if (win && (win.document instanceof HTMLDocument || win.document instanceof XMLDocument) ||
liberator.focus instanceof HTMLAnchorElement) {
if (config.isComposeWindow)
modes.set(modes.INSERT, modes.TEXTAREA);
else if (liberator.mode != modes.MESSAGE)
liberator.mode = modes.MESSAGE;
}
},*/
get browser() this.isComposeWindow ? window.GetCurrentEditorElement() : window.getBrowser(),
tabbrowser: {
__proto__: document.getElementById("tabmail"),
get mTabContainer() this.tabContainer,
get mTabs() this.tabContainer.childNodes,
get visibleTabs() Array.slice(this.mTabs),
get mCurrentTab() this.tabContainer.selectedItem,
get mCurrentBrowser() this.getBrowserForSelectedTab(),
get mStrip() this.tabStrip,
get browsers() {
let browsers = [];
for ([,tab] in Iterator(this.tabInfo)) {
let func = tab.mode.getBrowser || tab.mode.tabType.getBrowser;
if (func)
browsers.push(func.call(tab.mode.tabType, tab));
}
return browsers;
}
},
updateTitlebar: function () {
if (!this.isComposeWindow)
this.tabbrowser.setDocumentTitle(this.tabbrowser.currentTabInfo);
},
modes: [
["MESSAGE", { char: "m" }],
["COMPOSE"]
],
// NOTE: as I don't use TB I have no idea how robust this is. --djk
get outputHeight() {
if (!this.isComposeWindow) {
let container = document.getElementById("tabpanelcontainer").boxObject;
let deck = document.getElementById("displayDeck");
let box = document.getElementById("messagepanebox");
let splitter = document.getElementById("threadpane-splitter").boxObject;
if (splitter.width > splitter.height)
return container.height - deck.minHeight - box.minHeight- splitter.height;
else
return container.height - Math.max(deck.minHeight, box.minHeight);
}
else
return document.getElementById("appcontent").boxObject.height;
},
get scripts() this.isComposeWindow ? ["compose/compose.js"] : [
"addressbook.js",
"mail.js",
"tabs.js",
],
// to allow Vim to :set ft=mail automatically
tempFile: "mutt-ator-mail",
}, {
}, {
commands: function () {
commands.add(["pref[erences]", "prefs"],
"Show " + config.hostApplication + " preferences",
function () { window.openOptionsDialog(); },
{ argCount: "0" });
},
modes: function () {
this.ignoreKeys = {
"<Return>": modes.NORMAL | modes.INSERT,
"<Space>": modes.NORMAL | modes.INSERT,
"<Up>": modes.INSERT,
"<Down>": modes.INSERT
};
},
options: function () {
// FIXME: comment obviously incorrect
// 0: never automatically edit externally
// 1: automatically edit externally when message window is shown the first time
// 2: automatically edit externally, once the message text gets focus (not working currently)
options.add(["autoexternal", "ae"],
"Edit message with external editor by default",
"boolean", false);
if (!this.isComposeWindow) {
options.add(["online"],
"Set the 'work offline' option",
"boolean", true,
{
setter: function (value) {
if (MailOfflineMgr.isOnline() != value)
MailOfflineMgr.toggleOfflineStatus();
return value;
},
getter: function () MailOfflineMgr.isOnline()
});
}
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Compose = Module("compose", {
init: function () {
var stateListener = {
QueryInterface: function (id) {
if (id.equals(Ci.nsIDocumentStateListener))
return this;
throw Cr.NS_NOINTERFACE;
},
// this is (also) fired once the new compose window loaded the message for the first time
NotifyDocumentStateChanged: function (nowDirty) {
// only edit with external editor if this window was not cached!
if (options["autoexternal"] && !window.messageWasEditedExternally/* && !gMsgCompose.recycledWindow*/) {
window.messageWasEditedExternally = true;
editor.editFieldExternally();
}
},
NotifyDocumentCreated: function () {},
NotifyDocumentWillBeDestroyed: function () {}
};
// XXX: Hack!
window.addEventListener("load", function () {
if (window.messageWasEditedExternally === undefined) {
window.messageWasEditedExternally = false;
GetCurrentEditor().addDocumentStateListener(stateListener);
}
}, true);
window.addEventListener("compose-window-close", function () {
window.messageWasEditedExternally = false;
}, true);
}
}, {
}, {
mappings: function () {
mappings.add([modes.COMPOSE],
["e"], "Edit message",
function () {
GetCurrentEditorElement().contentWindow.focus();
editor.editFieldExternally();
});
mappings.add([modes.COMPOSE],
["y"], "Send message now",
function () { window.goDoCommand("cmd_sendNow"); });
mappings.add([modes.COMPOSE],
["Y"], "Send message later",
function () { window.goDoCommand("cmd_sendLater"); });
// FIXME: does not really work reliably
mappings.add([modes.COMPOSE],
["t"], "Select To: field",
function () { awSetFocus(0, awGetInputElement(1)); });
mappings.add([modes.COMPOSE],
["s"], "Select Subject: field",
function () { GetMsgSubjectElement().focus(); });
mappings.add([modes.COMPOSE],
["i"], "Select message body",
function () { SetMsgBodyFrameFocus(); });
mappings.add([modes.COMPOSE],
["q"], "Close composer, ask when for unsaved changes",
function () { DoCommandClose(); });
mappings.add([modes.COMPOSE],
["Q", "ZQ"], "Force closing composer",
function () { MsgComposeCloseWindow(true); /* cache window for better performance*/ });
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Mail = Module("mail", {
requires: ["liberator"],
init: function () {
services.add("smtpService", "@mozilla.org/messengercompose/smtp;1", Ci.nsISmtpService);
// used for asynchronously selecting messages after wrapping folders
this._selectMessageKeys = [];
this._selectMessageCount = 1;
this._selectMessageReverse = false;
this._mailSession = Cc["@mozilla.org/messenger/services/session;1"].getService(Ci.nsIMsgMailSession);
this._notifyFlags = Ci.nsIFolderListener.intPropertyChanged | Ci.nsIFolderListener.event;
this._mailSession.AddFolderListener(this._folderListener, this._notifyFlags);
liberator.open = this.open;
},
_folderListener: {
OnItemAdded: function (parentItem, item) {},
OnItemRemoved: function (parentItem, item) {},
OnItemPropertyChanged: function (item, property, oldValue, newValue) {},
OnItemIntPropertyChanged: function (item, property, oldValue, newValue) {},
OnItemBoolPropertyChanged: function (item, property, oldValue, newValue) {},
OnItemUnicharPropertyChanged: function (item, property, oldValue, newValue) {},
OnItemPropertyFlagChanged: function (item, property, oldFlag, newFlag) {},
OnItemEvent: function (folder, event) {
let eventType = event.toString();
if (eventType == "FolderLoaded") {
if (folder) {
let msgFolder = folder.QueryInterface(Ci.nsIMsgFolder);
autocommands.trigger("FolderLoaded", { url: msgFolder });
// Jump to a message when requested
let indices = [];
if (mail._selectMessageKeys.length > 0) {
for (let j = 0; j < mail._selectMessageKeys.length; j++)
indices.push([gDBView.findIndexFromKey(mail._selectMessageKeys[j], true), mail._selectMessageKeys[j]]);
indices.sort();
let index = mail._selectMessageCount - 1;
if (mail._selectMessageReverse)
index = mail._selectMessageKeys.length - 1 - index;
gDBView.selectMsgByKey(indices[index][1]);
mail._selectMessageKeys = [];
}
}
}
/*else if (eventType == "ImapHdrDownloaded") {}
else if (eventType == "DeleteOrMoveMsgCompleted") {}
else if (eventType == "DeleteOrMoveMsgFailed") {}
else if (eventType == "AboutToCompact") {}
else if (eventType == "CompactCompleted") {}
else if (eventType == "RenameCompleted") {}
else if (eventType == "JunkStatusChanged") {}*/
}
},
_getCurrentFolderIndex: function () {
// for some reason, the index is interpreted as a string, therefore the parseInt
return parseInt(gFolderTreeView.getIndexOfFolder(gFolderTreeView.getSelectedFolders()[0]));
},
_getRSSUrl: function () {
return gDBView.hdrForFirstSelectedMessage.messageId.replace(/(#.*)?@.*$/, "");
},
_moveOrCopy: function (copy, destinationFolder, operateOnThread) {
let folders = mail.getFolders(destinationFolder);
if (folders.length == 0)
return void liberator.echoerr("No matching folder for: " + destinationFolder);
else if (folders.length > 1)
return liberator.echoerr("More than one match for: " + destinationFolder);
let count = gDBView.selection.count;
if (!count)
return void liberator.beep();
(copy ? MsgCopyMessage : MsgMoveMessage)(folders[0]);
setTimeout(function () {
liberator.echomsg((copy ? "Copied " : "Moved ") + count + " message(s) " + " to: " + folders[0].prettyName);
}, 100);
},
_parentIndex: function (index) {
let parent = index;
let tree = GetThreadTree();
while (true) {
let tmp = tree.view.getParentIndex(parent);
if (tmp >= 0)
parent = tmp;
else
break;
}
return parent;
},
// does not wrap yet, intentional?
_selectUnreadFolder: function (backwards, count) {
count = Math.max(1, count);
let direction = backwards ? -1 : 1;
let c = this._getCurrentFolderIndex();
let i = direction;
let folder;
while (count > 0 && (c + i) < gFolderTreeView.rowCount && (c + i) >= 0) {
let resource = gFolderTreeView._rowMap[c+i]._folder;
if (!resource.isServer && resource.getNumUnread(false)) {
count -= 1;
folder = i;
}
i += direction;
}
if (!folder || count > 0)
liberator.beep();
else
gFolderTreeView.selection.timedSelect(c + folder, 500);
},
_escapeRecipient: function (recipient) {
// strip all ":
recipient = recipient.replace(/"/g, "");
return "\"" + recipient + "\"";
},
get currentAccount() this.currentFolder.rootFolder,
get currentFolder() gFolderTreeView.getSelectedFolders()[0],
/** @property {nsISmtpServer[]} The list of configured SMTP servers. */
get smtpServers() {
let servers = services.get("smtpService").smtpServers;
let ret = [];
while (servers.hasMoreElements()) {
let server = servers.getNext();
if (server instanceof Ci.nsISmtpServer)
ret.push(server);
}
return ret;
},
composeNewMail: function (args) {
let params = Cc["@mozilla.org/messengercompose/composeparams;1"].createInstance(Ci.nsIMsgComposeParams);
params.composeFields = Cc["@mozilla.org/messengercompose/composefields;1"].createInstance(Ci.nsIMsgCompFields);
if (args) {
if (args.originalMsg)
params.originalMsgURI = args.originalMsg;
if (args.to)
params.composeFields.to = args.to;
if (args.cc)
params.composeFields.cc = args.cc;
if (args.bcc)
params.composeFields.bcc = args.bcc;
if (args.newsgroups)
params.composeFields.newsgroups = args.newsgroups;
if (args.subject)
params.composeFields.subject = args.subject;
if (args.body)
params.composeFields.body = args.body;
if (args.attachments) {
while (args.attachments.length > 0) {
let url = args.attachments.pop();
let file = io.File(url);
if (!file.exists())
return void liberator.echoerr("Could not attach file: " + url);
attachment = Cc["@mozilla.org/messengercompose/attachment;1"].createInstance(Ci.nsIMsgAttachment);
attachment.url = "file://" + file.path;
params.composeFields.addAttachment(attachment);
}
}
}
params.type = Ci.nsIMsgCompType.New;
const msgComposeService = Cc["@mozilla.org/messengercompose;1"].getService();
msgComposeService = msgComposeService.QueryInterface(Ci.nsIMsgComposeService);
msgComposeService.OpenComposeWindowWithParams(null, params);
},
/**
* returns Generator of all folders in the current view
* @param {Boolean} includeServers
* @param {Boolean} includeMsgFolders
* @return {Generator}
* [
* [{Object ftvItem} row, {String} folderPath]
* ...
* ]
*/
getAllFolderRowMap: function (includeServers, includeMsgFolders) {
if (includeServers === undefined)
includeServers = false;
if (includeMsgFolders === undefined)
includeMsgFolders = true;
function walkChildren(children, prefix) {
for (let [, row] in Iterator(children)) {
let folder = row._folder;
let folderString = prefix + "/" +
(row.useServerNameOnly ? folder.server.prettyName : folder.abbreviatedName);
yield [row, folderString];
if (row.children.length > 0)
for (let child in walkChildren(row.children, folderString))
yield child;
}
}
for (let i = 0; i < gFolderTreeView.rowCount; i++) {
let row = gFolderTreeView._rowMap[i];
if (row.level != 0)
continue;
let folder = row._folder;
let folderString = folder.server.prettyName + ": " +
(row.useServerNameOnly ? folder.server.prettyName : folder.abbreviatedName);
if ((folder.isServer && includeServers) || (!folder.isServer && includeMsgFolders))
yield [row, folderString];
if (includeMsgFolders && row.children.length > 0)
for (let child in walkChildren(row.children, folderString))
yield child;
}
},
// returns an array of nsIMsgFolder objects
getFolders: function (filter, includeServers, includeMsgFolders) {
let folders = [];
if (!filter)
filter = "";
else
filter = filter.toLowerCase();
for (let [row, name] in this.getAllFolderRowMap(includeServers, includeMsgFolders)) {
let folder = row._folder;
// XXX: row._folder.prettyName is needed ? -- teramako
if (name.toLowerCase().indexOf(filter) >= 0)
folders.push(row._folder);
}
return folders;
},
/**
* returns array of nsIMsgFolder objects
* @param {Number} flag
* e.g.) Ci.nsMsgFolderFlags.Inbox
* @see Ci.nsMsgFolderFlags
* @return {nsIMsgFolder[]}
*/
getFoldersWithFlag: function (flag) {
if (flag) {
return [row._folder for ([row] in this.getAllFolderRowMap(true,true)) if (row._folder.flags & flag)]
}
return [];
},
getNewMessages: function (currentAccountOnly) {
if (currentAccountOnly)
MsgGetMessagesForAccount();
else
GetMessagesForAllAuthenticatedAccounts();
},
getStatistics: function (currentAccountOnly) {
let accounts = currentAccountOnly ? [this.currentAccount]
: this.getFolders("", true, false);
let unreadCount = 0, totalCount = 0, newCount = 0;
for (let i = 0; i < accounts.length; i++) {
let account = accounts[i];
unreadCount += account.getNumUnread(true); // true == deep (includes subfolders)
totalCount += account.getTotalMessages(true);
newCount += account.getNumUnread(true);
}
return { numUnread: unreadCount, numTotal: totalCount, numNew: newCount };
},
collapseThread: function () {
let tree = GetThreadTree();
if (tree) {
let parent = this._parentIndex(tree.currentIndex);
if (tree.changeOpenState(parent, false)) {
tree.view.selection.select(parent);
tree.treeBoxObject.ensureRowIsVisible(parent);
return true;
}
}
return false;
},
expandThread: function () {
let tree = GetThreadTree();
if (tree) {
let row = tree.currentIndex;
if (row >= 0 && tree.changeOpenState(row, true))
return true;
}
return false;
},
/**
* General-purpose method to find messages.
*
* @param {function(nsIMsgDBHdr):boolean} validatorFunc Return
* true/false whether msg should be selected or not.
* @param {boolean} canWrap When true, wraps around folders.
* @param {boolean} openThreads Should we open closed threads?
* @param {boolean} reverse Change direction of searching.
*/
selectMessage: function (validatorFunc, canWrap, openThreads, reverse, count) {
function currentIndex() {
let index = gDBView.selection.currentIndex;
if (index < 0)
index = 0;
return index;
}
function closedThread(index) {
if (!(gDBView.viewFlags & nsMsgViewFlagsType.kThreadedDisplay))
return false;
index = (typeof index == "number") ? index : currentIndex();
return !gDBView.isContainerOpen(index) && !gDBView.isContainerEmpty(index);
}
if (typeof validatorFunc != "function")
return;
if (typeof count != "number" || count < 1)
count = 1;
// first try to find in current folder
if (gDBView) {
for (let i = currentIndex() + (reverse ? -1 : (openThreads && closedThread() ? 0 : 1));
reverse ? (i >= 0) : (i < gDBView.rowCount);
reverse ? i-- : i++) {
let key = gDBView.getKeyAt(i);
let msg = gDBView.db.GetMsgHdrForKey(key);
// a closed thread
if (openThreads && closedThread(i)) {
let thread = gDBView.db.GetThreadContainingMsgHdr(msg);
let originalCount = count;
for (let j = (i == currentIndex() && !reverse) ? 1 : (reverse ? thread.numChildren - 1 : 0);
reverse ? (j >= 0) : (j < thread.numChildren);
reverse ? j-- : j++) {
msg = thread.getChildAt(j);
if (validatorFunc(msg) && --count == 0) {
// this hack is needed to get the correct message, because getChildAt() does not
// necessarily return the messages in the order they are displayed
gDBView.selection.timedSelect(i, GetThreadTree()._selectDelay || 500);
GetThreadTree().treeBoxObject.ensureRowIsVisible(i);
if (j > 0) {
GetThreadTree().changeOpenState(i, true);
this.selectMessage(validatorFunc, false, false, false, originalCount);
}
return;
}
}
}
else { // simple non-threaded message
if (validatorFunc(msg) && --count == 0) {
gDBView.selection.timedSelect(i, GetThreadTree()._selectDelay || 500);
GetThreadTree().treeBoxObject.ensureRowIsVisible(i);
return;
}
}
}
}
// then in other folders
if (canWrap) {
this._selectMessageReverse = reverse;
let folders = this.getFolders("", true, true);
let ci = this._getCurrentFolderIndex();
for (let i = 1; i < folders.length; i++) {
let index = (i + ci) % folders.length;
if (reverse)
index = folders.length - 1 - index;
let folder = folders[index];
if (folder.isServer)
continue;
this._selectMessageCount = count;
this._selectMessageKeys = [];
// sometimes folder.getMessages can fail with an exception
// TODO: find out why, and solve the problem
try {
var msgs = folder.messages;
}
catch (e) {
msgs = folder.getMessages(msgWindow); // for older thunderbirds
}
while (msgs.hasMoreElements()) {
let msg = msgs.getNext().QueryInterface(Ci.nsIMsgDBHdr);
if (validatorFunc(msg)) {
count--;
this._selectMessageKeys.push(msg.messageKey);
}
}
if (count <= 0) {
// SelectFolder is asynchronous, message is selected in this._folderListener
SelectFolder(folder.URI);
return;
}
}
}
// TODO: finally for the "rest" of the current folder
liberator.beep();
},
setHTML: function (value) {
let values = [[true, 1, gDisallow_classes_no_html], // plaintext
[false, 0, 0], // HTML
[false, 3, gDisallow_classes_no_html]]; // sanitized/simple HTML
if (typeof value != "number" || value < 0 || value > 2)
value = 1;
gPrefBranch.setBoolPref("mailnews.display.prefer_plaintext", values[value][0]);
gPrefBranch.setIntPref("mailnews.display.html_as", values[value][1]);
gPrefBranch.setIntPref("mailnews.display.disallow_mime_handlers", values[value][2]);
ReloadMessage();
},
/**
* open folders and URLs
* @param {Object} targets
* @param {Object|Number} params
*/
open: function (targets, params) {
let tabmail = document.getElementById("tabmail");
if (!(targets instanceof Array))
targets = [targets];
if (!params)
params = {};
else if (params instanceof Array)
params = { where: params };
let where = params.where || liberator.CURRENT_TAB;
if (liberator.forceNewTab || liberator.forceNewWindow)
where = liberator.NEW_TAB;
if ("from" in params) {
if (!("where" in params) && options["newtab"] && options.get("newtab").has("all", params.from))
where = liberator.NEW_TAB;
if (options["activate"] && !options.get("activate").has("all", params.from)) {
if (where == liberator.NEW_TAB)
where = liberator.NEW_BACKGROUND_TAB;
else if (where == liberator.NEW_BACKGROUND_TAB)
where = liberator.NEW_TAB;
}
}
function openTarget(target, where) {
if (target instanceof Ci.nsIMsgFolder) {
if (where == liberator.CURRENT_TAB && tabmail.currentTabInfo.mode.name == "folder") {
SelectFolder(target.URI);
return;
}
let args = {
folder: target,
background: where != liberator.NEW_TAB
};
["folderPaneVisible", "messagePaneVisible", "msgHdr"].forEach(function(opt){
if (opt in params)
args[opt] = params[opt];
});
tabmail.openTab("folder", args);
return;
}
if (typeof target == "string") {
try {
target = util.createURI(target);
} catch(e) {
return;
}
}
if (!(target instanceof Ci.nsIURI))
return;
if (target.schemeIs("mailto")){
mail.composeNewMail({to: target.path});
return;
}
switch (where) {
case liberator.CURRENT_TAB:
if (tabmail.currentTabInfo.mode.name == "contentTab") {
tabmail.currentTabInfo.browser.loadURI(target.spec);
break;
}
case liberator.NEW_TAB:
case liberator.NEW_WINDOW:
case liberator.NEW_BACKGROUND_TAB:
let tab = tabmail.openTab("contentTab", {
contentPage: target.spec,
background: where != liberator.NEW_TAB,
clickHandler: "liberator.modules.mail.siteClickHandler(event)"
});
let browser = tab.browser;
if (browser.hasAttribute("disablehistory")) {
browser.webNavigation.sessionHistory =
Cc["@mozilla.org/browser/shistory;1"].createInstance(Ci.nsISHistory);
browser.removeAttribute("disablehistory");
}
break;
}
}
for (let [,target] in Iterator(targets)) {
openTarget(target, where);
where = liberator.NEW_BACKGROUND_TAB;
}
},
/**
* @see specialTabs.siteClickHandler
*/
siteClickHandler: function(event){
if (!event.isTrusted || event.getPreventDefault() || event.button)
return true;
let href = hRefForClickEvent(event, true);
let isOpenExternal = true;
if (href) {
let uri = makeURI(href);
switch(uri.scheme){
case "http":
case "https":
case "chrome":
case "about":
isOpenExternal = false;
break;
case "liberator":
if (event.target.ownerDocument.location.protocol == "liberator:")
config.browser.loadURI(uri.spec);
event.preventDefault();
return true;
default:
if (specialTabs._protocolSvc.isExposedProtocol(uri.scheme))
isOpenExternal = false;
}
if (isOpenExternal) {
event.preventDefault();
openLinkExternally(href);
}
}
}
}, {
}, {
commands: function () {
commands.add(["go[to]"],
"Select a folder",
function (args) {
let count = Math.max(0, args.count - 1);
let arg = args.literalArg;
let folder = arg ?
mail.getFolders(arg, true, true)[count] :
mail.getFoldersWithFlag(Ci.nsMsgFolderFlags.Inbox)[count];
if (!folder)
liberator.echoerr("No such folder: " + arg);
else
liberator.open(folder, {from: "goto"});
},
{
argCount: "?",
completer: function (context) completion.mailFolder(context),
count: true,
literal: 0
});
function attachmentsCompletion (context) {
let i = context.filter.lastIndexOf(",");
if (i !== -1)
context.advance(i + 1);
completion.file(context);
return context.items;
}
commands.add(["c[ompose]"],
"Compose a new message",
function (args) {
let mailargs = {};
mailargs.to = args.join(", ");
mailargs.subject = args["-subject"];
mailargs.bcc = args["-bcc"];
mailargs.cc = args["-cc"];
mailargs.body = args["-text"];
mailargs.attachments = args["-attachment"] || [];
let addresses = args;
if (mailargs.bcc)
addresses = addresses.concat(mailargs.bcc);
if (mailargs.cc)
addresses = addresses.concat(mailargs.cc);
// TODO: is there a better way to check for validity?
if (addresses.some(function (recipient) !(/\S@\S+\.\S/.test(recipient))))
return void liberator.echoerr("Invalid e-mail address");
mail.composeNewMail(mailargs);
},
{
options: [[["-subject", "-s"], commands.OPTION_STRING],
[["-attachment", "-a"], commands.OPTION_LIST, null, attachmentsCompletion],
[["-bcc", "-b"], commands.OPTION_STRING],
[["-cc", "-c"], commands.OPTION_STRING],
[["-text", "-t"], commands.OPTION_STRING]]
});
commands.add(["copy[to]"],
"Copy selected messages",
function (args) { mail._moveOrCopy(true, args.literalArg); },
{
argCount: 1,
completer: function (context) completion.mailFolder(context),
literal: 0
});
commands.add(["move[to]"],
"Move selected messages",
function (args) { mail._moveOrCopy(false, args.literalArg); },
{
argCount: 1,
completer: function (context) completion.mailFolder(context),
literal: 0
});
commands.add(["empty[trash]"],
"Empty trash of the current account",
function () { window.goDoCommand("cmd_emptyTrash"); },
{ argCount: "0" });
commands.add(["get[messages]"],
"Check for new messages",
function (args) mail.getNewMessages(!args.bang),
{
argCount: "0",
bang: true,
});
},
completion: function () {
completion.mailFolder = function mailFolder(context) {
context.anchored = false;
context.quote = false;
context.completions = [[row[1], "Unread: " + row[0]._folder.getNumUnread(false)]
for (row in mail.getAllFolderRowMap(true,true))];
};
},
mappings: function () {
var myModes = config.mailModes;
mappings.add(myModes, ["<Return>", "m"],
"Start message mode",
//function () { config.browser.contentWindow.focus(); });
function () { modes.main = modes.MESSAGE; });
mappings.add(myModes, ["M"],
"Open the message in new tab",
function () {
if (gDBView && gDBView.selection.count < 1)
return void liberator.beep();
OpenMessageInNewTab({shiftKey: options.getPref("mail.tabs.loadInBackground") });
});
/*mappings.add([modes.NORMAL],
["o"], "Open a message",
function () { commandline.open("", "open ", modes.EX); });*/
mappings.add(myModes, ["<Space>"],
"Scroll message or select next unread one",
function () true,
{ route: true });
mappings.add(myModes, ["t"],
"Select thread",
function () { gDBView.ExpandAndSelectThreadByIndex(GetThreadTree().currentIndex, false); });
mappings.add(myModes, ["d", "<Del>"],
"Move mail to Trash folder",
function () { window.goDoCommand("cmd_delete"); });
mappings.add(myModes, ["j", "<Right>"],
"Select next message",
function (count) { mail.selectMessage(function (msg) true, false, false, false, count); },
{ count: true });
mappings.add(myModes, ["gj"],
"Select next message, including closed threads",
function (count) { mail.selectMessage(function (msg) true, false, true, false, count); },
{ count: true });
mappings.add(myModes, ["J", "<Tab>"],
"Select next unread message",
function (count) { mail.selectMessage(function (msg) !msg.isRead, true, true, false, count); },
{ count: true });
mappings.add(myModes, ["k", "<Left>"],
"Select previous message",
function (count) { mail.selectMessage(function (msg) true, false, false, true, count); },
{ count: true });
mappings.add(myModes, ["gk"],
"Select previous message",
function (count) { mail.selectMessage(function (msg) true, false, true, true, count); },
{ count: true });
mappings.add(myModes, ["K"],
"Select previous unread message",
function (count) { mail.selectMessage(function (msg) !msg.isRead, true, true, true, count); },
{ count: true });
mappings.add(myModes, ["*"],
"Select next message from the same sender",
function (count) {
try {
let author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase();
mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, false, count);
}
catch (e) { liberator.beep(); }
},
{ count: true });
mappings.add(myModes, ["#"],
"Select previous message from the same sender",
function (count) {
try {
let author = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor.toLowerCase();
mail.selectMessage(function (msg) msg.mime2DecodedAuthor.toLowerCase().indexOf(author) == 0, true, true, true, count);
}
catch (e) { liberator.beep(); }
},
{ count: true });
// SENDING MESSAGES
mappings.add(myModes, ["c"],
"Compose a new message",
function () { commandline.open("", "compose -subject=", modes.EX); });
mappings.add(myModes, ["C"],
"Compose a new message to the sender of selected mail",
function () {
try {
let to = mail._escapeRecipient(gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor);
commandline.open("", "compose " + to + " -subject=", modes.EX);
}
catch (e) {
liberator.beep();
}
});
mappings.add(myModes, ["r"],
"Reply to sender",
function () { window.goDoCommand("cmd_reply"); });
mappings.add(myModes, ["R"],
"Reply to all",
function () { window.goDoCommand("cmd_replyall"); });
mappings.add(myModes, ["f"],
"Forward message",
function () { window.goDoCommand("cmd_forward"); });
mappings.add(myModes, ["F"],
"Forward message inline",
function () { window.goDoCommand("cmd_forwardInline"); });
// SCROLLING
mappings.add(myModes, ["<Down>"],
"Scroll message down",
function (count) { buffer.scrollLines(Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, ["+"],
"Scroll message down pagewise",
function (count) { buffer.scrollPages(Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, ["<Up>"],
"Scroll message up",
function (count) { buffer.scrollLines(-Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, ["-"],
"Scroll message up pagewise",
function (count) { buffer.scrollPages(-Math.max(count, 1)); },
{ count: true });
mappings.add([modes.MESSAGE], ["<Left>"],
"Select previous message",
function (count) { mail.selectMessage(function (msg) true, false, false, true, count); },
{ count: true });
mappings.add([modes.MESSAGE], ["<Right>"],
"Select next message",
function (count) { mail.selectMessage(function (msg) true, false, false, false, count); },
{ count: true });
// UNDO/REDO
mappings.add(myModes, ["u"],
"Undo",
function () {
if (messenger.canUndo())
messenger.undo(msgWindow);
else
liberator.beep();
});
mappings.add(myModes, ["<C-r>"],
"Redo",
function () {
if (messenger.canRedo())
messenger.redo(msgWindow);
else
liberator.beep();
});
// GETTING MAIL
mappings.add(myModes, ["gm"],
"Get new messages",
function () { liberator.echomsg("Fetching mail..."); mail.getNewMessages(); });
mappings.add(myModes, ["gM"],
"Get new messages for current account only",
function () { liberator.echomsg("Fetching mail for current account..."); mail.getNewMessages(true); });
mappings.add(myModes, ["o"],
"Goto folder",
function () { commandline.open("", "goto ", modes.EX); });
// MOVING MAIL
mappings.add(myModes, ["s"],
"Move selected messages",
function () { commandline.open("", "moveto ", modes.EX); });
mappings.add(myModes, ["S"],
"Copy selected messages",
function () { commandline.open("", "copyto ", modes.EX); });
mappings.add(myModes, ["<C-s>"],
"Archive message",
function () { MsgArchiveSelectedMessages(); });
mappings.add(myModes, ["!"],
"Mark/unmark selected messages as junk",
function () { JunkSelectedMessages(!SelectedMessagesAreJunk()); });
mappings.add(myModes, ["]s"],
"Select next starred message",
function (count) { mail.selectMessage(function (msg) msg.isFlagged, true, true, false, count); },
{ count: true });
mappings.add(myModes, ["[s"],
"Select previous starred message",
function (count) { mail.selectMessage(function (msg) msg.isFlagged, true, true, true, count); },
{ count: true });
mappings.add(myModes, ["]a"],
"Select next message with an attachment",
function (count) { mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, false, count); },
{ count: true });
mappings.add(myModes, ["[a"],
"Select previous message with an attachment",
function (count) { mail.selectMessage(function (msg) gDBView.db.HasAttachments(msg.messageKey), true, true, true, count); },
{ count: true });
// FOLDER SWITCHING
mappings.add(myModes, ["gi"],
"Go to inbox",
function (count) {
let folder = mail.getFoldersWithFlag(Ci.nsMsgFolderFlags.Inbox)[(count > 0) ? (count - 1) : 0]
if (folder)
SelectFolder(folder.URI);
else
liberator.beep();
},
{ count: true });
mappings.add(myModes, ["<C-n>"],
"Select next folder",
function (count) {
count = Math.max(1, count);
let newPos = mail._getCurrentFolderIndex() + count;
if (newPos >= gFolderTreeView.rowCount) {
newPos = newPos % gFolderTreeView.rowCount;
commandline.echo("search hit BOTTOM, continuing at TOP", commandline.HL_WARNINGMSG, commandline.APPEND_TO_MESSAGES);
}
gFolderTreeView.selection.timedSelect(newPos, 500);
},
{ count: true });
mappings.add(myModes, ["<C-S-N>"],
"Go to next mailbox with unread messages",
function (count) {
mail._selectUnreadFolder(false, count);
},
{ count: true });
mappings.add(myModes, ["<C-p>"],
"Select previous folder",
function (count) {
count = Math.max(1, count);
let newPos = mail._getCurrentFolderIndex() - count;
if (newPos < 0) {
newPos = (newPos % gFolderTreeView.rowCount) + gFolderTreeView.rowCount;
commandline.echo("search hit TOP, continuing at BOTTOM", commandline.HL_WARNINGMSG, commandline.APPEND_TO_MESSAGES);
}
gFolderTreeView.selection.timedSelect(newPos, 500);
},
{ count: true });
mappings.add(myModes, ["<C-S-P>"],
"Go to previous mailbox with unread messages",
function (count) {
mail._selectUnreadFolder(true, count);
},
{ count: true });
// THREADING
mappings.add(myModes, ["za"],
"Toggle thread collapsed/expanded",
function () { if (!mail.expandThread()) mail.collapseThread(); });
mappings.add(myModes, ["zc"],
"Collapse thread",
function () { mail.collapseThread(); });
mappings.add(myModes, ["zo"],
"Open thread",
function () { mail.expandThread(); });
mappings.add(myModes, ["zr", "zR"],
"Expand all threads",
function () { window.goDoCommand("cmd_expandAllThreads"); });
mappings.add(myModes, ["zm", "zM"],
"Collapse all threads",
function () { window.goDoCommand("cmd_collapseAllThreads"); });
mappings.add(myModes, ["<C-i>"],
"Go forward",
function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.forward, true); },
{ count: true });
mappings.add(myModes, ["<C-o>"],
"Go back",
function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.back, true); },
{ count: true });
mappings.add(myModes, ["gg"],
"Select first message",
function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.firstMessage, true); },
{ count: true });
mappings.add(myModes, ["G"],
"Select last message",
function (count) { if (count < 1) count = 1; while (count--) GoNextMessage(nsMsgNavigationType.lastMessage, false); },
{ count: true });
// tagging messages
mappings.add(myModes, ["l"],
"Label message",
function (arg) {
if (!gDBView.numSelected)
return void liberator.beep();
switch (arg) {
case "r": MsgMarkMsgAsRead(); break;
case "s": MsgMarkAsFlagged(); break;
case "i": // Important
case "1":
ToggleMessageTagKey(1);
break;
case "w": // Work
case "2":
ToggleMessageTagKey(2);
break;
case "p": // Personal
case "3":
ToggleMessageTagKey(3);
break;
case "t": // TODO
case "4":
ToggleMessageTagKey(4);
break;
case "l": // Later
case "5":
ToggleMessageTagKey(5);
break;
default:
liberator.beep();
}
},
{
arg: true
});
// TODO: change binding?
mappings.add(myModes, ["T"],
"Mark current folder as read",
function () {
if (mail.currentFolder.isServer)
return liberator.beep();
mail.currentFolder.markAllMessagesRead(msgWindow);
});
mappings.add(myModes, ["<C-t>"],
"Mark all messages as read",
function () {
mail.getFolders("", false).forEach(function (folder) { folder.markAllMessagesRead(msgWindow); });
});
// DISPLAY OPTIONS
mappings.add(myModes, ["h"],
"Toggle displayed headers",
function () {
let value = gPrefBranch.getIntPref("mail.show_headers", 2);
gPrefBranch.setIntPref("mail.show_headers", value == 2 ? 1 : 2);
ReloadMessage();
});
mappings.add(myModes, ["x"],
"Toggle HTML message display",
function () {
let wantHtml = (gPrefBranch.getIntPref("mailnews.display.html_as", 1) == 1);
mail.setHTML(wantHtml ? 1 : 0);
});
// YANKING TEXT
mappings.add(myModes, ["y"],
"Yank field",
function (arg) {
try {
let text = "";
switch (arg) {
case "f":
case "y":
text = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor;
break;
case "s":
text = gDBView.hdrForFirstSelectedMessage.mime2DecodedSubject;
break;
case "#":
text = gDBView.hdrForFirstSelectedMessage.messageId;
break;
case "t":
text = gDBView.hdrForFirstSelectedMessage.mime2DecodedRecipients;
break;
case "r": // all recipients
let cc = gDBView.hdrForFirstSelectedMessage.ccList;
text = gDBView.hdrForFirstSelectedMessage.mime2DecodedRecipients + (cc ? ", " + cc : "");
break;
case "u":
if (mail.currentAccount.server.type == "rss") {
text = util.this._getRSSUrl(); // TODO: util.this?
} // if else, yank nothing
break;
default:
liberator.beep();
}
util.copyToClipboard(text, true);
}
catch (e) { liberator.beep(); }
},
{
arg: true
});
// RSS specific mappings
mappings.add(myModes, ["p"],
"Open RSS message in browser",
function () {
try {
if (mail.currentAccount.server.type == "rss")
messenger.launchExternalURL(mail._getRSSUrl());
// TODO: what to do for non-rss message?
}
catch (e) {
liberator.beep();
}
});
},
options: function () {
// TODO: generate the possible values dynamically from the menu
options.add(["layout"],
"Set the layout of the mail window",
"string", "inherit",
{
setter: function (value) {
switch (value) {
case "classic": ChangeMailLayout(0); break;
case "wide": ChangeMailLayout(1); break;
case "vertical": ChangeMailLayout(2); break;
// case "inherit" just does nothing
}
return value;
},
completer: function (context) [
["inherit", "Default View"], // FIXME: correct description?
["classic", "Classic View"],
["wide", "Wide View"],
["vertical", "Vertical View"]
],
validator: Option.validateCompleter
});
options.add(["smtpserver", "smtp"],
"Set the default SMTP server",
"string", services.get("smtpService").defaultServer.key, // TODO: how should we handle these persistent external defaults - "inherit" or null?
{
getter: function () services.get("smtpService").defaultServer.key,
setter: function (value) {
let server = mail.smtpServers.filter(function (s) s.key == value)[0];
services.get("smtpService").defaultServer = server;
return value;
},
completer: function (context) [[s.key, s.serverURI] for ([, s] in Iterator(mail.smtpServers))],
validator: Option.validateCompleter
});
options.add(["foldermode", "folder"],
"Set the folder mode",
"string", "smart",
{
getter: function () gFolderTreeView.mode,
setter: function (value) {
gFolderTreeView.mode = value;
return value;
},
completer: function (context) {
let modes = gFolderTreeView._modeNames;
return modes.map(function(mode) {
let name = (mode in gFolderTreeView._modeDisplayNames) ?
gFolderTreeView._modeDisplayNames[mode] :
document.getElementById("bundle_messenger").getString("folderPaneHeader_" + mode);
return [mode, name];
});
},
validator: Option.validateCompleter
});
options.add(["remotecontent", "rc"],
"Allow display remote content",
"boolean", false,
{
scope: Option.SCOPE_LOCAL,
getter: function () {
if (config.browser.id == "messagepane") {
let msg = gMessageDisplay.displayedMessage;
if (msg)
return msg.getUint32Property("remoteContentPolicy") == kAllowRemoteContent ? true : false;
}
},
setter: function (value) {
var policy = value ? kAllowRemoteContent : kBlockRemoteContent;
if (config.browser.id == "messagepane") {
let msg = gMessageDisplay.displayedMessage;
if (msg && msg.getUint32Property("remoteContentPolicy") != policy) {
msg.setUint32Property("remoteContentPolicy", policy);
ReloadMessage();
}
}
return value;
},
});
/*options.add(["threads"],
"Use threading to group messages",
"boolean", true,
{
setter: function (value) {
if (value)
MsgSortThreaded();
else
MsgSortUnthreaded();
return value;
}
});*/
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2008 by Christian Dietrich <stettberger@dokucode.de>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Addressbook = Module("addressbook", {
init: function () {
services.add("abManager", "@mozilla.org/abmanager;1", Ci.nsIAbManager);
},
// TODO: add option for a format specifier, like:
// :set displayname=%l, %f
generateDisplayName: function (firstName, lastName) {
if (firstName && lastName)
return lastName + ", " + firstName;
else if (firstName)
return firstName;
else if (lastName)
return lastName;
else
return "";
},
add: function (address, firstName, lastName, displayName) {
const personalAddressbookURI = "moz-abmdbdirectory://abook.mab";
let directory = services.get("abManager").getDirectory(personalAddressbookURI);
let card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(Ci.nsIAbCard);
if (!address || !directory || !card)
return false;
card.primaryEmail = address;
card.firstName = firstName;
card.lastName = lastName;
card.displayName = displayName;
return directory.addCard(card);
},
// TODO: add telephone number support
list: function (filter, newMail) {
let addresses = [];
let dirs = services.get("abManager").directories;
let lowerFilter = filter.toLowerCase();
while (dirs.hasMoreElements()) {
let addrbook = dirs.getNext().QueryInterface(Ci.nsIAbDirectory);
let cards = addrbook.childCards;
while (cards.hasMoreElements()) {
let card = cards.getNext().QueryInterface(Ci.nsIAbCard);
//var mail = card.primaryEmail || ""; //XXX
let displayName = card.displayName;
if (!displayName)
displayName = this.generateDisplayName(card.firstName, card.lastName);
if (displayName.toLowerCase().indexOf(lowerFilter) > -1
|| card.primaryEmail.toLowerCase().indexOf(lowerFilter) > -1)
addresses.push([displayName, card.primaryEmail]);
}
}
if (addresses.length < 1) {
if (!filter)
liberator.echoerr("No contacts");
else
liberator.echoerr("No matching contacts for: " + filter);
return false;
}
if (newMail) {
// Now we have to create a new message
let args = {};
args.to = addresses.map(
function (address) "\"" + address[0].replace(/"/g, "") + " <" + address[1] + ">\""
).join(", ");
mail.composeNewMail(args);
}
else {
let list = template.tabular(["Name", "Address"], [[util.clip(address[0], 50), address[1]] for ([, address] in Iterator(addresses))]);
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}
return true;
}
}, {
}, {
commands: function () {
commands.add(["con[tact]"],
"Add an address book entry",
function (args) {
let mailAddr = args[0]; // TODO: support more than one email address
let firstName = args["-firstname"] || null;
let lastName = args["-lastname"] || null;
let displayName = args["-name"] || null;
if (!displayName)
displayName = addressbook.generateDisplayName(firstName, lastName);
if (addressbook.add(mailAddr, firstName, lastName, displayName))
liberator.echomsg("Added contact: " + displayName + " <" + mailAddr + ">");
else
liberator.echoerr("Could not add contact: " + mailAddr);
},
{
argCount: "+",
options: [[["-firstname", "-f"], commands.OPTION_STRING],
[["-lastname", "-l"], commands.OPTION_STRING],
[["-name", "-n"], commands.OPTION_STRING]]
});
commands.add(["contacts", "addr[essbook]"],
"List or open multiple addresses",
function (args) { addressbook.list(args.string, args.bang); },
{ bang: true });
},
mappings: function () {
var myModes = config.mailModes;
mappings.add(myModes, ["a"],
"Open a prompt to save a new addressbook entry for the sender of the selected message",
function () {
try {
var to = gDBView.hdrForFirstSelectedMessage.mime2DecodedAuthor;
}
catch (e) {
liberator.beep();
}
if (!to)
return;
let address = to.substring(to.indexOf("<") + 1, to.indexOf(">"));
let displayName = to.substr(0, to.indexOf("<") - 1);
if (/^\S+\s+\S+\s*$/.test(displayName)) {
let names = displayName.split(/\s+/);
displayName = "-firstname=" + names[0].replace(/"/g, "")
+ " -lastname=" + names[1].replace(/"/g, "");
}
else
displayName = "-name=\"" + displayName.replace(/"/g, "") + "\"";
commandline.open("", "contact " + address + " " + displayName, modes.EX);
});
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2008-2009 Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/* Adds support for data: URIs with chrome privileges
* and fragment identifiers.
*
* "chrome-data:" <content-type> [; <flag>]* "," [<data>]
*
* By Kris Maglione, ideas from Ed Anuff's nsChromeExtensionHandler.
*/
const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "convert", function () {
var obj = new Object;
Cu.import("resource://liberator/template.js", obj);
return obj.convert;
});
const NS_BINDING_ABORTED = 0x804b0002;
const nsIProtocolHandler = Ci.nsIProtocolHandler;
const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
let channel = Components.classesByID["{61ba33c0-3031-11d3-8cd0-0060b0fc14a3}"]
.getService(Ci.nsIProtocolHandler)
.newChannel(ioService.newURI("chrome://liberator/content/data", null, null))
.QueryInterface(Ci.nsIRequest);
const systemPrincipal = channel.owner;
channel.cancel(NS_BINDING_ABORTED);
delete channel;
function dataURL(type, data) "data:" + (type || "application/xml;encoding=UTF-8") + "," + encodeURIComponent(data);
function makeChannel(url, orig) {
if (typeof url == "function")
url = dataURL.apply(null, url());
let uri = ioService.newURI(url, null, null);
let channel = ioService.newChannelFromURI(uri);
channel.owner = systemPrincipal;
channel.originalURI = orig;
return channel;
}
function fakeChannel(orig) makeChannel("chrome://liberator/content/does/not/exist", orig);
function redirect(to, orig) {
//xxx: escape
let html = '<html><head><meta http-equiv="Refresh" content="' + ("0;" + to).replace(/"/g, """) + '"/></head></html>';
return makeChannel(dataURL('text/html', html), ioService.newURI(to, null, null));
}
XPCOMUtils.defineLazyGetter(this, "cache", function () {
var dir = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
dir.append("liberatorCache");
if (!dir.exists()) {
dir.create(dir.DIRECTORY_TYPE, -1);
}
return dir;
});
XPCOMUtils.defineLazyGetter(this, "version", function () {
return Services.appinfo.version;
});
function ChromeData() {}
ChromeData.prototype = {
contractID: "@mozilla.org/network/protocol;1?name=chrome-data",
classID: Components.ID("{c1b67a07-18f7-4e13-b361-2edcc35a5a0d}"),
classDescription: "Data URIs with chrome privileges",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),
_xpcom_factory: {
createInstance: function (outer, iid) {
if (!ChromeData.instance)
ChromeData.instance = new ChromeData();
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return ChromeData.instance.QueryInterface(iid);
}
},
scheme: "chrome-data",
defaultPort: -1,
allowPort: function (port, scheme) false,
protocolFlags: nsIProtocolHandler.URI_NORELATIVE
| nsIProtocolHandler.URI_NOAUTH
| nsIProtocolHandler.URI_IS_UI_RESOURCE,
newURI: function (spec, charset, baseURI) {
var uri = Cc["@mozilla.org/network/standard-url;1"]
.createInstance(Ci.nsIStandardURL)
.QueryInterface(Ci.nsIURI);
uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, null);
return uri;
},
newChannel: function (uri) {
try {
if (uri.scheme == this.scheme)
return makeChannel(uri.spec.replace(/^.*?:\/*(.*)(?:#.*)?/, "data:$1"), uri);
}
catch (e) {}
return fakeChannel();
}
};
function Liberator() {
this.wrappedJSObject = this;
const self = this;
this.HELP_TAGS = {};
this.FILE_MAP = {};
this.OVERLAY_MAP = {};
}
Liberator.prototype = {
contractID: "@mozilla.org/network/protocol;1?name=liberator",
classID: Components.ID("{9c8f2530-51c8-4d41-b356-319e0b155c44}"),
classDescription: "Liberator utility protocol",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),
_xpcom_factory: {
createInstance: function (outer, iid) {
if (!Liberator.instance)
Liberator.instance = new Liberator();
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return Liberator.instance.QueryInterface(iid);
}
},
init: function (obj) {
for each (let prop in ["HELP_TAGS", "FILE_MAP", "OVERLAY_MAP"]) {
this[prop] = this[prop].constructor();
for (let [k, v] in Iterator(obj[prop] || {}))
this[prop][k] = v
}
},
scheme: "liberator",
defaultPort: -1,
allowPort: function (port, scheme) false,
protocolFlags: 0
| nsIProtocolHandler.URI_IS_UI_RESOURCE
| nsIProtocolHandler.URI_IS_LOCAL_RESOURCE,
newURI: function (spec, charset, baseURI) {
var uri = Cc["@mozilla.org/network/standard-url;1"]
.createInstance(Ci.nsIStandardURL)
.QueryInterface(Ci.nsIURI);
uri.init(uri.URLTYPE_STANDARD, this.defaultPort, spec, charset, baseURI);
if (uri.host !== "template") return uri;
try {
spec = uri.spec;
//uri.init(uri.URLTYPE_STANDARD, this.defaultPort, uri.path.substr(1), charset, null);
// xxx:
uri = ioService.newURI(uri.path.replace(new RegExp("^/+"), ""), charset, null);
// recursible when override
while (uri.scheme === "chrome") {
uri = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIChromeRegistry)
.convertChromeURL(uri);
}
var nest = Cc["@mozilla.org/network/util;1"].getService(Ci.nsINetUtil).newSimpleNestedURI(uri);
nest.spec = spec;
} catch (ex) { Cu.reportError(ex); }
return nest;
},
newChannel: function (uri) {
try {
if ((uri instanceof Ci.nsINestedURI)) {
var m = (new RegExp("^/{2,}([^/]+)/([^?]+)")).exec(uri.path);
if (m) {
var host = m[1];
var path = m[2];
switch (host) {
case "template":
try {
var nest = ioService.newURI(path, uri.charset, null);
var channel = ioService.newChannelFromURI(nest);
// xxx: support template
if (0) return channel;
// xxx: NG: Firefox 16, 17
// NG: Cu.import
if (parseFloat(version) < 17) {
var stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
var cstream = channel.open();
stream.init(cstream);
var text = stream.read(-1);
stream.close();
cstream.close();
stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
stream.setData(convert(text), -1);
var channel = Cc["@mozilla.org/network/input-stream-channel;1"]
.createInstance(Ci.nsIInputStreamChannel);
channel.contentStream = stream;
channel.QueryInterface(Ci.nsIChannel);
channel.setURI(uri);
return channel;
}
var innerURI = uri.innerURI;
var temp = cache.clone();
var path = nest.spec.replace(/[:\/]/g, "_");
var lastModifiedTime;
if (innerURI.scheme === "resource") {
innerURI = Cc["@mozilla.org/network/protocol;1?name=resource"]
.getService(Ci.nsIResProtocolHandler).resolveURI(innerURI);
innerURI = ioService.newURI(innerURI, null, null);
}
if (innerURI.scheme === "jar") {
innerURI = innerURI.QueryInterface(Ci.nsIJARURI).JARFile;
}
if (innerURI.scheme === "file") {
lastModifiedTime = innerURI.QueryInterface(Ci.nsIFileURL).file.lastModifiedTime;
} else {
Cu.reportError("do not support:" + innerURI.spec);
}
temp.append(path);
if (!temp.exists()
|| temp.lastModifiedTime !== lastModifiedTime) {
var stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
var cstream = channel.open();
stream.init(cstream);
var text = stream.read(-1);
stream.close();
cstream.close();
text = convert(text);
var stream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
Services.console.logStringMessage("create:" + temp.leafName);
stream.init(temp, 0x2 | 0x8 | 0x20, 0644, 0);
stream.write(text, text.length);
stream.close();
temp.lastModifiedTime = lastModifiedTime;
} else { Services.console.logStringMessage("use cache:" + uri.spec); }
return ioService.newChannelFromURI(ioService.newFileURI(temp));
} catch (ex) { Cu.reportError(ex); }
}
}
return fakeChannel(uri);
}
switch(uri.host) {
case "help":
let url = this.FILE_MAP[uri.path.replace(/^\/|#.*/g, "")];
return makeChannel(url, uri);
case "help-overlay":
url = this.OVERLAY_MAP[uri.path.replace(/^\/|#.*/g, "")];
return makeChannel(url, uri);
case "help-tag":
let tag = uri.path.substr(1);
if (tag in this.HELP_TAGS)
return redirect("liberator://help/" + this.HELP_TAGS[tag] + "#" + tag, uri);
}
}
catch (e) { Cu.reportError(e); }
return fakeChannel(uri);
}
};
var components = [ChromeData, Liberator];
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule(components);
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
/***** BEGIN LICENSE BLOCK ***** {{{
Copyright ©2008-2009 by Kris Maglione <maglione.k at Gmail>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
}}} ***** END LICENSE BLOCK *****/
var EXPORTED_SYMBOLS = ["storage", "Timer"];
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
// XXX: does not belong here
function Timer(minInterval, maxInterval, callback) {
let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this.doneAt = 0;
this.latest = 0;
this.notify = function (aTimer) {
timer.cancel();
this.latest = 0;
// minInterval is the time between the completion of the command and the next firing
this.doneAt = Date.now() + minInterval;
try {
callback(this.arg);
}
finally {
this.doneAt = Date.now() + minInterval;
}
};
this.tell = function (arg) {
if (arguments.length > 0)
this.arg = arg;
let now = Date.now();
if (this.doneAt == -1)
timer.cancel();
let timeout = minInterval;
if (now > this.doneAt && this.doneAt > -1)
timeout = 0;
else if (this.latest)
timeout = Math.min(timeout, this.latest - now);
else
this.latest = now + maxInterval;
timer.initWithCallback(this, Math.max(timeout, 0), timer.TYPE_ONE_SHOT);
this.doneAt = -1;
};
this.reset = function () {
timer.cancel();
this.doneAt = 0;
};
this.flush = function () {
if (this.doneAt == -1)
this.notify();
};
}
function getFile(name) {
let file = storage.infoPath.clone();
file.append(name);
return file;
}
function readFile(file) {
let fileStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
let stream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream);
try {
fileStream.init(file, -1, 0, 0);
stream.init(fileStream, "UTF-8", 4096, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); // 4096 bytes buffering
let hunks = [];
let res = {};
while (stream.readString(4096, res) != 0)
hunks.push(res.value);
stream.close();
fileStream.close();
return hunks.join("");
}
catch (e) {}
}
function writeFile(file, data) {
if (!file.exists())
file.create(file.NORMAL_FILE_TYPE, 0600);
let fileStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
let stream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
fileStream.init(file, 0x20 | 0x08 | 0x02, 0600, 0); // PR_TRUNCATE | PR_CREATE | PR_WRITE
stream.init(fileStream, "UTF-8", 0, 0);
stream.writeString(data);
stream.close();
fileStream.close();
}
var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
var prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.liberator.datastore.");
function getCharPref(name) {
try {
return prefService.getComplexValue(name, Ci.nsISupportsString).data;
}
catch (e) {}
}
function setCharPref(name, value) {
var str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString);
str.data = value;
return prefService.setComplexValue(name, Ci.nsISupportsString, str);
}
function loadPref(name, store, type) {
try {
if (store)
var pref = getCharPref(name);
if (!pref && storage.infoPath)
var file = readFile(getFile(name));
if (pref || file)
var result = JSON.parse(pref || file);
if (pref) {
prefService.clearUserPref(name);
savePref({ name: name, store: true, serial: pref });
}
if (result instanceof type)
return result;
}
catch (e) {}
}
function savePref(obj) {
if (obj.privateData && storage.privateMode)
return;
if (obj.store && storage.infoPath)
writeFile(getFile(obj.name), obj.serial);
}
var prototype = {
OPTIONS: ["privateData"],
fireEvent: function (event, arg) { storage.fireEvent(this.name, event, arg); },
save: function () { savePref(this); },
init: function (name, store, data, options) {
this.__defineGetter__("store", function () store);
this.__defineGetter__("name", function () name);
for (let [k, v] in Iterator(options))
if (this.OPTIONS.indexOf(k) >= 0)
this[k] = v;
this.reload();
}
};
function ObjectStore(name, store, load, options) {
var object = {};
this.reload = function reload() {
object = load() || {};
this.fireEvent("change", null);
};
this.init.apply(this, arguments);
this.__defineGetter__("serial", function () JSON.stringify(object));
this.set = function set(key, val) {
var defined = key in object;
var orig = object[key];
object[key] = val;
if (!defined)
this.fireEvent("add", key);
else if (orig != val)
this.fireEvent("change", key);
};
this.remove = function remove(key) {
var ret = object[key];
delete object[key];
this.fireEvent("remove", key);
return ret;
};
this.get = function get(val, default_) val in object ? object[val] : default_;
this.clear = function () {
object = {};
};
this.__iterator__ = function () Iterator(object);
}
ObjectStore.prototype = prototype;
function ArrayStore(name, store, load, options) {
var array = [];
this.reload = function reload() {
array = load() || [];
this.fireEvent("change", null);
};
this.init.apply(this, arguments);
this.__defineGetter__("serial", function () JSON.stringify(array));
this.__defineGetter__("length", function () array.length);
this.set = function set(index, value) {
var orig = array[index];
array[index] = value;
this.fireEvent("change", index);
};
this.push = function push(value) {
array.push(value);
this.fireEvent("push", array.length);
};
this.pop = function pop(value) {
var ret = array.pop();
this.fireEvent("pop", array.length);
return ret;
};
this.truncate = function truncate(length, fromEnd) {
var ret = array.length;
if (array.length > length) {
if (fromEnd)
array.splice(0, array.length - length);
array.length = length;
this.fireEvent("truncate", length);
}
return ret;
};
// XXX: Awkward.
this.mutate = function mutate(aFuncName) {
var funcName = aFuncName;
arguments[0] = array;
array = Array[funcName].apply(Array, arguments);
this.fireEvent("change", null);
};
this.get = function get(index) {
return index >= 0 ? array[index] : array[array.length + index];
};
this.__iterator__ = function () Iterator(array);
}
ArrayStore.prototype = prototype;
var keys = {};
var observers = {};
var timers = {};
var storage = {
alwaysReload: {},
newObject: function newObject(key, constructor, params) {
if (!params.reload && !params.store) {
let enumerator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator).getEnumerator("navigator:browser");
params.reload = enumerator.hasMoreElements() && enumerator.getNext() && !enumerator.hasMoreElements();
}
if (!(key in keys) || params.reload || this.alwaysReload[key]) {
if (key in this && !(params.reload || this.alwaysReload[key]))
throw Error();
let load = function () loadPref(key, params.store, params.type || Object);
keys[key] = new constructor(key, params.store, load, params);
timers[key] = new Timer(1000, 10000, function () storage.save(key));
this.__defineGetter__(key, function () keys[key]);
}
return keys[key];
},
newMap: function newMap(key, options) {
return this.newObject(key, ObjectStore, options);
},
newArray: function newArray(key, options) {
return this.newObject(key, ArrayStore, options);
},
addObserver: function addObserver(key, callback, ref) {
if (ref) {
if (!ref.liberatorStorageRefs)
ref.liberatorStorageRefs = [];
ref.liberatorStorageRefs.push(callback);
var callbackRef = Cu.getWeakReference(callback);
}
else {
callbackRef = { get: function () callback };
}
this.removeDeadObservers();
if (!(key in observers))
observers[key] = [];
if (!observers[key].some(function (o) o.callback.get() == callback))
observers[key].push({ ref: ref && Cu.getWeakReference(ref), callback: callbackRef });
},
removeObserver: function (key, callback) {
this.removeDeadObservers();
if (!(key in observers))
return;
observers[key] = observers[key].filter(function (elem) elem.callback.get() != callback);
if (observers[key].length == 0)
delete obsevers[key];
},
removeDeadObservers: function () {
for (let [key, ary] in Iterator(observers)) {
observers[key] = ary = ary.filter(function (o) o.callback.get() && (!o.ref || o.ref.get() && o.ref.get().liberatorStorageRefs));
if (!ary.length)
delete observers[key];
}
},
get observers() observers,
fireEvent: function fireEvent(key, event, arg) {
if (!(key in this))
return;
this.removeDeadObservers();
// Safe, since we have our own Array object here.
if (key in observers)
for each (let observer in observers[key])
observer.callback.get()(key, event, arg);
timers[key].tell();
},
load: function load(key) {
if (this[key].store && this[key].reload)
this[key].reload();
},
save: function save(key) {
savePref(keys[key]);
},
saveAll: function storeAll() {
for each (let obj in keys)
savePref(obj);
},
_privateMode: false,
get privateMode() this._privateMode,
set privateMode(val) {
if (!val && this._privateMode)
for (let key in keys)
this.load(key);
return this._privateMode = Boolean(val);
}
};
// vim: set fdm=marker sw=4 sts=4 et ft=javascript:
| JavaScript |
var EXPORTED_SYMBOLS = ["convert"];
const Cu = Components.utils;
//
// STATE
// ALL
// 0 TYPE
// TEMPLATE
// 1 HAS_HANDLER
// 2 RESULT
// 3 RAW
// 4 SUBSTITUDE
// ROUND1
// 1 keyword
function convert(str, options) {
function fnRawEscape(str) {
return ({
"\n": "\\n\\\n",
"\r\n": "\\n\\\n",
"\r": "\\n\\\n",
'"': '\\"',
"\\": '\\\\',
})[str];
}
const reRawEscape = /\r\n?|\n|"|\\/g;
const reEOL = /\r\n|[\r\n]/g;
//const TEMPLATE = {}, TEMPLATE_PORTION = {}, SQUARE = {}, ROUND = {}, CURLY = {}, ROUND1 = {}, ROOT = {};
const TEMPLATE = {s:"t"}, TEMPLATE_PORTION = {s: "tp"}, SQUARE = {s: "s["}, ROUND = {s:"s("}, CURLY = {s:"s{"}, ROUND1 = {s:"fn"}, ROUND1IN = {s: "in("}, ROOT = {s:"r"};
const TYPE = 0, HAS_HANDLER = 1, RESULT = 2, RAW = 3, SUBSTITUDE = 4;
var c, c0, c1, m, q_str, i, j;
var start = 0, offset = 0;
var isOp = false;
var whiteSpace = /^\s*/y;
var op = "!\"#%&'()=-~^\\`@+;*:{[}]<>,?/";
var idToken = new RegExp("^[^\\" + op.split("").join("\\") + "\\s]+", "y");
var expressionToken = /^\s*\(/y;
var reOpt = /^[igmy]*/y;
var last = str.length;
var stack = [];
const BackSlash = '\\';
var RET = '\r';
var NL = '\n';
var BQ = '`';
var $ = '$';
var re;
var depth = 0;
var state = [ROOT, null]; //xxx:
var raw, substitude, args, hasHandler, cooked;
res = "";
root_loop: while (offset < last) {
// white space
whiteSpace.lastIndex = offset;
m = whiteSpace.exec(str);
if (!m) break;
offset = whiteSpace.lastIndex;
c = str[offset++];
if (!c) break;
//xxx: goto
goto_switch: while (1) {
switch (c) {
case "/":
c0 = str[offset];
if (c0 === "/") {
reEOL.lastIndex = offset;
m = reEOL.exec(str);
if (!m) break root_loop;
offset = reEOL.lastIndex;
continue root_loop;
} else if (c0 === "*") {
offset = str.indexOf("*/", offset + 1) + 2;
if (offset === 1) break root_loop;
continue root_loop;
// xxx:
} else if (isOp) {
if (c0 === "=") {
offset++;
}
isOp = false;
} else {
// RegExp Literal
var x = offset;
while (c0 = str[offset++]) {
if (c0 === "\\") {
offset++;
//} else if (c0 === NL || c0 === RET) {
// break root_loop;
} else if (c0 === "/") {
reOpt.lastIndex = offset;
m = reOpt.exec(str);
offset = reOpt.lastIndex;
break;
} else if (c0 === "[") {
while (c1 = str[offset++]) {
if (c1 === "\\") offset++;
else if (c1 === "]") {
break;
}
}
}
}
isOp = true;
}
break;
case "`":
res += str.substring(start, offset - 1);
start = offset;
stack[depth++] = state;
state = [TEMPLATE, isOp, res, [], []];
res = "";
//c = TEMPLATE_PORTION;
//continue goto_switch;
//break;
case TEMPLATE_PORTION:
start = offset;
q_str = "";
while (c0 = str[offset++]) {
if (c0 === "\\") offset++;
else if (c0 === "`") {
// end quansi literal
res = state[RESULT];
hasHandler = state[HAS_HANDLER];
args = state[RAW];
substitude = state[SUBSTITUDE];
args[args.length] = q_str + str.substring(start, offset -1);
if (hasHandler) {
raw = args;
//xxx: cooked is not implement
cooked = [];
for (i = 0, j = raw.length; i < j; i++) {
cooked[i] = raw[i].replace(/(\\*)([\r\n]+|")/g, function (str, bs, c) {
var n = bs.length;
if (n % 2) {
if (c !== '"') str = bs.substr(1);
} else {
if (c === '"') str = "\\" + str;
else {
str = bs;
}
}
return str;
});
raw[i] = raw[i].replace(reRawEscape, fnRawEscape);
}
substitude = substitude.length ? "(" + substitude.join("), (") + ")" : "";
res +=
'({\
raw: ["' + raw.join('", "') + '"],\
cooked: ["' + cooked.join('", "') + '"]' +
'}, [' + substitude + '])';
} else {
// default handler
if (args.length === 1) {
res += '"' + args[0].replace(reRawEscape, fnRawEscape) + '"';
} else {
res += '("' + args[0].replace(reRawEscape, fnRawEscape) + '"';
for (i = 0, j = substitude.length; i < j; i++) {
res += ' + (' + substitude[i] + ') + "' + args[i + 1].replace(reRawEscape, fnRawEscape) + '"';
}
res += ")";
}
}
//end flush
state = stack[--depth];
start = offset;
isOp = true;
continue root_loop;
} else if (c0 === $) {
c1 = str[offset];
// close TemplateLiteralPortion
if (c1 === "{") // c1 === "{"
{
var args = state[RAW];
args[args.length] = q_str + str.substring(start, offset -1);
offset++;
start = offset;
isOp = false;
continue root_loop;
}
}
}
break root_loop;
case "'": case '"':
//string literal
for (c0 = str[offset++]; offset < last && c0 !== c; c0 = str[offset++]) {
if (c0 === BackSlash) offset++;
}
isOp = true;
break;
case ";":
isOp = false;
break;
case ":":
if (state[TYPE] === ROUND1) {
state = stack[--depth];
}
isOp = false;
break;
case "+": case "-": case "*": case "=": case ",":
case "!": case "|": case "&": case ">": case "%": case "~":
case "^": case "<": case "?": case ";":
isOp = false;
break;
case "(":
var aType = state[TYPE];
if (aType === ROUND1) {
state[TYPE] = ROUND1IN;
} else {
stack[depth++] = state;
state = [ROUND, offset];
}
isOp = false;
break;
case ")":
switch (state[TYPE]) {
case ROUND:
state = stack[--depth];
isOp = true;
break;
case ROUND1IN:
state = stack[--depth];
isOp = false;
break;
default:
break root_loop;
throw SynstaxError("MissMatch:)");
break;
}
break;
case "{":
stack[depth++] = state;
state = [CURLY, null, offset];
isOp = false;
break;
case "}":
switch (state[TYPE]) {
// Template's Substitution
case TEMPLATE:
args = state[SUBSTITUDE];
args[args.length] = res + str.substring(start, offset - 1);
res = "";
c = TEMPLATE_PORTION;
start = offset;
continue goto_switch;
case CURLY:
state = stack[--depth];
isOp = false;
break;
default:
break root_loop;
throw SynstaxError("MissMatch:}");
}
break;
case "[":
stack[depth++] = state;
state = [SQUARE, null];
isOp = false;
break;
case "]":
if (state[0] === SQUARE) {
state = stack[--depth];
isOp = true;
//xxx: error
} else { break root_loop; } //throw SyntaxError();
break;
default:
//xxx: e4x attribute
if (c === "@" && str[offset - 2] === ".") {
if (str[offset++] === "*") {
break;
}
}
idToken.lastIndex = offset - 1;
m = idToken.exec(str);
if(!m) break root_loop;
word = m[0];
if (state[TYPE] === ROUND1 && state[1] === "let") {
state = stack[--depth];
} else {
switch (word) {
case "get": case "set":
offset = idToken.lastIndex;
goto_getset: while (1) {
whiteSpace.lastIndex = offset;
m = whiteSpace.exec(str);
if (!m) break root_loop;
offset = whiteSpace.lastIndex;
c = str[offset++];
if (c === "/") {
c = str[offset++];
if (c === "*") {
// skip comment
offset = str.indexOf("*/", offset) + 2;
if (offset === 1) break root_loop;
} else if (c === "/") {
// skip line
reEOL.lastIndex = offset;
m = reEOL.exec(str);
if (!m) break root_loop;
offset = reEOL.lastIndex;
} else {
// c is divide
continue goto_switch;
}
} else {
if (op.indexOf(c) >= 0) {
// get/set is variable name
isOp = true;
} else {
// c is getter/setter name
isOp = true;
stack[depth++] = state;
state = [ROUND1, word, offset];
}
continue goto_switch;
}
} break;
case "if": case "while": case "for": case "with": case "catch": case "function": case "let":
offset = idToken.lastIndex;
if (word === "if" && state[TYPE] === ROUND1IN && state[1] === "catch") {
state = [ROUND, offset, state];
} else {
stack[depth++] = state;
state = [ROUND1, word, offset];
}
isOp = false;
break;
case "delete": case "new": case "return": case "yield": case "in": case "instanceof":
case "case": case "typeof": case "var": case "const": case "void": case "else":
offset = idToken.lastIndex;
isOp = false;
break;
default:
offset = idToken.lastIndex;
isOp = true;
}
}
break;
}
break; } // goto_switch: while (1)
}
if (depth > 0) {
reEOL.lastIndex = 0;
let lineNumber = (str.substr(0, offset).match(reEOL)||[]).length + 1;
Cu.reportError([lineNumber, str.substr(offset -16, 16).quote(), str.substr(offset, 16).quote()]);
Cu.reportError(JSON.stringify(stack.slice(0, depth), null, 1));
// force build source
stack[depth] = state;
Cu.reportError(JSON.stringify(stack.slice(0, depth + 1), null, 1));
let rest = str.substring(start);
while (state = stack[depth--]) {
if (state[0] === TEMPLATE) {
let [,,tag, raw, args] = state;
raw = raw.map(function (r) '"' + r.replace(reRawEscape, fnRawEscape) + '"');
if (raw.length === args.length) {
raw.push('`"' + rest.replace(reRawEscape, fnRawEscape) + '"`');
} else {
args.push("`" + res + rest + "`");
res = "";
}
rest = tag + "(({raw: [" + raw.join(", ") + "]}), [" + args.join(", ") + "])";
break;
}
}
while (state = stack[depth--]) {
if (state[0] === TEMPLATE) {
let [,,tag, raw, args] = state;
raw = raw.map(function (r) '"' + r.replace(reRawEscape, fnRawEscape) + '"');
args.push(rest);
rest = tag + "(({raw: [" + raw.join(", ") + "]}), [" + args.join(", ") + "])";
}
}
return res + rest;
}
return res + str.substring(start);
}
| JavaScript |
// vim: set fdm=marker:
var EXPORTED_SYMBOLS = ["raw", "safehtml", "tmpl", "xml", "e4x", "cooked"];
// {{{ escape function
//var obj1 = {};
//var obj2 = {};
//var c;
//
//function $s(s) {
// s = s.quote();
// return s.substring(1, s.length -1);
//}
//for (var i = 0, j = 0x7fff; i < j; i++) {
// c = String.fromCharCode(i);
// var xml = <>{c}</>.toXMLString();
// if (xml !== c) obj1[$s(c)] = xml;
// xml = <a a={c}/>.@a.toXMLString();
// if (xml !== c) obj2[$s(c)] = xml;
//}
//alert(JSON.stringify([obj1, obj2], null, 1));
function createEscapeFunc(obj) {
const c2c = obj;
const re = new RegExp("[" + [c for (c in c2c)].join("") + "]", "g");
return function _escapeFunc(s) String(s).replace(re, function (c) c2c[c]);
}
var escapeHTML = createEscapeFunc({
//"\r": "\n",
"&": "&",
"<": "<",
">": ">",
"\u2028": "\n",
"\u2029": "\n"
});
var escapeAttribute = createEscapeFunc({
"\t": "	",
"\n": "
",
"\r": "
",
"\"": """,
"&": "&",
"<": "<",
"\u2028": "
",
"\u2029": "
"
});
function escapeBackQuote(s) {
return String.replace(s, /`/g, "\\`");
}
function encodeTmplXml(xml) {
return "`" + String.replace(s, /`/g, "\\`") + "`";
}
function encodeTmplText(text) {
return "{" + String.replace(s, /}/g, "\\}") + "}";
}
// }}}
function TemplateSupportsXML() {}
function TemplateXML(s) {this.value = s;}
TemplateXML.prototype = new TemplateSupportsXML;
TemplateXML.prototype.toString = function () this.value;
function TemplateTmpl(s) {this.value = s;} //{{{
TemplateTmpl.prototype = new TemplateSupportsXML;
TemplateTmpl.prototype.toString = function () this.value;
TemplateTmpl.prototype.toXMLString = function () {
var str = this.value;
const whiteSpace = /^\s*/y;
const tagToken = /^([^`"',\s\[\]\{\}\(\)]+)\s*(\[)?/y;
const attrToken = /^\s*([^\s=]+)\s*=\s*(\S)/y;
const attrSep = /^\s*(\s|])/y;
const STATE = 0, NAME = 1, OPEN = 2;
const TAG = {}, ROOT = {}, GROUP = {};
var offset = 0;
var start = 0;
var res = "";
var stack = [];
var depth = 0;
var state = [ROOT];
var m;
label_root: while (1) {
whiteSpace.lastIndex = offset;
m = whiteSpace.exec(str);
if (!m) throw SyntaxError("ws");
offset = whiteSpace.lastIndex;
c = str[offset++];
if (!c) break;
switch (c) {
case "{":
if (state[STATE] === TAG && state[OPEN]) {
res += ">";
state[OPEN] = false;
}
start = offset;
while (c = str[offset++]) {
if (c === "\\") {
res += str.substring(start, offset - 1);
start = offset++;
}
else if (c === "}") {
res += escapeHTML(str.substring(start, offset - 1));
continue label_root;
}
}
throw SyntaxError("text");
case "`":
if (state[STATE] === TAG && state[OPEN]) {
res += ">";
state[OPEN] = false;
}
start = offset;
while (c = str[offset++]) {
if (c === "\\") {
res += str.substring(start, offset - 1);
start = offset++;
} else if (c === "`") {
res += str.substring(start, offset - 1);
continue label_root;
}
}
throw SyntaxError("xml");
case "(":
if (state[STATE] === TAG && state[OPEN]) {
res += ">";
state[OPEN] = false;
}
stack[depth++] = state;
state = [GROUP];
break;
case ")":
do {
switch (state[STATE]) {
case TAG:
if (state[OPEN]) {
res += "/>";
state[OPEN] = false;
} else {
res += "</" + state[NAME] + ">";
}
break;
case GROUP:
state = stack[--depth];
continue label_root;
case ROOT:
throw SyntaxError(")");
}
} while (state = stack[--depth]);
throw SyntaxError(")");
case ",":
do {
switch (state[STATE]) {
case TAG:
if (state[OPEN]) {
res += "/>";
state[OPEN] = false;
} else {
res += "</" + state[NAME] + ">";
}
break;
case GROUP:
case ROOT:
continue label_root;
}
} while (state = stack[--depth]);
throw SyntaxError(")");
default:
if (state[STATE] === TAG && state[OPEN]) {
res += ">";
state[OPEN] = false;
}
tagToken.lastIndex = offset - 1;
m = tagToken.exec(str);
if (!m) throw SyntaxError("tag");
offset = tagToken.lastIndex;
res += "<" + m[1];
stack[depth++] = state;
state = [TAG, m[1], true];
if (m[2]) {
label_attr: while (1) {
attrToken.lastIndex = offset;
m = attrToken.exec(str);
if (!m) throw new SyntaxError("attr");
offset = attrToken.lastIndex;
res += " " + m[1] + "=";
start = offset;
close = m[2];
while (c = str[offset++]) {
if (c === close) {
res += close + str.substring(start, offset - 1) + close;
attrSep.lastIndex = offset;
m = attrSep.exec(str);
if (!m) throw SyntaxError("attr sep");
offset = attrSep.lastIndex;
if (m[1] === "]") {
break label_attr;
}
continue label_attr;
}
}
}
}
break;
}
}
if (state[STATE] === TAG) res += state[OPEN] ? "/>" : "</" + state[NAME] + ">";
while (state = stack[--depth]) {
if (state[STATE] === TAG)
res += "</" + state[NAME] + ">";
}
return res;
};//}}}
function templateTmpl(portion, args) // {{{
{
var res = "";
const BODY = {}, ATTR1 = {}, ATTR2 = {}, TEXT = {}, XML = {};
var c;
var raw = portion.raw;
var i = 0, j = args.length;
var depth = 0;
var state = BODY, offset = 0;
var str = raw[0], arg = args[0];
var res = str;
label_root: while (1) {
switch(state) {
case BODY:
while (c = str[offset++]) {
switch (c) {
case "[":
state = ATTR1;
continue label_root;
case "`":
state = XML;
continue label_root;
case "{":
state = TEXT;
continue label_root;
case "(":
depth++;
break;
case ")":
if (--depth < 0) throw SyntaxError("depth");
break;
}
}
if (i >= j) break label_root;
else if (typeof arg === "xml") {
res += "`" + arg.toXMLString().replace(/([\\`])/g, "\\$1", "g") + "`";
} else if (arg instanceof TemplateTmpl) {
res += "(" + arg.value + ")";
} else if (arg instanceof TemplateXML) {
res += "`" + arg.value.replace(/([\\`])/g, "\\$1", "g") + "`";
} else {
res += "{" + String.replace(arg, /([\\}])/g, "\\$1") + "}";
}
break;
case ATTR1:
while (c = str[offset++]) {
if (c === "=") {
state = ATTR2;
continue label_root;
} else if (c === "]") {
state = BODY;
continue label_root;
}
}
if (i >= j) throw SyntaxError("attr left");
arg = String(arg);
if (/[=\[\]!"#$%&']/.test(arg)) throw SyntaxError("substitude:" + i);
res += arg;
break;
case ATTR2:
c1 = str[offset++];
if (!c1) {
if (i >= j) throw SyntaxError("attr right");
arg = String(arg);
res += '"' + String.replace(arg, /"/g, '\\"', "g") + '"';
state = ATTR1;
break;
}
else if (c1 === "{") c1 = "}";
while (c = str[offset++]) {
if (c === "\\") offset++;
else if (c === c1) {
state = ATTR1;
continue label_root;
}
}
// do not support attribute's value nesting
throw SyntaxError("attr2");
break;
case TEXT:
while (c = str[offset++]) {
if (c === "\\") offset++;
else if (c === "}") {
state = BODY;
continue label_root;
}
}
if (i >= j) throw SyntaxError("text");
arg = String(arg);
res += '{' + String.replace(arg, /}/g, '\\}', "g") + '}';
break;
case XML:
while (c = str[offset++]) {
if (c === "\\") offset++;
else if (c === "`") {
state = BODY;
continue label_root;
}
}
// do not support xml nesting
throw SyntaxError("xml");
break;
default:
throw SyntaxError("unknown state");
}
str = raw[++i];
arg = args[i];
res += str;
offset = 0;
}
if (depth !== 0) throw SyntaxError("depth");
return new TemplateTmpl(res);
}
// xxx: no check
templateTmpl.raw = function templateTmplRaw(portion, args) {
return new TemplateTmpl(templateRaw(portion, args));
};
templateTmpl.map = function templateTmplMap(data, fn) {
var val, res = "";
for (var i = 0, j = data.length; i < j; i++) {
val = fn(data[i]);
if (val instanceof TemplateTmpl)
res += "(" + val.value + ")";
else if (typeof val === "xml")
res += encodeTmplXml(val.toXMLString());
else if (val instanceof TemplateXML)
res += encodeTmplXml(val.value);
else
res += encodeTmplText(val);
}
return new TemplateTmpl(res);
};
templateTmpl.is = function is(obj) {
return obj instanceof TemplateTmpl;
};
templateTmpl.isEmpty = function isEmpty() {
return (value instanceof TemplateXML || value instanceof TemplateTmpl) && value.value === "";
};
templateTmpl["+="] = function (self, value) {
if (!(self instanceof TemplateTmpl)) throw SyntaxError();
else if (value instanceof TemplateTmpl)
self.value += "(" + value.value + ")";
else if (value instanceof TemplateXML)
self.value += "`" + value.value.replace(/`/g, "\\`") + "`";
else if (typeof value === "xml")
self.value += "`" + value.toXMLString().replace(/`/g, "\\`") + "`";
else
self.value = "{" + String(value).replace(/}/g, "\\}") + "}";
return self;
};
//}}}
function templateXML(portion, args) // {{{
{
var res = "";
const BODY = {}, ATTR1 = {}, ATTR2 = {}, TEXT = {}, XML = {}, CC = {}, TAG_OPEN = {} , TAG_CLOSE = {};
var c;
var raw = portion.raw;
var i = 0, j = args.length;
const whiteSpace = /^\s*/y;
var state = BODY, offset = 0;
var str = raw[0], arg = args[0];
var res = str;
var str2, close;
var depth = 0;
function DepthError() {
throw SyntaxError("depth erro: " + [depth, offset, str.substr(offset - 8, 16), res.substr(-32), (new Error).stack]);
}
label_root: while (1) {
switch(state) {
case BODY:
while (c = str[offset++]) {
if (c === "<") {
offset--;
str2 = str.substr(offset, 16);
if (!str2.lastIndexOf("<![CDATA[", 0)) {
state = CC;
close = "]]>";
offset += 9;
continue label_root;
} else if (!str2.lastIndexOf("<!--", 0)) {
state = CC;
close = "-->";
offset += 4;
continue label_root;
} else if (!str2.lastIndexOf("</", 0)) {
if (--depth < 0) DepthError();
state = TAG_CLOSE;
offset += 2;
continue label_root;
} else if (str2[0] === "<") {
state = TAG_OPEN;
offset++;
if (/\s|>/.test(str[offset])) throw SyntaxError("tagname");
continue label_root;
}
throw SyntaxError("body: " + offset);
}
}
if (i >= j) break label_root;
else if (arg instanceof TemplateTmpl || typeof arg === "xml") {
res += arg.toXMLString();
} else if (arg instanceof TemplateXML) {
res += arg.value;
} else if (arg instanceof TemplateSupportsXML) {
res += (arg.toXMLString || arg.toString)();
} else {
res += escapeHTML(arg);
}
break;
case CC:
offset = str.indexOf(close, offset);
if (offset === -1) {
if (i >= j) throw SyntaxError(close);
res += escapeHTML(arg);
break;
}
offset += close.length;
state = BODY;
continue label_root;
case TAG_OPEN:
while (c = str[offset++]) {
if (!/\s/.test(c)) {
state = ATTR1;
continue label_root;
}
}
if (i >= j) throw SyntaxError("tag");
arg = String(arg);
//if (/\s/.test(arg)) throw SyntaxError("tagname");
res += arg;
break;
case TAG_CLOSE:
while (c = str[offset++]) {
if (c === ">") {
state = BODY;
continue label_root;
} //else if (chk) throw SyntaxError("closetag");
}
if (i >= j) throw SyntaxError("tag close");
arg = String(arg);
//if (/\s/.test(arg)) throw SyntaxError("closetagname");
res += arg;
break;
case ATTR1:
while (c = str[offset++]) {
if (c === "=") {
state = ATTR2;
continue label_root;
} else if (c === ">") {
depth++;
state = BODY;
continue label_root;
} else if (c === "/") {
c = str[offset++];
if (c === ">") {
state = BODY;
continue label_root;
}
else throw SyntaxError("/");
}
}
if (i >= j) throw SyntaxError("attr left");
arg = String(arg);
res += arg;
break;
case ATTR2:
whiteSpace.lastIndex = offset;
whiteSpace.exec(str);
offset = whiteSpace.lastIndex;
close = str[offset++];
if (!close) {
if (i >= j) throw SyntaxError("attr right");
res += '"' + escapeAttribute(arg) + '"';
state = ATTR1;
break;
} else if (close === '"' || close === "'") {
while (c = str[offset++]) {
if (c === close) {
state = ATTR1;
continue label_root;
}
}
}
throw SyntaxError("attr2");
default:
throw SyntaxError("unknown state");
}
str = raw[++i];
arg = args[i];
res += str;
offset = 0;
}
if (depth !== 0) DepthError();
return new TemplateXML(res);
}
templateXML.map = function templateXmlMap(data, fn) {
var val, res = "";
for (var i = 0, j = data.length; i < j; i++) {
val = fn(data[i]);
if (val instanceof TemplateTmpl || typeof val === "xml")
res += val.toXMLString();
else if (val instanceof TemplateXML)
res += val.value;
else
res += val;
}
return new TemplateXML(res);
}
// xxx: xml check
templateXML.raw = function templateXmlRaw(portion, args) {
var str = templateRaw(portion, args);
var ps = new DOMParser
var doc = ps.parseFromString("<root>" + str + "</root>", "text/xml");
if (doc.documentElement.tagName === "parsererror") {
throw SyntaxError(doc.documentElement.childNodes[0].data);
}
return new TemplateXML(str);
};
templateXML.cdata = function templateXmlCDATA(portion, args) {
return new TemplateXML("<![CDATA[" + templateRaw(portion, args).replace(/>/g, ">") + "]]>");
};
templateXML["+="] = function (self, value) {
if (!(self instanceof TemplateXML)) throw SyntaxError();
else if (value instanceof TemplateTmpl)
self.value += value.toXMLString();
else if (value instanceof TemplateXML)
self.value += value.value;
else if (typeof value === "xml")
self.value += value.toXMLString();
else
self.value += escapeHTML(value);
return self;
};
templateXML.is = function is(obj) {
return obj instanceof TemplateXML;
};
templateXML.isEmpty = function (value) {
return (value instanceof TemplateXML || value instanceof TemplateTmpl) && value.value === "";
};
//}}}
function templateRaw(portion, args) {
var raw = portion.raw;
var i = 0, j = args.length, res = raw[0];
while (i < j) {
res += args[i++];
res += raw[i];
}
return res;
}
function templateCooked(portion, args) {
var str = portion.cooked;
var i = 0, j = args.length, res = str[0];
while (i < j) {
res += args[i++];
res += str[i];
}
return res;
}
function templateSafeHtml(portion, args) {
var raw = portion.raw;
var i = 0, j = args.length, res = raw[0];
while (i < j) {
res += escapeHTML(args[i++]);
res += raw[i];
}
return res;
}
function templateE4X(portion, args) // e4x {{{
{
try {
return new XMLList(templateXML(portion, args).value);
} catch (ex) {
alert(ex.stack);
throw ex;
}
}
templateE4X.raw = function raw(portion, args) {
return new XMLList(templateRaw(portion, args));
};
templateE4X.cdata = function cdata(portion, args) {
return new XMLList("<![CDATA[" + templateRaw(portion, args).replace(/>/g, ">") + "]]>");
};
templateE4X["+"] = function operatorPlus(lhs, rhs) {
function toE4X(a) {
if (a instanceof TemplateTmpl)
return new XMLList(a.toXMLString());
else if (a instanceof TemplateXML)
return new XMLList(a.toString());
else
return a;
}
return toE4X(lhs) + toE4X(rhs);
};
// xxx: xml object to E4X
templateE4X.cast = function cast(obj) {
if (obj instanceof TemplateTmpl)
return new XMLList(obj.toXMLString());
else if (obj instanceof TemplateXML)
return new XMLList(obj.value);
else
return obj;
};
templateE4X["+="] = function (self, value) {
if (typeof self !== "xml") throw SyntaxError();
self += templateE4X.cast(value);
return self;
};
//}}}
var tmpl = templateTmpl;
var xml = templateXML;
var e4x = templateE4X;
var raw = templateRaw;
var cooked = templateCooked;
var safehtml = templateSafeHtml;
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Some code based on Venkman
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
plugins.contexts = {};
const Script = Class("Script", {
init: function (file) {
let self = plugins.contexts[file.path];
if (self) {
if (self.onUnload)
self.onUnload();
return self;
}
plugins.contexts[file.path] = this;
this.NAME = file.leafName.replace(/\..*/, "").replace(/-([a-z])/g, function (m, n1) n1.toUpperCase());
this.PATH = file.path;
this.toString = this.toString;
this.__context__ = this;
this.__proto__ = plugins;
// This belongs elsewhere
for (let dir of io.getRuntimeDirectories("plugin")) {
if (dir.contains(file, false))
plugins[this.NAME] = this;
}
return this;
}
});
/**
* @class File A class to wrap nsIFile objects and simplify operations
* thereon.
*
* @param {nsIFile|string} path Expanded according to {@link IO#expandPath}
* @param {boolean} checkPWD Whether to allow expansion relative to the
* current directory. @default true
*/
const File = Class("File", {
init: function (path, checkPWD) {
if (arguments.length < 2)
checkPWD = true;
let file = services.create("file");
if (path instanceof Ci.nsIFile)
file = path;
else if (/file:\/\//.test(path))
file = services.create("file:").getFileFromURLSpec(path);
else {
let expandedPath = File.expandPath(path);
if (!File.isAbsolutePath(expandedPath) && checkPWD)
file = File.joinPaths(io.getCurrentDirectory().path, expandedPath);
else
file.initWithPath(expandedPath);
}
let self = XPCNativeWrapper(file);
self.__proto__ = File.prototype;
return self;
},
/**
* Iterates over the objects in this directory.
*/
iterDirectory: function () {
if (!this.isDirectory())
throw Error("Not a directory");
let entries = this.directoryEntries;
while (entries.hasMoreElements())
yield File(entries.getNext().QueryInterface(Ci.nsIFile));
},
/**
* Returns the list of files in this directory.
*
* @param {boolean} sort Whether to sort the returned directory
* entries.
* @returns {nsIFile[]}
*/
readDirectory: function (sort) {
if (!this.isDirectory())
throw Error("Not a directory");
let array = [e for (e in this.iterDirectory())];
if (sort)
array.sort(function (a, b) b.isDirectory() - a.isDirectory() || String.localeCompare(a.path, b.path));
return array;
},
/**
* Reads this file's entire contents in "text" mode and returns the
* content as a string.
*
* @param {string} encoding The encoding from which to decode the file.
* @default options["fileencoding"]
* @returns {string}
*/
read: function (encoding) {
let ifstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
let icstream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream);
if (!encoding)
encoding = options["fileencoding"];
ifstream.init(this, -1, 0, 0);
icstream.init(ifstream, encoding, 4096, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); // 4096 bytes buffering
let buffer = [];
let str = {};
while (icstream.readString(4096, str) != 0)
buffer.push(str.value);
icstream.close();
ifstream.close();
return buffer.join("");
},
/**
* Writes the string <b>buf</b> to this file.
*
* @param {string} buf The file content.
* @param {string|number} mode The file access mode, a bitwise OR of
* the following flags:
* {@link #MODE_RDONLY}: 0x01
* {@link #MODE_WRONLY}: 0x02
* {@link #MODE_RDWR}: 0x04
* {@link #MODE_CREATE}: 0x08
* {@link #MODE_APPEND}: 0x10
* {@link #MODE_TRUNCATE}: 0x20
* {@link #MODE_SYNC}: 0x40
* Alternatively, the following abbreviations may be used:
* ">" is equivalent to {@link #MODE_WRONLY} | {@link #MODE_CREATE} | {@link #MODE_TRUNCATE}
* ">>" is equivalent to {@link #MODE_WRONLY} | {@link #MODE_CREATE} | {@link #MODE_APPEND}
* @default ">"
* @param {number} perms The file mode bits of the created file. This
* is only used when creating a new file and does not change
* permissions if the file exists.
* @default 0644
* @param {string} encoding The encoding to used to write the file.
* @default options["fileencoding"]
*/
write: function (buf, mode, perms, encoding) {
let ofstream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
function getStream(defaultChar) {
let stream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
stream.init(ofstream, encoding, 0, defaultChar);
return stream;
}
if (!encoding)
encoding = options["fileencoding"];
if (mode == ">>")
mode = File.MODE_WRONLY | File.MODE_CREATE | File.MODE_APPEND;
else if (!mode || mode == ">")
mode = File.MODE_WRONLY | File.MODE_CREATE | File.MODE_TRUNCATE;
if (!perms)
perms = 0644;
ofstream.init(this, mode, perms, 0);
let ocstream = getStream(0);
try {
ocstream.writeString(buf);
}
catch (e) {
// liberator.log(e);
if (e.result == Cr.NS_ERROR_LOSS_OF_SIGNIFICANT_DATA) {
ocstream = getStream("?".charCodeAt(0));
ocstream.writeString(buf);
return false;
}
else
throw e;
}
finally {
try {
ocstream.close();
}
catch (e) {}
ofstream.close();
}
return true;
}
}, {
/**
* @property {number} Open for reading only.
* @final
*/
MODE_RDONLY: 0x01,
/**
* @property {number} Open for writing only.
* @final
*/
MODE_WRONLY: 0x02,
/**
* @property {number} Open for reading and writing.
* @final
*/
MODE_RDWR: 0x04,
/**
* @property {number} If the file does not exist, the file is created.
* If the file exists, this flag has no effect.
* @final
*/
MODE_CREATE: 0x08,
/**
* @property {number} The file pointer is set to the end of the file
* prior to each write.
* @final
*/
MODE_APPEND: 0x10,
/**
* @property {number} If the file exists, its length is truncated to 0.
* @final
*/
MODE_TRUNCATE: 0x20,
/**
* @property {number} If set, each write will wait for both the file
* data and file status to be physically updated.
* @final
*/
MODE_SYNC: 0x40,
/**
* @property {number} With MODE_CREATE, if the file does not exist, the
* file is created. If the file already exists, no action and NULL
* is returned.
* @final
*/
MODE_EXCL: 0x80,
expandPathList: function (list) list.split(",").map(this.expandPath).join(","),
expandPath: function (path, relative) {
// expand any $ENV vars - this is naive but so is Vim and we like to be compatible
// TODO: Vim does not expand variables set to an empty string (and documents it).
// Kris reckons we shouldn't replicate this 'bug'. --djk
// TODO: should we be doing this for all paths?
function expand(path) path.replace(
!liberator.has("Windows") ? /\$(\w+)\b|\${(\w+)}/g
: /\$(\w+)\b|\${(\w+)}|%(\w+)%/g,
function (m, n1, n2, n3) services.get("environment").get(n1 || n2 || n3) || m
);
path = expand(path);
// expand ~
// Yuck.
if (!relative && RegExp("~(?:$|[/" + util.escapeRegex(IO.PATH_SEP) + "])").test(path)) {
// Try $HOME first, on all systems
let home = services.get("environment").get("HOME");
// Windows has its own idiosyncratic $HOME variables.
if (!home && liberator.has("Windows"))
home = services.get("environment").get("USERPROFILE") ||
services.get("environment").get("HOMEDRIVE") + services.get("environment").get("HOMEPATH");
path = home + path.substr(1);
}
// TODO: Vim expands paths twice, once before checking for ~, once
// after, but doesn't document it. Is this just a bug? --Kris
path = expand(path);
return path.replace("/", IO.PATH_SEP, "g");
},
getPathsFromPathList: function (list) {
if (!list)
return [];
// empty list item means the current directory
return list.replace(/,$/, "").split(",")
.map(function (dir) dir == "" ? io.getCurrentDirectory().path : dir);
},
replacePathSep: function (path) path.replace("/", IO.PATH_SEP, "g"),
joinPaths: function (head, tail) {
let path = this(head);
try {
path.appendRelativePath(this.expandPath(tail, true)); // FIXME: should only expand env vars and normalise path separators
// TODO: This code breaks the external editor at least in ubuntu
// because /usr/bin/gvim becomes /usr/bin/vim.gnome normalized and for
// some strange reason it will start without a gui then (which is not
// optimal if you don't start firefox from a terminal ;)
// Why do we need this code?
// if (path.exists() && path.normalize)
// path.normalize();
}
catch (e) {
return { exists: function () false, __noSuchMethod__: function () { throw e; } };
}
return path;
},
isAbsolutePath: function (path) {
try {
services.create("file").initWithPath(path);
return true;
}
catch (e) {
return false;
}
}
});
// TODO: why are we passing around strings rather than file objects?
/**
* Provides a basic interface to common system I/O operations.
* @instance io
*/
const IO = Module("io", {
requires: ["config", "services"],
init: function () {
this._processDir = services.get("dirsvc").get("CurWorkD", Ci.nsIFile);
this._cwd = this._processDir;
this._oldcwd = null;
this._lastRunCommand = ""; // updated whenever the users runs a command with :!
this._scriptNames = [];
// XXX: nsIDownloadManager is deprecated on Firefox 26
// FIXME: need to listen to download state ? -- teramako
// FIXME: need to adapt to Download.jsm instead of nsIDownloadManager
if (services.get("vc").compare(Application.version, "26.0a1") < 0) {
this.downloadListener = {
onDownloadStateChange: function (state, download) {
if (download.state == services.get("downloads").DOWNLOAD_FINISHED) {
let url = download.source.spec;
let title = download.displayName;
let file = download.targetFile.path;
let size = download.size;
liberator.echomsg("Download of " + title + " to " + file + " finished");
autocommands.trigger("DownloadPost", { url: url, title: title, file: file, size: size });
}
},
onStateChange: function () {},
onProgressChange: function () {},
onSecurityChange: function () {}
};
services.get("downloads").addListener(this.downloadListener);
} else {
let downloadListener = this.downloadListener = {
onDownloadChanged: function (download) {
if (download.succeeded) {
let {
source: { url },
target: {path: file},
totalBytes: size,
} = download;
let title = File(file).leafName;
liberator.echomsg("Download of " + title + " to " + file + " finished");
autocommands.trigger("DownloadPost", { url: url, title: title, file: file, size: size });
}
},
};
let {Downloads} = Cu.import("resource://gre/modules/Downloads.jsm", {});
Downloads.getList(Downloads.ALL)
.then(function (downloadList) {
downloadList.addView(downloadListener);
});
}
},
destroy: function () {
if (services.get("vc").compare(Application.version, "26.0a1") < 0) {
services.get("downloads").removeListener(this.downloadListener);
} else {
let {Downloads} = Cu.import("resource://gre/modules/Downloads.jsm", {});
let downloadListener = this.downloadListener;
Downloads.getList(Downloads.ALL)
.then(function (downloadList) {
downloadList.removeView(downloadListener);
});
}
for (let [, plugin] in Iterator(plugins.contexts))
if (plugin.onUnload)
plugin.onUnload();
},
/**
* @property {function} File class.
* @final
*/
File: File,
/**
* @property {Object} The current file sourcing context. As a file is
* being sourced the 'file' and 'line' properties of this context
* object are updated appropriately.
*/
sourcing: null,
/**
* Expands "~" and environment variables in <b>path</b>.
*
* "~" is expanded to to the value of $HOME. On Windows if this is not
* set then the following are tried in order:
* $USERPROFILE
* ${HOMDRIVE}$HOMEPATH
*
* The variable notation is $VAR (terminated by a non-word character)
* or ${VAR}. %VAR% is also supported on Windows.
*
* @param {string} path The unexpanded path string.
* @param {boolean} relative Whether the path is relative or absolute.
* @returns {string}
*/
expandPath: File.expandPath,
// TODO: there seems to be no way, short of a new component, to change
// the process's CWD - see https://bugzilla.mozilla.org/show_bug.cgi?id=280953
/**
* Returns the current working directory.
*
* It's not possible to change the real CWD of the process so this
* state is maintained internally. External commands run via
* {@link #system} are executed in this directory.
*
* @returns {nsIFile}
*/
getCurrentDirectory: function () {
let dir = File(this._cwd.path);
// NOTE: the directory could have been deleted underneath us so
// fallback to the process's CWD
if (dir.exists() && dir.isDirectory())
return dir;
else
return this._processDir;
},
/**
* Sets the current working directory.
*
* @param {string} newDir The new CWD. This may be a relative or
* absolute path and is expanded by {@link #expandPath}.
*/
setCurrentDirectory: function (newDir) {
newDir = newDir || "~";
if (newDir == "-") {
[this._cwd, this._oldcwd] = [this._oldcwd, this.getCurrentDirectory()];
} else {
let dir = File(newDir);
if (!dir.exists() || !dir.isDirectory()) {
liberator.echoerr("Directory does not exist: " + dir.path);
return null;
}
dir.normalize();
[this._cwd, this._oldcwd] = [dir, this.getCurrentDirectory()];
}
return this.getCurrentDirectory();
},
/**
* Returns all directories named <b>name<b/> in 'runtimepath'.
*
* @param {string} name
* @returns {nsIFile[])
*/
getRuntimeDirectories: function (name) {
let dirs = File.getPathsFromPathList(options["runtimepath"]);
dirs = dirs.map(function (dir) File.joinPaths(dir, name))
.filter(function (dir) dir.exists() && dir.isDirectory() && dir.isReadable());
return dirs;
},
/**
* Returns the first user RC file found in <b>dir</b>.
*
* @param {string} dir The directory to search.
* @param {boolean} always When true, return a path whether
* the file exists or not.
* @default $HOME.
* @returns {nsIFile} The RC file or null if none is found.
*/
getRCFile: function (dir, always) {
dir = dir || "~";
let rcFile1 = File.joinPaths(dir, "." + config.name.toLowerCase() + "rc");
let rcFile2 = File.joinPaths(dir, "_" + config.name.toLowerCase() + "rc");
if (liberator.has("Windows"))
[rcFile1, rcFile2] = [rcFile2, rcFile1];
if (rcFile1.exists() && rcFile1.isFile())
return rcFile1;
else if (rcFile2.exists() && rcFile2.isFile())
return rcFile2;
else if (always)
return rcFile1;
return null;
},
// TODO: make secure
/**
* Creates a temporary file.
*
* @returns {File}
*/
createTempFile: function () {
let file = services.get("dirsvc").get("TmpD", Ci.nsIFile);
file.append(config.tempFile);
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
return File(file);
},
/**
* Runs an external program.
*
* @param {string} program The program to run.
* @param {string[]} args An array of arguments to pass to <b>program</b>.
* @param {boolean} blocking Whether to wait until the process terminates.
*/
blockingProcesses: [],
run: function (program, args, blocking) {
args = args || [];
blocking = !!blocking;
let file;
if (File.isAbsolutePath(program))
file = File(program, true);
else {
let dirs = services.get("environment").get("PATH").split(liberator.has("Windows") ? ";" : ":");
// Windows tries the CWD first TODO: desirable?
if (liberator.has("Windows"))
dirs = [io.getCurrentDirectory().path].concat(dirs);
lookup:
for (let dir of dirs) {
file = File.joinPaths(dir, program);
try {
if (file.exists())
break;
// TODO: couldn't we just palm this off to the start command?
// automatically try to add the executable path extensions on windows
if (liberator.has("Windows")) {
let extensions = services.get("environment").get("PATHEXT").split(";");
for (let extension of extensions) {
file = File.joinPaths(dir, program + extension);
if (file.exists())
break lookup;
}
}
}
catch (e) {}
}
}
if (!file || !file.exists()) {
liberator.callInMainThread(function() {
if (services.get("threadManager").isMainThread) // does not really seem to work but at least doesn't crash Firefox
liberator.echoerr("Command not found: " + program);
}, this);
return -1;
}
let process = services.create("process");
process.init(file);
process.run(false, args.map(String), args.length);
try {
if (blocking)
while (process.isRunning)
liberator.threadYield(false, true);
}
catch (e) {
process.kill();
throw e;
}
return process.exitValue;
},
// FIXME: multiple paths?
/**
* Sources files found in 'runtimepath'. For each relative path in
* <b>paths</b> each directory in 'runtimepath' is searched and if a
* matching file is found it is sourced. Only the first file found (per
* specified path) is sourced unless <b>all</b> is specified, then
* all found files are sourced.
*
* @param {string[]} paths An array of relative paths to source.
* @param {boolean} all Whether all found files should be sourced.
*/
sourceFromRuntimePath: function (paths, all) {
let dirs = File.getPathsFromPathList(options["runtimepath"]);
let found = false;
liberator.log("Searching for \"" + paths.join(" ") + "\" in \"" + options["runtimepath"] + "\"");
outer:
for (let dir of dirs) {
for (let path of paths) {
let file = File.joinPaths(dir, path);
if (file.exists() && file.isFile() && file.isReadable()) {
io.source(file.path, false);
found = true;
if (!all)
break outer;
}
}
}
if (!found)
liberator.log("not found in 'runtimepath': \"" + paths.join(" ") + "\"");
return found;
},
/**
* Reads Ex commands, JavaScript or CSS from <b>filename</b>.
*
* @param {string} filename The name of the file to source.
* @param {boolean} silent Whether errors should be reported.
*/
source: function (filename, silent) {
let wasSourcing = this.sourcing;
try {
var file = File(filename);
this.sourcing = {
file: file.path,
line: 0
};
if (!file.exists() || !file.isReadable() || file.isDirectory()) {
if (!silent) {
if (file.exists() && file.isDirectory())
liberator.echomsg("Cannot source a directory: " + filename);
else
liberator.echomsg("Could not source: " + filename);
liberator.echoerr("Cannot open file: " + filename);
}
return;
}
// liberator.echomsg("Sourcing \"" + filename + "\" ...");
let str = file.read();
let uri = services.get("io").newFileURI(file);
// handle pure JavaScript files specially
if (/\.js$/.test(filename)) {
try {
// Workaround for SubscriptLoader caching.
let suffix = '?' + encodeURIComponent(services.get("UUID").generateUUID().toString());
liberator.loadScript(uri.spec + suffix, Script(file));
if (liberator.initialized)
liberator.initHelp();
}
catch (e) {
let err = new Error();
for (let [k, v] in Iterator(e))
err[k] = v;
err.echoerr = xml`${file.path}:${e.lineNumber}: ${e}`;
throw err;
}
}
else if (/\.css$/.test(filename))
storage.styles.registerSheet(uri.spec, false, true);
else {
let heredoc = "";
let heredocEnd = null; // the string which ends the heredoc
let lines = str.split(/\r\n|[\r\n]/);
function execute(args) { command.execute(args, special, count, { setFrom: file }); }
for (let [i, line] in Iterator(lines)) {
if (heredocEnd) { // we already are in a heredoc
if (heredocEnd.test(line)) {
execute(heredoc);
heredoc = "";
heredocEnd = null;
}
else
heredoc += line + "\n";
}
else {
this.sourcing.line = i + 1;
// skip line comments and blank lines
line = line.replace(/\r$/, "");
if (/^\s*(".*)?$/.test(line))
continue;
var [count, cmd, special, args] = commands.parseCommand(line);
var command = commands.get(cmd);
if (!command) {
let lineNumber = i + 1;
liberator.echoerr("Error detected while processing: " + file.path);
commandline.echo("line " + lineNumber + ":", commandline.HL_LINENR, commandline.APPEND_TO_MESSAGES);
liberator.echoerr("Not an editor command: " + line);
}
else {
if (command.name == "finish")
break;
else if (command.hereDoc) {
// check for a heredoc
let matches = args.match(/(.*)<<\s*(\S+)$/);
if (matches) {
args = matches[1];
heredocEnd = RegExp("^" + matches[2] + "$", "m");
if (matches[1])
heredoc = matches[1] + "\n";
continue;
}
}
execute(args);
}
}
}
// if no heredoc-end delimiter is found before EOF then
// process the heredoc anyway - Vim compatible ;-)
if (heredocEnd)
execute(heredoc);
}
if (this._scriptNames.indexOf(file.path) == -1)
this._scriptNames.push(file.path);
liberator.log("Sourced: " + filename);
}
catch (e) {
liberator.echoerr(e, null, "Sourcing file failed: ");
}
finally {
this.sourcing = wasSourcing;
}
},
// TODO: when https://bugzilla.mozilla.org/show_bug.cgi?id=68702 is
// fixed use that instead of a tmpfile
/**
* Runs <b>command</b> in a subshell and returns the output in a
* string. The shell used is that specified by the 'shell' option.
*
* @param {string} command The command to run.
* @param {string} input Any input to be provided to the command on stdin.
* @returns {string}
*/
system: function (command, input) {
liberator.echomsg("Executing: " + command);
function escape(str) '"' + str.replace(/[\\"$]/g, "\\$&") + '"';
return this.withTempFiles(function (stdin, stdout, cmd) {
if (input)
stdin.write(input);
// TODO: implement 'shellredir'
if (liberator.has("Windows")) {
if (options["shell"] == "cmd.exe") {
command = "cd /D " + this._cwd.path + " && " + command + " > " + stdout.path + " 2>&1" + " < " + stdin.path;
} else {
// in this case, assume the shell is unix-like
command = "cd " + escape(this._cwd.path) + " && " + command + " > " + escape(stdout.path) + " 2>&1" + " < " + escape(stdin.path);
}
var res = this.run(options["shell"], options["shellcmdflag"].split(/\s+/).concat(command), true);
}
else {
cmd.write("cd " + escape(this._cwd.path) + "\n" +
["exec", ">" + escape(stdout.path), "2>&1", "<" + escape(stdin.path),
escape(options["shell"]), options["shellcmdflag"], escape(command)].join(" "));
res = this.run("/bin/sh", ["-e", cmd.path], true);
}
let output = stdout.read();
if (res > 0)
output += "\nshell returned " + res;
// if there is only one \n at the end, chop it off
else if (output && output.indexOf("\n") == output.length - 1)
output = output.substr(0, output.length - 1);
return output;
}) || "";
},
/**
* Creates a temporary file context for executing external commands.
* <b>func</b> is called with a temp file, created with
* {@link #createTempFile}, for each explicit argument. Ensures that
* all files are removed when <b>func</b> returns.
*
* @param {function} func The function to execute.
* @param {Object} self The 'this' object used when executing func.
* @returns {boolean} false if temp files couldn't be created,
* otherwise, the return value of <b>func</b>.
*/
withTempFiles: function (func, self) {
let args = util.map(util.range(0, func.length), this.createTempFile);
if (!args.every(util.identity))
return false;
try {
return func.apply(self || this, args);
}
finally {
args.forEach(function (f) f.remove(false));
}
}
}, {
/**
* @property {string} The value of the $VIMPERATOR_RUNTIME environment
* variable.
*/
get runtimePath() {
const rtpvar = config.name.toUpperCase() + "_RUNTIME";
let rtp = services.get("environment").get(rtpvar);
if (!rtp) {
rtp = "~/" + (liberator.has("Windows") ? "" : ".") + config.name.toLowerCase();
services.get("environment").set(rtpvar, rtp);
}
return rtp;
},
/**
* @property {string} The current platform's path seperator.
*/
get PATH_SEP() {
delete this.PATH_SEP;
let f = services.get("dirsvc").get("CurProcD", Ci.nsIFile);
f.append("foo");
return this.PATH_SEP = f.path.substr(f.parent.path.length, 1);
}
}, {
commands: function () {
commands.add(["cd", "chd[ir]"],
"Change the current directory",
function (args) {
let arg = args.literalArg;
if (!arg) {
arg = "~";
} else if (arg == "-") {
liberator.assert(io._oldcwd, "No previous directory");
arg = io._oldcwd.path;
}
arg = File.expandPath(arg);
// go directly to an absolute path or look for a relative path
// match in 'cdpath'
if (File.isAbsolutePath(arg)) {
if (io.setCurrentDirectory(arg))
liberator.echomsg(io.getCurrentDirectory().path);
} else {
let dirs = File.getPathsFromPathList(options["cdpath"]);
let found = false;
for (let dir of dirs) {
dir = File.joinPaths(dir, arg);
if (dir.exists() && dir.isDirectory() && dir.isReadable()) {
io.setCurrentDirectory(dir.path);
liberator.echomsg(io.getCurrentDirectory().path);
found = true;
break;
}
}
if (!found)
liberator.echoerr("Can't find directory " + arg.quote() + " in cdpath\n" + "Command failed");
}
}, {
argCount: "?",
completer: function (context) completion.directory(context, true),
literal: 0
});
// NOTE: this command is only used in :source
commands.add(["fini[sh]"],
"Stop sourcing a script file",
function () { liberator.echoerr(":finish used outside of a sourced file"); },
{ argCount: "0" });
commands.add(["pw[d]"],
"Print the current directory name",
function () { liberator.echomsg(io.getCurrentDirectory().path); },
{ argCount: "0" });
// "mkv[imperatorrc]" or "mkm[uttatorrc]"
commands.add([config.name.toLowerCase().replace(/(.)(.*)/, "mk$1[$2rc]")],
"Write current key mappings and changed options to the config file",
function (args) {
liberator.assert(args.length <= 1, "Only one file name allowed");
let filename = args[0] || io.getRCFile(null, true).path;
let file = File(filename);
liberator.assert(!file.exists() || args.bang,
"File exists: " + filename + ". Add ! to override.");
// TODO: Use a set/specifiable list here:
let lines = [cmd.serial().map(commands.commandToString) for (cmd in commands) if (cmd.serial)];
lines = util.Array.flatten(lines);
// source a user .vimperatorrc file
lines.unshift('"' + liberator.version + "\n");
// For the record, I think that adding this line is absurd. --Kris
// I can't disagree. --djk
lines.push(commands.commandToString({
command: "source",
bang: true,
arguments: [filename + ".local"]
}));
lines.push("\n\" vim: set ft=" + config.name.toLowerCase() + ":");
try {
file.write(lines.join("\n"));
}
catch (e) {
liberator.echoerr("Could not write to " + file.path + ": " + e.message);
}
}, {
argCount: "*", // FIXME: should be "?" but kludged for proper error message
bang: true,
completer: function (context) completion.file(context, true)
});
commands.add(["runt[ime]"],
"Source the specified file from each directory in 'runtimepath'",
function (args) { io.sourceFromRuntimePath(args, args.bang); }, {
argCount: "+",
bang: true
}
);
commands.add(["scrip[tnames]"],
"List all sourced script names",
function () {
let list = template.tabular([{ header: "<SNR>", style: "text-align: right; padding-right: 1em;" }, "Filename"],
([i + 1, file] for ([i, file] in Iterator(io._scriptNames))));
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
},
{ argCount: "0" });
commands.add(["so[urce]"],
"Read Ex commands from a file",
function (args) {
io.source(args.literalArg, args.bang);
}, {
literal: 0,
bang: true,
completer: function (context) completion.file(context, true)
});
commands.add(["!", "run"],
"Run a command",
function (args) {
let arg = args.literalArg;
// :!! needs to be treated specially as the command parser sets the
// bang flag but removes the ! from arg
if (args.bang)
arg = "!" + arg;
// replaceable bang and no previous command?
liberator.assert(!/((^|[^\\])(\\\\)*)!/.test(arg) || io._lastRunCommand, "No previous command");
// NOTE: Vim doesn't replace ! preceded by 2 or more backslashes and documents it - desirable?
// pass through a raw bang when escaped or substitute the last command
arg = arg.replace(/(\\)*!/g,
function (m) /^\\(\\\\)*!$/.test(m) ? m.replace("\\!", "!") : m.replace("!", io._lastRunCommand)
);
io._lastRunCommand = arg;
let output = io.system(arg);
commandline.command = "!" + arg;
commandline.echo(template.genericOutput("Command Output: " + arg, xml`<span highlight="CmdOutput">${String(output)}</span>`));
autocommands.trigger("ShellCmdPost", {});
}, {
argCount: "?",
bang: true,
completer: function (context) completion.shellCommand(context),
literal: 0
});
},
completion: function () {
JavaScript.setCompleter([this.File, File.expandPath],
[function (context, obj, args) {
context.quote[2] = "";
completion.file(context, true);
}]);
completion.charset = function (context) {
context.anchored = false;
context.generate = function () {
let names = util.Array(
"more1 more2 more3 more4 more5 static".split(" ").map(function (key)
options.getPref("intl.charsetmenu.browser." + key).split(', '))
).flatten().uniq();
let bundle = document.getElementById("liberator-charset-bundle");
return names.map(function (name) [name, bundle.getString(name.toLowerCase() + ".title")]);
};
};
completion.directory = function directory(context, full) {
this.file(context, full);
context.filters.push(function ({ item: f }) f.isDirectory());
};
completion.environment = function environment(context) {
let command = liberator.has("Windows") ? "set" : "env";
let lines = io.system(command).split("\n");
lines.pop();
context.title = ["Environment Variable", "Value"];
context.generate = function () lines.map(function (line) (line.match(/([^=]+)=(.+)/) || []).slice(1));
};
// TODO: support file:// and \ or / path separators on both platforms
// if "tail" is true, only return names without any directory components
completion.file = function file(context, full) {
// dir == "" is expanded inside readDirectory to the current dir
let [dir] = context.filter.match(/^(?:.*[\/\\])?/);
if (!full)
context.advance(dir.length);
context.title = [full ? "Path" : "Filename", "Type"];
context.keys = {
text: !full ? "leafName" : function (f) dir + f.leafName,
description: function (f) f.isDirectory() ? "Directory" : "File",
isdir: function (f) f.exists() && f.isDirectory(),
icon: function (f) f.isDirectory() ? "resource://gre/res/html/folder.png"
: "moz-icon://" + f.leafName
};
context.compare = function (a, b)
b.isdir - a.isdir || String.localeCompare(a.text, b.text);
context.match = function (str) {
let filter = this.filter;
if (!filter)
return true;
if (this.ignoreCase) {
filter = filter.toLowerCase();
str = str.toLowerCase();
}
return str.substr(0, filter.length) === filter;
};
// context.background = true;
context.key = dir;
context.generate = function generate_file() {
try {
return File(dir).readDirectory();
}
catch (e) {}
return [];
};
};
completion.shellCommand = function shellCommand(context) {
context.title = ["Shell Command", "Path"];
context.generate = function () {
let dirNames = services.get("environment").get("PATH").split(RegExp(liberator.has("Windows") ? ";" : ":"));
let commands = [];
for (let dirName of dirNames) {
let dir = io.File(dirName);
if (dir.exists() && dir.isDirectory()) {
commands.push([[file.leafName, dir.path] for (file in dir.iterDirectory())
if (file.isFile() && file.isExecutable())]);
}
}
return util.Array.flatten(commands);
};
};
completion.addUrlCompleter("f", "Local files", completion.file);
},
options: function () {
var shell, shellcmdflag;
if (liberator.has("Windows")) {
shell = "cmd.exe";
// TODO: setting 'shell' to "something containing sh" updates
// 'shellcmdflag' appropriately at startup on Windows in Vim
shellcmdflag = "/c";
}
else {
shell = services.get("environment").get("SHELL") || "sh";
shellcmdflag = "-c";
}
options.add(["fileencoding", "fenc"],
"Sets the character encoding of read and written files",
"string", "UTF-8", {
completer: function (context) completion.charset(context)
});
options.add(["cdpath", "cd"],
"List of directories searched when executing :cd",
"stringlist", "," + (services.get("environment").get("CDPATH").replace(/[:;]/g, ",") || ","),
{ setter: function (value) File.expandPathList(value) });
options.add(["runtimepath", "rtp"],
"List of directories searched for runtime files",
"stringlist", IO.runtimePath,
{ setter: function (value) File.expandPathList(value) });
options.add(["shell", "sh"],
"Shell to use for executing :! and :run commands",
"string", shell,
{ setter: function (value) File.expandPath(value) });
options.add(["shellcmdflag", "shcf"],
"Flag passed to shell when executing :! and :run commands",
"string", shellcmdflag);
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2011 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
// TODO: many methods do not work with Thunderbird correctly yet
/**
* @instance tabs
*/
const Tabs = Module("tabs", {
requires: ["config"],
init: function () {
this.updateSelectionHistory([config.tabbrowser.mCurrentTab, null]);
// used for the "gb" and "gB" mappings to remember the last :buffer[!] command
this._lastBufferSwitchArgs = "";
this._lastBufferSwitchSpecial = true;
},
_updateTabCount: function () {
statusline.updateField("tabcount", true);
},
_onTabSelect: function () {
// TODO: is all of that necessary?
// I vote no. --Kris
modes.reset();
statusline.updateField("tabcount", true);
this.updateSelectionHistory();
if (options["focuscontent"])
setTimeout(function () { liberator.focusContent(true); }, 10); // just make sure, that no widget has focus
},
/**
* @property {Object} The previously accessed tab or null if no tab
* other than the current one has been accessed.
*/
get alternate() {
var tab = this._alternates[1] ? this._alternates[1].get() : null;
return (tab && tab.parentNode) ? tab : null;
},
/**
* @property {Iterator(Object)} A genenerator that returns all browsers
* in the current window.
*/
get browsers() {
let browsers = config.tabbrowser.browsers;
for (let i = 0; i < browsers.length; i++)
yield [i, browsers[i]];
},
/**
* @property {number} The number of tabs in the current window.
*/
get count() config.tabbrowser.visibleTabs.length,
/**
* @property {Object} The local options store for the current tab.
*/
get options() {
let store = this.localStore;
if (!("options" in store))
store.options = {};
return store.options;
},
/**
* Returns the local state store for the tab at the specified
* <b>tabIndex</b>. If <b>tabIndex</b> is not specified then the
* current tab is used.
*
* @param {number} tabIndex
* @returns {Object}
*/
// FIXME: why not a tab arg? Why this and the property?
// : To the latter question, because this works for any tab, the
// property doesn't. And the property is so oft-used that it's
// convenient. To the former question, because I think this is mainly
// useful for autocommands, and they get index arguments. --Kris
getLocalStore: function (tabIndex) {
let tab = this.getTab(tabIndex);
if (!tab.liberatorStore)
tab.liberatorStore = {};
return tab.liberatorStore;
},
/**
* @property {Object} The local state store for the currently selected
* tab.
*/
get localStore() this.getLocalStore(),
/**
* @property {Object[]} The array of closed tabs for the current
* session.
*/
get closedTabs() JSON.parse(services.get("sessionStore").getClosedTabData(window)),
/**
* Returns the index of <b>tab</b> or the index of the currently
* selected tab if <b>tab</b> is not specified. This is a 0-based
* index.
*
* @param {Object} tab A tab from the current tab list.
* @returns {number}
*/
index: function (tab) {
if (tab)
return Array.indexOf(config.tabbrowser.visibleTabs, tab);
else
return Array.indexOf(config.tabbrowser.visibleTabs, config.tabbrowser.tabContainer.selectedItem);
},
// TODO: implement filter
/**
* Returns an array of all tabs in the tab list.
*
* @returns {Object[]}
*/
// FIXME: why not return the tab element?
// : unused? Remove me.
get: function () {
let buffers = [];
for (let [i, browser] in this.browsers) {
let title = browser.contentTitle || "(Untitled)";
let uri = browser.currentURI.spec;
let number = i + 1;
buffers.push([number, title, uri]);
}
return buffers;
},
/**
* Returns the index of the tab containing <b>content</b>.
*
* @param {Object} content Either a content window or a content
* document.
*/
// FIXME: Only called once...necessary?
getContentIndex: function (content) {
for (let [i, browser] in this.browsers) {
if (browser.contentWindow == content || browser.contentDocument == content)
return i;
}
return -1;
},
/**
* Returns the tab at the specified <b>index</b> or the currently
* selected tab if <b>index</b> is not specified. This is a 0-based
* index.
*
* @param {number} index The index of the tab required.
* @returns {Object}
*/
getTab: function (index) {
if (index != undefined)
return config.tabbrowser.mTabs[index];
else
return config.tabbrowser.mCurrentTab;
},
/**
* Lists all tabs matching <b>filter</b>.
*
* @param {string} filter A filter matching a substring of the tab's
* document title or URL.
* @param {boolean} showAll
*/
list: function (filter, showAll) {
completion.listCompleter("buffer", filter, null, completion.buffer[showAll ? "ALL" : "VISIBLE"]);
},
/**
* Moves a tab to a new position in the tab list.
*
* @param {Object} tab The tab to move.
* @param {string} spec See {@link Tabs.indexFromSpec}.
* @param {boolean} wrap Whether an out of bounds <b>spec</b> causes
* the destination position to wrap around the start/end of the tab
* list.
*/
move: function (tab, spec, wrap) {
let index = Tabs.indexFromSpec(spec, wrap, false);
index = tabs.getTab(index)._tPos;
config.tabbrowser.moveTabTo(tab, index);
},
/**
* Removes the specified <b>tab</b> from the tab list.
*
* @param {Object} tab The tab to remove.
* @param {number} count How many tabs to remove.
* @param {number} orientation Focus orientation
* 1 - Focus the tab to the right of the remove tab.
* 0 - Focus the altanate tab of the remove tab. if alternate tab is none, same as 1
* -1 - Focus the tab to the left of the remove tab.
* @param {number} quitOnLastTab Whether to quit if the tab being
* deleted is the only tab in the tab list:
* 1 - quit without saving session
* 2 - quit and save session
* @param {boolean} force Close even if the tab is an app tab.
*/
// FIXME: what is quitOnLastTab {1,2} all about then, eh? --djk
remove: function (tab, count, orientation, quitOnLastTab, force) {
let vTabs = config.tabbrowser.visibleTabs;
let removeOrBlankTab = {
Firefox: function (tab) {
if (vTabs.length > 1)
config.tabbrowser.removeTab(tab);
else {
let url = buffer.URL;
if (url != "about:blank" || url != "about:newtab" ||
window.getWebNavigation().sessionHistory.count > 0) {
liberator.open("", liberator.NEW_BACKGROUND_TAB);
config.tabbrowser.removeTab(tab);
}
else
liberator.beep();
}
},
Thunderbird: function (tab) {
if (config.tabbrowser.mTabs.length > 1 && !tab.hasAttribute("first-tab"))
config.tabbrowser.closeTab(tab);
else
liberator.beep();
},
}[config.hostApplication] || function () {};
if (typeof count != "number" || count < 1)
count = 1;
if (quitOnLastTab >= 1 && config.tabbrowser.mTabs.length <= count) {
if (liberator.windows.length > 1)
window.close();
else
liberator.quit(quitOnLastTab == 2);
return;
}
if (!orientation)
orientation = 0;
let index = vTabs.indexOf(tab);
// should close even if the tab is not visible such as ":tabclose arg"
if (index < 0) {
// XXX: should consider the count variable ?
if (tab.pinned && !force)
liberator.echoerr("Cannot close an app tab [" + tab.label + "]. Use :tabclose!");
else
removeOrBlankTab(tab);
return;
}
let start, end, selIndex = 0;
if (orientation < 0) {
start = Math.max(0, index - count + 1);
end = index;
}
else {
start = index;
end = Math.min(index + count, vTabs.length) - 1;
selIndex = end + 1;
}
if (!force) {
for (; start <= end && vTabs[start].pinned; start++)
liberator.echoerr("Cannot close an app tab [" + vTabs[start].label + "]. Use :tabclose!");
if (start > end)
return;
}
if ((orientation < 0 && 0 < start - 1) || selIndex >= vTabs.length)
selIndex = start - 1;
let currentIndex = vTabs.indexOf(tabs.getTab());
if (start <= currentIndex && currentIndex <= end) {
let selTab = vTabs[selIndex];
if (orientation == 0 &&
config.tabbrowser.mTabContainer.contains(this.alternate) &&
!this.alternate.hidden) // XXX: should be in the visible tabs ?
{
let lastTabIndex = vTabs.indexOf(this.alternate);
if (lastTabIndex < start || end < lastTabIndex)
selTab = this.alternate;
}
config.tabbrowser.mTabContainer.selectedItem = selTab;
}
for (let i = end; i >= start; i--) {
removeOrBlankTab(vTabs[i]);
vTabs.splice(i, 1);
}
},
/**
* Removes all tabs from the tab list except the specified <b>tab</b>.
*
* @param {Object} tab The tab to keep.
*/
keepOnly: function (tab) {
config.tabbrowser.removeAllTabsBut(tab);
},
/**
* Selects the tab at the position specified by <b>spec</b>.
*
* @param {string} spec See {@link Tabs.indexFromSpec}
* @param {boolean} wrap Whether an out of bounds <b>spec</b> causes
* the selection position to wrap around the start/end of the tab
* list.
* @param {boolean} allTabs
*/
select: function (spec, wrap, allTabs) {
let index = Tabs.indexFromSpec(spec, wrap, allTabs);
// FIXME:
if (index == -1)
liberator.beep();
else
config.tabbrowser.mTabContainer.selectedIndex = index;
},
/**
* Reloads the specified tab.
*
* @param {Object} tab The tab to reload.
* @param {boolean} bypassCache Whether to bypass the cache when
* reloading.
*/
reload: function (tab, bypassCache) {
if (bypassCache) {
const flags = Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
config.tabbrowser.getBrowserForTab(tab).reloadWithFlags(flags);
}
else
config.tabbrowser.reloadTab(tab);
},
/**
* Reloads all tabs.
*
* @param {boolean} bypassCache Whether to bypass the cache when
* reloading.
*/
reloadAll: function (bypassCache) {
if (bypassCache) {
for (let i = 0; i < config.tabbrowser.mTabs.length; i++) {
try {
this.reload(config.tabbrowser.mTabs[i], bypassCache);
}
catch (e) {
// FIXME: can we do anything useful here without stopping the
// other tabs from reloading?
}
}
}
else
config.tabbrowser.reloadAllTabs();
},
/**
* Stops loading the specified tab.
*
* @param {Object} tab The tab to stop loading.
*/
stop: function (tab) {
if (config.stop)
config.stop(tab);
else
tab.linkedBrowser.stop();
},
/**
* Stops loading all tabs.
*/
stopAll: function () {
for (let [, browser] in this.browsers)
browser.stop();
},
/**
* Returns tabs containing the specified <b>buffer</b>.
* @param {string} buffer
* @return {array} array of tabs
*/
getTabsFromBuffer: function (buffer) {
if (!buffer || typeof buffer != "string")
return [];
if (buffer == "#")
return [tabs.alternate];
let matches = buffer.match(/^(\d+):?/);
if (matches)
return [tabs.getTab(parseInt(matches[1], 10) - 1)];
else if (liberator.has("tabgroup")) {
matches = buffer.match(/^(.+?)\.(\d+):?/);
if (matches) {
let [, groupName, tabNum] = matches;
tabNum = parseInt(tabNum, 10);
let group = tabGroup.getGroup(groupName);
if (group) {
let tabItem = group.getChild(tabNum - 1);
if (tabItem)
return [tabItem.tab];
}
}
}
matches = [];
let lowerBuffer = buffer.toLowerCase();
let first = tabs.index();
let nbrowsers = config.tabbrowser.browsers.length;
for (let [i, ] in tabs.browsers) {
let index = (i + first) % nbrowsers;
let browser = config.tabbrowser.browsers[index];
let tab = tabs.getTab(index);
let url = browser.contentDocument.location.href;
let title = tab.label.toLowerCase();
if (url == buffer)
return [tab];
if (url.indexOf(buffer) >= 0 || title.indexOf(lowerBuffer) >= 0)
matches.push(tab);
}
return matches;
},
/**
* Selects the tab containing the specified <b>buffer</b>.
*
* @param {string} buffer A string which matches the URL or title of a
* buffer, if it is null, the last used string is used again.
* @param {boolean} allowNonUnique Whether to select the first of
* multiple matches.
* @param {number} count If there are multiple matches select the
* count'th match.
* @param {boolean} reverse Whether to search the buffer list in
* reverse order.
*
*/
// FIXME: help!
switchTo: function (buffer, allowNonUnique, count, reverse) {
if (buffer == "")
return;
if (buffer != null) {
// store this command, so it can be repeated with "B"
this._lastBufferSwitchArgs = buffer;
this._lastBufferSwitchSpecial = allowNonUnique;
}
else {
buffer = this._lastBufferSwitchArgs;
if (allowNonUnique === undefined || allowNonUnique == null) // XXX
allowNonUnique = this._lastBufferSwitchSpecial;
}
if (!count || count < 1)
count = 1;
if (typeof reverse != "boolean")
reverse = false;
let tabItems = tabs.getTabsFromBuffer(buffer);
if (tabItems.length == 0)
liberator.echoerr("No matching buffer for: " + buffer);
else if (tabItems.length == 1)
config.tabbrowser.mTabContainer.selectedItem = tabItems[0];
else if (!allowNonUnique)
liberator.echoerr("More than one match for: " + buffer);
else {
let length = tabItems.length;
if (reverse) {
index = length - count;
while (index < 0)
index += length;
}
else
index = count % length;
config.tabbrowser.mTabContainer.selectedItem = tabItems[index];
}
},
/**
* Clones the specified <b>tab</b> and append it to the tab list.
*
* @param {Object} tab The tab to clone.
* @param {boolean} activate Whether to select the newly cloned tab.
*/
cloneTab: function (tab, activate) {
let newTab = config.tabbrowser.addTab();
Tabs.copyTab(newTab, tab);
if (activate)
config.tabbrowser.mTabContainer.selectedItem = newTab;
return newTab;
},
/**
* Detaches the specified <b>tab</b> and open it in a new window. If no
* tab is specified the currently selected tab is detached.
*
* @param {Object} tab The tab to detach.
*/
detachTab: function (tab) {
if (!tab)
tab = config.tabbrowser.mTabContainer.selectedItem;
services.get("ww")
.openWindow(window, window.getBrowserURL(), null, "chrome,dialog=no,all", tab);
},
/**
* Selects the alternate tab.
*/
selectAlternateTab: function () {
let alternate = tabs.alternate;
liberator.assert(alternate != null && tabs.getTab() != alternate, "No alternate page");
config.tabbrowser.tabContainer.selectedItem = alternate;
},
// NOTE: when restarting a session FF selects the first tab and then the
// tab that was selected when the session was created. As a result the
// alternate after a restart is often incorrectly tab 1 when there
// shouldn't be one yet.
/**
* Sets the current and alternate tabs, updating the tab selection
* history.
*
* @param {Array(Object)} tabs The current and alternate tab.
* @see tabs#alternate
*/
updateSelectionHistory: function (tabs) {
var tab1, tab2;
if (tabs && tabs.length > 1) {
tab1 = tabs[0] ? Cu.getWeakReference(tabs[0]) : null,
tab2 = tabs[1] ? Cu.getWeakReference(tabs[1]) : null;
}
else {
tab1 = Cu.getWeakReference(this.getTab()),
tab2 = this._alternates[0];
}
this._alternates = [tab1, tab2];
}
}, {
copyTab: function (to, from) {
if (!from)
from = config.tabbrowser.mTabContainer.selectedItem;
let tabState = services.get("sessionStore").getTabState(from);
services.get("sessionStore").setTabState(to, tabState);
},
/**
* @param spec can either be:
* - an absolute integer
* - "" for the current tab
* - "+1" for the next tab
* - "-3" for the tab, which is 3 positions left of the current
* - "$" for the last tab
* @param wrap
* @param allTabs
*/
indexFromSpec: function (spec, wrap, allTabs) {
let tabs = allTabs ? config.tabbrowser.mTabs : config.tabbrowser.visibleTabs;
let position = allTabs ?
config.tabbrowser.mTabContainer.selectedIndex :
tabs.indexOf(config.tabbrowser.mCurrentTab);
let length = tabs.length;
let last = length - 1;
if (spec === undefined || spec === "")
return position;
if (typeof spec === "number")
position = spec;
else if (spec === "$")
position = last;
else if (/^[+-]\d+$/.test(spec))
position += parseInt(spec, 10);
else if (/^\d+$/.test(spec))
position = parseInt(spec, 10);
else
return -1;
if (position > last)
position = wrap ? position % length : last;
else if (position < 0)
position = wrap ? ((position % length) + length) % length : 0;
if (config.hostApplication === "Firefox")
return tabs[position]._tPos;
return position;
}
}, {
commands: function () {
commands.add(["bd[elete]", "bw[ipeout]", "bun[load]", "tabc[lose]"],
"Delete current buffer",
function (args) {
let special = args.bang;
let count = args.count;
let arg = args.literalArg;
let orientation = 1;
if (args["-select"] === "lastactive") {
orientation = 0;
} else if (args["-select"] === "left") {
orientation = -1;
}
if (arg) {
let removed = 0;
let matches = arg.match(/^(\d+):?/);
if (matches) {
tabs.remove(tabs.getTab(parseInt(matches[1], 10) - 1), 1, orientation, 0, special);
removed = 1;
}
else {
let str = arg.toLowerCase();
let browsers = config.tabbrowser.browsers;
for (let i = browsers.length - 1; i >= 0; i--) {
let host, title, uri = browsers[i].currentURI.spec;
if (browsers[i].currentURI.schemeIs("about")) {
host = "";
title = "(Untitled)";
}
else {
host = browsers[i].currentURI.host;
title = browsers[i].contentTitle;
}
[host, title, uri] = [host, title, uri].map(String.toLowerCase);
if (host.indexOf(str) >= 0 || uri == str ||
(special && (title.indexOf(str) >= 0 || uri.indexOf(str) >= 0))) {
tabs.remove(tabs.getTab(i), 1, orientation, 0, special);
removed++;
}
}
}
if (removed == 1)
liberator.echomsg("Removed tab: " + arg);
else if (removed > 1)
liberator.echomsg("Removed " + removed + " tabs");
else
liberator.echoerr("No matching tab for: " + arg);
}
else // just remove the current tab
tabs.remove(tabs.getTab(), Math.max(count, 1), orientation, 0, special);
}, {
argCount: "?",
bang: true,
count: true,
options: [
[["-select", "-s"], commands.OPTION_STRING, null,
[["lastactive", "Select last active tab"],
["left", "Select the tab to the left"],
["right", "Select the tab to the right"]]],
],
completer: function (context) completion.buffer(context),
literal: 0
});
commands.add(["keepa[lt]"],
"Execute a command without changing the current alternate buffer",
function (args) {
let alternate = tabs.alternate;
try {
liberator.execute(args[0], null, true);
}
finally {
tabs.updateSelectionHistory([tabs.getTab(), alternate]);
}
}, {
argCount: "+",
completer: function (context) completion.ex(context),
literal: 0
});
commands.add(["tab"],
"Execute a command and tell it to output in a new tab",
function (args) {
try {
liberator.forceNewTab = true;
liberator.execute(args.string, null, true);
}
finally {
liberator.forceNewTab = false;
}
}, {
argCount: "+",
completer: function (context) completion.ex(context),
literal: 0
});
commands.add(["tabd[o]", "bufd[o]"],
"Execute a command in each tab",
function (args) {
for (let i = 0; i < tabs.count; i++) {
tabs.select(i);
liberator.execute(args.string, null, true);
}
}, {
argCount: "1",
completer: function (context) completion.ex(context),
literal: 0
});
commands.add(["tabl[ast]", "bl[ast]"],
"Switch to the last tab",
function () tabs.select("$", false),
{ argCount: "0" });
// TODO: "Zero count" if 0 specified as arg
commands.add(["tabp[revious]", "tp[revious]", "tabN[ext]", "tN[ext]", "bp[revious]", "bN[ext]"],
"Switch to the previous tab or go [count] tabs back",
function (args) {
let count = args.count;
let arg = args[0];
// count is ignored if an arg is specified, as per Vim
if (arg) {
if (/^\d+$/.test(arg))
tabs.select("-" + arg, true);
else
liberator.echoerr("Trailing characters");
}
else if (count > 0)
tabs.select("-" + count, true);
else
tabs.select("-1", true);
}, {
argCount: "?",
count: true
});
// TODO: "Zero count" if 0 specified as arg
commands.add(["tabn[ext]", "tn[ext]", "bn[ext]"],
"Switch to the next or [count]th tab",
function (args) {
let count = args.count;
let arg = args[0];
if (arg || count > 0) {
let index;
// count is ignored if an arg is specified, as per Vim
if (arg) {
liberator.assert(/^\d+$/.test(arg), "Trailing characters");
index = arg - 1;
}
else
index = count - 1;
if (index < tabs.count)
tabs.select(index, true);
else
liberator.beep();
}
else
tabs.select("+1", true);
}, {
argCount: "?",
count: true
});
commands.add(["tabr[ewind]", "tabfir[st]", "br[ewind]", "bf[irst]"],
"Switch to the first tab",
function () { tabs.select(0, false); },
{ argCount: "0" });
if (config.hasTabbrowser) {
// TODO: "Zero count" if 0 specified as arg, multiple args and count ranges?
commands.add(["b[uffer]"],
"Switch to a buffer",
function (args) {
let special = args.bang;
let count = args.count;
let arg = args.literalArg;
if (arg && count > 0) {
liberator.assert(/^\d+$/.test(arg), "Trailing characters");
tabs.switchTo(arg, special);
}
else if (count > 0)
tabs.switchTo(count.toString(), special);
else
tabs.switchTo(arg, special);
}, {
argCount: "?",
bang: true,
count: true,
completer: function (context) completion.buffer(context, completion.buffer.ALL),
literal: 0
});
commands.add(["buffers", "files", "ls", "tabs"],
"Show a list of all buffers",
function (args) { tabs.list(args.literalArg, args.bang); }, {
argCount: "?",
bang: true,
literal: 0
});
commands.add(["quita[ll]", "qa[ll]"],
"Quit " + config.name,
function (args) { liberator.quit(false, args.bang); }, {
argCount: "0",
bang: true
});
commands.add(["reloada[ll]"],
"Reload all tab pages",
function (args) { tabs.reloadAll(args.bang); }, {
argCount: "0",
bang: true
});
commands.add(["stopa[ll]"],
"Stop loading all tab pages",
function () { tabs.stopAll(); },
{ argCount: "0" });
// TODO: add count support
commands.add(["tabm[ove]"],
"Move the current tab after tab N",
function (args) {
let arg = args[0];
// FIXME: tabmove! N should probably produce an error
liberator.assert(!arg || /^([+-]?\d+)$/.test(arg), "Trailing characters");
// if not specified, move to after the last tab
tabs.move(config.tabbrowser.mCurrentTab, arg || "$", args.bang);
}, {
argCount: "?",
bang: true
});
commands.add(["tabo[nly]"],
"Close all other tabs",
function () { tabs.keepOnly(config.tabbrowser.mCurrentTab); },
{ argCount: "0" });
commands.add(["tabopen", "t[open]", "tabnew"],
"Open one or more URLs in a new tab",
function (args) {
let special = args.bang;
args = args.string;
if (options.get("activate").has("all", "tabopen"))
special = !special;
let where = special ? liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB;
if (args)
liberator.open(args, { where: where });
else
liberator.open("", { where: where });
}, {
bang: true,
completer: function (context) completion.url(context),
literal: 0,
privateData: true
});
commands.add(["tabde[tach]"],
"Detach current tab to its own window",
function () {
liberator.assert(tabs.count > 1, "Can't detach the last tab");
tabs.detachTab(null);
},
{ argCount: "0" });
commands.add(["tabdu[plicate]"],
"Duplicate current tab",
function (args) {
let tab = tabs.getTab();
let activate = args.bang ? true : false;
if (options.get("activate").has("tabopen", "all"))
activate = !activate;
for (let i in util.range(0, Math.max(1, args.count)))
tabs.cloneTab(tab, activate);
}, {
argCount: "0",
bang: true,
count: true
});
// TODO: match window by title too?
// : accept the full :tabmove arg spec for the tab index arg?
// : better name or merge with :tabmove?
commands.add(["taba[ttach]"],
"Attach the current tab to another window",
function (args) {
liberator.assert(args.length <= 2 && !args.some(function (i) !/^\d+$/.test(i)),
"Trailing characters");
let [winIndex, tabIndex] = args.map(function(i) { return parseInt(i, 10) });
let win = liberator.windows[winIndex - 1];
liberator.assert(win, "Window " + winIndex + " does not exist");
liberator.assert(win != window, "Cannot reattach to the same window");
let browser = win.getBrowser();
let dummy = browser.addTab("about:blank");
browser.stop();
// XXX: the implementation of DnD in tabbrowser.xml suggests
// that we may not be guaranteed of having a docshell here
// without this reference?
browser.docShell;
let last = browser.mTabs.length - 1;
browser.moveTabTo(dummy, util.Math.constrain(tabIndex || last, 0, last));
browser.selectedTab = dummy; // required
browser.swapBrowsersAndCloseOther(dummy, config.tabbrowser.mCurrentTab);
}, {
argCount: "+",
completer: function (context, args) {
if (args.completeArg == 0) {
context.filters.push(function ({ item: win }) win != window);
completion.window(context);
}
}
});
}
if (liberator.has("tabs_undo")) {
commands.add(["u[ndo]"],
"Undo closing of a tab",
function (args) {
if (args.length)
args = args[0];
else
args = args.count || 0;
let m = /^(\d+)(:|$)/.exec(args || '1');
if (m)
window.undoCloseTab(Number(m[1]) - 1);
else if (args) {
for (let [i, item] in Iterator(tabs.closedTabs))
if (item.state.entries[item.state.index - 1].url == args) {
window.undoCloseTab(i);
return;
}
liberator.echoerr("No matching closed tab: " + args);
}
}, {
argCount: "?",
completer: function (context) {
context.anchored = false;
context.compare = CompletionContext.Sort.unsorted;
context.filters = [CompletionContext.Filter.textDescription];
context.keys = { text: function ([i, { state: s }]) (i + 1) + ": " + s.entries[s.index - 1].url, description: "[1].title", icon: "[1].image" };
context.completions = Iterator(tabs.closedTabs);
},
count: true,
literal: 0
});
commands.add(["undoa[ll]"],
"Undo closing of all closed tabs",
function (args) {
for (let i in Iterator(tabs.closedTabs))
window.undoCloseTab(0);
},
{ argCount: "0" });
}
if (liberator.has("session")) {
commands.add(["wqa[ll]", "wq", "xa[ll]"],
"Save the session and quit",
function () { liberator.quit(true); },
{ argCount: "0" });
}
},
completion: function () {
completion.addUrlCompleter("t",
"Open tabs",
completion.buffer);
},
events: function () {
let tabContainer = config.tabbrowser.mTabContainer;
["TabMove", "TabOpen", "TabClose"].forEach(function (event) {
events.addSessionListener(tabContainer, event, this.closure._updateTabCount, false);
}, this);
events.addSessionListener(tabContainer, "TabSelect", this.closure._onTabSelect, false);
},
mappings: function () {
mappings.add([modes.NORMAL], ["g0", "g^"],
"Go to the first tab",
function (count) { tabs.select(0); });
mappings.add([modes.NORMAL], ["g$"],
"Go to the last tab",
function (count) { tabs.select("$"); });
mappings.add([modes.NORMAL], ["gt"],
"Go to the next tab",
function (count) {
if (count != null)
tabs.select(count - 1, false);
else
tabs.select("+1", true);
},
{ count: true });
mappings.add([modes.NORMAL], ["<C-n>", "<C-Tab>", "<C-PageDown>"],
"Go to the next tab",
function (count) { tabs.select("+" + (count || 1), true); },
{ count: true });
mappings.add([modes.NORMAL], ["gT", "<C-p>", "<C-S-Tab>", "<C-PageUp>"],
"Go to previous tab",
function (count) { tabs.select("-" + (count || 1), true); },
{ count: true });
if (config.hasTabbrowser) {
mappings.add([modes.NORMAL], ["b"],
"Open a prompt to switch buffers",
function (count) {
if (count != null)
tabs.select(count - 1);
else
commandline.open("", "buffer! ", modes.EX);
},
{ count: true });
mappings.add([modes.NORMAL], ["B"],
"Show buffer list",
function () { tabs.list(false); commandline.show("buffers"); });
mappings.add([modes.NORMAL], ["d"],
"Delete current tab and select the tab to the right",
function (count) { tabs.remove(tabs.getTab(), count, 1, 0); },
{ count: true });
mappings.add([modes.NORMAL], ["D"],
"Delete current buffer and select the tab to the left",
function (count) { tabs.remove(tabs.getTab(), count, -1, 0); },
{ count: true });
mappings.add([modes.NORMAL], ["gb"],
"Repeat last :buffer[!] command",
function (count) { tabs.switchTo(null, null, count, false); },
{ count: true });
mappings.add([modes.NORMAL], ["gB"],
"Repeat last :buffer[!] command in reverse direction",
function (count) { tabs.switchTo(null, null, count, true); },
{ count: true });
// TODO: feature dependencies - implies "session"?
if (liberator.has("tabs_undo")) {
mappings.add([modes.NORMAL], ["u"],
"Undo closing of a tab",
function (count) { commands.get("undo").execute("", false, count); },
{ count: true });
}
mappings.add([modes.NORMAL], ["<C-^>", "<C-6>"],
"Select the alternate tab or the [count]th tab",
function (count) {
if (count < 1)
tabs.selectAlternateTab();
else
tabs.switchTo(count.toString(), false);
},
{ count: true });
}
},
options: function () {
if (config.hasTabbrowser) {
options.add(["activate", "act"],
"Define when tabs are automatically activated",
"stringlist", "addons,downloads,extoptions,help,homepage,quickmark,tabopen,paste",
{
completer: function (context) [
["all", "All tabs created by any commands and mappings"],
["addons", ":addo[ns] command"],
["downloads", ":downl[oads] command"],
["extoptions", ":exto[ptions] command"],
["help", ":h[elp] command"],
["homepage", "gH mapping"],
["quickmark", "go and gn mappings"],
["tabopen", ":tabopen[!] command"],
["paste", "P and gP mappings"]
]
});
options.add(["newtab"],
"Define which commands should output in a new tab by default",
"stringlist", "",
{
completer: function (context) [
["all", "All commands"],
["addons", ":addo[ns] command"],
["downloads", ":downl[oads] command"],
["extoptions", ":exto[ptions] command"],
["help", ":h[elp] command"],
["javascript", ":javascript! or :js! command"],
["prefs", ":pref[erences]! or :prefs! command"]
]
});
options.add(["popups", "pps"],
"Where to show requested popup windows",
"stringlist", "tab",
{
setter: function (value) {
let [open, restriction] = [1, 0];
for (let opt of this.parseValues(value)) {
if (opt == "tab")
open = 3;
else if (opt == "window")
open = 2;
else if (opt == "resized")
restriction = 2;
}
options.safeSetPref("browser.link.open_newwindow", open, "See 'popups' option.");
options.safeSetPref("browser.link.open_newwindow.restriction", restriction, "See 'popups' option.");
return value;
},
completer: function (context) [
["tab", "Open popups in a new tab"],
["window", "Open popups in a new window"],
["resized", "Open resized popups in a new window"]
]
});
options.add(["tabnumbers", "tn"],
"Show small numbers at each tab to allow quicker selection",
"boolean", false,
{
setter: function (value) {
// TODO: Change this stuff for muttator
if (value)
styles.addSheet(true, "tabnumbers", "chrome://*",
// we need to change the visible of the "new tab" buttons because the "inline" "new tab" button in the toolbar
// gets moved just after the last app tab with tab numbers on
"#TabsToolbar { counter-reset:tabnumber; } #TabsToolbar tab::after { counter-increment:tabnumber; content:counter(tabnumber); font:bold 0.84em monospace; cursor: default; } #TabsToolbar tab:not([pinned])::after { display:block; padding-bottom:0.4em; } .tabs-newtab-button { display: none !important; } #new-tab-button { visibility: visible !important; }"
);
else
styles.removeSheet(true, "tabnumbers");
return value;
}
});
}
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/**
* @scope modules
* @instance marks
*/
const Marks = Module("marks", {
requires: ["config", "storage"],
init: function init() {
this._localMarks = storage.newMap("local-marks", { store: true, privateData: true });
this._urlMarks = storage.newMap("url-marks", { store: false, privateData: true });
this._pendingJumps = [];
},
/**
* @property {Array} Returns all marks, both local and URL, in a sorted
* array.
*/
get all() {
// local marks
let location = window.content.location.href;
let lmarks = [i for (i in this._localMarkIter()) if (i[1].location == location)];
lmarks.sort();
// URL marks
// FIXME: why does umarks.sort() cause a "Component is not available =
// NS_ERROR_NOT_AVAILABLE" exception when used here?
let umarks = [i for (i in this._urlMarks)];
umarks.sort(function (a, b) a[0].localeCompare(b[0]));
return lmarks.concat(umarks);
},
/**
* Add a named mark for the current buffer, at its current position.
* If mark matches [A-Z], it's considered a URL mark, and will jump to
* the same position at the same URL no matter what buffer it's
* selected from. If it matches [a-z'"], it's a local mark, and can
* only be recalled from a buffer with a matching URL.
*
* @param {string} mark The mark name.
* @param {boolean} silent Whether to output informative messages.
*/
// TODO: add support for frameset pages
add: function (mark, silent) {
let win = window.content;
let doc = win.document;
if (!doc.body)
return;
if (doc.body instanceof HTMLFrameSetElement) {
if (!silent)
liberator.echoerr("Marks support for frameset pages not implemented yet");
return;
}
let x = win.scrollMaxX ? win.pageXOffset / win.scrollMaxX : 0;
let y = win.scrollMaxY ? win.pageYOffset / win.scrollMaxY : 0;
let position = { x: x, y: y };
if (Marks.isURLMark(mark)) {
this._urlMarks.set(mark, { location: win.location.href, position: position, tab: tabs.getTab() });
if (!silent)
liberator.echomsg("Added URL mark: " + Marks.markToString(mark, this._urlMarks.get(mark)));
}
else if (Marks.isLocalMark(mark)) {
// remove any previous mark of the same name for this location
this._removeLocalMark(mark);
if (!this._localMarks.get(mark))
this._localMarks.set(mark, []);
let vals = { location: win.location.href, position: position };
this._localMarks.get(mark).push(vals);
if (!silent)
liberator.echomsg("Added local mark: " + Marks.markToString(mark, vals));
}
},
/**
* Remove the specified local marks. The <b>filter</b> is a list of
* local marks. Ranges are supported. Eg. "ab c d e-k".
*
* @param {string} filter A string containing local marks to be removed.
*/
remove: function (filter) {
if (!filter) {
// :delmarks! only deletes a-z marks
for (let [mark, ] in this._localMarks)
this._removeLocalMark(mark);
}
else {
let pattern = RegExp("[" + filter.replace(/\s+/g, "") + "]");
for (let [mark, ] in this._urlMarks) {
if (pattern.test(mark))
this._removeURLMark(mark);
}
for (let [mark, ] in this._localMarks) {
if (pattern.test(mark))
this._removeLocalMark(mark);
}
}
},
/**
* Jumps to the named mark. See {@link #add}
*
* @param {string} mark The mark to jump to.
*/
jumpTo: function (mark) {
let ok = false;
if (Marks.isURLMark(mark)) {
let slice = this._urlMarks.get(mark);
if (slice && slice.tab && slice.tab.linkedBrowser) {
if (slice.tab.parentNode != config.browser.tabContainer) {
this._pendingJumps.push(slice);
// NOTE: this obviously won't work on generated pages using
// non-unique URLs :(
liberator.open(slice.location, liberator.NEW_TAB);
return;
}
let index = tabs.index(slice.tab);
if (index != -1) {
tabs.select(index, false, true);
let win = slice.tab.linkedBrowser.contentWindow;
if (win.location.href != slice.location) {
this._pendingJumps.push(slice);
win.location.href = slice.location;
return;
}
buffer.scrollToPercent(slice.position.x * 100, slice.position.y * 100);
ok = true;
}
}
}
else if (Marks.isLocalMark(mark)) {
let win = window.content;
let slice = this._localMarks.get(mark) || [];
for (let lmark of slice) {
if (win.location.href == lmark.location) {
buffer.scrollToPercent(lmark.position.x * 100, lmark.position.y * 100);
ok = true;
break;
}
}
}
if (!ok)
liberator.echoerr("Mark not set: " + mark);
},
/**
* List all marks matching <b>filter</b>.
*
* @param {string} filter
*/
list: function (filter) {
let marks = this.all;
liberator.assert(marks.length > 0, "No marks set");
if (filter.length > 0) {
marks = marks.filter(function (mark) filter.indexOf(mark[0]) >= 0);
liberator.assert(marks.length > 0, "No matching marks for: " + filter.quote());
}
let list = template.tabular(
[ { header: "Mark", style: "padding-left: 2ex" },
{ header: "Line", style: "text-align: right" },
{ header: "Column", style: "text-align: right" },
{ header: "File", highlight: "URL" }],
([mark[0],
Math.round(mark[1].position.x * 100) + "%",
Math.round(mark[1].position.y * 100) + "%",
mark[1].location]
for (mark of marks)));
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
},
_onPageLoad: function _onPageLoad(event) {
let win = event.originalTarget.defaultView;
for (let [i, mark] in Iterator(this._pendingJumps)) {
if (win && win.location.href == mark.location) {
buffer.scrollToPercent(mark.position.x * 100, mark.position.y * 100);
this._pendingJumps.splice(i, 1);
return;
}
}
},
_removeLocalMark: function _removeLocalMark(mark) {
let localmark = this._localMarks.get(mark);
if (localmark) {
let win = window.content;
for (let [i, lmark] in Iterator(localmark)) {
if (lmark.location == win.location.href) {
localmark.splice(i, 1);
if (localmark.length == 0)
this._localMarks.remove(mark);
break;
}
}
}
},
_removeURLMark: function _removeURLMark(mark) {
let urlmark = this._urlMarks.get(mark);
if (urlmark)
this._urlMarks.remove(mark);
},
_localMarkIter: function _localMarkIter() {
return ([m,val] for ([m, value] in marks._localMarks) for (val of value));
}
}, {
markToString: function markToString(name, mark) {
return name + ", " + mark.location +
", (" + Math.round(mark.position.x * 100) +
"%, " + Math.round(mark.position.y * 100) + "%)" +
(("tab" in mark) ? ", tab: " + tabs.index(mark.tab) : "");
},
isLocalMark: function isLocalMark(mark) /^['`a-z]$/.test(mark),
isURLMark: function isURLMark(mark) /^[A-Z0-9]$/.test(mark)
}, {
events: function () {
let appContent = document.getElementById("appcontent");
if (appContent)
events.addSessionListener(appContent, "load", this.closure._onPageLoad, true);
},
mappings: function () {
var myModes = config.browserModes;
mappings.add(myModes,
["m"], "Set mark at the cursor position",
function (arg) {
liberator.assert(/^[a-zA-Z]$/.test(arg));
marks.add(arg);
},
{ arg: true });
mappings.add(myModes,
["'", "`"], "Jump to the mark in the current buffer",
function (arg) { marks.jumpTo(arg); },
{ arg: true });
},
commands: function () {
commands.add(["delm[arks]"],
"Delete the specified marks",
function (args) {
liberator.assert( args.bang || args.string, "Argument required");
liberator.assert(!args.bang || !args.string, "Invalid argument");
if (args.bang) {
marks.remove();
} else {
args = args.string;
let matches = args.match(/((^|[^a-zA-Z])-|-($|[^a-zA-Z])|[^a-zA-Z -]).*/);
// NOTE: this currently differs from Vim's behavior which
// deletes any valid marks in the arg list, up to the first
// invalid arg, as well as giving the error message.
let msg = matches ? "Invalid argument:" + matches[0] : "";
liberator.assert(!matches, msg);
// check for illegal ranges - only allow a-z A-Z
if (matches = args.match(/[a-zA-Z]-[a-zA-Z]/g)) {
for (let match in values(matches)) {
liberator.assert(/[a-z]-[a-z]|[A-Z]-[A-Z]/.test(match) &&
match[0] <= match[2],
"Invalid argument: " + args.match(match + ".*")[0]);
}
}
marks.remove(args);
}
},
{
bang: true,
completer: function (context) completion.mark(context)
});
commands.add(["ma[rk]"],
"Mark current location within the web page",
function (args) {
let mark = args[0];
liberator.assert(mark.length <= 1, "Trailing characters");
liberator.assert(/[a-zA-Z]/.test(mark),
"Mark must be a letter or forward/backward quote");
marks.add(mark);
},
{ argCount: "1" });
commands.add(["marks"],
"Show all location marks of current web page",
function (args) {
args = args.string;
// ignore invalid mark characters unless there are no valid mark chars
liberator.assert(!args || /[a-zA-Z]/.test(args),
"No matching marks for: " + args.quote());
let filter = args.replace(/[^a-zA-Z]/g, "");
marks.list(filter);
});
},
completion: function () {
completion.mark = function mark(context) {
function percent(i) Math.round(i * 100);
// FIXME: Line/Column doesn't make sense with %
context.title = ["Mark", "Line Column File"];
context.keys.description = function ([, m]) percent(m.position.y) + "% " + percent(m.position.x) + "% " + m.location;
context.completions = marks.all;
};
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
const Modes = Module("modes", {
requires: ["config", "util"],
init: function () {
this._main = 1; // NORMAL
this._extended = 0; // NONE
this._lastShown = null;
this._passNextKey = false;
this._passAllKeys = false;
this._passKeysExceptions = null; // Which keys are still allowed in ignore mode. ONLY set when an :ignorekeys LocationChange triggered it
this._isRecording = false;
this._isReplaying = false; // playing a macro
this._modeStack = [];
this._mainModes = [this.NONE];
this._lastMode = 0;
this._modeMap = {};
// main modes, only one should ever be active
this.addMode("NORMAL", { char: "n", display: -1 });
this.addMode("INSERT", { char: "i", input: true });
this.addMode("VISUAL", { char: "v", display: function () "VISUAL" + (editor.getVisualMode() ? " " + editor.getVisualMode() : "") });
this.addMode("COMMAND_LINE", { char: "c", input: true, display: -1 });
this.addMode("CARET"); // text cursor is visible
this.addMode("TEXTAREA", { char: "i" });
this.addMode("EMBED", { input: true });
this.addMode("CUSTOM", { display: function () plugins.mode });
// this._extended modes, can include multiple modes, and even main modes
this.addMode("EX", true);
this.addMode("HINTS", true);
this.addMode("INPUT_MULTILINE", true);
this.addMode("OUTPUT_MULTILINE", true);
this.addMode("SEARCH_FORWARD", true);
this.addMode("SEARCH_BACKWARD", true);
this.addMode("SEARCH_VIEW_FORWARD", true);
this.addMode("SEARCH_VIEW_BACKWARD", true);
this.addMode("LINE", true); // linewise visual mode
this.addMode("PROMPT", true);
config.modes.forEach(function (mode) { this.addMode.apply(this, mode); }, this);
},
_getModeMessage: function () {
if (this._passNextKey) {
return "IGNORE";
} else if (this._passAllKeys) {
if (!this._passKeysExceptions || this._passKeysExceptions.length == 0)
return "IGNORE ALL KEYS (Press <S-Esc> or <Insert> to exit)";
else
return "IGNORE MOST KEYS (All except " + this._passKeysExceptions + ")";
}
// when recording or replaying a macro
if (modes.isRecording)
return "RECORDING";
else if (modes.isReplaying)
return "REPLAYING";
if (this._main in this._modeMap && typeof this._modeMap[this._main].display === "function")
return this._modeMap[this._main].display();
return ""; // default mode message
},
// NOTE: Pay attention that you don't run into endless loops
// Usually you should only indicate to leave a special mode like HINTS
// by calling modes.reset() and adding the stuff which is needed
// for its cleanup here
_handleModeChange: function (oldMode, newMode, oldExtended) {
switch (oldMode) {
case modes.TEXTAREA:
case modes.INSERT:
editor.unselectText();
break;
case modes.VISUAL:
if (newMode == modes.CARET) {
try { // clear any selection made; a simple if (selection) does not work
let selection = Buffer.focusedWindow.getSelection();
selection.collapseToStart();
}
catch (e) {}
}
else
editor.unselectText();
break;
case modes.CUSTOM:
plugins.stop();
break;
case modes.COMMAND_LINE:
// clean up for HINT mode
if (oldExtended & modes.HINTS)
hints.hide();
commandline.close();
break;
}
if (newMode == modes.NORMAL) {
// disable caret mode when we want to switch to normal mode
if (options.getPref("accessibility.browsewithcaret"))
options.setPref("accessibility.browsewithcaret", false);
if (oldMode == modes.COMMAND_LINE)
liberator.focusContent(false); // when coming from the commandline, we might want to keep the focus (after a Search, e.g.)
else
liberator.focusContent(true); // unfocus textareas etc.
} else if (newMode === modes.COMPOSE) {
services.get("focus").clearFocus(window);
}
},
NONE: 0,
__iterator__: function () util.Array.itervalues(this.all),
get all() this._mainModes.slice(),
get mainModes() (mode for ([k, mode] in Iterator(modes._modeMap)) if (!mode.extended && mode.name == k)),
get mainMode() this._modeMap[this._main],
addMode: function (name, extended, options) {
let disp = name.replace("_", " ", "g");
this[name] = 1 << this._lastMode++;
if (typeof extended == "object") {
options = extended;
extended = false;
}
this._modeMap[name] = this._modeMap[this[name]] = update({
extended: extended,
count: true,
input: false,
mask: this[name],
name: name,
disp: disp
}, options);
this._modeMap[name].display = this._modeMap[name].display || function () disp;
if (!extended)
this._mainModes.push(this[name]);
if ("mappings" in modules)
mappings.addMode(this[name]);
},
getMode: function (name) this._modeMap[name],
getCharModes: function (chr) [m for (m in values(this._modeMap)) if (m.char == chr)],
matchModes: function (obj) [m for (m in values(this._modeMap)) if (array(keys(obj)).every(function (k) obj[k] == (m[k] || false)))],
// show the current mode string in the command line
show: function () {
if (options["showmode"])
commandline.setModeMessage(this._getModeMessage());
},
// add/remove always work on the this._extended mode only
add: function (mode) {
this._extended |= mode;
this.show();
},
// helper function to set both modes in one go
// if silent == true, you also need to take care of the mode handling changes yourself
set: function (mainMode, extendedMode, silent, stack) {
silent = (silent || this._main == mainMode && this._extended == extendedMode);
// if a this._main mode is set, the this._extended is always cleared
let oldMain = this._main, oldExtended = this._extended;
if (typeof extendedMode === "number")
this._extended = extendedMode;
if (typeof mainMode === "number") {
this._main = mainMode;
if (!extendedMode)
this._extended = modes.NONE;
if (this._main != oldMain) {
this._handleModeChange(oldMain, mainMode, oldExtended);
liberator.triggerObserver("modeChange", [oldMain, oldExtended], [this._main, this._extended]);
// liberator.log("Changing mode from " + oldMain + "/" + oldExtended + " to " + this._main + "/" + this._extended + "(" + this._getModeMessage() + ")");
if (!silent)
this.show();
}
}
},
// TODO: Deprecate this in favor of addMode? --Kris
// Ya --djk
setCustomMode: function (modestr, oneventfunc, stopfunc) {
// TODO this.plugin[id]... ('id' maybe submode or what..)
plugins.mode = modestr;
plugins.onEvent = oneventfunc;
plugins.stop = stopfunc;
},
passAllKeysExceptSome: function passAllKeysExceptSome(exceptions) {
this._passAllKeys = true;
this._passKeysExceptions = exceptions || [];
this.show();
},
isKeyIgnored: function isKeyIgnored(key) {
if (modes.passNextKey)
return true;
if (modes.passAllKeys) { // handle Escape-all-keys mode (Shift-Esc)
// Respect "unignored" keys
if (modes._passKeysExceptions == null || modes._passKeysExceptions.indexOf(key) < 0)
return true;
else
return false;
// TODO: "unignore" option
// TODO: config.ignoreKeys support or remove config.ignoreKeys
}
return false;
},
// keeps recording state
reset: function (silent) {
this._modeStack = [];
if (config.isComposeWindow)
this.set(modes.COMPOSE, modes.NONE, silent);
else
this.set(modes.NORMAL, modes.NONE, silent);
},
remove: function (mode) {
if (this._extended & mode) {
this._extended &= ~mode;
this.show();
}
},
isMenuShown: false, // when a popup menu is active
get passNextKey() this._passNextKey,
set passNextKey(value) { this._passNextKey = value; this.show(); },
get passAllKeys() this._passAllKeys,
set passAllKeys(value) {
this._passAllKeys = value;
this._passKeysExceptions = null;
this.show();
},
get isRecording() this._isRecording,
set isRecording(value) { this._isRecording = value; this.show(); },
get isReplaying() this._isReplaying,
set isReplaying(value) { this._isReplaying = value; this.show(); },
get main() this._main,
set main(value) { this.set(value); },
get extended() this._extended,
set extended(value) { this.set(null, value); }
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const DEFAULT_FAVICON = "chrome://mozapps/skin/places/defaultFavicon.png";
// also includes methods for dealing with keywords and search engines
const Bookmarks = Module("bookmarks", {
requires: ["autocommands", "config", "liberator", "storage", "services"],
init: function () {
const faviconService = services.get("favicon");
const bookmarksService = services.get("bookmarks");
const historyService = services.get("history");
const tagging = PlacesUtils.tagging;
function getFavicon (uri) {
if (typeof uri === "string")
uri = util.newURI(uri);
var url = null;
faviconService.getFaviconDataForPage(uri, function (iconURI) {
url = iconURI ? iconURI.spec : "";
});
while (url === null)
liberator.threadYield(false, true);
return url;
}
this.getFavicon = getFavicon;
// Fix for strange Firefox bug:
// Error: [Exception... "Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIObserverService.addObserver]"
// nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)"
// location: "JS frame :: file://~firefox/components/nsTaggingService.js :: anonymous :: line 89"
// data: no]
// Source file: file://~firefox/components/nsTaggingService.js
tagging.getTagsForURI(window.makeURI("http://mysterious.bug"), {});
const Bookmark = Struct("url", "title", "icon", "keyword", "tags", "id");
const Keyword = Struct("keyword", "title", "icon", "url");
Bookmark.defaultValue("icon", function () getFavicon(this.url));
Bookmark.prototype.__defineGetter__("extra", function () [
["keyword", this.keyword, "Keyword"],
["tags", this.tags.join(", "), "Tag"]
].filter(function (item) item[1]));
const storage = modules.storage;
function Cache(name, store) {
const rootFolders = [bookmarksService.toolbarFolder, bookmarksService.bookmarksMenuFolder, bookmarksService.unfiledBookmarksFolder];
const sleep = liberator.sleep; // Storage objects are global to all windows, 'liberator' isn't.
let bookmarks = [];
let self = this;
this.__defineGetter__("name", function () name);
this.__defineGetter__("store", function () store);
this.__defineGetter__("bookmarks", function () this.load());
this.__defineGetter__("keywords",
function () [Keyword(k.keyword, k.title, k.icon, k.url) for (k of self.bookmarks) if (k.keyword)]);
this.__iterator__ = function () (val for (val of self.bookmarks));
function loadBookmark(node) {
if (node.uri == null) // How does this happen?
return false;
let uri = util.newURI(node.uri);
let keyword = bookmarksService.getKeywordForBookmark(node.itemId);
let tags = tagging.getTagsForURI(uri, {}) || [];
let bmark = Bookmark(node.uri, node.title, node.icon, keyword, tags, node.itemId);
bookmarks.push(bmark);
return bmark;
}
function readBookmark(id) {
return {
itemId: id,
uri: bookmarksService.getBookmarkURI(id).spec,
title: bookmarksService.getItemTitle(id)
};
}
function deleteBookmark(id) {
let length = bookmarks.length;
bookmarks = bookmarks.filter(function (item) item.id != id);
return bookmarks.length < length;
}
this.findRoot = function findRoot(id) {
do {
var root = id;
id = bookmarksService.getFolderIdForItem(id);
} while (id != bookmarksService.placesRoot && id != root);
return root;
};
this.isBookmark = function (id) rootFolders.indexOf(self.findRoot(id)) >= 0;
// since we don't use a threaded bookmark loading (by set preload)
// anymore, is this loading synchronization still needed? --mst
let loading = false;
this.load = function load() {
if (loading) {
while (loading)
sleep(10);
return bookmarks;
}
// update our bookmark cache
bookmarks = [];
loading = true;
let folders = rootFolders.slice();
let query = historyService.getNewQuery();
let options = historyService.getNewQueryOptions();
while (folders.length > 0) {
query.setFolders(folders, 1);
folders.shift();
let result = historyService.executeQuery(query, options);
let folder = result.root;
folder.containerOpen = true;
// iterate over the immediate children of this folder
for (let i = 0; i < folder.childCount; i++) {
let node = folder.getChild(i);
if (node.type == node.RESULT_TYPE_FOLDER) // folder
folders.push(node.itemId);
else if (node.type == node.RESULT_TYPE_URI) // bookmark
loadBookmark(node);
}
// close a container after using it!
folder.containerOpen = false;
}
this.__defineGetter__("bookmarks", function () bookmarks);
loading = false;
return bookmarks;
};
var observer = {
onBeginUpdateBatch: function onBeginUpdateBatch() {},
onEndUpdateBatch: function onEndUpdateBatch() {},
onItemVisited: function onItemVisited() {},
onItemMoved: function onItemMoved() {},
onItemAdded: function onItemAdded(itemId, folder, index) {
if (bookmarksService.getItemType(itemId) == bookmarksService.TYPE_BOOKMARK) {
if (self.isBookmark(itemId)) {
let bmark = loadBookmark(readBookmark(itemId));
storage.fireEvent(name, "add", bmark);
statusline.updateField("bookmark");
}
}
},
onItemRemoved: function onItemRemoved(itemId, folder, index) {
if (deleteBookmark(itemId)) {
storage.fireEvent(name, "remove", itemId);
statusline.updateField("bookmark");
}
},
onItemChanged: function onItemChanged(itemId, property, isAnnotation, value) {
if (isAnnotation)
return;
let bookmark = bookmarks.filter(function (item) item.id == itemId)[0];
if (bookmark) {
if (property == "tags")
value = tagging.getTagsForURI(util.newURI(bookmark.url), {});
if (property in bookmark)
bookmark[property] = value;
storage.fireEvent(name, "change", itemId);
}
},
QueryInterface: function QueryInterface(iid) {
if (iid.equals(Ci.nsINavBookmarkObserver) || iid.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
}
};
bookmarksService.addObserver(observer, false);
}
let bookmarkObserver = function (key, event, arg) {
if (event == "add")
autocommands.trigger("BookmarkAdd", arg);
};
this._cache = storage.newObject("bookmark-cache", Cache, { store: false });
storage.addObserver("bookmark-cache", bookmarkObserver, window);
},
get format() ({
anchored: false,
title: ["URL", "Info"],
keys: { text: "url", description: "title", icon: function(item) item.icon || DEFAULT_FAVICON,
extra: "extra", tags: "tags", keyword: "keyword" },
process: [template.icon, template.bookmarkDescription]
}),
// TODO: why is this a filter? --djk
get: function get(filter, tags, maxItems, extra) {
return completion.runCompleter("bookmark", filter, maxItems, tags, extra);
},
// if starOnly = true it is saved in the unfiledBookmarksFolder, otherwise in the bookmarksMenuFolder
add: function add(starOnly, title, url, keyword, tags, folder, force) {
var bs = services.get("bookmarks");
try {
let uri = util.createURI(url);
if (!force) {
for (let bmark in this._cache) {
if (bmark[0] == uri.spec) {
var id = bmark[5];
if (title)
bs.setItemTitle(id, title);
break;
}
}
}
let folderId = bs[starOnly ? "unfiledBookmarksFolder" : "bookmarksMenuFolder"];
if (folder) {
let folders = folder.split("/");
if (!folders[folders.length - 1])
folders.pop();
let rootFolderId = folderId;
if (folders[0] === "TOOLBAR") {
rootFolderId = bs.toolbarFolder;
folders.shift();
}
let node = Bookmarks.getBookmarkFolder(folders, rootFolderId);
if (node)
folderId = node.itemId;
else {
liberator.echoerr("Bookmark folder is not found: `" + folder + "'");
return false;
}
}
if (id == undefined)
id = bs.insertBookmark(folderId, uri, -1, title || url);
if (!id)
return false;
if (keyword)
bs.setKeywordForBookmark(id, keyword);
if (tags) {
PlacesUtils.tagging.untagURI(uri, null);
PlacesUtils.tagging.tagURI(uri, tags);
}
}
catch (e) {
liberator.echoerr(e);
return false;
}
return true;
},
toggle: function toggle(url) {
if (!url)
return;
let count = this.remove(url);
if (count > 0)
liberator.echomsg("Removed bookmark: " + url);
else {
let title = buffer.title || url;
let extra = "";
if (title != url)
extra = " (" + title + ")";
this.add(true, title, url);
liberator.echomsg("Added bookmark: " + url);
}
},
isBookmarked: function isBookmarked(url) services.get("bookmarks").isBookmarked(util.newURI(url)),
// returns number of deleted bookmarks
remove: function remove(url) {
try {
let uri = util.newURI(url);
let bmarks = services.get("bookmarks").getBookmarkIdsForURI(uri, {});
bmarks.forEach(services.get("bookmarks").removeItem);
return bmarks.length;
}
catch (e) {
liberator.echoerr(e);
return 0;
}
},
// TODO: add filtering
// also ensures that each search engine has a Liberator-friendly alias
getSearchEngines: function getSearchEngines() {
let searchEngines = [];
for (let [, engine] in Iterator(services.get("search").getVisibleEngines({}))) {
let alias = engine.alias;
if (!alias || !/^[a-z0-9_-]+$/.test(alias))
alias = engine.name.replace(/^\W*([a-zA-Z_-]+).*/, "$1").toLowerCase();
if (!alias)
alias = "search"; // for search engines which we can't find a suitable alias
// make sure we can use search engines which would have the same alias (add numbers at the end)
let newAlias = alias;
for (let j = 1; j <= 10; j++) { // <=10 is intentional
if (!searchEngines.some(function (item) item[0] == newAlias))
break;
newAlias = alias + j;
}
// only write when it changed, writes are really slow
if (engine.alias != newAlias)
engine.alias = newAlias;
searchEngines.push([engine.alias, engine.description, engine.iconURI && engine.iconURI.spec]);
}
return searchEngines;
},
getSuggestions: function getSuggestions(engineName, query, callback) {
const responseType = "application/x-suggestions+json";
let engine = services.get("search").getEngineByAlias(engineName);
if (engine && engine.supportsResponseType(responseType))
var queryURI = engine.getSubmission(query, responseType).uri.spec;
if (!queryURI)
return [];
function process(resp) {
let results = [];
try {
results = JSON.parse(resp.responseText)[1];
results = [[item, ""] for ([k, item] in Iterator(results)) if (typeof item == "string")];
}
catch (e) {}
if (!callback)
return results;
return callback(results);
}
let resp = util.httpGet(queryURI, callback && process);
if (!callback)
return process(resp);
return null;
},
// TODO: add filtering
// format of returned array:
// [keyword, helptext, url]
getKeywords: function getKeywords() {
return this._cache.keywords;
},
// full search string including engine name as first word in @param text
// if @param useDefSearch is true, it uses the default search engine
// @returns the url for the search string
// if the search also requires a postData, [url, postData] is returned
getSearchURL: function getSearchURL(text, useDefsearch) {
let searchString = (useDefsearch ? options["defsearch"] + " " : "") + text;
// we need to make sure our custom alias have been set, even if the user
// did not :open <tab> once before
this.getSearchEngines();
// ripped from Firefox
function getShortcutOrURI(url) {
var keyword = url;
var param = "";
var offset = url.indexOf(" ");
if (offset > 0) {
keyword = url.substr(0, offset);
param = url.substr(offset + 1);
}
var engine = services.get("search").getEngineByAlias(keyword);
if (engine) {
var submission = engine.getSubmission(param, null);
return [submission.uri.spec, submission.postData];
}
let [shortcutURL, postData] = PlacesUtils.getURLAndPostDataForKeyword(keyword);
if (!shortcutURL)
return [url, null];
let data = window.unescape(postData || "");
if (/%s/i.test(shortcutURL) || /%s/i.test(data)) {
var charset = "";
var matches = shortcutURL.match(/^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/);
if (matches)
[, shortcutURL, charset] = matches;
else {
try {
charset = services.get("history").getCharsetForURI(window.makeURI(shortcutURL));
}
catch (e) {}
}
var encodedParam;
if (charset)
encodedParam = escape(window.convertFromUnicode(charset, param));
else
encodedParam = encodeURIComponent(param);
shortcutURL = shortcutURL.replace(/%s/g, encodedParam).replace(/%S/g, param);
if (/%s/i.test(data))
postData = window.getPostDataStream(data, param, encodedParam, "application/x-www-form-urlencoded");
}
else if (param)
return [shortcutURL, null];
return [shortcutURL, postData];
}
let [url, postData] = getShortcutOrURI(searchString);
if (url == searchString)
return null;
if (postData)
return [url, postData];
return url; // can be null
},
// if openItems is true, open the matching bookmarks items in tabs rather than display
list: function list(filter, tags, openItems, maxItems, keyword) {
// FIXME: returning here doesn't make sense
// Why the hell doesn't it make sense? --Kris
// Because it unconditionally bypasses the final error message
// block and does so only when listing items, not opening them. In
// short it breaks the :bmarks command which doesn't make much
// sense to me but I'm old-fashioned. --djk
let kw = (keyword == "") ? undefined : {keyword:keyword};
if (!openItems)
return completion.listCompleter("bookmark", filter, maxItems, tags, kw, CompletionContext.Filter.textAndDescription);
let items = completion.runCompleter("bookmark", filter, maxItems, tags, kw, CompletionContext.Filter.textAndDescription);
if (items.length)
return liberator.open(items.map(function (i) i.url), liberator.NEW_TAB);
if (filter.length > 0 && tags.length > 0)
liberator.echoerr("No bookmarks matching tags: \"" + tags + "\" and string: \"" + filter + "\"");
else if (filter.length > 0)
liberator.echoerr("No bookmarks matching string: \"" + filter + "\"");
else if (tags.length > 0)
liberator.echoerr("No bookmarks matching tags: \"" + tags + "\"");
else
liberator.echoerr("No bookmarks set");
return null;
}
}, {
getBookmarkFolder: function (folders, rootFolderId) {
var q = PlacesUtils.history.getNewQuery(),
o = PlacesUtils.history.getNewQueryOptions();
if (rootFolderId == PlacesUtils.tagsFolderId)
o.resultType = o.RESULTS_AS_TAG_QUERY;
else {
q.setFolders([rootFolderId], 1);
o.expandQueries = false;
}
var res = PlacesUtils.history.executeQuery(q, o);
var node = res.root;
for (let folder of folders) {
node = getFolderFromNode(node, folder);
if (!node)
break;
}
return node;
function getFolderFromNode (node, title) {
for (let child in Bookmarks.iterateFolderChildren(node)) {
if (child.title == title && child instanceof Ci.nsINavHistoryContainerResultNode) {
node.containerOpen = false;
return child;
}
}
return null;
}
},
iterateFolderChildren: function (node, onlyFolder, onlyWritable) {
if (!node.containerOpen)
node.containerOpen = true;
for (let i = 0, len = node.childCount; i < len; i++) {
let child = node.getChild(i);
if (PlacesUtils.nodeIsContainer(child))
child.QueryInterface(Ci.nsINavHistoryContainerResultNode);
if (PlacesUtils.nodeIsFolder(child)) {
if (onlyWritable && child.childrenReadOnly)
continue;
}
else if (onlyFolder)
continue;
yield child;
}
},
}, {
commands: function () {
commands.add(["ju[mps]"],
"Show jumplist",
function () {
let sh = history.session;
let jumps = [[idx == sh.index ? ">" : "",
Math.abs(idx - sh.index),
val.title,
let(url=val.URI.spec) xml`<a highlight="URL" href=${url}>${url}</a>`]
for ([idx, val] in Iterator(sh))];
let list = template.tabular([{ header: "Jump", style: "color: red", colspan: 2 },
{ header: "", style: "text-align: right", highlight: "Number" },
{ header: "Title", style: "width: 250px; max-width: 500px; overflow: hidden" },
{ header: "URL", highlight: "URL jump-list" }],
jumps);
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
},
{ argCount: "0" });
// TODO: Clean this up.
function tags(context, args) {
let filter = context.filter;
let have = filter.split(",");
args.completeFilter = have.pop();
let prefix = filter.substr(0, filter.length - args.completeFilter.length);
let tags = util.Array.uniq(util.Array.flatten([b.tags for (b of bookmarks._cache.bookmarks)]));
return [[prefix + tag, tag] for (tag of tags) if (have.indexOf(tag) < 0)];
}
function title(context, args) {
if (!args.bang)
return [[content.document.title, "Current Page Title"]];
context.keys.text = "title";
context.keys.description = "url";
return bookmarks.get(args.join(" "), args["-tags"], null, { keyword: args["-keyword"], title: context.filter });
}
function keyword(context, args) {
let keywords = util.Array.uniq(util.Array.flatten([b.keyword for (b of bookmarks._cache.keywords)]));
return [[kw, kw] for (kw of keywords)];
}
commands.add(["bma[rk]"],
"Add a bookmark",
function (args) {
let url = args.length == 0 ? buffer.URL : args[0];
let title = args["-title"] || (args.length == 0 ? buffer.title : null);
let keyword = args["-keyword"] || null;
let tags = args["-tags"] || [];
let folder = args["-folder"] || "";
if (bookmarks.add(false, title, url, keyword, tags, folder, args.bang)) {
let extra = (title == url) ? "" : " (" + title + ")";
liberator.echomsg("Added bookmark: " + url + extra);
}
else
liberator.echoerr("Could not add bookmark: " + title);
}, {
argCount: "?",
bang: true,
completer: function (context, args) {
if (!args.bang) {
context.completions = [[content.document.documentURI, "Current Location"]];
return;
}
completion.bookmark(context, args["-tags"], { keyword: args["-keyword"], title: args["-title"] });
},
options: [[["-title", "-t"], commands.OPTION_STRING, null, title],
[["-tags", "-T"], commands.OPTION_LIST, null, tags],
[["-keyword", "-k"], commands.OPTION_STRING, function (arg) /\w/.test(arg)],
[["-folder", "-f"], commands.OPTION_STRING, null, function (context, args) {
return completion.bookmarkFolder(context, args, PlacesUtils.bookmarksMenuFolderId, true, true);
}]],
});
commands.add(["bmarks"],
"List or open multiple bookmarks",
function (args) {
bookmarks.list(args.join(" "), args["-tags"] || [], args.bang, args["-max"], args["-keyword"] || []);
},
{
bang: true,
completer: function completer(context, args) {
context.quote = null;
context.filter = args.join(" ");
context.filters = [CompletionContext.Filter.textAndDescription];
let kw = (args["-keyword"]) ? {keyword: args["-keyword"]} : undefined;
completion.bookmark(context, args["-tags"], kw);
},
options: [[["-tags", "-T"], commands.OPTION_LIST, null, tags],
[["-max", "-m"], commands.OPTION_INT],
[["-keyword", "-k"], commands.OPTION_STRING, null, keyword]]
});
commands.add(["delbm[arks]"],
"Delete a bookmark",
function (args) {
if (args.bang) {
commandline.input("This will delete all bookmarks. Would you like to continue? (yes/[no]) ",
function (resp) {
if (resp && resp.match(/^y(es)?$/i)) {
bookmarks._cache.bookmarks.forEach(function (bmark) { services.get("bookmarks").removeItem(bmark.id); });
liberator.echomsg("All bookmarks deleted");
}
});
}
else {
let url = args.string || buffer.URL;
let deletedCount = bookmarks.remove(url);
liberator.echomsg("Deleted " + deletedCount + " bookmark(s) with url: " + url.quote());
}
},
{
argCount: "?",
bang: true,
completer: function completer(context) completion.bookmark(context),
literal: 0
});
},
mappings: function () {
var myModes = config.browserModes;
mappings.add(myModes, ["a"],
"Open a prompt to bookmark the current URL",
function () {
let options = {};
let bmarks = bookmarks.get(buffer.URL).filter(function (bmark) bmark.url == buffer.URL);
if (bmarks.length == 1) {
let bmark = bmarks[0];
options["-title"] = bmark.title;
if (bmark.keyword)
options["-keyword"] = bmark.keyword;
if (bmark.tags.length > 0)
options["-tags"] = bmark.tags.join(", ");
}
else {
if (buffer.title != buffer.URL)
options["-title"] = buffer.title;
}
commandline.open("",
commands.commandToString({ command: "bmark", options: options, arguments: [buffer.URL], bang: bmarks.length > 1 }),
modes.EX);
});
mappings.add(myModes, ["A"],
"Toggle bookmarked state of current URL",
function () { bookmarks.toggle(buffer.URL); });
},
options: function () {
options.add(["defsearch", "ds"],
"Set the default search engine",
"string", "google",
{
completer: function completer(context) {
completion.search(context, true);
context.completions = [["", "Don't perform searches by default"]].concat(context.completions);
}
});
var browserSearch = services.get("search");
browserSearch.init(function() {
var alias = browserSearch.defaultEngine.alias;
if (alias) {
let defsearch = options.get("defsearch");
// when already changed, it means the user had been changed in RC file
if (defsearch.value === defsearch.defaultValue)
defsearch.value = alias
defsearch.defaultValue = alias;
}
});
},
completion: function () {
completion.bookmark = function bookmark(context, tags, extra) {
context.title = ["Bookmark", "Title"];
context.format = bookmarks.format;
for (let val in Iterator(extra || [])) {
let [k, v] = val; // Need block scope here for the closure
if (v)
context.filters.push(function (item) this._match(v, item[k] || ""));
}
// Need to make a copy because set completions() checks instanceof Array,
// and this may be an Array from another window.
context.completions = Array.slice(storage["bookmark-cache"].bookmarks);
completion.urls(context, tags);
};
completion.search = function search(context, noSuggest) {
let [, keyword, space, args] = context.filter.match(/^\s*(\S*)(\s*)(.*)$/);
let keywords = bookmarks.getKeywords();
let engines = bookmarks.getSearchEngines();
context.title = ["Search Keywords"];
context.completions = keywords.concat(engines);
context.keys = { text: 0, description: 1, icon: function(item) item[2] || DEFAULT_FAVICON };
if (!space || noSuggest)
return;
context.fork("suggest", keyword.length + space.length, this, "searchEngineSuggest",
keyword, true);
let item = keywords.filter(function (k) k.keyword == keyword)[0];
if (item && item.url.indexOf("%s") > -1) {
context.fork("keyword/" + keyword, keyword.length + space.length, null, function (context) {
context.format = history.format;
context.title = [keyword + " Quick Search"];
// context.background = true;
context.compare = CompletionContext.Sort.unsorted;
context.generate = function () {
let [begin, end] = item.url.split("%s");
return history.get({ uri: window.makeURI(begin), uriIsPrefix: true }).map(function (item) {
let rest = item.url.length - end.length;
let query = item.url.substring(begin.length, rest);
if (item.url.substr(rest) == end && query.indexOf("&") == -1) {
query = query.replace(/#.*/, "");
// Countermeasure for "Error: malformed URI sequence".
try {
item.url = decodeURIComponent(query);
}
catch (e) {
item.url = query;
}
return item;
}
return null;
}).filter(util.identity);
};
});
}
};
completion.searchEngineSuggest = function searchEngineSuggest(context, engineAliases, kludge) {
if (!context.filter)
return;
let engineList = (engineAliases || options["suggestengines"] || "google").split(",");
engineList.forEach(function (name) {
let engine = services.get("search").getEngineByAlias(name);
if (!engine)
return;
let [, word] = /^\s*(\S+)/.exec(context.filter) || [];
if (!kludge && word == name) // FIXME: Check for matching keywords
return;
let ctxt = context.fork(name, 0);
ctxt.title = [engine.description + " Suggestions"];
ctxt.compare = CompletionContext.Sort.unsorted;
ctxt.incomplete = true;
ctxt.match = function (str) str.toLowerCase().indexOf(this.filter.toLowerCase()) === 0;
bookmarks.getSuggestions(name, ctxt.filter, function (compl) {
ctxt.incomplete = false;
ctxt.completions = compl;
});
});
};
completion.bookmarkFolder = function bookmarkFolder (context, args, rootFolderId, onlyFolder, onlyWritable) {
let filter = context.filter,
folders = filter.split("/"),
item = folders.pop();
if (!rootFolderId)
rootFolderId = PlacesUtils.bookmarksMenuFolderId;
let folderPath = folders.length ? folders.join("/") + "/" : "";
if (folders[0] === "TOOLBAR") {
rootFolderId = PlacesUtils.toolbarFolderId;
folders.shift();
}
let folder = Bookmarks.getBookmarkFolder(folders, rootFolderId);
context.title = ["Bookmarks", folders.join("/") + "/"];
context._match = function (filter, str) str.toLowerCase().startsWith(filter.toLowerCase());
let results = [];
if (folders.length === 0) {
results.push(["TOOLBAR", "Bookmarks Toolbar"]);
}
if (folder) {
for (let child in Bookmarks.iterateFolderChildren(folder, onlyFolder, onlyWritable)) {
if (PlacesUtils.nodeIsSeparator(child))
continue;
results.push([folderPath + PlacesUIUtils.getBestTitle(child), child.uri]);
}
folder.containerOpen = false;
}
return context.completions = results;
};
completion.addUrlCompleter("S", "Suggest engines", completion.searchEngineSuggest);
completion.addUrlCompleter("b", "Bookmarks", completion.bookmark);
completion.addUrlCompleter("s", "Search engines and keyword URLs", completion.search);
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* This class is used for prompting of user input and echoing of messages.
*
* It consists of a prompt and command field be sure to only create objects of
* this class when the chrome is ready.
*/
const CommandLine = Module("commandline", {
requires: ["config", "liberator", "modes", "services", "storage", "template", "util"],
init: function () {
const self = this;
this._callbacks = {};
storage.newArray("history-search", { store: true, privateData: true });
storage.newArray("history-command", { store: true, privateData: true });
// Really inideal.
let services = modules.services; // Storage objects are global to all windows, 'modules' isn't.
storage.newObject("sanitize", function () {
({
CLEAR: "browser:purge-session-history",
QUIT: "quit-application",
init: function () {
services.get("obs").addObserver(this, this.CLEAR, false);
services.get("obs").addObserver(this, this.QUIT, false);
},
observe: function (subject, topic, data) {
switch (topic) {
case this.CLEAR:
["search", "command"].forEach(function (mode) {
CommandLine.History(null, mode).sanitize();
});
break;
case this.QUIT:
services.get("obs").removeObserver(this, this.CLEAR);
services.get("obs").removeObserver(this, this.QUIT);
break;
}
}
}).init();
}, { store: false });
storage.addObserver("sanitize",
function (key, event, value) {
autocommands.trigger("Sanitize", {});
}, window);
this._messageHistory = { //{{{
_messages: [],
get messages() {
let max = options["messages"];
// resize if 'messages' has changed
if (this._messages.length > max)
this._messages = this._messages.splice(this._messages.length - max);
return this._messages;
},
get length() this._messages.length,
clear: function clear() {
this._messages = [];
},
add: function add(message) {
if (!message)
return;
if (this._messages.length >= options["messages"])
this._messages.shift();
this._messages.push(message);
}
}; //}}}
this._lastMowOutput = null;
this._silent = false;
this._quiet = false;
this._lastEcho = null;
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// TIMERS //////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
this._statusTimer = new Timer(5, 100, function statusTell() {
if (self._completions == null)
return;
});
this._autocompleteTimer = new Timer(200, 500, function autocompleteTell(tabPressed) {
if (!events.feedingKeys && self._completions && options["autocomplete"]) {
self._completions.complete(true, false);
self._completions.itemList.show();
}
});
// This timer just prevents <Tab>s from queueing up when the
// system is under load (and, thus, giving us several minutes of
// the completion list scrolling). Multiple <Tab> presses are
// still processed normally, as the time is flushed on "keyup".
this._tabTimer = new Timer(0, 0, function tabTell(event) {
if (self._completions)
self._completions.tab(event.shiftKey);
});
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// VARIABLES ///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
this._completionList = ItemList("liberator-completions");
this._completions = null;
this._history = null;
this._startHints = false; // whether we're waiting to start hints mode
this._lastSubstring = "";
// the label for showing the mode message
this._modeWidget = document.getElementById("liberator-mode");
// the containing box for the this._promptWidget and this._commandWidget
this._commandlineWidget = document.getElementById("liberator-commandline");
// the text part of the prompt for the current command, for example "Find" or "Follow hint". Can be blank
this._promptWidget = document.getElementById("liberator-commandline-prompt-text");
// the command bar which contains the current command
this._commandWidget = document.getElementById("liberator-commandline-command");
this._messageBox = document.getElementById("liberator-message");
// this._messageBox.addEventListener("transitionend", this.close.bind(this), false);
this._commandWidget.inputField.QueryInterface(Ci.nsIDOMNSEditableElement);
// the widget used for multiline output
this._multilineOutputWidget = document.getElementById("liberator-multiline-output");
this._outputContainer = this._multilineOutputWidget.parentNode;
this._multilineOutputWidget.contentDocument.body.id = "liberator-multiline-output-content";
// the widget used for multiline intput
this._multilineInputWidget = document.getElementById("liberator-multiline-input");
// the widget used for bottombar
this._bottomBarWidget = document.getElementById("liberator-bottombar");
// we need to save the mode which we were in before opening the command line
// this is then used if we focus the command line again without the "official"
// way of calling "open"
this._currentExtendedMode = null; // the extended mode which we last openend the command line for
this._currentPrompt = null;
this._currentCommand = null;
// save the arguments for the inputMultiline method which are needed in the event handler
this._multilineRegexp = null;
this._multilineCallback = null;
this._input = {};
this._keepOpenForInput = false;
this._commandlineDisplayTimeoutID = null;
this.registerCallback("submit", modes.EX, function (command) {
if (self._commandlineDisplayTimeoutID) {
window.clearTimeout(self._commandlineDisplayTimeoutID);
self._commandlineDisplayTimeoutID = null;
}
commands.repeat = command;
liberator.trapErrors(function () liberator.execute(command));
//if (!(modes.main == modes.COMMAND_LINE) && !commandline._commandlineWidget.classList.contains("hidden"))
// this.close();
});
this.registerCallback("complete", modes.EX, function (context) {
context.fork("ex", 0, completion, "ex");
});
this.registerCallback("change", modes.EX, function (command) {
self._autocompleteTimer.tell(false);
});
this.registerCallback("cancel", modes.PROMPT, cancelPrompt);
this.registerCallback("submit", modes.PROMPT, closePrompt);
this.registerCallback("change", modes.PROMPT, function (str) {
if (self._input.complete)
self._autocompleteTimer.tell(false);
if (self._input.change)
self._input.change.call(commandline, str);
});
this.registerCallback("complete", modes.PROMPT, function (context) {
if (self._input.complete)
context.fork("input", 0, commandline, self._input.complete);
});
this.hide();
this._setHighlightGroup(this.HL_NORMAL);
function cancelPrompt(value) {
let callback = self._input.cancel;
self._input = {};
if (callback)
callback.call(self, value != null ? value : commandline.command);
}
function closePrompt(value) {
self._keepOpenForInput = false;
let callback = self._input.submit;
self._input = {};
if (callback)
callback.call(self, value != null ? value : commandline.command);
}
},
/**
* Highlight the messageBox according to <b>group</b>.
*/
_setHighlightGroup: function (group) {
this._messageBox.setAttributeNS(NS.uri, "highlight", group);
// also the underlying element needs to take on our color group
// otherwise e.g. a red background doesn't stretch the whole width
document.getElementById('liberator-statusline').setAttributeNS(NS.uri, "highlight", group);
},
/**
* reset messasaBox
*/
_resetStatusline: function () {
this._messageBox.value = "";
this._setHighlightGroup("");
},
/**
* Determines whether the command line should be visible.
*
* @returns {boolean}
*/
_commandShown: function () modes.main == modes.COMMAND_LINE &&
!(modes.extended & (modes.INPUT_MULTILINE | modes.OUTPUT_MULTILINE)),
/**
* Set the command-line prompt.
*
* @param {string} val
* @param {string} highlightGroup
*/
_setPrompt: function (val, highlightGroup) {
this._promptWidget.value = val;
this._promptWidget.collapsed = (val == "");
this._promptWidget.style.maxWidth = "-moz-calc(1em * " + val.length + ")";
},
/**
* Set the command-line input value. The caret is reset to the
* end of the line.
*
* @param {string} cmd
*/
_setCommand: function (cmd) {
this._commandWidget.value = cmd;
this._commandWidget.selectionStart = cmd.length;
this._commandWidget.selectionEnd = cmd.length;
},
/**
* Display a message in the command-line area.
*
* @param {string} str
* @param {string} highlightGroup
* @param {boolean} forceSingle If provided, don't let over-long
* messages move to the MOW.
*/
_echoLine: let (timeID = null) function (str, highlightGroup, forceSingle) {
if (timeID) {
window.clearTimeout(timeID);
timeID = null;
}
if (this._messageBox.classList.contains("liberator-hiding"))
this._messageBox.classList.remove("liberator-hiding");
this._setHighlightGroup(highlightGroup);
this._messageBox.value = str;
if (str && options["messagetimeout"] != -1 &&
[this.HL_INFOMSG, this.HL_WARNINGMSG].indexOf(highlightGroup) != -1)
timeID = this.setTimeout(function(){ this._messageBox.classList.add("liberator-hiding"); },
options["messagetimeout"]);
liberator.triggerObserver("echoLine", str, highlightGroup, forceSingle);
//if (!this._commandShown())
;//commandline.hide();
/*let field = this._messageBox.inputField;
if (!forceSingle && field.editor.rootElement.scrollWidth > field.scrollWidth)
this._echoMultiline(<span highlight="Message">{str}</span>, highlightGroup);*/
},
/**
* Display a multiline message.
*
* @param {string} str
* @param {string} highlightGroup
*/
// TODO: resize upon a window resize
_echoMultiline: function (str, highlightGroup) {
let doc = this._multilineOutputWidget.contentDocument;
let win = this._multilineOutputWidget.contentWindow;
liberator.triggerObserver("echoMultiline", str, highlightGroup);
this._lastMowOutput = xml`<div class="ex-command-output" style="white-space: nowrap" highlight=${highlightGroup}>${template.maybeXML(str)}</div>`;
let output = util.xmlToDom(this._lastMowOutput, doc);
// FIXME: need to make sure an open MOW is closed when commands
// that don't generate output are executed
//if (this._outputContainer.collapsed)
doc.body.innerHTML = "";
doc.body.appendChild(output);
commandline.updateOutputHeight(true);
if (win.scrollMaxY > 0) {
// start the last executed command's output at the top of the screen
let elements = doc.getElementsByClassName("ex-command-output");
elements[elements.length - 1].scrollIntoView(true);
}
else
win.scrollTo(0, doc.body.clientHeight);
win.focus();
modes.set(modes.COMMAND_LINE, modes.OUTPUT_MULTILINE);
},
/**
* Ensure that the multiline input widget is the correct size.
*/
_autosizeMultilineInputWidget: function () {
let lines = this._multilineInputWidget.value.split("\n").length - 1;
this._multilineInputWidget.setAttribute("rows", Math.max(lines, 1));
},
HL_NORMAL: "Normal",
HL_ERRORMSG: "ErrorMsg",
HL_MODEMSG: "ModeMsg",
HL_MOREMSG: "MoreMsg",
HL_QUESTION: "Question",
HL_INFOMSG: "InfoMsg",
HL_WARNINGMSG: "WarningMsg",
HL_LINENR: "LineNr",
FORCE_MULTILINE : 1 << 0,
FORCE_SINGLELINE : 1 << 1,
DISALLOW_MULTILINE : 1 << 2, // if an echo() should try to use the single line
// but output nothing when the MOW is open; when also
// FORCE_MULTILINE is given, FORCE_MULTILINE takes precedence
APPEND_TO_MESSAGES : 1 << 3, // add the string to the message this._history
get completionContext() this._completions.context,
get mode() (modes.extended == modes.EX) ? "cmd" : "search",
get silent() this._silent,
set silent(val) {
this._silent = val;
this._quiet = this._quiet;
},
get quiet() this._quiet,
set quiet(val) {
this._quiet = val;
Array.forEach(document.getElementById("liberator-commandline").childNodes, function (node) {
node.style.opacity = this._quiet || this._silent ? "0" : "";
});
},
// @param type can be:
// "submit": when the user pressed enter in the command line
// "change"
// "cancel"
// "complete"
registerCallback: function (type, mode, func) {
if (!(type in this._callbacks))
this._callbacks[type] = {};
this._callbacks[type][mode] = func;
},
triggerCallback: function (type, mode, data) {
if (type && mode && this._callbacks[type] && this._callbacks[type][mode])
//this._callbacks[type][mode].call(this, data);
this._callbacks[type][mode](data);
},
runSilently: function (func, self) {
let wasSilent = this._silent;
this._silent = true;
try {
func.call(self);
}
finally {
this._silent = wasSilent;
}
},
get command() {
try {
// The long path is because of complications with the
// completion preview.
return this._commandWidget.inputField.editor.rootElement.firstChild.textContent;
}
catch (e) {
return this._commandWidget.value;
}
},
set command(cmd) this._commandWidget.value = cmd,
get message() this._messageBox.value,
get messages() this._messageHistory,
/**
* Removes any previous output from the command line
*/
clear: function() {
this._commandWidget.value = "";
this._echoLine(""); // this also resets a possible background color from echoerr()
},
/**
* Show a mode message like "INSERT" in the command line
*/
setModeMessage: function(message, style) {
// we shouldn't need this check, but the XUL caching may not see this
// widget until the cache is rebuilt! So at least we don't break modes completely
if (this._modeWidget) {
this._modeWidget.collapsed = !message;
this._modeWidget.value = message;
}
},
/**
* Open the command line. The main mode is set to
* COMMAND_LINE, the extended mode to <b>extendedMode</b>.
* Further, callbacks defined for <b>extendedMode</b> are
* triggered as appropriate (see {@link #registerCallback}).
*
* @param {string} prompt
* @param {string} cmd
* @param {number} extendedMode
*/
open: function open(prompt, cmd, extendedMode) {
if (this._commandlineDisplayTimeoutID) {
window.clearTimeout(this._commandlineDisplayTimeoutID);
this._commandlineDisplayTimeoutID = null;
}
// save the current prompts, we need it later if the command widget
// receives focus without calling the this.open() method
this._currentPrompt = prompt || "";
this._currentCommand = cmd || "";
this._currentExtendedMode = extendedMode || null;
this._setPrompt(this._currentPrompt);
this._setCommand(this._currentCommand);
modes.set(modes.COMMAND_LINE, this._currentExtendedMode);
this.show();
this._history = CommandLine.History(this._commandWidget.inputField, (modes.extended == modes.EX) ? "command" : "search");
this._completions = CommandLine.Completions(this._commandWidget.inputField);
// open the completion list automatically if wanted
if (cmd.length)
commandline.triggerCallback("change", this._currentExtendedMode, cmd);
this._resetStatusline();
},
/**
* Closes the command line. This is ordinarily triggered automatically
* by a mode change. Will not hide the command line immediately if
* called directly after a successful command, otherwise it will.
*/
close: function close() {
this._keepOpenForInput = false;
let mode = this._currentExtendedMode;
this._currentExtendedMode = null;
commandline.triggerCallback("cancel", mode); // FIXME
if (this._history) {
this._history.save();
this._history = null;
}
// The completion things must be always reset
this.resetCompletions(); // cancels any asynchronous completion still going on, must be before we set completions = null
this._completionList.hide();
this._completions = null;
// liberator.log('closing with : ' + modes.main + "/" + modes.extended);
// hint prompt is available
if (this._startHints && modes.extended & modes.PROMPT) {
this._startHints = false;
return;
}
this._startHints = false;
// don't have input and output widget open at the same time
if (modes.extended & modes.INPUT_MULTILINE)
this._outputContainer.collapsed = true;
else if (modes.extended & modes.OUTPUT_MULTILINE) {
this._multilineInputWidget.collapsed = true;
liberator.focusContent();
} else {
liberator.focusContent();
this._multilineInputWidget.collapsed = true;
this._outputContainer.collapsed = true;
if (this._messageBox.getAttributeNS(NS.uri, "highlight") === this.HL_MOREMSG)
this._messageBox.value = "";
this.hide();
//modes.pop(true);
modes.reset();
}
},
/**
* Hides the command line, and shows any status messages that
* are under it.
*/
hide: function hide() {
// liberator.log('hiding commandline');
this._commandlineWidget.classList.add("hidden");
this._commandWidget.blur();
// needed for the sliding animation of the prompt text to be shown correctly
// on subsequent calls
this._setPrompt("");
},
/**
* Make the command line visible, hiding the status messages below
*
* @param {string} text: Optionally set the command line's text to this string
*/
show: function (text, prompt) {
if (typeof(text) === "string")
this._setCommand(text);
if (typeof(prompt) === "string")
this._setPrompt(prompt);
this._commandlineWidget.classList.remove("hidden");
this._commandWidget.focus();
},
/**
* Output the given string onto the command line. With no flags, the
* message will be shown in the status line if it's short enough to
* fit, and contains no new lines, and isn't XML. Otherwise, it will be
* shown in the MOW.
*
* @param {string} str
* @param {string} highlightGroup The Highlight group for the
* message.
* @default "Normal"
* @param {number} flags Changes the behavior as follows:
* commandline.APPEND_TO_MESSAGES - Causes message to be added to the
* messages history, and shown by :messages.
* commandline.FORCE_SINGLELINE - Forbids the command from being
* pushed to the MOW if it's too long or of there are already
* status messages being shown.
* commandline.DISALLOW_MULTILINE - Cancels the operation if the MOW
* is already visible.
* commandline.FORCE_MULTILINE - Forces the message to appear in
* the MOW.
*/
echo: function echo(str, highlightGroup, flags) {
if ((flags & this.FORCE_SINGLELINE) && (flags & this.FORCE_MULTILINE))
return liberator.echoerr("Conflicted flags argument for echo(): FORCE_SINGLELINE | FORCE_MULTILINE");
// liberator.echo uses different order of flags as it omits the highlight group,
// change commandline.echo argument order? --mst
if (this._silent)
return;
highlightGroup = highlightGroup || this.HL_NORMAL;
if (flags & this.APPEND_TO_MESSAGES)
this._messageHistory.add({ str: str, highlight: highlightGroup });
// The DOM isn't threadsafe. It must only be accessed from the main thread.
liberator.callInMainThread(function () {
if ((flags & this.DISALLOW_MULTILINE) && !this._outputContainer.collapsed)
return;
let single = flags & (this.FORCE_SINGLELINE | this.DISALLOW_MULTILINE);
let action = this._echoLine;
// TODO: this is all a bit convoluted - clean up.
// assume that FORCE_MULTILINE output is fully styled
if (!(flags & this.FORCE_MULTILINE) && !single && (!this._outputContainer.collapsed || this._messageBox.value == this._lastEcho)) {
highlightGroup += " Message";
action = this._echoMultiline;
}
if ((flags & this.FORCE_MULTILINE) || (/\n/.test(str) || typeof str == "xml" || str instanceof TemplateSupportsXML ) && !(flags & this.FORCE_SINGLELINE))
action = this._echoMultiline;
if (single)
this._lastEcho = null;
else {
if (this._messageBox.value == this._lastEcho)
this._echoMultiline(xml`<span highlight="Message">${this._lastEcho}</span>`,
this._messageBox.getAttributeNS(NS.uri, "highlight"));
this._lastEcho = (action == this._echoLine) && str;
}
if (action)
action.call(this, str, highlightGroup, single);
}, this);
},
/**
* Prompt the user. Sets modes.main to COMMAND_LINE, which the user may
* pop at any time to close the prompt.
*
* @param {string} prompt The input prompt to use.
* @param {function(string)} callback
* @param {Object} extra
* @... {function} onChange - A function to be called with the current
* input every time it changes.
* @... {function(CompletionContext)} completer - A completion function
* for the user's input.
* @... {string} promptHighlight - The HighlightGroup used for the
* prompt. @default "Question"
* @... {string} default - The initial value that will be returned
* if the user presses <CR> straightaway. @default ""
*/
input: function _input(prompt, callback, extra) {
extra = extra || {};
this._input = {
submit: callback,
change: extra.onChange,
complete: extra.completer,
cancel: extra.onCancel
};
this._keepOpenForInput = true;
modes.set(modes.COMMAND_LINE, modes.PROMPT);
this._currentExtendedMode = modes.PROMPT;
this._setPrompt(prompt, extra.promptHighlight || this.HL_QUESTION);
this._setCommand(extra.default || "");
// this._commandlineWidget.collapsed = false;
this.show();
this._commandWidget.focus();
this._history = CommandLine.History(this._commandWidget.inputField, (modes.extended == modes.EX) ? "command" : "search");
this._completions = CommandLine.Completions(this._commandWidget.inputField);
},
/**
* Get a multiline input from a user, up to but not including the line
* which matches the given regular expression. Then execute the
* callback with that string as a parameter.
*
* @param {RegExp} untilRegexp
* @param {function(string)} callbackFunc
*/
// FIXME: Buggy, especially when pasting. Shouldn't use a RegExp.
inputMultiline: function inputMultiline(untilRegexp, callbackFunc) {
modes.set(modes.COMMAND_LINE, modes.INPUT_MULTILINE);
//this._currentExtendedMode = modes.PROMPT; // like in input: ?
// save the arguments, they are needed in the event handler onEvent
this._multilineRegexp = untilRegexp;
this._multilineCallback = callbackFunc;
this._multilineInputWidget.collapsed = false;
this._multilineInputWidget.value = "";
this._autosizeMultilineInputWidget();
this.setTimeout(function () { this._multilineInputWidget.focus(); }, 10);
},
/**
* Handles all command-line events. All key events are passed here when
* COMMAND_LINE mode is active, as well as all input, keyup, focus, and
* blur events sent to the command-line XUL element.
*
* @param {Event} event
* @private
*/
onEvent: function onEvent(event) {
let command = this.command;
if (event.type == "blur") {
// prevent losing focus, there should be a better way, but it just didn't work otherwise
this.setTimeout(function () {
if (this._commandShown() && event.originalTarget == this._commandWidget.inputField)
this._commandWidget.inputField.focus();
}, 0);
}
else if (event.type == "focus") {
if (!this._commandShown() && event.originalTarget == this._commandWidget.inputField) {
event.originalTarget.blur();
}
}
else if (event.type == "input") {
this.resetCompletions();
commandline.triggerCallback("change", this._currentExtendedMode, command);
}
else if (event.type == "keypress") {
let key = events.toString(event);
if (this._completions)
this._completions.previewClear();
if (!this._currentExtendedMode)
return;
// user pressed <Enter> to carry out a command
// user pressing <Esc> is handled in the global onEscape
// FIXME: <Esc> should trigger "cancel" event
if (events.isAcceptKey(key)) {
//let currentExtendedMode = this._currentExtendedMode;
//this._currentExtendedMode = null; // Don't let modes.pop trigger "cancel"
commandline.triggerCallback("submit", this._currentExtendedMode, command);
if (!this._keepOpenForInput)
this.close();
}
// user pressed <Up> or <Down> arrow to cycle this._history completion
else if (/^<(Up|Down|S-Up|S-Down|PageUp|PageDown)>$/.test(key)) {
// prevent tab from moving to the next field
event.preventDefault();
event.stopPropagation();
liberator.assert(this._history);
this._history.select(/Up/.test(key), !/(Page|S-)/.test(key));
}
// user pressed <Tab> to get completions of a command
else if (/^<(Tab|S-Tab)>$/.test(key)) {
// prevent tab from moving to the next field
event.preventDefault();
event.stopPropagation();
this._tabTimer.tell(event);
}
else if (key == "<BS>") {
// reset the tab completion
//this.resetCompletions();
// and blur the command line if there is no text left
if (command.length == 0) {
commandline.triggerCallback("cancel", this._currentExtendedMode);
//modes.pop();
modes.reset();
}
}
else { // any other key
//this.resetCompletions();
}
// allow this event to be handled by the host app
}
else if (event.type == "keyup") {
let key = events.toString(event);
if (/^<(Tab|S-Tab)>$/.test(key))
this._tabTimer.flush();
}
},
/**
* Multiline input events, they will come straight from
* #liberator-multiline-input in the XUL.
*
* @param {Event} event
*/
onMultilineInputEvent: function onMultilineInputEvent(event) {
if (event.type == "keypress") {
let key = events.toString(event);
if (events.isAcceptKey(key)) {
let text = this._multilineInputWidget.value.substr(0, this._multilineInputWidget.selectionStart);
if (text.match(this._multilineRegexp)) {
text = text.replace(this._multilineRegexp, "");
modes.reset();
this._multilineInputWidget.collapsed = true;
this._multilineCallback.call(this, text);
}
}
else if (events.isCancelKey(key)) {
modes.reset();
this._multilineInputWidget.collapsed = true;
}
}
else if (event.type == "blur") {
if (modes.extended & modes.INPUT_MULTILINE)
this.setTimeout(function () { this._multilineInputWidget.inputField.focus(); }, 0);
}
else if (event.type == "input")
this._autosizeMultilineInputWidget();
return true;
},
/**
* Handle events when we are in multiline output mode, these come from
* liberator when modes.extended & modes.MULTILINE_OUTPUT and also from
* #liberator-multiline-output in the XUL.
*
* @param {Event} event
*/
onMultilineOutputEvent: function onMultilineOutputEvent(event) {
let win = this._multilineOutputWidget.contentWindow;
let key = events.toString(event);
if (event.type == "click" && event.target instanceof HTMLAnchorElement) {
function openLink(where) {
event.preventDefault();
// FIXME: Why is this needed? --djk
if (event.target.getAttribute("href") == "#")
liberator.open(event.target.textContent, where);
else
liberator.open(event.target.href, where);
}
switch (key) {
case "<LeftMouse>":
if (event.originalTarget.getAttributeNS(NS.uri, "highlight") == "URL buffer-list") {
event.preventDefault();
let textContent = event.originalTarget.parentNode.parentNode.firstElementChild.textContent.trim();
tabs.select(parseInt(textContent.replace(/^[^\d]*/, ""), 10) - 1, false, true);
}
else
openLink(liberator.CURRENT_TAB);
break;
case "<MiddleMouse>":
case "<C-LeftMouse>":
case "<C-M-LeftMouse>":
openLink(liberator.NEW_BACKGROUND_TAB);
break;
case "<S-MiddleMouse>":
case "<C-S-LeftMouse>":
case "<C-M-S-LeftMouse>":
openLink(liberator.NEW_TAB);
break;
case "<S-LeftMouse>":
openLink(liberator.NEW_WINDOW);
break;
}
return;
}
let isScrollable = win.scrollMaxY !== 0;
let showHelp = false;
switch (key) {
// close the window
case "<Esc>":
case "q":
modes.reset();
return; // handled globally in events.js:onEscape()
// reopen command line
case ":":
commandline.open("", "", modes.EX);
break;
// extended hint modes
case ";":
this._startHints = true;
hints.startExtendedHint("", win)
return;
// down a line
case "j":
case "<Down>":
case "<C-j>":
case "<C-m>":
case "<Return>":
if (isScrollable)
win.scrollByLines(1);
else
showHelp = true;
break;
// up a line
case "k":
case "<Up>":
case "<BS>":
if (isScrollable)
win.scrollByLines(-1);
else
showHelp = true;
break;
// half page down
case "d":
if (isScrollable)
win.scrollBy(0, win.innerHeight / 2);
else
showHelp = true;
break;
// half page up
case "u":
if (isScrollable)
win.scrollBy(0, -(win.innerHeight / 2));
else
showHelp = true;
break;
// page down
case "f":
case "<C-f>":
case "<Space>":
case "<PageDown>":
if (isScrollable)
win.scrollByPages(1);
else
showHelp = true;
break;
// page up
case "b":
case "<C-f>":
case "<PageUp>":
if (isScrollable)
win.scrollByPages(-1);
else
showHelp = true;
break;
// top of page
case "g":
case "<Home>":
if (isScrollable)
win.scrollTo(0, 0);
else
showHelp = true;
break;
// bottom of page
case "G":
case "<End>":
if (isScrollable)
win.scrollTo(0, win.scrollMaxY);
else
showHelp = true;
break;
case "Y":
let (sel = win.getSelection().toString()) {
if (sel)
util.copyToClipboard(sel, false);
else
showHelp = true;
}
break;
// unmapped key -> show Help
default:
showHelp = true;
}
if (showHelp) {
this.hide(); // hide the command line
let helpMsg = "Y: yank | ;o: follow hint | ESC/q: quit";
if (isScrollable)
helpMsg = "SPACE/d/j: screen/page/line down | b/u/k: screen/page/line up | " +
"HOME/g: top | END/G: bottom | " +
helpMsg;
this._echoLine(helpMsg, this.HL_MOREMSG, true);
} else {
this.show();
}
},
getSpaceNeeded: function getSpaceNeeded() {
let rect = this._commandlineWidget.getBoundingClientRect();
let offset = rect.bottom - window.innerHeight;
return Math.max(0, offset);
},
/**
* Changes the height of the message window to fit in the available space.
*
* @param {boolean} open If true, the widget will be opened if it's not
* already so.
*/
updateOutputHeight: function updateOutputHeight(open) {
if (!open && this._outputContainer.collapsed)
return;
let doc = this._multilineOutputWidget.contentDocument;
// xxx:
//let availableHeight = config.outputHeight;
//if (!this._outputContainer.collapsed)
// availableHeight += parseFloat(this._outputContainer.height);
doc.body.style.minWidth = this._commandlineWidget.scrollWidth + "px";
this._outputContainer.style.bottom = this.bottombarPosition;
this._outputContainer.style.maxHeight =
(this._outputContainer.height = Math.min(doc.body.clientHeight, config.outputHeight)) + "px";
doc.body.style.minWidth = "";
this._outputContainer.collapsed = false;
},
resetCompletions: function resetCompletions() {
if (this._completions) {
this._completions.context.cancelAll();
this._completions.wildIndex = -1;
this._completions.previewClear();
}
if (this._history)
this._history.reset();
},
// related floatbox
get bottombarPosition() (document.documentElement.boxObject.height - this._bottomBarWidget.boxObject.y) + "px",
}, {
/**
* A class for managing the history of an input field.
*
* @param {HTMLInputElement} inputField
* @param {string} mode The mode for which we need history.
*/
History: Class("History", {
init: function (inputField, mode) {
this.mode = mode;
this.input = inputField;
this.store = storage["history-" + mode];
this.reset();
},
/**
* Reset the history index to the first entry.
*/
reset: function () {
this.index = null;
},
/**
* Save the last entry to the permanent store. All duplicate entries
* are removed and the list is truncated, if necessary.
*/
save: function () {
if (events.feedingKeys)
return;
let str = this.input.value;
if (/^\s*$/.test(str))
return;
this.store.mutate("filter", function (line) (line.value || line) != str);
this.store.push({ value: str, timestamp: Date.now(), privateData: this.checkPrivate(str) });
this.store.truncate(options["history"], true);
},
/**
* @property {function} Returns whether a data item should be
* considered private.
*/
checkPrivate: function (str) {
// Not really the ideal place for this check.
if (this.mode == "command")
return (commands.get(commands.parseCommand(str)[1]) || {}).privateData;
return false;
},
/**
* Removes any private data from this history.
*/
sanitize: function (timespan) {
let range = [0, Number.MAX_VALUE];
if (liberator.has("sanitizer") && (timespan || options["sanitizetimespan"]))
range = sanitizer.getClearRange(timespan || options["sanitizetimespan"]);
const self = this;
this.store.mutate("filter", function (item) {
let timestamp = (item.timestamp || Date.now()/1000) * 1000;
return !line.privateData || timestamp < self.range[0] || timestamp > self.range[1];
});
},
/**
* Replace the current input field value.
*
* @param {string} val The new value.
*/
replace: function (val) {
this.input.value = val;
commandline.triggerCallback("change", this._currentExtendedMode, val);
},
/**
* Move forward or backward in history.
*
* @param {boolean} backward Direction to move.
* @param {boolean} matchCurrent Search for matches starting
* with the current input value.
*/
select: function (backward, matchCurrent) {
// always reset the tab completion if we use up/down keys
commandline._completions.reset();
let diff = backward ? -1 : 1;
if (this.index == null) {
this.original = this.input.value;
this.index = this.store.length;
}
// search the this._history for the first item matching the current
// commandline string
while (true) {
this.index += diff;
if (this.index < 0 || this.index > this.store.length) {
this.index = util.Math.constrain(this.index, 0, this.store.length);
liberator.beep();
// I don't know why this kludge is needed. It
// prevents the caret from moving to the end of
// the input field.
if (this.input.value == "") {
this.input.value = " ";
this.input.value = "";
}
break;
}
let hist = this.store.get(this.index);
// user pressed DOWN when there is no newer this._history item
if (!hist)
hist = this.original;
else
hist = (hist.value || hist);
if (!matchCurrent || hist.substr(0, this.original.length) == this.original) {
this.replace(hist);
break;
}
}
}
}),
/**
* A class for tab completions on an input field.
*
* @param {Object} input
*/
Completions: Class("Completions", {
init: function (input) {
this.context = CompletionContext(input);
this.context.onUpdate = this.closure._reset;
this.editor = input.editor;
this.selected = null;
this.wildmode = options.get("wildmode");
this.itemList = commandline._completionList;
this.itemList.setItems(this.context);
this.reset();
},
UP: {},
DOWN: {},
PAGE_UP: {},
PAGE_DOWN: {},
RESET: null,
get completion() {
let str = commandline.command;
return str.substring(this.prefix.length, str.length - this.suffix.length);
},
set completion(completion) {
this.previewClear();
// Change the completion text.
// The second line is a hack to deal with some substring
// preview corner cases.
let (str = this.prefix + completion + this.suffix) {
commandline._commandWidget.value = str;
this.editor.selection.focusNode.textContent = str;
}
// Reset the caret to one position after the completion.
this.caret = this.prefix.length + completion.length;
},
get caret() commandline._commandWidget.selectionEnd,
set caret(offset) {
commandline._commandWidget.selectionStart = offset;
commandline._commandWidget.selectionEnd = offset;
},
get start() this.context.allItems.start,
get items() this.context.allItems.items,
get substring() this.context.longestAllSubstring,
get wildtype() this.wildtypes[this.wildIndex] || "",
get type() ({
list: this.wildmode.checkHas(this.wildtype, "list"),
longest: this.wildmode.checkHas(this.wildtype, "longest"),
first: this.wildmode.checkHas(this.wildtype, ""),
full: this.wildmode.checkHas(this.wildtype, "full")
}),
complete: function complete(show, tabPressed) {
this.context.reset();
this.context.tabPressed = tabPressed;
commandline.triggerCallback("complete", commandline._currentExtendedMode, this.context);
this.context.updateAsync = true;
this.reset(show, tabPressed);
this.wildIndex = 0;
},
preview: function preview() {
this.previewClear();
if (this.wildIndex < 0 || this.suffix || !this.items.length)
return;
let substring = "";
switch (this.wildtype.replace(/.*:/, "")) {
case "":
substring = this.items[0].text;
break;
case "longest":
if (this.items.length > 1) {
substring = this.substring;
break;
}
// Fallthrough
case "full":
let item = this.items[this.selected != null ? this.selected + 1 : 0];
if (item)
substring = item.text;
break;
}
// Don't show 1-character substrings unless we've just hit backspace
if (substring.length < 2 && (!this._lastSubstring || !this._lastSubstring.startsWith(substring)))
return;
this._lastSubstring = substring;
let value = this.completion;
if (util.compareIgnoreCase(value, substring.substr(0, value.length)))
return;
substring = substring.substr(value.length);
this.removeSubstring = substring;
let node = util.xmlToDom(xml`<span highlight="Preview">${substring}</span>`,
document);
let start = this.caret;
this.editor.insertNode(node, this.editor.rootElement, 1);
this.caret = start;
},
previewClear: function previewClear() {
let node = this.editor.rootElement.firstChild;
if (node && node.nextSibling) {
try {
this.editor.deleteNode(node.nextSibling);
}
catch (e) {
node.nextSibling.textContent = "";
}
}
else if (this.removeSubstring) {
let str = this.removeSubstring;
let cmd = commandline._commandWidget.value;
if (cmd.substr(cmd.length - str.length) == str)
commandline._commandWidget.value = cmd.substr(0, cmd.length - str.length);
}
delete this.removeSubstring;
},
reset: function reset(show) {
this.wildIndex = -1;
this.prefix = this.context.value.substring(0, this.start);
this.value = this.context.value.substring(this.start, this.caret);
this.suffix = this.context.value.substring(this.caret);
if (show) {
this.itemList.reset();
this.selected = null;
this.wildIndex = 0;
}
this.wildtypes = this.wildmode.values;
this.preview();
},
// FIXME: having reset() and _reset() really sucks!
_reset: function _reset() {
this.prefix = this.context.value.substring(0, this.start);
this.value = this.context.value.substring(this.start, this.caret);
this.suffix = this.context.value.substring(this.caret);
if (this.selected >= this.items.length)
this.selected = null;
this.itemList.reset();
this.itemList.selectItem(this.selected);
this.preview();
},
select: function select(idx) {
switch (idx) {
case this.UP:
if (this.selected == null)
idx = -2;
else
idx = this.selected - 1;
break;
case this.DOWN:
if (this.selected == null)
idx = 0;
else
idx = this.selected + 1;
break;
case this.RESET:
idx = null;
break;
default:
idx = util.Math.constrain(idx, 0, this.items.length - 1);
break;
}
if (idx == -1 || this.items.length && idx >= this.items.length || idx == null) {
// Wrapped. Start again.
this.selected = null;
this.completion = this.value;
}
else {
// Wait for contexts to complete if necessary.
// FIXME: Need to make idx relative to individual contexts.
let list = this.context.contextList;
if (idx == -2)
list = list.slice().reverse();
let n = 0;
try {
this.waiting = true;
for (let context of list) {
function done() !(idx >= n + context.items.length || idx == -2 && !context.items.length);
while (context.incomplete && !done())
liberator.threadYield(false, true);
if (done())
break;
n += context.items.length;
}
}
finally {
this.waiting = false;
}
// See previous FIXME. This will break if new items in
// a previous context come in.
if (idx < 0)
idx = this.items.length - 1;
if (this.items.length == 0)
return;
this.selected = idx;
this.completion = this.items[idx].text;
}
this.itemList.selectItem(idx);
},
tabs: [],
tab: function tab(reverse) {
commandline._autocompleteTimer.flush();
// Check if we need to run the completer.
if (this.context.waitingForTab || this.wildIndex == -1)
this.complete(true, true);
this.tabs.push(reverse);
if (this.waiting)
return;
while (this.tabs.length) {
reverse = this.tabs.shift();
switch (this.wildtype.replace(/.*:/, "")) {
case "":
this.select(0);
break;
case "longest":
if (this.items.length > 1) {
if (this.substring && this.substring != this.completion)
this.completion = this.substring;
break;
}
// Fallthrough
case "full":
this.select(reverse ? this.UP : this.DOWN);
break;
}
if (this.type.list)
this.itemList.show();
this.wildIndex = util.Math.constrain(this.wildIndex + 1, 0, this.wildtypes.length - 1);
this.preview();
commandline._statusTimer.tell();
}
if (this.items.length == 0)
liberator.beep();
}
}),
/**
* eval() a JavaScript expression and return a string suitable
* to be echoed.
*
* @param {string} arg
* @param {boolean} useColor When true, the result is a
* highlighted XML object.
*/
echoArgumentToString: function (arg, useColor) {
if (!arg)
return "";
try {
arg = liberator.eval(arg);
}
catch (e) {
liberator.echoerr(e);
return null;
}
if (arg instanceof TemplateSupportsXML);
else if (typeof arg === "object")
arg = util.objectToString(arg, useColor);
else
arg = String(arg);
if (typeof arg == "string" && /\n/.test(arg))
arg = xml`<span highlight="CmdOutput">${arg}</span>`;
return arg;
}
}, {
commands: function () {
[
{
name: "ec[ho]",
description: "Echo the expression",
action: liberator.echo
},
{
name: "echoe[rr]",
description: "Echo the expression as an error message",
action: liberator.echoerr
},
{
name: "echom[sg]",
description: "Echo the expression as an informational message",
action: liberator.echomsg
}
].forEach(function (command) {
commands.add([command.name],
command.description,
function (args) {
var str = args.literalArg;
let str = CommandLine.echoArgumentToString(str, true);
if (str != null)
command.action(str);
}, {
completer: function (context) completion.javascript(context),
literal: 0
});
});
commands.add(["mes[sages]"],
"Display previously given messages",
function () {
if (commandline._messageHistory.length == 0)
liberator.echomsg("No previous messages");
// TODO: are all messages single line? Some display an aggregation
// of single line messages at least. E.g. :source
/*if (commandline._messageHistory.length == 1) {
let message = commandline._messageHistory.messages[0];
commandline.echo(message.str, message.highlight, commandline.FORCE_SINGLELINE);
}*/
else { //if (commandline._messageHistory.length > 1) {
let list = template.map2(xml, commandline._messageHistory.messages, function (message)
xml`<div highlight=${message.highlight + " Message"}>${message.str}</div>`);
liberator.echo(list, commandline.FORCE_MULTILINE);
}
},
{ argCount: "0" });
commands.add(["messc[lear]"],
"Clear the :messages list",
function () { commandline._messageHistory.clear(); },
{ argCount: "0" });
commands.add(["sil[ent]"],
"Run a command silently",
function (args) {
commandline.runSilently(function () liberator.execute(args[0], null, true));
}, {
completer: function (context) completion.ex(context),
literal: 0
});
},
mappings: function () {
var myModes = [modes.COMMAND_LINE];
// TODO: move "<Esc>", "<C-[>" here from mappings
mappings.add(myModes,
["<C-c>"], "Focus content",
function () {
let controller = window.document.commandDispatcher.getControllerForCommand("cmd_copy");
if (controller && controller.isCommandEnabled("cmd_copy"))
controller.doCommand("cmd_copy");
else
events.onEscape();
});
// Any "non-keyword" character triggers abbreviation expansion
// TODO: Add "<CR>" and "<Tab>" to this list
// At the moment, adding "<Tab>" breaks tab completion. Adding
// "<CR>" has no effect.
// TODO: Make non-keyword recognition smarter so that there need not
// be two lists of the same characters (one here and a regex in
// mappings.js)
mappings.add(myModes,
["<Space>", '"', "'"], "Expand command line abbreviation",
function () {
commandline.resetCompletions();
return editor.expandAbbreviation(modes.COMMAND_LINE);
},
{ route: true });
mappings.add(myModes,
["<C-]>", "<C-5>"], "Expand command line abbreviation",
function () { editor.expandAbbreviation(modes.COMMAND_LINE); });
mappings.add([modes.NORMAL],
["g<"], "Redisplay the last command output",
function () {
let lastMowOutput = commandline._lastMowOutput;
liberator.assert(lastMowOutput);
commandline._echoMultiline(lastMowOutput, commandline.HL_NORMAL);
});
},
options: function () {
options.add(["autocomplete", "ac"],
"Automatically list completions while typing",
"boolean", true);
options.add(["complete", "cpt"],
"Items which are completed at the :open prompts",
"charlist", typeof(config.defaults["complete"]) == "string" ? config.defaults["complete"] : "slf",
{
completer: function (context) array(values(completion.urlCompleters))
});
options.add(["history", "hi"],
"Number of Ex commands and search patterns to store in the command-line this._history",
"number", 500,
{ validator: function (value) value >= 0 });
options.add(["maxitems"],
"Maximum number of items to display at once",
"number", 20,
{ validator: function (value) value >= 1 });
options.add(["messages", "msgs"],
"Number of messages to store in the message this._history",
"number", 100,
{ validator: function (value) value >= 0 });
options.add(["messagetimeout", "mto"],
"Automatically hide messages after a timeout (in ms)",
"number", 10000,
{
completer: function (context) [
["-1", "Keep forever"],
["0", "Close immediately"],
],
validator: function (value) value >= -1
});
options.add(["showmode", "smd"],
"Show the current mode in the command line",
"boolean", true);
options.add(["suggestengines"],
"Engine Alias which has a feature of suggest",
"stringlist", "google",
{
completer: function completer(value) {
let engines = services.get("search").getEngines({})
.filter(function (engine) engine.supportsResponseType("application/x-suggestions+json"));
return engines.map(function (engine) [engine.alias, engine.description]);
}
});
options.add(["wildmode", "wim"],
"Define how command line completion works",
"stringlist", "list:full",
{
completer: function (context) [
// Why do we need ""?
["", "Complete only the first match"],
["full", "Complete the next full match"],
["longest", "Complete to longest common string"],
["list", "If more than one match, list all matches"],
["list:full", "List all and complete first match"],
["list:longest", "List all and complete common string"]
],
checkHas: function (value, val) {
let [first, second] = value.split(":", 2);
return first == val || second == val;
}
});
let idList = ["liberator-multiline-output", "liberator-completions"];
function floatBox(id) document.getElementById(id).parentNode
let animation = "animation";
options.add(["animations", "ani"], "enabled animation", "boolean", false, {
setter: function (value) {
let attr = value ? "add" : "remove";
idList.forEach(function (id) {
floatBox(id).classList[attr](animation);
});
return value;
},
getter: function () floatBox(idList[0]).classList.contains(animation),
});
},
styles: function () {
let fontSize = util.computedStyle(document.getElementById(config.mainWindowId)).fontSize;
styles.registerSheet("chrome://liberator/skin/liberator.css");
let error = styles.addSheet(true, "font-size", "chrome://liberator/content/buffer.xhtml",
"body { font-size: " + fontSize + "; }");
}
});
/**
* The list which is used for the completion box (and QuickFix window in
* future).
*
* @param {string} id The id of the <iframe> which will display the list. It
* must be in its own container element, whose height it will update as
* necessary.
*/
const ItemList = Class("ItemList", {
init: function (id) {
this._completionElements = [];
var iframe = document.getElementById(id);
if (!iframe) {
liberator.echoerr("No iframe with id: " + id + " found, strange things may happen!"); // "The truth is out there..." -- djk
return;
}
this._doc = iframe.contentDocument;
this._container = iframe.parentNode;
this._doc.body.id = id + "-content";
this._doc.body.appendChild(this._doc.createTextNode(""));
this._items = null;
this._startIndex = -1; // The index of the first displayed item
this._endIndex = -1; // The index one *after* the last displayed item
this._selIndex = -1; // The index of the currently selected element
this._div = null;
this._divNodes = {};
this._minHeight = 0;
},
_dom: function (xml, map) util.xmlToDom(xml, this._doc, map),
_autoSize: function () {
if (this._container.collapsed)
this._div.style.minWidth = document.getElementById("liberator-commandline").scrollWidth + "px";
this._minHeight = Math.max(this._minHeight, this._divNodes.completions.getBoundingClientRect().bottom);
this._container.style.maxHeight = this._minHeight + "px";
this._container.height = this._minHeight;
if (this._container.collapsed)
this._div.style.minWidth = "";
// FIXME: Belongs elsewhere.
commandline.updateOutputHeight(false);
this.setTimeout(function () { this._container.height -= commandline.getSpaceNeeded(); }, 0);
},
// Our dotted separator does not look good in combination with
// the completion window visible
// FIXME: Probably not the right thing to do for some themes
// Rather set a pseudo style which can be handled with :highlight
_updateSeparatorVisibility: function () {
let mowVisible = !(document.getElementById("liberator-multiline-output").parentNode.collapsed);
let separator = document.getElementById("liberator-separator");
separator.collapsed = this.visible() && !mowVisible;
},
_getCompletion: function (index) this._completionElements.snapshotItem(index - this._startIndex),
_init: function () {
this._div = this._dom(
xml`<div class="ex-command-output" highlight="Normal" style="white-space: nowrap">
<div highlight="Completions" key="noCompletions"><span highlight="Title">No Completions</span></div>
<div key="completions"/>
<div highlight="Completions">
${
template.map2(xml, util.range(0, options["maxitems"] * 2), function (i)
xml`<span highlight="CompItem">
<li highlight="NonText">~</li>
</span>`)
}
</div>
</div>`, this._divNodes);
this._doc.body.replaceChild(this._div, this._doc.body.firstChild);
//div.scrollIntoView(true);
this._items.contextList.forEach(function init_eachContext(context) {
delete context.cache.nodes;
if (!context.items.length && !context.message && !context.incomplete)
return;
context.cache.nodes = [];
this._dom(xml`<div key="root" highlight="CompGroup">
<div highlight="Completions">
${ context.createRow(context.title || [], "CompTitle") }
</div>
<div key="message" highlight="CompMsg"/>
<div key="items" highlight="Completions"/>
<div key="waiting" highlight="CompMsg">${ItemList.WAITING_MESSAGE}</div>
</div>`, context.cache.nodes);
this._divNodes.completions.appendChild(context.cache.nodes.root);
}, this);
setTimeout(this.closure._autoSize, 0);
},
/**
* Uses the entries in "items" to fill the listbox and does incremental
* filling to speed up things.
*
* @param {number} offset Start at this index and show options["maxitems"].
*/
_fill: function (offset) {
let diff = offset - this._startIndex;
if (this._items == null || offset == null || diff == 0 || offset < 0)
return false;
this._startIndex = offset;
this._endIndex = Math.min(this._startIndex + options["maxitems"], this._items.allItems.items.length);
let haveCompletions = false;
let off = 0;
let end = this._startIndex + options["maxitems"];
function getRows(context) {
function fix(n) util.Math.constrain(n, 0, len);
let len = context.items.length;
let start = off;
end -= !!context.message + context.incomplete;
off += len;
let s = fix(offset - start), e = fix(end - start);
return [s, e, context.incomplete && e >= offset && off - 1 < end];
}
this._items.contextList.forEach(function fill_eachContext(context) {
let nodes = context.cache.nodes;
if (!nodes)
return;
haveCompletions = true;
let root = nodes.root;
let items = nodes.items;
let [start, end, waiting] = getRows(context);
if (context.message)
nodes.message.textContent = context.message;
nodes.message.style.display = context.message ? "block" : "none";
nodes.waiting.style.display = waiting ? "block" : "none";
for (let [i, row] in Iterator(context.getRows(start, end, this._doc)))
nodes[i] = row;
for (let [i, row] in util.Array.iteritems(nodes)) {
if (!row)
continue;
let display = (i >= start && i < end);
if (display && row.parentNode != items) {
do {
var next = nodes[++i];
if (next && next.parentNode != items)
next = null;
}
while (!next && i < end)
items.insertBefore(row, next);
}
else if (!display && row.parentNode == items)
items.removeChild(row);
}
}, this);
this._divNodes.noCompletions.style.display = haveCompletions ? "none" : "block";
this._completionElements = util.evaluateXPath("//xhtml:div[@liberator:highlight='CompItem']", this._doc);
return true;
},
clear: function clear() { this.setItems(); this._doc.body.innerHTML = ""; },
hide: function hide() {
this._container.collapsed = true;
this._updateSeparatorVisibility();
},
show: function show() {
this._container.style.bottom = commandline.bottombarPosition;
this._container.collapsed = false;
this._updateSeparatorVisibility();
},
visible: function visible() !this._container.collapsed,
reset: function () {
this._startIndex = this._endIndex = this._selIndex = -1;
this._div = null;
this.selectItem(-1);
},
// if @param selectedItem is given, show the list and select that item
setItems: function setItems(newItems, selectedItem) {
if (this._container.collapsed)
this._minHeight = 0;
this._startIndex = this._endIndex = this._selIndex = -1;
this._items = newItems;
this.reset();
if (typeof selectedItem == "number") {
this.selectItem(selectedItem);
this.show();
}
},
// select index, refill list if necessary
selectItem: function selectItem(index) {
if (this._div == null)
this._init();
let sel = this._selIndex;
let len = this._items.allItems.items.length;
let newOffset = this._startIndex;
let maxItems = options["maxitems"];
let contextLines = Math.min(3, parseInt((maxItems - 1) / 2));
if (index == -1 || index == null || index == len) { // wrapped around
if (this._selIndex < 0)
newOffset = 0;
this._selIndex = -1;
index = -1;
}
else {
if (index <= this._startIndex + contextLines)
newOffset = index - contextLines;
if (index >= this._endIndex - contextLines)
newOffset = index + contextLines - maxItems + 1;
newOffset = Math.min(newOffset, len - maxItems);
newOffset = Math.max(newOffset, 0);
this._selIndex = index;
}
if (sel > -1)
this._getCompletion(sel).removeAttribute("selected");
this._fill(newOffset);
if (index >= 0)
this._getCompletion(index).setAttribute("selected", "true");
},
onEvent: function onEvent(event) false
}, {
WAITING_MESSAGE: "Generating results..."
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2010 by anekos <anekos@snca.net>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
const Abbreviation = Class("Abbreviation", {
init: function (modes, lhs, rhs) {
this.modes = modes;
this.lhs = lhs;
this.rhs = rhs;
},
equals: function (other) {
return this.lhs == other.lhs && this.rhs == other.rhs;
},
modesEqual: function (modes) {
return (modes.length === this.modes.length) &&
(this.modes.every(function (m1) modes.some(function (m2) m1 === m2)));
},
get text() (this.rhs instanceof Function ? this.rhs() : this.rhs).toString(),
inMode: function (mode) {
return this.modes.some(function (_mode) _mode == mode);
},
inModes: function (modes) {
let self = this;
return modes.some(function (mode) self.inMode(mode));
},
removeMode: function (mode) {
this.modes = this.modes.filter(function (m) m != mode);
},
get modeChar() Abbreviation.modeChar(this.modes)
}, {
modeChar: function (_modes) {
let result = "";
for ([, mode] in Iterator(_modes))
result += modes.getMode(mode).char;
if (/^(ic|ci)$/.test(result))
result = "!";
return result;
}
});
const Abbreviations = Module("abbreviations", {
requires: ["config", "modes"],
init: function () {
this.abbrevs = {};
// (summarized from Vim's ":help abbreviations")
//
// There are three types of abbreviations.
//
// full-id: Consists entirely of keyword characters.
// ("foo", "g3", "-1")
//
// end-id: Ends in a keyword character, but all other
// are not keyword characters.
// ("#i", "..f", "$/7")
//
// non-id: Ends in a non-keyword character, but the
// others can be of any type other than space
// and tab.
// ("def#", "4/7$")
//
// Example strings that cannot be abbreviations:
// "a.b", "#def", "a b", "_$r"
//
// For now, a keyword character is anything except for \s, ", or '
// (i.e., whitespace and quotes). In Vim, a keyword character is
// specified by the 'iskeyword' setting and is a much less inclusive
// list.
//
// TODO: Make keyword definition closer to Vim's default keyword
// definition (which differs across platforms).
let nonkw = "\\s\"'";
let keyword = "[^" + nonkw + "]";
let nonkeyword = "[" + nonkw + "]";
let fullId = keyword + "+";
let endId = nonkeyword + "+" + keyword;
let nonId = "\\S*" + nonkeyword;
// Used in add and expand
this._match = fullId + "|" + endId + "|" + nonId;
},
/**
* Adds a new abbreviation.
*
* @param {Abbreviation}
* @returns {Abbreviation}
*/
add: function (abbr) {
if (!(abbr instanceof Abbreviation))
abbr = Abbreviation.apply(null, arguments);
for (let mode of abbr.modes) {
if (!this.abbrevs[mode])
this.abbrevs[mode] = {};
this.abbrevs[mode][abbr.lhs] = abbr;
}
return abbr;
},
/**
* Returns matched abbreviation.
*
* @param {mode}
* @param {string}
*/
get: function (mode, lhs) {
let abbrevs = this.abbrevs[mode];
return abbrevs && abbrevs.hasOwnProperty(lhs) && abbrevs.propertyIsEnumerable(lhs) && abbrevs[lhs];
},
/**
* The list of the abbreviations merged from each modes.
*/
get merged() {
let result = [];
let lhses = util.Array.uniq([lhs for ([, mabbrevs] in Iterator(this.abbrevs)) for (lhs of Object.keys(mabbrevs))].sort());
for (let lhs of lhses) {
let exists = {};
for (let [, mabbrevs] in Iterator(this.abbrevs)) {
let abbr = mabbrevs[lhs];
if (abbr && !exists[abbr.rhs]) {
exists[abbr.rhs] = 1;
result.push(abbr);
}
}
}
return result;
},
/**
* Lists all abbreviations matching <b>modes</b> and <b>lhs</b>.
*
* @param {Array} list of mode.
* @param {string} lhs The LHS of the abbreviation.
*/
list: function (modes, lhs) {
let list = this.merged.filter(function (abbr) (abbr.inModes(modes) && abbr.lhs.startsWith(lhs)));
if (!list.length)
liberator.echomsg("No abbreviations found");
else if (list.length == 1) {
let head = list[0];
liberator.echo(head.modeChar + " " + head.lhs + " " + head.rhs, commandline.FORCE_SINGLELINE); // 2 spaces, 3 spaces
}
else {
list = list.map(function (abbr) [abbr.modeChar, abbr.lhs, abbr.rhs]);
list = template.tabular([{ header: "Mode", style: "padding-left: 1ex"}, { header: "Abbreviation", highlight: "Mapping"}, "Expanded text"], list);
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}
},
/**
* Remove the specified abbreviations.
*
* @param {Array} list of mode.
* @param {string} lhs of abbreviation.
* @returns {boolean} did the deleted abbreviation exist?
*/
remove: function (modes, lhs) {
let result = false;
for (let mode of modes) {
if ((mode in this.abbrevs) && (lhs in this.abbrevs[mode])) {
result = true;
this.abbrevs[mode][lhs].removeMode(mode);
delete this.abbrevs[mode][lhs];
}
}
return result;
},
/**
* Removes all abbreviations specified <b>modes<b>.
*
* @param {Array} list of mode.
*/
removeAll: function (modes) {
for (let mode of modes) {
if (!(mode in this.abbrevs))
return;
for (let [, abbr] in this.abbrevs[mode])
abbr.removeMode(mode);
delete this.abbrevs[mode];
}
}
}, {
}, {
completion: function () {
// TODO: shouldn't all of these have a standard signature (context, args, ...)? --djk
completion.abbreviation = function abbreviation(context, args, modes) {
if (args.completeArg == 0) {
let abbrevs = abbreviations.merged.filter(function (abbr) abbr.inModes(modes));
context.completions = [[abbr.lhs, abbr.rhs] for (abbr of abbrevs)];
}
};
},
commands: function () {
function addAbbreviationCommands(modes, ch, modeDescription) {
function splitArg (arg) {
return arg.match(RegExp("^\\s*($|" + abbreviations._match + ")(?:\\s*$|\\s+(.*))"));
}
modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";
commands.add([ch ? ch + "a[bbrev]" : "ab[breviate]"],
"Abbreviate a key sequence" + modeDescription,
function (args) {
let matches = splitArg(args.literalArg);
liberator.assert(matches, "Invalid argument: " + args.literalArg);
let [, lhs, rhs] = matches;
if (rhs) {
if (args["-javascript"]) {
let expr = rhs;
rhs = function () liberator.eval(expr);
rhs.toString = function () expr;
}
abbreviations.add(modes, lhs, rhs);
}
else {
abbreviations.list(modes, lhs || "");
}
}, {
options: [[["-javascript", "-j"], commands.OPTION_NOARG, null]],
completer: function (context, args) {
let [, lhs, rhs] = splitArg(args.literalArg);
if (rhs && args["-javascript"])
return completion.javascript(context);
completion.abbreviation(context, args, modes)
},
literal: 0,
serial: function () [ {
command: this.name,
arguments: [abbr.lhs],
literalArg: abbr.rhs,
options: abbr.rhs instanceof Function ? {"-javascript": null} : {}
}
for ([, abbr] in Iterator(abbreviations.merged))
if (abbr.modesEqual(modes))
]
});
commands.add([ch ? ch + "una[bbrev]" : "una[bbreviate]"],
"Remove an abbreviation" + modeDescription,
function (args) {
let lhs = args.literalArg;
if (!lhs)
return liberator.echoerr("Invalid argument");
if (!abbreviations.remove(modes, lhs))
return liberator.echoerr("No such abbreviation: " + lhs);
}, {
argCount: "1",
completer: function (context, args) completion.abbreviation(context, args, modes),
literal: 0
});
commands.add([ch + "abc[lear]"],
"Remove all abbreviations" + modeDescription,
function () { abbreviations.removeAll(modes); },
{ argCount: "0" });
}
addAbbreviationCommands([modes.INSERT, modes.COMMAND_LINE], "", "");
addAbbreviationCommands([modes.INSERT], "i", "insert");
addAbbreviationCommands([modes.COMMAND_LINE], "c", "command line");
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
try { __liberator_eval_result = eval(__liberator_eval_string);
}
catch (e) {
__liberator_eval_error = e;
}
// IMPORTANT: The eval statement *must* remain on the first line
// in order for line numbering in any errors to remain correct.
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2010 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* @param {String} name
* @param {String} description
* @param {String|TemplateXML} node
* String : the id attribute value of the existing node
* TemplateXML: a TemplateXML instance. e.g) xml`<xul:label ...>`
* @param {Function} updater
* @param {Object} extraInfo
*/
const StatusField = Class("StatusField", {
init: function (name, description, node, updater, extraInfo) {
this.name = name;
this.description = description;
if (typeof updater === "function")
this._updater = updater;
if (typeof node === "string") {
this.node = document.getElementById(node);
if (!this.node)
throw new Error('the element is not found: "' + node + '"');
}
else if (node instanceof TemplateXML) {
this.node = util.xmlToDom(node, document);
this.node.setAttribute("id", "liberator-status-" + name);
statusline._statuslineWidget.appendChild(this.node);
}
else
throw new TypeError("the argument node must be String or TemplateXML: " + node);
this.node.hidden = true;
if (extraInfo)
update(this, extraInfo);
},
/**
* field position starting 0.
* if set -1, this field will be hidden.
* @type {Number}
*/
get position () {
if (this.node.hasAttribute("liberatorPosition"))
return parseInt(this.node.getAttribute("libeatorPosition"), 10);
this.node.setAttribute("liberatorPosition", -1);
return -1;
},
set position (val) {
if (typeof val !== "number")
return false;
this.node.hidden = (val === -1);
this.node.setAttribute("liberatorPosition", val);
return true;
},
update: function (value) {
if (this._updater)
this._updater(this.node, value);
},
destroy: function () {
this.node.parentNode.removeChild(this.node);
},
});
const StatusLine = Module("statusline", {
init: function () {
// our status bar fields
this._statusfields = {};
this._statuslineWidget = document.getElementById("liberator-status");
},
/**
* @see StatusField
*/
addField: function (name, description, node, updater, extraInfo) {
if (name in this._statusfields)
return this._statusfields[name];
try {
var field = new StatusField(name, description, node, updater, extraInfo);
Object.defineProperty(this, name, { value: field, configurable: true, enumerable: true });
}
catch (e) {
Cu.reportError(e);
return null;
}
return this._statusfields[name] = field;
},
removeField: function (name) {
if (name in this._statusfields) {
this._statusfields[name].destroy();
return delete this._statusfields[name] && delete this[name];
}
return false;
},
sortFields: function (fieldNames) {
if (!fieldNames)
fieldNames = options.get("status").values;
for (var name of Object.keys(this._statusfields))
this._statusfields[name].position = fieldNames.indexOf(name);
Cc["@mozilla.org/xul/xul-sort-service;1"]
.getService(Ci.nsIXULSortService)
.sort(this._statuslineWidget, "liberatorPosition", "integer ascending");
},
// update all fields of the statusline
update: function update() {
let statusfields = this._statusfields;
let fieldNames = options.get("status").values;
this.sortFields(fieldNames);
for (let field of fieldNames) {
if (field in statusfields)
statusfields[field].update();
}
},
/**
* Set any field in the statusbar
*
* @param {String} fieldname
* @param {any} value
*/
updateField: function updateField (fieldname, value) {
var field = this._statusfields[fieldname];
if (field)
field.update(value);
},
}, {
}, {
statusline: function () {
statusline.addField("input", "Any partially entered key mapping", "liberator-status-input",
/**
* Set the contents of the status line's input buffer to the given
* string. Used primarily when a key press requires further input
* before being processed, including mapping counts and arguments,
* along with multi-key mappings.
*
* @param {Element} node
* @param {string} buffer
*/
function updateInputBuffer (node, buffer) {
if (!buffer || typeof buffer != "string")
buffer = "";
node.value = buffer;
});
statusline.addField("ssl", "The currently SSL status", "liberator-status-ssl",
function updateSSLState (node, state) {
var className = "";
if (!state) {
let securityUI = config.tabbrowser.securityUI;
if (securityUI)
state = securityUI.state || 0;
}
const WPL = Components.interfaces.nsIWebProgressListener;
if (state & WPL.STATE_IDENTITY_EV_TOPLEVEL)
className = "verifiedIdentity";
else if (state & WPL.STATE_IS_SECURE)
className = "verifiedDomain";
else if (state & WPL.STATE_IS_BROKEN) {
if ((state & WPL.STATE_LOADED_MIXED_ACTIVE_CONTENT) &&
options.getPref("security.mixed_content.block_active_content", false))
className = "mixedActiveContent";
}
node.className = className;
}, {
openPopup: function (anchor) {
var handler = window.gIdentityHandler;
if (typeof handler === "undefiend") // Thunderbird has none
return;
handler._identityPopup.hidden = false;
handler.setPopupMessages(handler._identityBox.className);
handler._identityPopup.openPopup(anchor);
},
});
statusline.addField("location", "The currently loaded URL", "liberator-status-location",
/**
* Update the URL displayed in the status line
*
* @param {Element} node
* @param {string} url The URL to display.
* @default buffer.URL
*/
function updateUrl (node, url) {
if (typeof(buffer) == "undefined") // quick hack to make the muttator compose work, needs more thought
return;
if (url == null)
// TODO: this probably needs a more general solution.
url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL);
// make it even more Vim-like
if (url == "about:blank") {
if (!buffer.title)
url = "[No Name]";
}
else {
url = url.replace(RegExp("^liberator://help/(\\S+)#(.*)"), function (m, n1, n2) n1 + " " + decodeURIComponent(n2) + " [Help]")
.replace(RegExp("^liberator://help/(\\S+)"), "$1 [Help]");
}
node.value = url;
});
statusline.addField("history", "The backward / forward history indicators", "liberator-status-history",
function updateHistory (node) {
let history = "";
if (window.getWebNavigation) {
let sh = window.getWebNavigation().sessionHistory;
if (sh && sh.index > 0)
history += "<";
if (sh && sh.index < sh.count - 1)
history += ">";
}
node.value = history;
});
statusline.addField("bookmark", "The bookmark indicator (heart)", "liberator-status-bookmark",
function updateBookmark (node, url) {
if (typeof(buffer) == "undefined") // quick hack to make the muttator compose work, needs more thought
return;
// if no url is given as the argument, use the current page
if (url == null)
url = buffer.URL;
let bookmark = "";
if ((modules.bookmarks) && (bookmarks.isBookmarked(url)))
bookmark = "\u2764";
node.value = bookmark;
});
statusline.addField("tabcount", "The number of currently selected tab and total number of tabs", "liberator-status-tabcount",
/**
* Display the correct tabcount (e.g., [1/5]) on the status bar.
*
* @param {Element} node
* @param {bool} delayed When true, update count after a
* brief timeout. Useful in the many cases when an
* event that triggers an update is broadcast before
* the tab state is fully updated.
*/
function updateTabCount (node, delayed) {
if (liberator.has("tabs")) {
if (delayed) {
window.setTimeout(function() updateTabCount(node, false), 0);
return;
}
node.value = "[" + (tabs.index() + 1) + "/" + tabs.count + "]";
}
});
statusline.addField("position", "The vertical scroll position", "liberator-status-position",
/**
* Display the main content's vertical scroll position in the status
* bar.
*
* @param {Element} node
* @param {number} percent The position, as a percentage. @optional
*/
function updateBufferPosition (node, percent) {
if (!percent || typeof percent != "number") {
let win = document.commandDispatcher.focusedWindow;
if (!win)
return;
percent = win.scrollMaxY == 0 ? -1 : win.scrollY / win.scrollMaxY;
}
let bufferPositionStr = "";
percent = Math.round(percent * 100);
if (percent < 0)
bufferPositionStr = "All";
else if (percent == 0)
bufferPositionStr = "Top";
else if (percent < 10)
bufferPositionStr = " " + percent + "%";
else if (percent >= 100)
bufferPositionStr = "Bot";
else
bufferPositionStr = percent + "%";
node.value = bufferPositionStr;
});
},
options: function () {
options.add(["status"],
"Define which information to show in the status bar",
"stringlist", "input,location,bookmark,history,tabcount,position",
{
setter: function setter(value) {
statusline.sortFields(this.values);
return value;
},
completer: function completer(context) {
var fields = statusline._statusfields;
return [[name, fields[name].description] for (name of Object.keys(fields))];
},
});
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
const AutoCommand = Struct("event", "pattern", "command");
/**
* @instance autocommands
*/
const AutoCommands = Module("autocommands", {
requires: ["config"],
init: function () {
this._store = [];
},
__iterator__: function () util.Array.itervalues(this._store),
/**
* Adds a new autocommand. <b>cmd</b> will be executed when one of the
* specified <b>events</b> occurs and the URL of the applicable buffer
* matches <b>regex</b>.
*
* @param {Array} events The array of event names for which this
* autocommand should be executed.
* @param {string} regex The URL pattern to match against the buffer URL.
* @param {string} cmd The Ex command to run.
*/
add: function (events, regex, cmd) {
if (typeof events == "string")
events = events.split(",");
events.forEach(function (event) {
this._store.push(AutoCommand(event, RegExp(regex), cmd));
}, this);
},
/**
* Returns all autocommands with a matching <b>event</b> and
* <b>regex</b>.
*
* @param {string} event The event name filter.
* @param {string} regex The URL pattern filter.
* @returns {AutoCommand[]}
*/
get: function (event, regex) {
return this._store.filter(function (autoCmd) AutoCommands.matchAutoCmd(autoCmd, event, regex));
},
/**
* Deletes all autocommands with a matching <b>event</b> and
* <b>regex</b>.
*
* @param {string} event The event name filter.
* @param {string} regex The URL pattern filter.
*/
remove: function (event, regex) {
this._store = this._store.filter(function (autoCmd) !AutoCommands.matchAutoCmd(autoCmd, event, regex));
},
/**
* Lists all autocommands with a matching <b>event</b> and
* <b>regex</b>.
*
* @param {string} event The event name filter.
* @param {string} regex The URL pattern filter.
*/
list: function (event, regex) {
let cmds = {};
// XXX
this._store.forEach(function (autoCmd) {
if (AutoCommands.matchAutoCmd(autoCmd, event, regex)) {
cmds[autoCmd.event] = cmds[autoCmd.event] || [];
cmds[autoCmd.event].push(autoCmd);
}
});
let list = template.genericOutput("Auto Commands",
xml`<table>
${
template.map2(xml, cmds, function ([event, items])
xml`<tr highlight="Title">
<td colspan="2">${event}</td>
</tr>${
template.map2(xml, items, function (item)
xml`<tr>
<td> ${item.pattern.source}</td>
<td>${item.command}</td>
</tr>`)}`)
}
</table>`);
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
},
/**
* Triggers the execution of all autocommands registered for
* <b>event</b>. A map of <b>args</b> is passed to each autocommand
* when it is being executed.
*
* @param {string} event The event to fire.
* @param {Object} args The args to pass to each autocommand.
*/
trigger: function (event, args) {
if (options.get("eventignore").has("all", event))
return;
let autoCmds = this._store.filter(function (autoCmd) autoCmd.event == event);
let lastPattern = null;
let url = args.url || "";
for (let autoCmd of autoCmds) {
if (autoCmd.pattern.test(url)) {
if (!lastPattern || lastPattern.source != autoCmd.pattern.source)
liberator.echomsg("Executing " + event + " Auto commands for \"" + autoCmd.pattern.source + "\"");
lastPattern = autoCmd.pattern;
// liberator.echomsg("autocommand " + autoCmd.command, 9);
if (typeof autoCmd.command == "function") {
try {
autoCmd.command.call(autoCmd, args);
}
catch (e) {
liberator.reportError(e);
liberator.echoerr(e);
}
}
else
liberator.execute(commands.replaceTokens(autoCmd.command, args), null, true);
}
}
}
}, {
matchAutoCmd: function (autoCmd, event, regex) {
return (!event || autoCmd.event == event) && (!regex || autoCmd.pattern.source == regex);
}
}, {
commands: function () {
commands.add(["au[tocmd]"],
"Execute commands automatically on events",
function (args) {
let [event, regex, cmd] = args;
let events = [];
try {
RegExp(regex);
}
catch (e) {
liberator.assert(false, "Invalid argument: " + regex);
}
if (event) {
// NOTE: event can only be a comma separated list for |:au {event} {pat} {cmd}|
let validEvents = config.autocommands.map(function (event) event[0]);
validEvents.push("*");
events = event.split(",");
liberator.assert(events.every(function (event) validEvents.indexOf(event) >= 0),
"No such group or event: " + event);
}
if (cmd) { // add new command, possibly removing all others with the same event/pattern
if (args.bang)
autocommands.remove(event, regex);
if (args["-javascript"])
cmd = eval("(function (args) { with(args) {" + cmd + "} })");
autocommands.add(events, regex, cmd);
}
else {
if (event == "*")
event = null;
if (args.bang) {
// TODO: "*" only appears to work in Vim when there is a {group} specified
if (args[0] != "*" || regex)
autocommands.remove(event, regex); // remove all
}
else
autocommands.list(event, regex); // list all
}
}, {
bang: true,
completer: function (context, args) {
if (args.length == 1)
return completion.autocmdEvent(context);
if (args.length == 3)
return args["-javascript"] ? completion.javascript(context) : completion.ex(context);
},
literal: 2,
options: [[["-javascript", "-js"], commands.OPTION_NOARG]]
});
[
{
name: "do[autocmd]",
description: "Apply the autocommands matching the specified URL pattern to the current buffer"
}, {
name: "doautoa[ll]",
description: "Apply the autocommands matching the specified URL pattern to all buffers"
}
].forEach(function (command) {
commands.add([command.name],
command.description,
// TODO: Perhaps this should take -args to pass to the command?
function (args) {
// Vim compatible
if (args.length == 0) {
liberator.echomsg("No matching autocommands");
return;
}
let [event, url] = args;
let defaultURL = url || buffer.URL;
let validEvents = config.autocommands.map(function (e) e[0]);
// TODO: add command validators
liberator.assert(event != "*",
"Cannot execute autocommands for ALL events");
liberator.assert(validEvents.indexOf(event) >= 0,
"No such group or event: " + args);
liberator.assert(autocommands.get(event).some(function (c) c.pattern.test(defaultURL)),
"No matching autocommands");
if (this.name == "doautoall" && liberator.has("tabs")) {
let current = tabs.index();
for (let i = 0; i < tabs.count; i++) {
tabs.select(i, false, true);
// if no url arg is specified use the current buffer's URL
autocommands.trigger(event, { url: defaultURL });
}
tabs.select(current);
}
else
autocommands.trigger(event, { url: defaultURL });
}, {
argCount: "*", // FIXME: kludged for proper error message should be "1".
completer: function (context) completion.autocmdEvent(context)
});
});
},
completion: function () {
JavaScript.setCompleter(this.get, [function () config.autocommands]);
completion.autocmdEvent = function autocmdEvent(context) {
context.completions = config.autocommands;
};
completion.macro = function macro(context) {
context.title = ["Macro", "Keys"];
context.completions = [item for (item in events.getMacros())];
};
},
options: function () {
options.add(["eventignore", "ei"],
"List of autocommand event names which should be ignored",
"stringlist", "",
{
completer: function () config.autocommands.concat([["all", "All events"]])
});
options.add(["focuscontent", "fc"],
"Try to stay in normal mode after loading a web page",
"boolean", false);
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
const Template = Module("template", {
add: function add(a, b) a + b,
join: function join(c) function (a, b) a + c + b,
map: function map(iter, func, sep, interruptable) {
return this.map2(xml, iter, func, sep, interruptable);
},
map2: function map(tag, iter, func, sep, interruptable) {
if (iter.length) // FIXME: Kludge?
iter = util.Array.itervalues(iter);
let ret = tag``;
let n = 0;
var op = tag["+="] || tag["+"] ||function (lhs, rhs) tag`${lhs}${rhs}`;
for each (let i in Iterator(iter)) {
let val = func(i);
if (val == undefined || (tag.isEmpty && tag.isEmpty(val)))
continue;
if (sep && n++)
ret = op(ret, sep);
if (interruptable && n % interruptable == 0)
liberator.threadYield(true, true);
ret = op(ret, val);
}
return ret;
},
maybeXML: function maybeXML(val) {
if (typeof val == "xml" || val instanceof TemplateSupportsXML)
return val;
try {
return xml.raw`${val}`;
}
catch (e) {}
return xml`${val}`;
},
completionRow: function completionRow(item, highlightGroup) {
if (typeof icon == "function")
icon = icon();
if (highlightGroup) {
var text = item[0] || "";
var desc = item[1] || "";
}
else {
var text = this.process[0].call(this, item, item.text);
var desc = this.process[1].call(this, item, item.description);
}
return xml`<div highlight=${highlightGroup || "CompItem"} style="white-space: nowrap">
<!-- The non-breaking spaces prevent empty elements
- from pushing the baseline down and enlarging
- the row.
-->
<li highlight="CompResult">${text} </li>
<li highlight="CompDesc">${desc} </li>
</div>`;
},
bookmarkDescription: function (item, text, filter)
xml`
<a href=${item.item.url} highlight="URL">${template.highlightFilter(text || "", filter)}</a> 
${
!(item.extra && item.extra.length) ? "" :
xml`<span class="extra-info">
(${
template.map2(xml, item.extra,
function (e) xml`${e[0]}: <span highlight=${e[2]}>${e[1]}</span>`,
xml.cdata` `/* Non-breaking space */)
})
</span>`
}
`,
icon: function (item, text) {
return xml`<span highlight="CompIcon">${item.icon ? xml`<img src=${item.icon}/>` : ""}</span><span class="td-strut"/>${text}`;
},
filter: function (str) xml`<span highlight="Filter">${str}</span>`,
// if "processStrings" is true, any passed strings will be surrounded by " and
// any line breaks are displayed as \n
highlight: function highlight(arg, processStrings, clip) {
// some objects like window.JSON or getBrowsers()._browsers need the try/catch
try {
let str = clip ? util.clip(String(arg), clip) : String(arg);
switch (arg == null ? "undefined" : typeof arg) {
case "number":
return xml`<span highlight="Number">${str}</span>`;
case "string":
if (processStrings)
str = str.quote();
return xml`<span highlight="String">${str}</span>`;
case "boolean":
return xml`<span highlight="Boolean">${str}</span>`;
case "function":
// Vim generally doesn't like /foo*/, because */ looks like a comment terminator.
// Using /foo*(:?)/ instead.
if (processStrings)
return xml`<span highlight="Function">${str.replace(/\{(.|\n)*(?:)/g, "{ ... }")}</span>`;
return xml`${arg}`;
case "undefined":
return xml`<span highlight="Null">${arg}</span>`;
case "object":
if (arg instanceof TemplateSupportsXML)
return arg;
// for java packages value.toString() would crash so badly
// that we cannot even try/catch it
if (/^\[JavaPackage.*\]$/.test(arg))
return xml`[JavaPackage]`;
if (processStrings && false)
str = template.highlightFilter(str, "\n", function () xml`<span highlight="NonText">^J</span>`);
return xml`<span highlight="Object">${str}</span>`;
case "xml":
return arg;
default:
return `<unknown type>`;
}
}
catch (e) {
return `<unknown>`;
}
},
highlightFilter: function highlightFilter(str, filter, highlight) {
if (filter.length == 0)
return str;
let filterArr = filter.split(" ");
let matchArr = [];
for (let item of filterArr) {
if (!item)
continue;
let lcstr = String.toLowerCase(str);
let lcfilter = item.toLowerCase();
let start = 0;
while ((start = lcstr.indexOf(lcfilter, start)) > -1) {
matchArr.push({pos:start, len:lcfilter.length});
start += lcfilter.length;
}
}
return this.highlightSubstrings(str, matchArr, highlight || template.filter);
},
highlightRegexp: function highlightRegexp(str, re, highlight) {
let matchArr = [];
let res;
while ((res = re.exec(str)) && res[0].length)
matchArr.push({pos:res.index, len:res[0].length});
return this.highlightSubstrings(str, matchArr, highlight || template.filter);
},
removeOverlapMatch: function removeOverlapMatch(matchArr) {
matchArr.sort(function(a,b) a.pos - b.pos || b.len - a.len); // Ascending start positions
let resArr = [];
let offset = -1;
let last, prev;
for (let item of matchArr) {
last = item.pos + item.len;
if (item.pos > offset) {
prev = resArr[resArr.length] = item;
offset = last;
} else if (last > offset) {
prev.len += (last - offset);
offset = last;
}
}
return resArr;
},
highlightSubstrings: function highlightSubstrings(str, iter, highlight) {
if (typeof str == "xml" || str instanceof TemplateSupportsXML)
return str;
if (str == "")
return xml`${str}`;
str = String(str).replace(" ", "\u00a0");
let s = xml``;
var add = xml["+="];
let start = 0;
let n = 0;
for (let item of this.removeOverlapMatch(iter)) {
if (n++ > 50) // Prevent infinite loops.
return add(s, xml`${str.substr(start)}`);
add(s, xml`${str.substring(start, item.pos)}`);
add(s, highlight(str.substr(item.pos, item.len)));
start = item.pos + item.len;
}
return add(s, xml`${str.substr(start)}`);
},
highlightURL: function highlightURL(str, force, highlight) {
highlight = "URL" + (highlight ? " " + highlight : "");
if (force || /^[a-zA-Z]+:\/\//.test(str))
return xml`<a highlight=${highlight} href=${str}>${str}</a>`;
else
return str;
},
// A generic output function which can have an (optional)
// title and the output can be an XML which is just passed on
genericOutput: function generic(title, value) {
if (title)
return xml`<table style="width: 100%">
<tr style="text-align: left;" highlight="CompTitle">
<th>${title}</th>
</tr>
</table>
<div style="padding-left: 0.5ex; padding-right: 0.5ex">${value}</div>
`;
else
return xml`${value}`;
},
// every item must have a .xml property which defines how to draw itself
// @param headers is an array of strings, the text for the header columns
genericTable: function genericTable(items, format) {
completion.listCompleter(function (context) {
context.filterFunc = null;
if (format)
context.format = format;
context.completions = items;
});
},
options: function options(title, opts) {
return this.genericOutput("",
xml`<table style="width: 100%">
<tr highlight="CompTitle" align="left">
<th>${title}</th>
</tr>
${
this.map2(xml, opts, function (opt) xml`
<tr>
<td>
<span style=${opt.isDefault ? "" : "font-weight: bold"}>${opt.pre}${opt.name}</span><span>${opt.value}</span>
${opt.isDefault || opt.default == null ? "" : xml`<span class="extra-info"> (default: ${opt.default})</span>`}
</td>
</tr>`)
}
</table>`);
},
// only used by showPageInfo: look for some refactoring
table: function table(title, data, indent) {
return this.table2(xml, title, data, indent);
},
table2: function table2(tag, title, data, indent) {
var body = this.map2(tag, data, function (datum) tag`
<tr>
<td style=${"font-weight: bold; min-width: 150px; padding-left: " + (indent || "2ex")}>${datum[0]}</td>
<td>${template.maybeXML(datum[1])}</td>
</tr>`);
let table =
tag`<table>
<tr highlight="Title" align="left">
<th colspan="2">${title}</th>
</tr>
${body}
</table>`;
return body ? table : tag``;
},
// This is a generic function which can display tabular data in a nice way.
// @param {string|array(string|object)} columns: Can either be:
// a) A string which is the only column header, streching the whole width
// b) An array of strings: Each string is the header of a column
// c) An array of objects: An object has optional properties "header", "style"
// and "highlight" which define the columns appearance
// @param {object} rows: The rows as an array or arrays (or other iterable objects)
tabular: function tabular(columns, rows) {
function createHeadings() {
if (typeof(columns) == "string")
return xml`<th colspan=${(rows && rows[0].length) || 1}>${columns}</th>`;
let colspan = 1;
return template.map(columns, function (h) {
if (colspan > 1) {
colspan--;
return xml``;
}
if (typeof(h) == "string")
return xml`<th>${h}</th>`;
let header = h.header || "";
colspan = h.colspan || 1;
return xml`<th colspan=${colspan}>${header}</th>`;
});
}
function createRow(row) {
return template.map(Iterator(row), function ([i, d]) {
let style = ((columns && columns[i] && columns[i].style) || "") + (i == (row.length - 1) ? "; width: 100%" : ""); // the last column should take the available space -> width: 100%
let highlight = (columns && columns[i] && columns[i].highlight) || "";
return xml`<td style=${style} highlight=${highlight}>${template.maybeXML(d)}</td>`;
});
}
return xml`<table style="width: 100%">
<tr highlight="CompTitle" align="left">
${
createHeadings()
}
</tr>
${
this.map2(xml, rows, function (row)
xml`<tr highlight="CompItem">
${
createRow(row)
}
</tr>`)
}
</table>`;
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* Creates a new completion context.
*
* @class A class to provide contexts for command completion.
* Manages the filtering and formatting of completions, and keeps
* track of the positions and quoting of replacement text. Allows for
* the creation of sub-contexts with different headers and quoting
* rules.
*
* @param {HTMLInputElement} input The editor for which completion is
* intended. May be a {CompletionContext} when forking a context,
* or a {string} when creating a new one.
* @param {string} name The name of this context. Used when the
* context is forked.
* @param {number} offset The offset from the parent context.
* @author Kris Maglione <maglione.k@gmail.com>
* @constructor
*/
const CompletionContext = Class("CompletionContext", {
init: function (input, name, offset) {
if (!name)
name = "";
let self = this;
if (input instanceof this.constructor) {
let parent = input;
name = parent.name + "/" + name;
this.contexts = parent.contexts;
if (name in this.contexts)
self = this.contexts[name];
else
self.contexts[name] = this;
/**
* @property {CompletionContext} This context's parent. {null} when
* this is a top-level context.
*/
self.parent = parent;
["filters", "keys", "title", "quote"].forEach(function (key)
self[key] = parent[key] && util.cloneObject(parent[key]));
["anchored", "compare", "editor", "inputField", "_filter", "filterFunc", "keys", "_process", "top"].forEach(function (key)
self[key] = parent[key]);
self.__defineGetter__("value", function () this.top.value);
self.offset = parent.offset;
self.advance(offset);
/**
* @property {boolean} Specifies that this context is not finished
* generating results.
* @default false
*/
self.incomplete = false;
self.message = null;
/**
* @property {boolean} Specifies that this context is waiting for the
* user to press <Tab>. Useful when fetching completions could be
* dangerous or slow, and the user has enabled autocomplete.
*/
self.waitingForTab = false;
delete self._generate;
delete self._ignoreCase;
if (self != this)
return self;
["_caret", "contextList", "maxItems", "onUpdate", "selectionTypes", "tabPressed", "updateAsync", "value"].forEach(function (key) {
self.__defineGetter__(key, function () this.top[key]);
self.__defineSetter__(key, function (val) this.top[key] = val);
});
}
else {
if (typeof input == "string")
this._value = input;
else {
this.inputField = input;
this.editor = input.editor;
}
this.compare = function (a, b) String.localeCompare(a.text, b.text);
/**
* @property {function} This function is called when we close
* a completion window with Esc or Ctrl-c. Usually this callback
* is only needed for long, asynchronous completions
*/
this.cancel = null;
/**
* @property {function} The function used to filter the results.
* @default Selects all results which match every predicate in the
* {@link #filters} array.
*/
this.filterFunc = function (items) {
let self = this;
return this.filters.
reduce(function (res, filter) res.filter(function (item) filter.call(self, item)),
items);
};
/**
* @property {Array} An array of predicates on which to filter the
* results.
*/
this.filters = [CompletionContext.Filter.text];
/**
* @property {boolean} Specifies whether this context results must
* match the filter at the beginning of the string.
* @default true
*/
this.anchored = true;
/**
* @property {Object} A map of all contexts, keyed on their names.
* Names are assigned when a context is forked, with its specified
* name appended, after a '/', to its parent's name. May
* contain inactive contexts. For active contexts, see
* {@link #contextList}.
*/
this.contexts = { "": this };
/**
* @property {Object} A mapping of keys, for {@link #getKey}. Given
* { key: value }, getKey(item, key) will return values as such:
* if value is a string, it will return item.item[value]. If it's a
* function, it will return value(item.item).
*/
this.keys = { text: 0, description: 1, icon: "icon" };
/**
* @property {number} This context's offset from the beginning of
* {@link #editor}'s value.
*/
this.offset = offset || 0;
/**
* @property {function} A function which is called when any subcontext
* changes its completion list. Only called when
* {@link #updateAsync} is true.
*/
this.onUpdate = function () true;
/**
* @property {CompletionContext} The top-level completion context.
*/
this.top = this;
this.__defineGetter__("incomplete", function () this.contextList.some(function (c) c.parent && c.incomplete));
this.__defineGetter__("waitingForTab", function () this.contextList.some(function (c) c.parent && c.waitingForTab));
this.reset();
}
/**
* @property {Object} A general-purpose store for functions which need to
* cache data between calls.
*/
this.cache = {};
/**
* @private
* @property {Object} A cache for return values of {@link #generate}.
*/
this.itemCache = {};
/**
* @property {string} A key detailing when the cached value of
* {@link #generate} may be used. Every call to
* {@link #generate} stores its result in {@link #itemCache}.
* When itemCache[key] exists, its value is returned, and
* {@link #generate} is not called again.
*/
this.key = "";
/**
* @property {string} A message to be shown before any results.
*/
this.message = null;
this.name = name || "";
/** @private */
this._completions = []; // FIXME
/**
* Returns a key, as detailed in {@link #keys}.
* @function
*/
this.getKey = function (item, key) (typeof self.keys[key] == "function") ? self.keys[key].call(this, item.item) :
key in self.keys ? item.item[self.keys[key]]
: item.item[key];
return this;
},
// Temporary
/**
* @property {Object}
*
* An object describing the results from all sub-contexts. Results are
* adjusted so that all have the same starting offset.
*
* @deprecated
*/
get allItems() {
try {
let self = this;
let minStart = Math.min.apply(Math, [context.offset for ([k, context] in Iterator(this.contexts)) if (context.items.length && context.hasItems)]);
if (minStart == Infinity)
minStart = 0;
let items = this.contextList.map(function (context) {
if (!context.hasItems)
return [];
let prefix = self.value.substring(minStart, context.offset);
return context.items.map(function (item) ({
text: prefix + item.text,
__proto__: item
}));
});
return { start: minStart, items: util.Array.flatten(items), longestSubstring: this.longestAllSubstring };
}
catch (e) {
liberator.echoerr(e);
return { start: 0, items: [], longestAllSubstring: "" };
}
},
// Temporary
get allSubstrings() {
let contexts = this.contextList.filter(function (c) c.hasItems && c.items.length);
let minStart = Math.min.apply(Math, contexts.map(function (c) c.offset));
let lists = contexts.map(function (context) {
let prefix = context.value.substring(minStart, context.offset);
return context.substrings.map(function (s) prefix + s);
});
let substrings = lists.reduce(
function (res, list) res.filter(function (str) list.some(function (s) s.substr(0, str.length) == str)),
lists.pop());
if (!substrings) // FIXME: How is this undefined?
return [];
return util.Array.uniq(Array.slice(substrings));
},
// Temporary
get longestAllSubstring() {
return this.allSubstrings.reduce(function (a, b) a.length > b.length ? a : b, "");
},
get caret() this._caret - this.offset,
set caret(val) this._caret = val + this.offset,
get compare() this._compare || function () 0,
set compare(val) this._compare = val,
get completions() this._completions || [],
set completions(items) {
// Accept a generator
if ({}.toString.call(items) != '[object Array]')
items = [x for (x in Iterator(items))];
delete this.cache.filtered;
delete this.cache.filter;
this.cache.rows = [];
this.hasItems = items.length > 0;
this._completions = items;
let self = this;
if (this.updateAsync && !this.noUpdate)
liberator.callInMainThread(function () { self.onUpdate.call(self); });
},
get createRow() this._createRow || template.completionRow, // XXX
set createRow(createRow) this._createRow = createRow,
get filterFunc() this._filterFunc || util.identity,
set filterFunc(val) this._filterFunc = val,
get filter() this._filter != null ? this._filter : this.value.substr(this.offset, this.caret),
set filter(val) {
delete this._ignoreCase;
return this._filter = val;
},
get format() ({
anchored: this.anchored,
title: this.title,
keys: this.keys,
process: this.process
}),
set format(format) {
this.anchored = format.anchored,
this.title = format.title || this.title;
this.keys = format.keys || this.keys;
this.process = format.process || this.process;
},
get message() this._message || (this.waitingForTab ? "Waiting for <Tab>" : null),
set message(val) this._message = val,
get proto() {
let res = {};
for (let i in Iterator(this.keys)) {
let [k, v] = i;
let _k = "_" + k;
if (typeof v == "string" && /^[.[]/.test(v))
v = eval("(function (i) i" + v + ")");
if (typeof v == "function")
res.__defineGetter__(k, function () _k in this ? this[_k] : (this[_k] = v(this.item)));
else
res.__defineGetter__(k, function () _k in this ? this[_k] : (this[_k] = this.item[v]));
res.__defineSetter__(k, function (val) this[_k] = val);
}
return res;
},
get regenerate() this._generate && (!this.completions || !this.itemCache[this.key] || this.cache.offset != this.offset),
set regenerate(val) { if (val) delete this.itemCache[this.key]; },
get generate() !this._generate ? null : function () {
if (this.offset != this.cache.offset)
this.itemCache = {};
this.cache.offset = this.offset;
if (!this.itemCache[this.key])
this.itemCache[this.key] = this._generate.call(this) || [];
return this.itemCache[this.key];
},
set generate(arg) {
this.hasItems = true;
this._generate = arg;
if (this.background && this.regenerate) {
let lock = {};
this.cache.backgroundLock = lock;
this.incomplete = true;
let thread = this.getCache("backgroundThread", liberator.newThread);
liberator.callAsync(thread, this, function () {
if (this.cache.backgroundLock != lock)
return;
let items = this.generate();
if (this.cache.backgroundLock != lock)
return;
this.incomplete = false;
this.completions = items;
});
}
},
// TODO: Is this actually broken anyway?
get ignoreCase() {
if ("_ignoreCase" in this)
return this._ignoreCase;
// smart case by default unless overriden above
return this._ignoreCase = !/[A-Z]/.test(this.filter);
},
set ignoreCase(val) this._ignoreCase = val,
get items() {
if (!this.hasItems || this.backgroundLock)
return [];
if (this.cache.filtered && this.cache.filter == this.filter)
return this.cache.filtered;
this.cache.rows = [];
let items = this.completions;
if (this.generate && !this.background) {
// XXX
this.noUpdate = true;
this.completions = items = this.generate();
this.noUpdate = false;
}
this.cache.filter = this.filter;
if (items == null)
return items;
let self = this;
delete this._substrings;
let proto = this.proto;
let filtered = this.filterFunc(items.map(function (item) ({ __proto__: proto, item: item })));
if (this.maxItems)
filtered = filtered.slice(0, this.maxItems);
if (this.compare)
filtered.sort(this.compare);
let quote = this.quote;
if (quote)
filtered.forEach(function (item) {
item.unquoted = item.text;
item.text = quote[0] + quote[1](item.text) + quote[2];
});
return this.cache.filtered = filtered;
},
get process() { // FIXME
let self = this;
let process = this._process;
process = [process[0] || template.icon, process[1] || function (item, k) k];
let first = process[0];
let second = process[1];
let filter = this.filter;
if (!this.anchored){
process[0] = function (item, text) first.call(self, item, template.highlightFilter(item.text, filter));
process[1] = function (item, text) second.call(self, item, item.description, filter);
}
return process;
},
set process(process) {
this._process = process;
},
get substrings() {
let items = this.items;
if (items.length == 0 || !this.hasItems)
return [];
if (this._substrings)
return this._substrings;
let fixCase = this.ignoreCase ? String.toLowerCase : util.identity;
let text = fixCase(items[0].unquoted || items[0].text);
let filter = fixCase(this.filter);
if (this.anchored) {
var compare = function compare(text, s) text.substr(0, s.length) == s;
var substrings = util.map(util.range(filter.length, text.length + 1),
function (end) text.substring(0, end));
}
else {
var compare = function compare(text, s) text.indexOf(s) >= 0;
substrings = [];
let start = 0;
let idx;
let length = filter.length;
while ((idx = text.indexOf(filter, start)) > -1 && idx < text.length) {
for (let end in util.range(idx + length, text.length + 1))
substrings.push(text.substring(idx, end));
start = idx + 1;
}
}
substrings = items.reduce(
function (res, item) res.filter(function (str) compare(fixCase(item.unquoted || item.text), str)),
substrings);
let quote = this.quote;
if (quote)
substrings = substrings.map(function (str) quote[0] + quote[1](str));
return this._substrings = substrings;
},
/**
* Advances the context <b>count</b> characters. {@link #filter} is
* advanced to match. If {@link #quote} is non-null, its prefix and suffix
* are set to the null-string.
*
* This function is still imperfect for quoted strings. When
* {@link #quote} is non-null, it adjusts the count based on the quoted
* size of the <b>count</b>-character substring of the filter, which is
* accurate so long as unquoting and quoting a string will always map to
* the original quoted string, which is often not the case.
*
* @param {number} count The number of characters to advance the context.
*/
advance: function advance(count) {
delete this._ignoreCase;
if (this.quote) {
count = this.quote[0].length + this.quote[1](this.filter.substr(0, count)).length;
this.quote[0] = "";
this.quote[2] = "";
}
this.offset += count;
if (this._filter)
this._filter = this._filter.substr(count);
},
cancelAll: function () {
for (let context of this.contextList) {
if (context.cancel)
context.cancel();
}
},
/**
* Gets a key from {@link #cache}, setting it to <b>defVal</b> if it
* doesn't already exists.
*
* @param {string} key
* @param defVal
*/
getCache: function (key, defVal) {
if (!(key in this.cache))
this.cache[key] = defVal();
return this.cache[key];
},
getItems: function getItems(start, end) {
let self = this;
let items = this.items;
let step = start > end ? -1 : 1;
start = Math.max(0, start || 0);
end = Math.min(items.length, end ? end : items.length);
return util.map(util.range(start, end, step), function (i) items[i]);
},
getRows: function getRows(start, end, doc) {
let self = this;
let items = this.items;
let cache = this.cache.rows;
let step = start > end ? -1 : 1;
start = Math.max(0, start || 0);
end = Math.min(items.length, end != null ? end : items.length);
for (let i in util.range(start, end, step))
yield [i, cache[i] = cache[i] || util.xmlToDom(self.createRow(items[i]), doc)];
},
fork: function fork(name, offset, self, completer) {
if (typeof completer == "string")
completer = self[completer];
let context = CompletionContext(this, name, offset);
this.contextList.push(context);
if (completer)
return completer.apply(self || this, [context].concat(Array.slice(arguments, arguments.callee.length)));
return context;
},
getText: function getText(item) {
let text = item[self.keys["text"]];
if (self.quote)
return self.quote(text);
return text;
},
highlight: function highlight(start, length, type) {
try { // Gecko < 1.9.1 doesn't have repaintSelection
this.selectionTypes[type] = null;
const selType = Ci.nsISelectionController["SELECTION_" + type];
const editor = this.editor;
let sel = editor.selectionController.getSelection(selType);
if (length == 0)
sel.removeAllRanges();
else {
let range = editor.selection.getRangeAt(0).cloneRange();
range.setStart(range.startContainer, this.offset + start);
range.setEnd(range.startContainer, this.offset + start + length);
sel.addRange(range);
}
editor.selectionController.repaintSelection(selType);
}
catch (e) {}
},
// FIXME
_match: function _match(filter, str) {
if (!filter)
return true;
let ignoreCase = this.ignoreCase;
let filterArr = filter.split(" ");
let self = this;
let res = filterArr.filter(function(word) {
if (!word)
return false;
if (ignoreCase) {
word = word.toLowerCase();
str = str.toLowerCase();
}
if (self.anchored)
return str.substr(0, word.length) == word; // TODO: Why not just use indexOf() == 0 ?
else
return str.indexOf(word) > -1;
});
return res.length == filterArr.length;
},
match: function match(str) {
return this._match(this.filter, str);
},
reset: function reset() {
let self = this;
if (this.parent)
throw Error();
// Not ideal.
for (let type in this.selectionTypes)
this.highlight(0, 0, type);
/**
* @property {[CompletionContext]} A list of active
* completion contexts, in the order in which they were
* instantiated.
*/
this.contextList = [];
this.offset = 0;
this.process = [];
this.selectionTypes = {};
this.tabPressed = false;
this.title = ["Completions"];
this.updateAsync = false;
this.cancelAll();
if (this.editor) {
this.value = this.editor.selection.focusNode.textContent;
this._caret = this.inputField.selectionEnd;
}
else {
this.value = this._value;
this._caret = this.value.length;
}
//for (let key in (k for ([k, v] in Iterator(self.contexts)) if (v.offset > this.caret)))
// delete this.contexts[key];
for (let [, context] in Iterator(this.contexts)) {
context.hasItems = false;
if (context != context.top)
context.incomplete = false;
}
},
/**
* Wait for all subcontexts to complete.
*
* @param {boolean} interruptible When true, the call may be interrupted
* via <C-c>, in which case, "Interrupted" may be thrown.
* @param {number} timeout The maximum time, in milliseconds, to wait.
* If 0 or null, wait indefinately.
*/
wait: function wait(interruptable, timeout) {
let end = Date.now() + timeout;
while (this.incomplete && (!timeout || Date.now() > end))
liberator.threadYield(false, interruptable);
return this.incomplete;
}
}, {
Sort: {
number: function (a, b) parseInt(b) - parseInt(a) || String.localeCompare(a, b),
unsorted: null
},
Filter: {
text: function (item) {
let text = Array.concat(item.text);
for (let [i, str] in Iterator(text)) {
if (this.match(String(str))) {
item.text = String(text[i]);
return true;
}
}
return false;
},
textDescription: function (item) {
return CompletionContext.Filter.text.call(this, item) || this.match(item.description);
},
textAndDescription: function (item) {
return this.match(item.text + item.description);
}
}
});
/**
* @instance completion
*/
const Completion = Module("completion", {
init: function () {
},
get setFunctionCompleter() JavaScript.setCompleter, // Backward compatibility
// FIXME
_runCompleter: function _runCompleter(name, filter, maxItems, tags, keyword, contextFilter) {
let context = CompletionContext(filter || "");
context.maxItems = maxItems;
if (contextFilter)
context.filters = [contextFilter];
let res = context.fork.apply(context, ["run", 0, this, name].concat(Array.slice(arguments, 3)));
if (res) // FIXME
return { items: res.map(function (i) ({ item: i })) };
context.wait(true);
return context.allItems;
},
runCompleter: function runCompleter(name, filter, maxItems, tags, keyword, contextFilter) {
return this._runCompleter.apply(this, Array.slice(arguments))
.items.map(function (i) i.item);
},
listCompleter: function listCompleter(name, filter, maxItems, tags, keyword, contextFilter) {
let context = CompletionContext(filter || "");
context.maxItems = maxItems;
if (contextFilter)
context.filters = [contextFilter];
context.fork.apply(context, ["list", 0, completion, name].concat(Array.slice(arguments, 3)));
context.wait();
for (let [key, context] in Iterator(context.contexts)) {
if (key.startsWith("/list")) {
let list = template.genericOutput("",
xml`<div highlight="Completions">
${ template.completionRow(context.title, "CompTitle") }
${ template.map2(xml, context.items, function (item) context.createRow(item), null, 100) }
</div>`);
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}
}
},
////////////////////////////////////////////////////////////////////////////////
////////////////////// COMPLETION TYPES ////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
// filter a list of urls
//
// may consist of search engines, filenames, bookmarks and history,
// depending on the 'complete' option
// if the 'complete' argument is passed like "h", it temporarily overrides the complete option
url: function url(context, complete) {
let numLocationCompletions = 0; // how many async completions did we already return to the caller?
let start = 0;
let skip = 0;
if (options["urlseparator"])
skip = context.filter.match("^.*" + options["urlseparator"]); // start after the last 'urlseparator'
if (skip)
context.advance(skip[0].length);
if (typeof complete === "undefined")
complete = options["complete"];
// Will, and should, throw an error if !(c in opts)
Array.forEach(complete, function (c) {
let completer = completion.urlCompleters[c];
context.fork.apply(context, [c, 0, completion, completer.completer].concat(completer.args));
});
},
urlCompleters: {},
addUrlCompleter: function addUrlCompleter(opt) {
let completer = Completion.UrlCompleter.apply(null, Array.slice(arguments));
completer.args = Array.slice(arguments, completer.length);
this.urlCompleters[opt] = completer;
},
urls: function (context, tags) {
let compare = String.localeCompare;
let contains = String.indexOf;
if (context.ignoreCase) {
compare = util.compareIgnoreCase;
contains = function (a, b) a && a.toLowerCase().indexOf(b.toLowerCase()) > -1;
}
if (tags)
context.filters.push(function (item) tags.
every(function (tag) (item.tags || []).
some(function (t) !compare(tag, t))));
context.anchored = false;
if (!context.title)
context.title = ["URL", "Title"];
}
//}}}
}, {
UrlCompleter: Struct("name", "description", "completer")
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2010 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
Cu.import("resource://gre/modules/XPCOMUtils.jsm", modules);
const Point = Struct("x", "y");
/**
* A class to manage the primary web content buffer. The name comes
* from Vim's term, 'buffer', which signifies instances of open
* files.
* @instance buffer
*/
const Buffer = Module("buffer", {
requires: ["config"],
init: function () {
this.pageInfo = {};
this.addPageInfoSection("f", "Feeds", function (verbose) {
let doc = config.browser.contentDocument;
const feedTypes = {
"application/rss+xml": "RSS",
"application/atom+xml": "Atom",
"text/xml": "XML",
"application/xml": "XML",
"application/rdf+xml": "XML"
};
function isValidFeed(data, principal, isFeed) {
if (!data || !principal)
return false;
if (!isFeed) {
var type = data.type && data.type.toLowerCase();
type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
isFeed = ["application/rss+xml", "application/atom+xml"].indexOf(type) >= 0 ||
// really slimy: general XML types with magic letters in the title
type in feedTypes && /\brss\b/i.test(data.title);
}
if (isFeed) {
try {
window.urlSecurityCheck(data.href, principal,
Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
}
catch (e) {
isFeed = false;
}
}
if (type)
data.type = type;
return isFeed;
}
let nFeed = 0;
for (let link in util.evaluateXPath(["link[@href and (@rel='feed' or (@rel='alternate' and @type))]"], doc)) {
let rel = link.rel.toLowerCase();
let feed = { title: link.title, href: link.href, type: link.type || "" };
if (isValidFeed(feed, doc.nodePrincipal, rel == "feed")) {
nFeed++;
let type = feedTypes[feed.type] || "RSS";
if (verbose)
yield [feed.title, xml`${template.highlightURL(feed.href, true)}<span class="extra-info"> (${type})</span>`];
}
}
if (!verbose && nFeed)
yield nFeed + " feed" + (nFeed > 1 ? "s" : "");
});
this.addPageInfoSection("g", "Document", function (verbose) {
let doc = config.browser.contentDocument;
// get file size
const ACCESS_READ = Ci.nsICache.ACCESS_READ;
let cacheKey = doc.location.toString().replace(/#.*$/, "");
for (let proto of ["HTTP", "FTP"]) {
try {
var cacheEntryDescriptor = services.get("cache").createSession(proto, 0, true)
.openCacheEntry(cacheKey, ACCESS_READ, false);
break;
}
catch (e) {}
}
let pageSize = []; // [0] bytes; [1] kbytes
if (cacheEntryDescriptor) {
pageSize[0] = util.formatBytes(cacheEntryDescriptor.dataSize, 0, false);
pageSize[1] = util.formatBytes(cacheEntryDescriptor.dataSize, 2, true);
if (pageSize[1] == pageSize[0])
pageSize.length = 1; // don't output "xx Bytes" twice
}
let lastModVerbose = new Date(doc.lastModified).toLocaleString();
let lastMod = new Date(doc.lastModified).toLocaleFormat("%x %X");
if (lastModVerbose == "Invalid Date" || new Date(doc.lastModified).getFullYear() == 1970)
lastModVerbose = lastMod = null;
if (!verbose) {
if (pageSize[0])
yield (pageSize[1] || pageSize[0]) + " bytes";
yield lastMod;
return;
}
yield ["Title", doc.title];
yield ["URL", template.highlightURL(doc.location.toString(), true)];
let ref = "referrer" in doc && doc.referrer;
if (ref)
yield ["Referrer", template.highlightURL(ref, true)];
if (pageSize[0])
yield ["File Size", pageSize[1] ? pageSize[1] + " (" + pageSize[0] + ")"
: pageSize[0]];
yield ["Mime-Type", doc.contentType];
yield ["Encoding", doc.characterSet];
yield ["Compatibility", doc.compatMode == "BackCompat" ? "Quirks Mode" : "Full/Almost Standards Mode"];
if (lastModVerbose)
yield ["Last Modified", lastModVerbose];
});
this.addPageInfoSection("m", "Meta Tags", function (verbose) {
// get meta tag data, sort and put into pageMeta[]
let metaNodes = config.browser.contentDocument.getElementsByTagName("meta");
return Array.map(metaNodes, function (node) [(node.name || node.httpEquiv), template.highlightURL(node.content)])
.sort(function (a, b) util.compareIgnoreCase(a[0], b[0]));
});
},
destroy: function () {
},
_triggerLoadAutocmd: function _triggerLoadAutocmd(name, doc) {
let args = {
url: doc.location.href,
title: doc.title
};
if (liberator.has("tabs")) {
args.tab = tabs.getContentIndex(doc) + 1;
args.doc = "tabs.getTab(" + (args.tab - 1) + ").linkedBrowser.contentDocument";
}
autocommands.trigger(name, args);
},
// called when the active document is scrolled
_updateBufferPosition: function _updateBufferPosition() {
statusline.updateField("position");
// modes.show();
},
onDOMContentLoaded: function onDOMContentLoaded(event) {
let doc = event.originalTarget;
if (doc instanceof HTMLDocument && !doc.defaultView.frameElement)
this._triggerLoadAutocmd("DOMLoad", doc);
},
// TODO: see what can be moved to onDOMContentLoaded()
// event listener which is is called on each page load, even if the
// page is loaded in a background tab
onPageLoad: function onPageLoad(event) {
if (event.originalTarget instanceof HTMLDocument) {
let doc = event.originalTarget;
// document is part of a frameset
if (doc.defaultView.frameElement) {
return;
}
// code which should happen for all (also background) newly loaded tabs goes here:
// mark the buffer as loaded, we can't use buffer.loaded
// since that always refers to the current buffer, while doc can be
// any buffer, even in a background tab
doc.pageIsFullyLoaded = 1;
// code which is only relevant if the page load is the current tab goes here:
if (doc == config.browser.contentDocument) {
// we want to stay in command mode after a page has loaded
// TODO: move somewhere else, as focusing can already happen earlier than on "load"
if (options["focuscontent"]) {
setTimeout(function () {
let focused = liberator.focus;
if (focused && (focused.value != null) && focused.value.length == 0)
focused.blur();
}, 0);
}
}
// else // background tab
// liberator.echomsg("Background tab loaded: " + doc.title || doc.location.href);
this._triggerLoadAutocmd("PageLoad", doc);
}
},
/**
* @property {Object} The document loading progress listener.
*/
progressListener: {
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIWebProgressListener, Ci.nsIMsgStatusFeedback, Ci.nsIActivityMgrListener, Ci.nsIActivityListener]),
// XXX: function may later be needed to detect a canceled synchronous openURL()
onStateChange: function onStateChange(webProgress, request, flags, status) {
onStateChange.superapply(this, arguments);
// STATE_IS_DOCUMENT | STATE_IS_WINDOW is important, because we also
// receive statechange events for loading images and other parts of the web page
if (flags & (Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | Ci.nsIWebProgressListener.STATE_IS_WINDOW)) {
// This fires when the load event is initiated
// only thrown for the current tab, not when another tab changes
if (flags & Ci.nsIWebProgressListener.STATE_START) {
webProgress.DOMWindow.document.pageIsFullyLoaded = 0;
buffer.loaded = 0;
autocommands.trigger("PageLoadPre", { url: buffer.URL });
// don't reset mode if a frame of the frameset gets reloaded which
// is not the focused frame
if (document.commandDispatcher.focusedWindow == webProgress.DOMWindow) {
setTimeout(function () { modes.reset(false); },
liberator.mode == modes.HINTS ? 500 : 0);
}
}
else if (flags & Ci.nsIWebProgressListener.STATE_STOP) {
webProgress.DOMWindow.document.pageIsFullyLoaded = (status == 0 ? 1 : 2);
buffer.loaded = (status == 0 ? 1 : 2);
}
}
},
// for notifying the user about secure web pages
onSecurityChange: function onSecurityChange(webProgress, request, state) {
onSecurityChange.superapply(this, arguments);
statusline.updateField("ssl", state);
},
onStatusChange: function onStatusChange(webProgress, request, status, message) {
onStatusChange.superapply(this, arguments);
},
onProgressChange: function onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) {
onProgressChange.superapply(this, arguments);
},
// happens when the users switches tabs
onLocationChange: function onLocationChange() {
onLocationChange.superapply(this, arguments);
statusline.updateField("location");
statusline.updateField("bookmark");
statusline.updateField("history");
// This is a bit scary but we trigger ignore mode when the new URL is in the list
// of pages with ignored keys and then exit it on a new page but ONLY, if:
// a) The new page hasn't ignore as well and
// b) We initiated ignore mode, and not the user manually with <Insert>
if (modules.ignoreKeys != undefined) {
let ignoredKeyExceptions = ignoreKeys.hasIgnoredKeys(buffer.URL);
if (ignoredKeyExceptions !== null)
modes.passAllKeysExceptSome(ignoredKeyExceptions);
else if (modes._passKeysExceptions !== null)
modes.passAllKeys = false;
}
autocommands.trigger("LocationChange", { url: buffer.URL });
// if this is not delayed we get the position of the old buffer
setTimeout(function () { statusline.updateField("position"); }, 250);
},
// called at the very end of a page load
asyncUpdateUI: function asyncUpdateUI() {
asyncUpdateUI.superapply(this, arguments);
},
setOverLink: function setOverLink(link, b) {
setOverLink.superapply(this, arguments);
let ssli = options["showstatuslinks"];
if (link && ssli) {
if (ssli == 1) {
statusline.updateField("location", "Link: " + link);
statusline.updateField("bookmark", link);
}
else if (ssli == 2)
liberator.echo("Link: " + link, commandline.DISALLOW_MULTILINE);
}
if (link == "") {
if (ssli == 1) {
statusline.updateField("location");
statusline.updateField("bookmark");
}
else if (ssli == 2)
modes.show();
}
},
},
/**
* @property {Array} The alternative style sheets for the current
* buffer. Only returns style sheets for the 'screen' media type.
*/
get alternateStyleSheets() {
let stylesheets = window.getAllStyleSheets(config.browser.contentWindow);
return stylesheets.filter(
function (stylesheet) /^(screen|all|)$/i.test(stylesheet.media.mediaText) && !/^\s*$/.test(stylesheet.title)
);
},
/**
* @property {Array[Window]} All frames in the current buffer.
*/
getAllFrames: function(win) {
let frames = [];
(function rec(frame) {
if (frame.document.body instanceof HTMLBodyElement)
frames.push(frame);
Array.forEach(frame.frames, rec);
})(win || config.browser.contentWindow);
return frames;
},
/**
* @property {Object} A map of page info sections to their
* content generating functions.
*/
pageInfo: null,
/**
* @property {number} A value indicating whether the buffer is loaded.
* Values may be:
* 0 - Loading.
* 1 - Fully loaded.
* 2 - Load failed.
*/
get loaded() {
let doc = config.browser.contentDocument;
if (doc.pageIsFullyLoaded !== undefined)
return doc.pageIsFullyLoaded;
return 0; // in doubt return "loading"
},
set loaded(value) {
config.browser.contentDocument.pageIsFullyLoaded = value;
},
/**
* @property {Object} The local state store for the currently selected
* tab.
*/
get localStore() {
let content = config.browser.contentWindow;
if (!content.liberatorStore)
content.liberatorStore = {};
return content.liberatorStore;
},
/**
* @property {Node} The last focused input field in the buffer. Used
* by the "gi" key binding.
*/
get lastInputField() config.browser.contentDocument.lastInputField || null,
set lastInputField(value) { config.browser.contentDocument.lastInputField = value; },
/**
* @property {string} The current top-level document's URL.
*/
get URL() window.content ? window.content.location.href : config.browser.currentURI.spec,
/**
* @property {string} The current top-level document's URL, sans any
* fragment identifier.
*/
get URI() {
let loc = config.browser.contentWindow.location;
return loc.href.substr(0, loc.href.length - loc.hash.length);
},
/**
* @property {String} The current document's character set
*/
get charset() {
try {
return config.browser.docShell.charset;
} catch (e) {
return "UTF-8";
}
},
/**
* @property {number} The buffer's height in pixels.
*/
get pageHeight() window.content ? window.content.innerHeight : config.browser.contentWindow.innerHeight,
/**
* @property {number} The current browser's text zoom level, as a
* percentage with 100 as 'normal'. Only affects text size.
*/
get textZoom() config.browser.markupDocumentViewer.textZoom * 100,
set textZoom(value) { Buffer.setZoom(value, false); },
/**
* @property {number} The current browser's text zoom level, as a
* percentage with 100 as 'normal'. Affects text size, as well as
* image size and block size.
*/
get fullZoom() config.browser.markupDocumentViewer.fullZoom * 100,
set fullZoom(value) { Buffer.setZoom(value, true); },
/**
* @property {string} The current document's title.
*/
get title() config.browser.contentTitle,
/**
* @property {number} The buffer's horizontal scroll percentile.
*/
get scrollXPercent() {
let win = Buffer.findScrollableWindow();
if (win.scrollMaxX > 0)
return Math.round(win.scrollX / win.scrollMaxX * 100);
else
return 0;
},
/**
* @property {number} The buffer's vertical scroll percentile.
*/
get scrollYPercent() {
let win = Buffer.findScrollableWindow();
if (win.scrollMaxY > 0)
return Math.round(win.scrollY / win.scrollMaxY * 100);
else
return 0;
},
/**
* Adds a new section to the page information output.
*
* @param {string} option The section's value in 'pageinfo'.
* @param {string} title The heading for this section's
* output.
* @param {function} func The function to generate this
* section's output.
*/
addPageInfoSection: function addPageInfoSection(option, title, func) {
this.pageInfo[option] = [func, title];
},
/**
* Returns the currently selected word. If the selection is
* null, it tries to guess the word that the caret is
* positioned in.
*
* NOTE: might change the selection
*
* @returns {string}
*/
// FIXME: getSelection() doesn't always preserve line endings, see:
// https://www.mozdev.org/bugs/show_bug.cgi?id=19303
getCurrentWord: function () {
function _getCurrentWord (win) {
let elem = win.frameElement;
if (elem && elem.getClientRects().length === 0)
return;
let selection = win.getSelection();
if (selection.rangeCount <= 0)
return;
let range = selection.getRangeAt(0);
if (selection.isCollapsed) {
let selController = buffer.selectionController;
let caretmode = selController.getCaretEnabled();
selController.setCaretEnabled(true);
// Only move backwards if the previous character is not a space.
if (range.startOffset > 0 && !/\s/.test(range.startContainer.textContent[range.startOffset - 1]))
selController.wordMove(false, false);
selController.wordMove(true, true);
selController.setCaretEnabled(caretmode);
return String.match(selection, /\w*/)[0];
}
if (util.computedStyle(range.startContainer).whiteSpace == "pre"
&& util.computedStyle(range.endContainer).whiteSpace == "pre")
return String(range);
return String(selection);
}
return util.Array.compact(buffer.getAllFrames().map(_getCurrentWord)).join("\n");
},
/**
* Focuses the given element. In contrast to a simple
* elem.focus() call, this function works for iframes and
* image maps.
*
* @param {Node} elem The element to focus.
*/
focusElement: function (elem) {
if (elem instanceof HTMLFrameElement || elem instanceof HTMLIFrameElement)
Buffer.focusedWindow = elem.contentWindow;
else if (elem instanceof HTMLInputElement && elem.type == "file") {
Buffer.openUploadPrompt(elem);
buffer.lastInputField = elem;
}
else {
elem.focus();
// for imagemap
if (elem instanceof HTMLAreaElement) {
let doc = config.browser.contentDocument;
try {
let [x, y] = elem.getAttribute("coords").split(",").map(parseFloat);
elem.dispatchEvent(events.create(doc, "mouseover", { screenX: x, screenY: y }));
}
catch (e) {}
}
}
},
/**
* Tries to guess links the like of "next" and "prev". Though it has a
* singularly horrendous name, it turns out to be quite useful.
*
* @param {string} rel The relationship to look for. Looks for
* links with matching @rel or @rev attributes, and,
* failing that, looks for an option named rel +
* "pattern", and finds the last link matching that
* RegExp.
*/
followDocumentRelationship: function (rel) {
let regexes = options.get(rel + "pattern").values
.map(function (re) RegExp(re, "i"));
function followFrame(frame) {
function iter(elems) {
for (let i = 0; i < elems.length; i++)
if (elems[i].rel.toLowerCase() == rel || elems[i].rev.toLowerCase() == rel)
yield elems[i];
}
// <link>s have higher priority than normal <a> hrefs
let elems = frame.document.getElementsByTagName("link");
for (let elem in iter(elems)) {
liberator.open(elem.href);
return true;
}
// no links? ok, look for hrefs
elems = frame.document.getElementsByTagName("a");
for (let elem in iter(elems)) {
buffer.followLink(elem, liberator.CURRENT_TAB);
return true;
}
let res = util.evaluateXPath(options.get("hinttags").value, frame.document);
for (let regex of regexes) {
for (let i in util.range(res.snapshotLength, 0, -1)) {
let elem = res.snapshotItem(i);
if (regex.test(elem.textContent) || regex.test(elem.title) ||
Array.some(elem.childNodes, function (child) regex.test(child.alt))) {
buffer.followLink(elem, liberator.CURRENT_TAB);
return true;
}
}
}
return false;
}
let ret = followFrame(config.browser.contentWindow);
if (!ret) {
// only loop through frames (ordered by size) if the main content didn't match
let frames = buffer.getAllFrames().slice(1)
.sort( function(a, b) {
return ((b.scrollMaxX+b.innerWidth)*(b.scrollMaxY+b.innerHeight)) - ((a.scrollMaxX+a.innerWidth)*(a.scrollMaxY+a.innerHeight))
} );
ret = Array.some(frames, followFrame);
}
if (!ret)
liberator.beep();
},
/**
* Fakes a click on a link.
*
* @param {Node} elem The element to click.
* @param {number} where Where to open the link. See
* {@link liberator.open}.
*/
followLink: function (elem, where) {
let doc = elem.ownerDocument;
let view = doc.defaultView;
let offsetX = 1;
let offsetY = 1;
if (elem instanceof HTMLFrameElement || elem instanceof HTMLIFrameElement) {
elem.contentWindow.focus();
return;
}
else if (elem instanceof HTMLAreaElement) { // for imagemap
let coords = elem.getAttribute("coords").split(",");
offsetX = Number(coords[0]) + 1;
offsetY = Number(coords[1]) + 1;
}
else if (elem instanceof HTMLInputElement && elem.type == "file") {
Buffer.openUploadPrompt(elem);
return;
}
let ctrlKey = false, shiftKey = false;
switch (where) {
case liberator.NEW_TAB:
case liberator.NEW_BACKGROUND_TAB:
ctrlKey = true;
shiftKey = (where != liberator.NEW_BACKGROUND_TAB);
break;
case liberator.NEW_WINDOW:
shiftKey = true;
break;
case liberator.CURRENT_TAB:
break;
default:
liberator.echoerr("Invalid where argument for followLink(): " + where);
}
elem.focus();
options.withContext(function () {
options.setPref("browser.tabs.loadInBackground", true);
["mousedown", "mouseup", "click"].forEach(function (event) {
elem.dispatchEvent(events.create(doc, event, {
screenX: offsetX, screenY: offsetY,
ctrlKey: ctrlKey, shiftKey: shiftKey, metaKey: ctrlKey
}));
});
});
},
/**
* @property {nsISelectionController} The current document's selection
* controller.
*/
get selectionController() Buffer.focusedWindow
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell)
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsISelectionDisplay)
.QueryInterface(Ci.nsISelectionController),
/**
* Opens the appropriate context menu for <b>elem</b>.
*
* @param {Node} elem The context element.
*/
openContextMenu: function (elem) {
document.popupNode = elem;
let menu = document.getElementById("contentAreaContextMenu");
menu.showPopup(elem, -1, -1, "context", "bottomleft", "topleft");
},
/**
* Saves a page link to disk.
*
* @param {HTMLAnchorElement} elem The page link to save.
* @param {boolean} skipPrompt Whether to open the "Save Link As..."
* dialog.
*/
saveLink: function (elem, skipPrompt) {
let doc = elem.ownerDocument;
let url = window.makeURLAbsolute(elem.baseURI, elem.href ? elem.href : elem.src);
let text = elem.textContent;
try {
window.urlSecurityCheck(url, doc.nodePrincipal);
// we always want to save that link relative to the current working directory
options.setPref("browser.download.lastDir", io.getCurrentDirectory().path);
window.saveURL(url, text, null, true, skipPrompt, makeURI(url, doc.characterSet), doc);
}
catch (e) {
liberator.echoerr(e);
}
},
/**
* Scrolls to the bottom of the current buffer.
*/
scrollBottom: function () {
Buffer.scrollToPercent(null, 100);
},
/**
* Scrolls the buffer laterally <b>cols</b> columns.
*
* @param {number} cols The number of columns to scroll. A positive
* value scrolls right and a negative value left.
*/
scrollColumns: function (cols) {
Buffer.scrollHorizontal(null, "columns", cols);
},
/**
* Scrolls to the top of the current buffer.
*/
scrollEnd: function () {
Buffer.scrollToPercent(100, null);
},
/**
* Scrolls the buffer vertically <b>lines</b> rows.
*
* @param {number} lines The number of lines to scroll. A positive
* value scrolls down and a negative value up.
*/
scrollLines: function (lines) {
Buffer.scrollVertical(null, "lines", lines);
},
/**
* Scrolls the buffer vertically <b>pages</b> pages.
*
* @param {number} pages The number of pages to scroll. A positive
* value scrolls down and a negative value up.
*/
scrollPages: function (pages) {
Buffer.scrollVertical(null, "pages", pages);
},
/**
* Scrolls the buffer vertically 'scroll' lines.
*
* @param {boolean} direction The direction to scroll. If true then
* scroll up and if false scroll down.
* @param {number} count The multiple of 'scroll' lines to scroll.
* @optional
*/
scrollByScrollSize: function (direction, count) {
direction = direction ? 1 : -1;
count = count || 1;
let win = Buffer.findScrollableWindow();
Buffer.checkScrollYBounds(win, direction);
if (options["scroll"] > 0)
this.scrollLines(options["scroll"] * direction);
else // scroll half a page down in pixels
win.scrollBy(0, win.innerHeight / 2 * direction);
},
_scrollByScrollSize: function _scrollByScrollSize(count, direction) {
if (count > 0)
options["scroll"] = count;
buffer.scrollByScrollSize(direction);
},
/**
* Scrolls the buffer to the specified screen percentiles.
*
* @param {number} x The horizontal page percentile.
* @param {number} y The vertical page percentile.
*/
scrollToPercent: function (x, y) {
Buffer.scrollToPercent(x, y);
},
/**
* Scrolls the buffer to the specified screen pixels.
*
* @param {number} x The horizontal pixel.
* @param {number} y The vertical pixel.
*/
scrollTo: function (x, y) {
marks.add("'", true);
config.browser.contentWindow.scrollTo(x, y);
},
/**
* Scrolls the current buffer laterally to its leftmost.
*/
scrollStart: function () {
Buffer.scrollToPercent(0, null);
},
/**
* Scrolls the current buffer vertically to the top.
*/
scrollTop: function () {
Buffer.scrollToPercent(null, 0);
},
// TODO: allow callback for filtering out unwanted frames? User defined?
/**
* Shifts the focus to another frame within the buffer. Each buffer
* contains at least one frame.
*
* @param {number} count The number of frames to skip through.
* @param {boolean} forward The direction of motion.
*/
shiftFrameFocus: function (count, forward) {
let content = config.browser.contentWindow;
if (!(content.document instanceof HTMLDocument))
return;
count = Math.max(count, 1);
let frames = [];
// find all frames - depth-first search
(function findFrames(frame) {
if (frame.document.body instanceof HTMLBodyElement)
frames.push(frame);
Array.forEach(frame.frames, findFrames);
})(content);
if (frames.length == 0) // currently top is always included
return;
// remove all unfocusable frames
// TODO: find a better way to do this - walking the tree is too slow
let start = document.commandDispatcher.focusedWindow;
frames = frames.filter(function (frame) {
frame.focus();
return document.commandDispatcher.focusedWindow == frame;
});
start.focus();
// find the currently focused frame index
// TODO: If the window is a frameset then the first _frame_ should be
// focused. Since this is not the current FF behaviour,
// we initalize current to -1 so the first call takes us to the
// first frame.
let current = frames.indexOf(document.commandDispatcher.focusedWindow);
// calculate the next frame to focus
let next = current;
if (forward) {
next = current + count;
if (next > frames.length - 1) {
if (current == frames.length - 1)
liberator.beep();
next = frames.length - 1; // still allow the frame indicator to be activated
}
}
else {
next = current - count;
if (next < 0) {
if (current == 0)
liberator.beep();
next = 0; // still allow the frame indicator to be activated
}
}
// focus next frame and scroll into view
frames[next].focus();
if (frames[next] != window.content)
frames[next].frameElement.scrollIntoView(false);
// add the frame indicator
let doc = frames[next].document;
let indicator = util.xmlToDom(xml`<div highlight="FrameIndicator"/>`, doc);
doc.body.appendChild(indicator);
setTimeout(function () { doc.body.removeChild(indicator); }, 500);
// Doesn't unattach
//doc.body.setAttributeNS(NS.uri, "activeframe", "true");
//setTimeout(function () { doc.body.removeAttributeNS(NS.uri, "activeframe"); }, 500);
},
// similar to pageInfo
// TODO: print more useful information, just like the DOM inspector
/**
* Displays information about the specified element.
*
* @param {Node} elem The element to query.
*/
showElementInfo: function (elem) {
liberator.echo(xml`Element:<br/>${util.objectToString(elem, true)}`, commandline.FORCE_MULTILINE);
},
/**
* Displays information about the current buffer.
*
* @param {boolean} verbose Display more verbose information.
* @param {string} sections A string limiting the displayed sections.
* @default The value of 'pageinfo'.
*/
showPageInfo: function (verbose, sections) {
// Ctrl-g single line output
if (!verbose) {
let content = config.browser.contentWindow;
let file = content.document.location.pathname.split("/").pop() || "[No Name]";
let title = content.document.title || "[No Title]";
let info = template.map2(xml, "gf",
function (opt) template.map2(xml, buffer.pageInfo[opt][0](), util.identity, ", "),
", ");
if (bookmarks.isBookmarked(this.URL))
xml["+="](info, ", bookmarked");
let pageInfoText = xml`${file.quote()} [${info}] ${title}`;
liberator.echo(pageInfoText, commandline.FORCE_SINGLELINE);
return;
}
let option = sections || options["pageinfo"];
let list = template.map2(xml, option, function (option) {
let opt = buffer.pageInfo[option];
return opt ? template.table2(xml, opt[1], opt[0](true)) : undefined;
}, xml`<br/>`);
liberator.echo(template.genericOutput("Page Information", list), commandline.FORCE_MULTILINE);
},
/**
* Opens a viewer to inspect the source of the currently selected
* range.
*/
viewSelectionSource: function () {
// copied (and tuned somebit) from browser.jar -> nsContextMenu.js
let focusedWindow = document.commandDispatcher.focusedWindow;
if (focusedWindow == window)
focusedWindow = config.browser.contentWindow;
let docCharset = null;
if (focusedWindow)
docCharset = "charset=" + focusedWindow.document.characterSet;
let reference = null;
reference = focusedWindow.getSelection();
let docUrl = null;
window.openDialog("chrome://global/content/viewPartialSource.xul",
"_blank", "scrollbars,resizable,chrome,dialog=no",
docUrl, docCharset, reference, "selection");
},
/**
* Opens a viewer to inspect the source of the current buffer or the
* specified <b>url</b>. Either the default viewer or the configured
* external editor is used.
*
* @param {string} url The URL of the source.
* @default The current buffer.
* @param {boolean} useExternalEditor View the source in the external editor.
*/
viewSource: function (url, useExternalEditor) {
url = url || buffer.URI;
if (useExternalEditor)
editor.editFileExternally(url);
else {
const PREFIX = "view-source:";
if (url.startsWith(PREFIX))
url = url.substr(PREFIX.length);
else
url = PREFIX + url;
liberator.open(url, { hide: true });
}
},
/**
* Increases the zoom level of the current buffer.
*
* @param {number} steps The number of zoom levels to jump.
* @param {boolean} fullZoom Whether to use full zoom or text zoom.
*/
zoomIn: function (steps, fullZoom) {
Buffer.bumpZoomLevel(steps, fullZoom);
},
/**
* Decreases the zoom level of the current buffer.
*
* @param {number} steps The number of zoom levels to jump.
* @param {boolean} fullZoom Whether to use full zoom or text zoom.
*/
zoomOut: function (steps, fullZoom) {
Buffer.bumpZoomLevel(-steps, fullZoom);
}
}, {
ZOOM_MIN: "ZoomManager" in window && Math.round(ZoomManager.MIN * 100),
ZOOM_MAX: "ZoomManager" in window && Math.round(ZoomManager.MAX * 100),
get focusedWindow() this.getFocusedWindow(),
set focusedWindow(win) {
if (win === document.commandDispatcher.focusedWindow) return;
// XXX: if win has frame and win is not content's focus window, win.focus() cannot focus.
var e = win.document.activeElement;
if (e && e.contentWindow) {
services.get("focus").clearFocus(win);
}
win.focus();
},
getFocusedWindow: function (win) {
win = win || config.browser.contentWindow;
let elem = win.document.activeElement;
if (elem) {
let doc;
while (doc = elem.contentDocument) {
elem = doc.activeElement;
}
return elem.ownerDocument.defaultView;
} else
return win;
},
setZoom: function setZoom(value, fullZoom, browser = config.tabbrowser.mCurrentBrowser) {
liberator.assert(value >= Buffer.ZOOM_MIN || value <= Buffer.ZOOM_MAX,
"Zoom value out of range (" + Buffer.ZOOM_MIN + " - " + Buffer.ZOOM_MAX + "%)");
ZoomManager.useFullZoom = fullZoom;
ZoomManager.zoom = value / 100;
if ("FullZoom" in window)
FullZoom._applyZoomToPref(browser);
liberator.echomsg((fullZoom ? "Full" : "Text") + " zoom: " + value + "%");
},
bumpZoomLevel: function bumpZoomLevel(steps, fullZoom) {
let values = ZoomManager.zoomValues;
let cur = values.indexOf(ZoomManager.snap(ZoomManager.zoom));
let i = util.Math.constrain(cur + steps, 0, values.length - 1);
if (i == cur && fullZoom == ZoomManager.useFullZoom)
liberator.beep();
Buffer.setZoom(Math.round(values[i] * 100), fullZoom);
},
checkScrollYBounds: function checkScrollYBounds(win, direction) {
// NOTE: it's possible to have scrollY > scrollMaxY - FF bug?
if (direction > 0 && win.scrollY >= win.scrollMaxY || direction < 0 && win.scrollY == 0)
liberator.beep();
},
findScrollableWindow: function findScrollableWindow() {
let win = this.focusedWindow;
if (win && (win.scrollMaxX > 0 || win.scrollMaxY > 0))
return win;
win = config.browser.contentWindow;
if (win.scrollMaxX > 0 || win.scrollMaxY > 0)
return win;
for (let frame in util.Array.itervalues(win.frames))
if (frame.scrollMaxX > 0 || frame.scrollMaxY > 0)
return frame;
return win;
},
findScrollable: function findScrollable(dir, horizontal) {
let pos = "scrollTop", maxPos = "scrollTopMax", clientSize = "clientHeight";
if (horizontal)
pos = "scrollLeft", maxPos = "scrollLeftMax", clientSize = "clientWidth";
function find(elem) {
if (elem && !(elem instanceof Element))
elem = elem.parentNode;
for (; elem && elem.parentNode instanceof Element; elem = elem.parentNode) {
if (elem[clientSize] == 0)
continue;
if (dir < 0 && elem[pos] > 0 || dir > 0 && elem[pos] < elem[maxPos])
break;
}
return elem;
}
let win = this.focusedWindow;
if (win.getSelection().rangeCount)
var elem = find(win.getSelection().getRangeAt(0).startContainer);
if (!(elem instanceof Element)) {
let doc = Buffer.findScrollableWindow().document;
elem = find(doc.body || doc.getElementsByTagName("body")[0] ||
doc.documentElement);
}
return elem;
},
scrollVertical: function scrollVertical(elem, increment, number) {
elem = elem || Buffer.findScrollable(number, false);
let fontSize = parseInt(util.computedStyle(elem).fontSize);
if (increment == "lines")
increment = fontSize;
else if (increment == "pages")
increment = elem.clientHeight - fontSize;
else
throw Error()
elem.scrollTop += number * increment;
},
scrollHorizontal: function scrollHorizontal(elem, increment, number) {
elem = elem || Buffer.findScrollable(number, true);
let fontSize = parseInt(util.computedStyle(elem).fontSize);
if (increment == "columns")
increment = fontSize; // Good enough, I suppose.
else if (increment == "pages")
increment = elem.clientWidth - fontSize;
else
throw Error()
elem.scrollLeft += number * increment;
},
scrollElemToPercent: function scrollElemToPercent(elem, horizontal, vertical) {
elem = elem || Buffer.findScrollable();
marks.add("'", true);
if (horizontal != null)
elem.scrollLeft = (elem.scrollWidth - elem.clientWidth) * (horizontal / 100);
if (vertical != null)
elem.scrollTop = (elem.scrollHeight - elem.clientHeight) * (vertical / 100);
},
scrollToPercent: function scrollToPercent(horizontal, vertical) {
let win = Buffer.findScrollableWindow();
let h, v;
if (horizontal == null)
h = win.scrollX;
else
h = win.scrollMaxX / 100 * horizontal;
if (vertical == null)
v = win.scrollY;
else
v = win.scrollMaxY / 100 * vertical;
marks.add("'", true);
win.scrollTo(h, v);
},
openUploadPrompt: function openUploadPrompt(elem) {
commandline.input("Upload file: ", function (path) {
let file = io.File(path);
liberator.assert(file.exists());
elem.value = file.path;
}, {
completer: completion.file,
default: elem.value
});
}
}, {
commands: function () {
commands.add(["frameo[nly]"],
"Show only the current frame's page",
function (args) {
liberator.open(buffer.localStore.focusedFrame.document.documentURI);
},
{ argCount: "0" });
commands.add(["ha[rdcopy]"],
"Print current document",
function (args) {
let arg = args[0];
// FIXME: arg handling is a bit of a mess, check for filename
liberator.assert(!arg || arg[0] == ">" && !liberator.has("Windows"),
"Trailing characters");
options.withContext(function () {
if (arg) {
options.setPref("print.print_to_file", "true");
options.setPref("print.print_to_filename", io.File(arg.substr(1)).path);
liberator.echomsg("Printing to file: " + arg.substr(1));
}
else
liberator.echomsg("Sending to printer...");
options.setPref("print.always_print_silent", args.bang);
options.setPref("print.show_print_progress", !args.bang);
config.browser.contentWindow.print();
});
if (arg)
liberator.echomsg("Printed: " + arg.substr(1));
else
liberator.echomsg("Print job sent.");
},
{
argCount: "?",
literal: 0,
bang: true
});
commands.add(["pa[geinfo]"],
"Show various page information",
function (args) { buffer.showPageInfo(true, args[0]); },
{
argCount: "?",
completer: function (context) {
completion.optionValue(context, "pageinfo", "+", "");
context.title = ["Page Info"];
}
});
commands.add(["pagest[yle]", "pas"],
"Select the author style sheet to apply",
function (args) {
let arg = args.literalArg;
let titles = buffer.alternateStyleSheets.map(function (stylesheet) stylesheet.title);
liberator.assert(!arg || titles.indexOf(arg) >= 0,
"Invalid argument: " + arg);
if (options["usermode"])
options["usermode"] = false;
window.stylesheetSwitchAll(config.browser.contentWindow, arg);
},
{
argCount: "?",
completer: function (context) completion.alternateStyleSheet(context),
literal: 0
});
commands.add(["re[load]"],
"Reload the current web page",
function (args) { tabs.reload(config.browser.mCurrentTab, args.bang); },
{
bang: true,
argCount: "0"
});
// TODO: we're prompted if download.useDownloadDir isn't set and no arg specified - intentional?
commands.add(["sav[eas]", "w[rite]"],
"Save current document to disk",
function (args) {
let doc = config.browser.contentDocument;
let chosenData = null;
let filename = args[0];
if (filename) {
let file = io.File(filename);
liberator.assert(!file.exists() || args.bang, "File exists (add ! to override)");
chosenData = { file: file, uri: window.makeURI(doc.location.href, doc.characterSet) };
}
// if browser.download.useDownloadDir = false then the "Save As"
// dialog is used with this as the default directory
// TODO: if we're going to do this shouldn't it be done in setCWD or the value restored?
options.setPref("browser.download.lastDir", io.getCurrentDirectory().path);
try {
var contentDisposition = config.browser.contentWindow
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils)
.getDocumentMetadata("content-disposition");
}
catch (e) {}
window.internalSave(doc.location.href, doc, null, contentDisposition,
doc.contentType, false, null, chosenData, doc.referrer ?
window.makeURI(doc.referrer) : null, doc, true);
},
{
argCount: "?",
bang: true,
completer: function (context) completion.file(context)
});
commands.add(["st[op]"],
"Stop loading the current web page",
function () { tabs.stop(config.browser.mCurrentTab); },
{ argCount: "0" });
commands.add(["vie[wsource]"],
"View source code of current document",
function (args) { buffer.viewSource(args[0], args.bang); },
{
argCount: "?",
bang: true,
completer: function (context) completion.url(context, "bhf")
});
commands.add(["zo[om]"],
"Set zoom value of current web page",
function (args) {
let arg = args[0];
let level;
if (!arg)
level = 100;
else if (/^\d+$/.test(arg))
level = parseInt(arg, 10);
else if (/^[+-]\d+$/.test(arg)) {
if (args.bang)
level = buffer.fullZoom + parseInt(arg, 10);
else
level = buffer.textZoom + parseInt(arg, 10);
// relative args shouldn't take us out of range
level = util.Math.constrain(level, Buffer.ZOOM_MIN, Buffer.ZOOM_MAX);
}
else
liberator.assert(false, "Trailing characters");
if (args.bang)
buffer.fullZoom = level;
else
buffer.textZoom = level;
},
{
argCount: "?",
bang: true
});
},
completion: function () {
completion.alternateStyleSheet = function alternateStylesheet(context) {
context.title = ["Stylesheet", "Location"];
// unify split style sheets
let styles = {};
buffer.alternateStyleSheets.forEach(function (style) {
if (!(style.title in styles))
styles[style.title] = [];
styles[style.title].push(style.href || "inline");
});
context.completions = [[s, styles[s].join(", ")] for (s in styles)];
};
const UNTITLED_LABEL = "(Untitled)";
function getIndicator (tab) {
if (tab == config.tabbrowser.mCurrentTab)
return "%";
else if (tab == tabs.alternate)
return "#";
return " ";
}
function getURLFromTab (tab) {
if ("linkedBrowser" in tab)
return tab.linkedBrowser.contentDocument.location.href;
else {
let i = config.tabbrowser.mTabContainer.getIndexOfItem(tab);
let info = config.tabbrowser.tabInfo[i];
return info.browser ?
info.browser.contentDocument.location.href :
info.mode.getBrowser(tab).contentDocument.location.href;
}
}
function createItem (prefix, label, url, indicator, icon) {
return {
text: [prefix + label, prefix + url],
url: template.highlightURL(url, true, "buffer-list"),
indicator: indicator,
icon: icon || DEFAULT_FAVICON
};
}
function generateTabs (tabs) {
for (let i = 0, tab; tab = tabs[i]; i++) {
let indicator = getIndicator(tab) + (tab.pinned ? "@" : " "),
label = tab.label || UNTITLED_LABEL,
url = getURLFromTab(tab),
index = ((tab._tPos || i) + 1) + ": ";
let item = createItem(index, label, url, indicator, tab.image);
if (!tab.pinned && tab._tabViewTabItem && tab._tabViewTabItem.parent) {
let groupName = tab._tabViewTabItem.parent.getTitle();
if (groupName) {
let prefix = groupName + "." + (i + 1) + ": ";
item.text.push(prefix + label, prefix + url);
}
}
yield item;
}
}
function generateGroupList (group, groupName) {
let hasName = !!groupName;
for (let [i, tabItem] in Iterator(group.getChildren())) {
let index = (tabItem.tab._tPos + 1) + ": ",
label = tabItem.tab.label || UNTITLED_LABEL,
url = getURLFromTab(tabItem.tab);
let item = createItem(index, label, url, getIndicator(tabItem.tab), tabItem.tab.image);
if (hasName) {
let gPrefix = groupName + "." + (i + 1) + ": ";
item.text.push(gPrefix + label, gPrefix + url);
}
yield item;
}
}
completion.buffer = function buffer(context, flags) {
context.anchored = false;
context.keys = { text: "text", description: "url", icon: "icon" };
context.compare = CompletionContext.Sort.number;
let process = context.process[0];
context.process = [function (item, text)
xml`
<span highlight="Indicator" style="display: inline-block; width: 2ex; padding-right: 0.5ex; text-align: right">${item.item.indicator}</span>
${ process.call(this, item, text) }
`];
let tabs;
if (!flags) {
flags = this.buffer.VISIBLE;
tabs = config.tabbrowser.mTabs;
}
if (flags & this.buffer.VISIBLE) {
context.title = ["Buffers"];
context.completions = [item for (item in generateTabs(tabs || config.tabbrowser.visibleTabs))];
}
if (!liberator.has("tabgroup"))
return;
let groups = tabGroup.tabView.GroupItems;
if (flags & this.buffer.GROUPS) {
let activeGroup = groups.getActiveGroupItem();
let activeGroupId = activeGroup === null ? null : activeGroup.id;
for (let group of groups.groupItems) {
if (group.id != activeGroupId) {
let groupName = group.getTitle();
context.fork("GROUP_" + group.id, 0, this, function (context) {
context.title = [groupName || UNTITLED_LABEL];
context.completions = [item for (item in generateGroupList(group, groupName))];
});
}
}
}
};
completion.buffer.ALL = 1 << 0 | 1 << 1 | 1 << 2;
completion.buffer.VISIBLE = 1 << 0;
completion.buffer.GROUPS = 1 << 1;
},
events: function () {
let browserWindow;
if (config.hostApplication == "Thunderbird") {
browserWindow = "MsgStatusFeedback";
let activityManager = Cc["@mozilla.org/activity-manager;1"].getService(Ci.nsIActivityManager);
activityManager.removeListener(window.MsgStatusFeedback);
this.progressListener = update(Object.create(window.MsgStatusFeedback), this.progressListener);
statusFeedback.setWrappedStatusFeedback(this.progressListener);
activityManager.addListener(this.progressListener);
} else {
browserWindow = "XULBrowserWindow";
this.progressListener = update(Object.create(window.XULBrowserWindow), this.progressListener);
}
window[browserWindow] = this.progressListener;
window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.treeOwner
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIXULWindow)
.XULBrowserWindow = this.progressListener;
try {
config.browser.addProgressListener(this.progressListener);
}
catch (e) {} // Why? --djk
let appContent = document.getElementById("appcontent");
if (appContent) {
events.addSessionListener(appContent, "DOMContentLoaded", this.closure.onDOMContentLoaded, true);
events.addSessionListener(appContent, "load", this.closure.onPageLoad, true);
events.addSessionListener(appContent, "scroll", this.closure._updateBufferPosition, false);
}
},
mappings: function () {
var myModes = config.browserModes;
mappings.add(myModes, ["."],
"Repeat the last key event",
function (count) {
if (mappings.repeat) {
for (let i in util.interruptibleRange(0, Math.max(count, 1), 100))
mappings.repeat();
}
},
{ count: true });
mappings.add(myModes, ["c"],
"Start caret mode",
function () {
if (Editor.windowIsEditable()) {
if (options["insertmode"])
modes.set(modes.INSERT);
else if (Buffer.focusedWindow.getSelection().toString() != "")
modes.set(modes.VISUAL, modes.TEXTAREA);
else {
options.setPref("accessibility.browsewithcaret", true);
modes.main = modes.TEXTAREA;
}
} else {
// setting this option notifies an observer which takes care of the
// mode setting
options.setPref("accessibility.browsewithcaret", true);
}
});
mappings.add(myModes, ["<C-c>"],
"Stop loading the current web page",
function () {
let controller = window.document.commandDispatcher.getControllerForCommand("cmd_copy");
if (controller && controller.isCommandEnabled("cmd_copy")) {
controller.doCommand("cmd_copy");
// clear any selection made
let selection = Buffer.focusedWindow.getSelection();
try { // a simple if (selection) does not seem to work
selection.collapseToStart();
} catch (e) {}
} else {
// stop loading page
tabs.stop(config.browser.mCurrentTab);
}
});
// scrolling
mappings.add(myModes, ["j", "<Down>", "<C-e>"],
"Scroll document down",
function (count) { buffer.scrollLines(Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, ["k", "<Up>", "<C-y>"],
"Scroll document up",
function (count) { buffer.scrollLines(-Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, liberator.has("mail") ? ["h"] : ["h", "<Left>"],
"Scroll document to the left",
function (count) { buffer.scrollColumns(-Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, liberator.has("mail") ? ["l"] : ["l", "<Right>"],
"Scroll document to the right",
function (count) { buffer.scrollColumns(Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, ["0", "^"],
"Scroll to the absolute left of the document",
function () { buffer.scrollStart(); });
mappings.add(myModes, ["$"],
"Scroll to the absolute right of the document",
function () { buffer.scrollEnd(); });
mappings.add(myModes, ["gg", "<Home>"],
"Go to the top of the document",
function (count) { buffer.scrollToPercent(buffer.scrollXPercent, Math.max(count, 0)); },
{ count: true });
mappings.add(myModes, ["G", "<End>"],
"Go to the end of the document",
function (count) { buffer.scrollToPercent(buffer.scrollXPercent, count != null ? count : 100); },
{ count: true });
mappings.add(myModes, ["%"],
"Scroll to {count} percent of the document",
function (count) {
liberator.assert(count > 0 && count <= 100);
buffer.scrollToPercent(buffer.scrollXPercent, count);
},
{ count: true });
mappings.add(myModes, ["<C-d>"],
"Scroll window downwards in the buffer",
function (count) { buffer._scrollByScrollSize(count, true); },
{ count: true });
mappings.add(myModes, ["<C-u>"],
"Scroll window upwards in the buffer",
function (count) { buffer._scrollByScrollSize(count, false); },
{ count: true });
mappings.add(myModes, ["<C-b>", "<PageUp>", "<S-Space>"],
"Scroll up a full page",
function (count) { buffer.scrollPages(-Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, ["<C-f>", "<PageDown>", "<Space>"],
"Scroll down a full page",
function (count) { buffer.scrollPages(Math.max(count, 1)); },
{ count: true });
mappings.add(myModes, ["]f"],
"Focus next frame",
function (count) { buffer.shiftFrameFocus(Math.max(count, 1), true); },
{ count: true });
mappings.add(myModes, ["[f"],
"Focus previous frame",
function (count) { buffer.shiftFrameFocus(Math.max(count, 1), false); },
{ count: true });
mappings.add(myModes, ["]]"],
"Follow the link labeled 'next' or '>' if it exists",
function (count) { buffer.followDocumentRelationship("next"); },
{ count: true });
mappings.add(myModes, ["[["],
"Follow the link labeled 'prev', 'previous' or '<' if it exists",
function (count) { buffer.followDocumentRelationship("previous"); },
{ count: true });
mappings.add(myModes, ["gf"],
"View source",
function () { buffer.viewSource(null, false); });
mappings.add(myModes, ["gF"],
"View source with an external editor",
function () { buffer.viewSource(null, true); });
mappings.add(myModes, ["gi"],
"Focus last used input field",
function (count) {
if (count < 1 && buffer.lastInputField)
buffer.focusElement(buffer.lastInputField);
else {
let xpath = ["input[not(@type) or @type='text' or @type='password' or @type='file' or @type='datetime' or @type='datetime-local' or @type='date' or @type='month' or @type='time' or @type='week' or @type='number' or @type='range' or @type='email' or @type='url' or @type='search' or @type='tel' or @type='color']",
"textarea[not(@disabled) and not(@readonly)]",
"iframe"];
let elements = [m for (m in util.evaluateXPath(xpath))
if(m.getClientRects().length && (!(m instanceof HTMLIFrameElement) || Editor.windowIsEditable(m.contentWindow)))
];
liberator.assert(elements.length > 0);
buffer.focusElement(elements[util.Math.constrain(count, 1, elements.length) - 1]);
}
},
{ count: true });
mappings.add(myModes, ["gP"],
"Open (put) a URL based on the current clipboard contents in a new buffer",
function () {
liberator.open(util.readFromClipboard(),
liberator[options.get("activate").has("paste") ? "NEW_BACKGROUND_TAB" : "NEW_TAB"]);
});
mappings.add(myModes, ["p", "<MiddleMouse>"],
"Open (put) a URL based on the current clipboard contents in the current buffer",
function () {
let url = util.readFromClipboard();
liberator.assert(url);
liberator.open(url);
});
mappings.add(myModes, ["P"],
"Open (put) a URL based on the current clipboard contents in a new buffer",
function () {
let url = util.readFromClipboard();
liberator.assert(url);
liberator.open(url, { from: "paste", where: liberator.NEW_TAB });
});
// reloading
mappings.add(myModes, ["r"],
"Reload the current web page",
function () { tabs.reload(config.browser.mCurrentTab, false); });
mappings.add(myModes, ["R"],
"Reload while skipping the cache",
function () { tabs.reload(config.browser.mCurrentTab, true); });
// yanking
mappings.add(myModes, ["Y"],
"Copy selected text or current word",
function () {
let sel = buffer.getCurrentWord();
liberator.assert(sel);
util.copyToClipboard(sel, true);
});
// zooming
mappings.add(myModes, ["zi", "+"],
"Enlarge text zoom of current web page",
function (count) { buffer.zoomIn(Math.max(count, 1), false); },
{ count: true });
mappings.add(myModes, ["zm"],
"Enlarge text zoom of current web page by a larger amount",
function (count) { buffer.zoomIn(Math.max(count, 1) * 3, false); },
{ count: true });
mappings.add(myModes, ["zo", "-"],
"Reduce text zoom of current web page",
function (count) { buffer.zoomOut(Math.max(count, 1), false); },
{ count: true });
mappings.add(myModes, ["zr"],
"Reduce text zoom of current web page by a larger amount",
function (count) { buffer.zoomOut(Math.max(count, 1) * 3, false); },
{ count: true });
mappings.add(myModes, ["zz"],
"Set text zoom value of current web page",
function (count) { buffer.textZoom = count > 1 ? count : 100; },
{ count: true });
mappings.add(myModes, ["zI"],
"Enlarge full zoom of current web page",
function (count) { buffer.zoomIn(Math.max(count, 1), true); },
{ count: true });
mappings.add(myModes, ["zM"],
"Enlarge full zoom of current web page by a larger amount",
function (count) { buffer.zoomIn(Math.max(count, 1) * 3, true); },
{ count: true });
mappings.add(myModes, ["zO"],
"Reduce full zoom of current web page",
function (count) { buffer.zoomOut(Math.max(count, 1), true); },
{ count: true });
mappings.add(myModes, ["zR"],
"Reduce full zoom of current web page by a larger amount",
function (count) { buffer.zoomOut(Math.max(count, 1) * 3, true); },
{ count: true });
mappings.add(myModes, ["zZ"],
"Set full zoom value of current web page",
function (count) { buffer.fullZoom = count > 1 ? count : 100; },
{ count: true });
// page info
mappings.add(myModes, ["<C-g>"],
"Print the current file name",
function (count) { buffer.showPageInfo(false); },
{ count: true });
mappings.add(myModes, ["g<C-g>"],
"Print file information",
function () { buffer.showPageInfo(true); commandline.show("pageinfo"); });
},
options: function () {
options.add(["nextpattern"], // \u00BB is » (>> in a single char)
"Patterns to use when guessing the 'next' page in a document sequence",
"stringlist", "\\bnext\\b,^>$,^(>>|\u00BB)$,^(>|\u00BB),(>|\u00BB)$,\\bmore\\b");
options.add(["previouspattern"], // \u00AB is « (<< in a single char)
"Patterns to use when guessing the 'previous' page in a document sequence",
"stringlist", "\\bprev|previous\\b,^<$,^(<<|\u00AB)$,^(<|\u00AB),(<|\u00AB)$");
options.add(["pageinfo", "pa"],
"Desired info in the :pageinfo output",
"charlist", "gfm",
{
completer: function (context) [[k, v[1]] for ([k, v] in Iterator(buffer.pageInfo))]
});
options.add(["scroll", "scr"],
"Number of lines to scroll with <C-u> and <C-d> commands",
"number", 0,
{ validator: function (value) value >= 0 });
options.add(["showstatuslinks", "ssli"],
"Show the destination of the link under the cursor in the status bar",
"number", 1,
{
completer: function (context) [
["0", "Don't show link destination"],
["1", "Show the link in the status line"],
["2", "Show the link in the command line"]
]
});
// TODO: Fix the compose window
if (!config.isComposeWindow) {
options.add(["usermode", "um"],
"Show current website with a minimal style sheet to make it easily accessible",
"boolean", false,
{
setter: function (value) config.browser.markupDocumentViewer.authorStyleDisabled = value,
getter: function () config.browser.markupDocumentViewer.authorStyleDisabled
});
}
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* @instance browser
*/
const Browser = Module("browser", {
}, {
// TODO: support 'nrformats'? -> probably not worth it --mst
incrementURL: function (count) {
let matches = buffer.URL.match(/(.*?)(\d+)(\D*)$/);
liberator.assert(matches);
let [, pre, number, post] = matches;
let newNumber = parseInt(number, 10) + count;
let newNumberStr = String(newNumber > 0 ? newNumber : 0);
if (number.match(/^0/)) { // add 0009<C-a> should become 0010
while (newNumberStr.length < number.length)
newNumberStr = "0" + newNumberStr;
}
liberator.open(pre + newNumberStr + post);
}
}, {
options: function () {
options.add(["encoding", "enc"],
"Sets the current buffer's character encoding",
"string", "UTF-8",
{
scope: Option.SCOPE_LOCAL,
getter: function () config.browser.docShell.QueryInterface(Ci.nsIDocCharset).charset,
setter: function (val) {
if (options["encoding"] == val)
return val;
// Stolen from browser.jar/content/browser/browser.js, more or less.
try {
config.browser.docShell.QueryInterface(Ci.nsIDocCharset).charset = val;
PlacesUtils.history.setCharsetForURI(getWebNavigation().currentURI, val);
getWebNavigation().reload(Ci.nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
}
catch (e) { liberator.echoerr(e); }
return null;
},
completer: function (context) completion.charset(context)
});
// only available in FF 3.5-19
// TODO: remove when FF ESR's version is over 20. privateBrowsing will be per-window from FF 20+
// XXX: on Fx20, nsIPrivateBrowsingService exists yet but has no properties
let pb = services.get("privateBrowsing");
if (pb && "privateBrowsingEnabled" in pb) {
options.add(["private", "pornmode"],
"Set the 'private browsing' option",
"boolean", false,
{
setter: function (value) services.get("privateBrowsing").privateBrowsingEnabled = value,
getter: function () services.get("privateBrowsing").privateBrowsingEnabled
});
let services = modules.services; // Storage objects are global to all windows, 'modules' isn't.
storage.newObject("private-mode", function () {
({
init: function () {
services.get("obs").addObserver(this, "private-browsing", false);
services.get("obs").addObserver(this, "quit-application", false);
this.private = services.get("privateBrowsing").privateBrowsingEnabled;
},
observe: function (subject, topic, data) {
if (topic == "private-browsing") {
if (data == "enter")
storage.privateMode = true;
else if (data == "exit")
storage.privateMode = false;
storage.fireEvent("private-mode", "change", storage.privateMode);
}
else if (topic == "quit-application") {
services.get("obs").removeObserver(this, "quit-application");
services.get("obs").removeObserver(this, "private-browsing");
}
}
}).init();
}, { store: false });
storage.addObserver("private-mode",
function (key, event, value) {
autocommands.trigger("PrivateMode", { state: value });
}, window);
}
options.add(["urlseparator"],
"Set the separator regex used to separate multiple URL args",
"string", ",\\s");
},
mappings: function () {
mappings.add([modes.NORMAL],
["y"], "Yank current location to the clipboard",
function () {
var url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL);
util.copyToClipboard(url, true);
});
// opening websites
mappings.add([modes.NORMAL],
["o"], "Open one or more URLs",
function () { commandline.open("", "open ", modes.EX); });
mappings.add([modes.NORMAL], ["O"],
"Open one or more URLs, based on current location",
function () {
var url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL);
commandline.open("", "open " + url, modes.EX);
});
mappings.add([modes.NORMAL], ["t"],
"Open one or more URLs in a new tab",
function () { commandline.open("", "tabopen ", modes.EX); });
mappings.add([modes.NORMAL], ["T"],
"Open one or more URLs in a new tab, based on current location",
function () {
var url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL);
commandline.open("", "tabopen " + url, modes.EX);
});
mappings.add([modes.NORMAL], ["w"],
"Open one or more URLs in a new window",
function () { commandline.open("", "winopen ", modes.EX); });
mappings.add([modes.NORMAL], ["W"],
"Open one or more URLs in a new window, based on current location",
function () {
var url = services.get("textToSubURI").unEscapeURIForUI(buffer.charset, buffer.URL);
commandline.open("", "winopen " + url, modes.EX);
});
mappings.add([modes.NORMAL],
["<C-a>"], "Increment last number in URL",
function (count) { Browser.incrementURL(Math.max(count, 1)); },
{ count: true });
mappings.add([modes.NORMAL],
["<C-x>"], "Decrement last number in URL",
function (count) { Browser.incrementURL(-Math.max(count, 1)); },
{ count: true });
mappings.add([modes.NORMAL], ["~"],
"Open home directory",
function () { liberator.open("~"); });
mappings.add([modes.NORMAL], ["gh"],
"Open homepage",
function () { BrowserHome(); });
mappings.add([modes.NORMAL], ["gH"],
"Open homepage in a new tab",
function () {
let homepages = gHomeButton.getHomePage();
homepages = homepages.replace(/\|/g, options["urlseparator"] || ", "); // we use a different url seperator than Firefox
liberator.open(homepages, { from: "homepage", where: liberator.NEW_TAB });
});
mappings.add([modes.NORMAL], ["gu"],
"Go to parent directory",
function (count) {
function getParent(url, count) {
function getParentPath(path) {
if (!path)
return;
path = path.replace(/\/$/, "").replace(/^\/+/, "");
if (path.indexOf("#") > 0)
return path.replace(/#.*/, "");
if (path.indexOf("?") > 0)
return path.replace(/\?.*/, "");
path = path.replace(/\/+$/, "");
if (path.indexOf("/") > 0)
return path.replace(/\/[^\/]*$/,"/");
}
function getParentHost(host) {
if (!/\./.test(host) || /^[0-9+.:]+$/.test(host))
return host;
let hostSuffix = "";
let x = host.lastIndexOf(":");
if (x > 0) {
hostSuffix = host.substr(x);
host = host.substr(0, x);
}
hostSuffix = host.substr(host.length - 6) + hostSuffix;
host = host.substr(0, host.length - 6);
return host.replace(/[^.]*\./, "") + hostSuffix;
}
let parent = url;
let regexp = new RegExp("([a-z]+:///?)([^/]*)(/.*)");
let [, scheme, host, path] = regexp.exec(url);
path = path.replace(/\/$/, "").replace(/^\/+/, "");
for (let i = 0; i < count; i++) {
if (path) {
if (path = getParentPath(path))
parent = scheme + host + "/" + path;
else
parent = scheme + host + "/";
}
else {
host = getParentHost(host);
parent = scheme + host + "/";
}
}
return parent;
}
if (count < 1)
count = 1;
let url = getParent(buffer.URL, count);
if (url == buffer.URL)
liberator.beep();
else
liberator.open(url);
},
{ count: true });
mappings.add([modes.NORMAL], ["gU"],
"Go to the root of the website",
function () {
let uri = content.document.location;
liberator.assert(!/(about|mailto):/.test(uri.protocol)); // exclude these special protocols for now
liberator.open(uri.protocol + "//" + (uri.host || "") + "/");
});
},
commands: function () {
commands.add(["downl[oads]", "dl"],
"Show progress of current downloads",
function () {
liberator.open("chrome://mozapps/content/downloads/downloads.xul",
{ from: "downloads"});
},
{ argCount: "0" });
commands.add(["o[pen]"],
"Open one or more URLs in the current tab",
function (args) {
args = args.string;
if (args)
liberator.open(args);
else
liberator.open("");
}, {
completer: function (context) completion.url(context),
literal: 0,
privateData: true
});
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* @instance events
*/
const Events = Module("events", {
requires: ["autocommands", "config"],
init: function () {
const self = this;
this._fullscreen = window.fullScreen;
this._lastFocus = null;
this._currentMacro = "";
this._lastMacro = "";
this.sessionListeners = [];
this._macros = storage.newMap("macros", { store: true, privateData: true });
// NOTE: the order of ["Esc", "Escape"] or ["Escape", "Esc"]
// matters, so use that string as the first item, that you
// want to refer to within liberator's source code for
// comparisons like if (key == "<Esc>") { ... }
this._keyTable = {
add: ["Plus", "Add"],
back_space: ["BS"],
delete: ["Del"],
escape: ["Esc", "Escape"],
insert: ["Insert", "Ins"],
left_shift: ["LT", "<"],
return: ["Return", "CR", "Enter"],
right_shift: [">"],
space: ["Space", " "],
subtract: ["Minus", "Subtract"]
};
this._code_key = {};
this._key_code = {};
for (let [k, v] in Iterator(KeyEvent))
if (/^DOM_VK_(?![A-Z0-9]$)/.test(k)) {
k = k.substr(7).toLowerCase();
let names = [k.replace(/(^|_)(.)/g, function (m, n1, n2) n2.toUpperCase())
.replace(/^NUMPAD/, "k")];
if (k in this._keyTable)
names = this._keyTable[k];
this._code_key[v] = names[0];
for (let name of names)
this._key_code[name.toLowerCase()] = v;
}
// HACK: as Gecko does not include an event for <, we must add this in manually.
if (!("<" in this._key_code)) {
this._key_code["<"] = 60;
this._key_code["lt"] = 60;
this._code_key[60] = "lt";
}
this._input = {
buffer: "", // partial command storage
pendingMotionMap: null, // e.g. "d{motion}" if we wait for a motion of the "d" command
pendingArgMap: null, // pending map storage for commands like m{a-z}
count: null // parsed count from the input buffer
};
// load all macros
// setTimeout needed since io. is loaded after events.
setTimeout(function () {
try {
let dirs = io.getRuntimeDirectories("macros");
if (dirs.length > 0) {
for (let dir of dirs) {
liberator.log("Sourcing macros directory: " + dir.path);
for (let file in dir.iterDirectory()) {
if (file.exists() && !file.isDirectory() && file.isReadable() &&
/^[\w_-]+(\.vimp)?$/i.test(file.leafName)) {
let name = file.leafName.replace(/\.vimp$/i, "");
this._macros.set(name, file.read().split("\n")[0]);
liberator.echomsg("Macro " + name + " added: " + this._macros.get(name));
}
}
}
}
else
liberator.log("No user macros directory found");
}
catch (e) {
// thrown if directory does not exist
liberator.log("Error sourcing macros directory: " + e);
}
}, 100);
function wrapListener(method) {
return function (event) {
try {
self[method](event);
}
catch (e) {
if (e.message == "Interrupted")
liberator.echoerr("Interrupted");
else
liberator.echoerr("Processing " + event.type + " event: " + (e.echoerr || e));
liberator.echoerr(e);
}
};
}
this._wrappedOnKeyPress = wrapListener("onKeyPress");
this._wrappedOnKeyUpOrDown = wrapListener("onKeyUpOrDown");
this.addSessionListener(window, "keypress", this.closure._wrappedOnKeyPress, true);
this.addSessionListener(window, "keydown", this.closure._wrappedOnKeyUpOrDown, true);
this.addSessionListener(window, "keyup", this.closure._wrappedOnKeyUpOrDown, true);
this._activeMenubar = false;
this.addSessionListener(window, "popupshown", this.closure.onPopupShown, true);
this.addSessionListener(window, "popuphidden", this.closure.onPopupHidden, true);
this.addSessionListener(window, "DOMMenuBarActive", this.closure.onDOMMenuBarActive, true);
this.addSessionListener(window, "DOMMenuBarInactive", this.closure.onDOMMenuBarInactive, true);
this.addSessionListener(window, "resize", this.closure.onResize, true);
},
destroy: function () {
liberator.log("Removing all event listeners");
for (let args in values(this.sessionListeners))
args[0].removeEventListener.apply(args[0], args.slice(1));
},
/**
* Adds an event listener for this session and removes it on
* liberator shutdown.
*
* @param {Element} target The element on which to listen.
* @param {string} event The event to listen for.
* @param {function} callback The function to call when the event is received.
* @param {boolean} capture When true, listen during the capture
* phase, otherwise during the bubbling phase.
*/
addSessionListener: function (target, event, callback, capture) {
let args = Array.slice(arguments, 0);
target.addEventListener.apply(target, args.slice(1));
this.sessionListeners.push(args);
},
/**
* @property {boolean} Whether synthetic key events are currently being
* processed.
*/
feedingKeys: false,
/**
* Initiates the recording of a key event macro.
*
* @param {string} macro The name for the macro.
*/
startRecording: function (macro) {
// TODO: ignore this like Vim?
liberator.assert(/[a-zA-Z0-9]/.test(macro), "Invalid register name: '" + macro + "'");
modes.isRecording = true;
if (/[A-Z]/.test(macro)) { // uppercase (append)
this._currentMacro = macro.toLowerCase();
if (!this._macros.get(this._currentMacro))
this._macros.set(this._currentMacro, ""); // initialize if it does not yet exist
}
else {
this._currentMacro = macro;
this._macros.set(this._currentMacro, "");
}
},
/**
* Replays a macro.
*
* @param {string} The name of the macro to replay.
* @returns {boolean}
*/
playMacro: function (macro) {
let res = false;
if (!/[a-zA-Z0-9@]/.test(macro) && macro.length == 1) {
liberator.echoerr("Invalid macro name: " + macro);
return false;
}
if (macro == "@") { // use lastMacro if it's set
if (!this._lastMacro) {
liberator.echoerr("No previously used macro");
return false;
}
}
else {
if (macro.length == 1)
this._lastMacro = macro.toLowerCase(); // XXX: sets last played macro, even if it does not yet exist
else
this._lastMacro = macro; // e.g. long names are case sensitive
}
if (this._macros.get(this._lastMacro)) {
// make sure the page is stopped before starting to play the macro
try {
window.getWebNavigation().stop(nsIWebNavigation.STOP_ALL);
}
catch (e) {}
buffer.loaded = 1; // even if not a full page load, assume it did load correctly before starting the macro
modes.isReplaying = true;
res = events.feedkeys(this._macros.get(this._lastMacro), { noremap: true });
modes.isReplaying = false;
}
else {
liberator.echoerr("Macro not set: " + this._lastMacro);
}
return res;
},
/**
* Returns all macros matching <b>filter</b>.
*
* @param {string} filter A regular expression filter string. A null
* filter selects all macros.
*/
getMacros: function (filter) {
if (!filter)
return this._macros;
let re = RegExp(filter);
return ([macro, keys] for ([macro, keys] in this._macros) if (re.test(macro)));
},
/**
* Deletes all macros matching <b>filter</b>.
*
* @param {string} filter A regular expression filter string. A null
* filter deletes all macros.
*/
deleteMacros: function (filter) {
let re = RegExp(filter);
for (let [item, ] in this._macros) {
if (re.test(item) || !filter)
this._macros.remove(item);
}
},
/**
* Pushes keys onto the event queue from liberator. It is similar to
* Vim's feedkeys() method, but cannot cope with 2 partially-fed
* strings, you have to feed one parsable string.
*
* @param {string} keys A string like "2<C-f>" to push onto the event
* queue. If you want "<" to be taken literally, prepend it with a
* "\\".
* @param {boolean} noremap Allow recursive mappings.
* @param {boolean} silent Whether the command should be echoed to the
* command line.
* @returns {boolean}
*/
feedkeys: function (keys, noremap, quiet) {
let doc = window.document;
let view = window.document.defaultView;
let wasFeeding = this.feedingKeys;
this.feedingKeys = true;
this.duringFeed = this.duringFeed || [];
let wasQuiet = commandline.quiet;
if (quiet)
commandline.quiet = quiet;
try {
feed: {
liberator.threadYield(1, true);
for (let evt_obj of events.fromString(keys)) {
let elem = liberator.focus || config.browser.contentWindow;
let evt = events.create(doc, "keypress", evt_obj);
if (typeof noremap == "object")
for (let [k, v] in Iterator(noremap))
evt[k] = v;
else
evt.noremap = !!noremap;
evt.isMacro = true;
// A special hack for liberator-specific key names.
if (evt_obj.liberatorString || evt_obj.liberatorShift) {
evt.liberatorString = evt_obj.liberatorString; // for key-less keypress events e.g. <Nop>
evt.liberatorShift = evt_obj.liberatorShift; // for untypable shift keys e.g. <S-1>
events.onKeyPress(evt);
}
else
elem.dispatchEvent(evt);
if (!this.feedingKeys)
break feed;
// Stop feeding keys if page loading failed.
if (modes.isReplaying && !this.waitForPageLoad())
break feed;
}
return true;
}
}
finally {
this.feedingKeys = wasFeeding;
if (quiet)
commandline.quiet = wasQuiet;
if (this.duringFeed.length) {
let duringFeed = this.duringFeed;
this.duringFeed = [];
for (let evt of duringFeed)
evt.target.dispatchEvent(evt);
}
}
},
/**
* Creates an actual event from a pseudo-event object.
*
* The pseudo-event object (such as may be retrieved from events.fromString)
* should have any properties you want the event to have.
*
* @param {Document} doc The DOM document to associate this event with
* @param {Type} type The type of event (keypress, click, etc.)
* @param {Object} opts The pseudo-event.
*/
create: function (doc, type, opts) {
var DEFAULTS = {
Key: {
type: type,
bubbles: true, cancelable: true,
view: doc.defaultView,
ctrlKey: false, altKey: false, shiftKey: false, metaKey: false,
keyCode: 0, charCode: 0
},
Mouse: {
type: type,
bubbles: true, cancelable: true,
view: doc.defaultView,
detail: 1,
screenX: 0, screenY: 0,
clientX: 0, clientY: 0,
ctrlKey: false, altKey: false, shiftKey: false, metaKey: false,
button: 0,
relatedTarget: null
}
};
const TYPES = {
click: "Mouse", mousedown: "Mouse", mouseup: "Mouse",
mouseover: "Mouse", mouseout: "Mouse",
keypress: "Key", keyup: "Key", keydown: "Key"
};
var t = TYPES[type];
var evt = doc.createEvent(t + "Events");
evt["init" + t + "Event"].apply(evt, [v for (v of values(update(DEFAULTS[t], opts)))]);
return evt;
},
/**
* Converts a user-input string of keys into a canonical
* representation.
*
* <C-A> maps to <C-a>, <C-S-a> maps to <C-S-A>
* <C- > maps to <C-Space>, <S-a> maps to A
* << maps to <lt><lt>
*
* <S-@> is preserved, as in vim, to allow untypable key-combinations
* in macros.
*
* canonicalKeys(canonicalKeys(x)) == canonicalKeys(x) for all values
* of x.
*
* @param {string} keys Messy form.
* @returns {string} Canonical form.
*/
canonicalKeys: function (keys) {
return events.fromString(keys).map(events.closure.toString).join("");
},
/**
* Converts an event string into an array of pseudo-event objects.
*
* These objects can be used as arguments to events.toString or
* events.create, though they are unlikely to be much use for other
* purposes. They have many of the properties you'd expect to find on a
* real event, but none of the methods.
*
* Also may contain two "special" parameters, .liberatorString and
* .liberatorShift these are set for characters that can never by
* typed, but may appear in mappings, for example <Nop> is passed as
* liberatorString, and liberatorShift is set when a user specifies
* <S-@> where @ is a non-case-changable, non-space character.
*
* @param {string} keys The string to parse.
* @returns {Array[Object]}
*/
fromString: function (input) {
let out = [];
let re = RegExp("<.*?>?>|[^<]|<(?!.*>)", "g");
let match;
while ((match = re.exec(input))) {
let evt_str = match[0];
let evt_obj = { ctrlKey: false, shiftKey: false, altKey: false, metaKey: false,
keyCode: 0, charCode: 0, type: "keypress" };
if (evt_str.length > 1) { // <.*?>
let [match, modifier, keyname] = evt_str.match(/^<((?:[CSMA]-)*)(.+?)>$/i) || [false, '', ''];
modifier = modifier.toUpperCase();
keyname = keyname.toLowerCase();
if (keyname && !(keyname.length == 1 && modifier.length == 0 || // disallow <> and <a>
!(keyname.length == 1 || this._key_code[keyname] || keyname == "nop" || /mouse$/.test(keyname)))) { // disallow <misteak>
evt_obj.ctrlKey = /C-/.test(modifier);
evt_obj.altKey = /A-/.test(modifier);
evt_obj.shiftKey = /S-/.test(modifier);
evt_obj.metaKey = /M-/.test(modifier);
if (keyname.length == 1) { // normal characters
if (evt_obj.shiftKey) {
keyname = keyname.toUpperCase();
if (keyname == keyname.toLowerCase())
evt_obj.liberatorShift = true;
}
evt_obj.charCode = keyname.charCodeAt(0);
}
else if (keyname == "nop") {
evt_obj.liberatorString = "<Nop>";
}
else if (/mouse$/.test(keyname)) { // mouse events
evt_obj.type = (/2-/.test(modifier) ? "dblclick" : "click");
evt_obj.button = ["leftmouse", "middlemouse", "rightmouse"].indexOf(keyname);
delete evt_obj.keyCode;
delete evt_obj.charCode;
}
else { // spaces, control characters, and <
evt_obj.keyCode = this._key_code[keyname];
evt_obj.charCode = 0;
}
}
else { // an invalid sequence starting with <, treat as a literal
out = out.concat(events.fromString("<lt>" + evt_str.substr(1)));
continue;
}
}
else // a simple key (no <...>)
evt_obj.charCode = evt_str.charCodeAt(0);
// TODO: make a list of characters that need keyCode and charCode somewhere
if (evt_obj.keyCode == 32 || evt_obj.charCode == 32)
evt_obj.charCode = evt_obj.keyCode = 32; // <Space>
if (evt_obj.keyCode == 60 || evt_obj.charCode == 60)
evt_obj.charCode = evt_obj.keyCode = 60; // <lt>
out.push(evt_obj);
}
return out;
},
/**
* Converts the specified event to a string in liberator key-code
* notation. Returns null for an unknown event.
*
* E.g. pressing ctrl+n would result in the string "<C-n>".
*
* @param {Event} event
* @returns {string}
*/
toString: function (event) {
if (!event)
return "[instance events]";
if (event.liberatorString)
return event.liberatorString;
let key = null;
let modifier = "";
if (event.ctrlKey)
modifier += "C-";
if (event.altKey)
modifier += "A-";
if (event.metaKey)
modifier += "M-";
if (/^key/.test(event.type)) {
let charCode = event.type == "keyup" ? 0 : event.charCode;
if (charCode == 0) {
if (event.shiftKey)
modifier += "S-";
if (event.keyCode in this._code_key)
key = this._code_key[event.keyCode];
}
// [Ctrl-Bug] special handling of mysterious <C-[>, <C-\\>, <C-]>, <C-^>, <C-_> bugs (OS/X)
// (i.e., cntrl codes 27--31)
// ---
// For more information, see:
// [*] Vimp FAQ: http://vimperator.org/trac/wiki/Vimperator/FAQ#WhydoesntC-workforEscMacOSX
// [*] Referenced mailing list msg: http://www.mozdev.org/pipermail/vimperator/2008-May/001548.html
// [*] Mozilla bug 416227: event.charCode in keypress handler has unexpected values on Mac for Ctrl with chars in "[ ] _ \"
// https://bugzilla.mozilla.org/show_bug.cgi?query_format=specific&order=relevance+desc&bug_status=__open__&id=416227
// [*] Mozilla bug 432951: Ctrl+'foo' doesn't seem same charCode as Meta+'foo' on Cocoa
// https://bugzilla.mozilla.org/show_bug.cgi?query_format=specific&order=relevance+desc&bug_status=__open__&id=432951
// ---
//
// The following fixes are only activated if liberator.has("MacUnix").
// Technically, they prevent mappings from <C-Esc> (and
// <C-C-]> if your fancy keyboard permits such things<?>), but
// these <C-control> mappings are probably pathological (<C-Esc>
// certainly is on Windows), and so it is probably
// harmless to remove the has("MacUnix") if desired.
//
else if (liberator.has("MacUnix") && event.ctrlKey && charCode >= 27 && charCode <= 31) {
if (charCode == 27) { // [Ctrl-Bug 1/5] the <C-[> bug
key = "Esc";
modifier = modifier.replace("C-", "");
}
else // [Ctrl-Bug 2,3,4,5/5] the <C-\\>, <C-]>, <C-^>, <C-_> bugs
key = String.fromCharCode(charCode + 64);
}
// a normal key like a, b, c, 0, etc.
else if (charCode > 0) {
key = String.fromCharCode(charCode);
if (key in this._key_code) {
// a named charcode key (<Space> and <lt>) space can be shifted, <lt> must be forced
if ((key.match(/^\s$/) && event.shiftKey) || event.liberatorShift)
modifier += "S-";
key = this._code_key[this._key_code[key]];
}
else {
// a shift modifier is only allowed if the key is alphabetical and used in a C-A-M- mapping in the uppercase,
// or if the shift has been forced for a non-alphabetical character by the user while :map-ping
if ((key != key.toLowerCase() && (event.ctrlKey || event.altKey || event.metaKey)) || event.liberatorShift)
modifier += "S-";
else if (modifier.length == 0)
return key;
}
}
if (key == null)
return null;
}
else if (event.type == "click" || event.type == "dblclick") {
if (event.shiftKey)
modifier += "S-";
if (event.type == "dblclick")
modifier += "2-";
switch (event.button) {
case 0:
key = "LeftMouse";
break;
case 1:
key = "MiddleMouse";
break;
case 2:
key = "RightMouse";
break;
}
}
if (key == null)
return null;
return "<" + modifier + key + ">";
},
/**
* Whether <b>key</b> is a key code defined to accept/execute input on
* the command line.
*
* @param {string} key The key code to test.
* @returns {boolean}
*/
isAcceptKey: function (key) key == "<Return>" || key == "<C-j>" || key == "<C-m>",
/**
* Whether <b>key</b> is a key code defined to reject/cancel input on
* the command line.
*
* @param {string} key The key code to test.
* @returns {boolean}
*/
isCancelKey: function (key) key == "<Esc>" || key == "<C-[>" || key == "<C-c>",
/**
* Waits for the current buffer to successfully finish loading. Returns
* true for a successful page load otherwise false.
*
* @returns {boolean}
*/
waitForPageLoad: function () {
liberator.threadYield(true); // clear queue
if (buffer.loaded == 1)
return true;
const maxWaitTime = 25;
let start = Date.now();
let end = start + (maxWaitTime * 1000); // maximum time to wait - TODO: add option
let now;
while (now = Date.now(), now < end) {
liberator.threadYield();
if (!events.feedingKeys)
return false;
if (buffer.loaded > 0) {
liberator.sleep(250);
break;
}
else
liberator.echomsg("Waiting for page to load...");
}
modes.show();
let ret = (buffer.loaded == 1);
if (!ret)
liberator.echoerr("Page did not load completely in " + maxWaitTime + " seconds. Macro stopped.");
// sometimes the input widget had focus when replaying a macro
// maybe this call should be moved somewhere else?
// liberator.focusContent(true);
return ret;
},
// argument "event" is deliberately not used, as i don't seem to have
// access to the real focus target
// Huh? --djk
onFocusChange: function (event) {
// command line has it's own focus change handler
if (liberator.mode == modes.COMMAND_LINE)
return;
function hasHTMLDocument(win) win && win.document && win.document instanceof HTMLDocument
let win = window.document.commandDispatcher.focusedWindow;
let elem = window.document.commandDispatcher.focusedElement;
if (win && win.top == content)
buffer.localStore.focusedFrame = win;
try {
if (elem && elem.readOnly)
return;
if ((elem instanceof HTMLInputElement && /^(text|password|datetime|datetime-local|date|month|time|week|number|range|email|url|search|tel|color)$/.test(elem.type)) ||
(elem instanceof HTMLSelectElement)) {
liberator.mode = modes.INSERT;
if (hasHTMLDocument(win))
buffer.lastInputField = elem;
return;
}
if (elem instanceof HTMLEmbedElement || elem instanceof HTMLObjectElement) {
liberator.mode = modes.EMBED;
return;
}
if (elem instanceof HTMLTextAreaElement || (elem && elem.contentEditable == "true")) {
if (options["insertmode"])
modes.set(modes.INSERT);
else if (elem.selectionEnd - elem.selectionStart > 0)
modes.set(modes.VISUAL, modes.TEXTAREA);
else
modes.main = modes.TEXTAREA;
if (hasHTMLDocument(win))
buffer.lastInputField = elem;
return;
}
if (Editor.windowIsEditable(win)) {
if (options["insertmode"])
modes.set(modes.INSERT);
else if (win.getSelection().toString() != "")
modes.set(modes.VISUAL, modes.TEXTAREA);
else
modes.main = modes.TEXTAREA;
buffer.lastInputField = win;
return;
}
if (config.focusChange) {
config.focusChange(win);
return;
}
let urlbar = document.getElementById("urlbar");
if (elem == null && urlbar && urlbar.inputField == this._lastFocus)
liberator.threadYield(true);
if (liberator.mode & (modes.EMBED | modes.INSERT | modes.TEXTAREA | modes.VISUAL))
modes.reset();
}
finally {
this._lastFocus = elem;
}
},
onSelectionChange: function (event) {
let couldCopy = false;
let controller = document.commandDispatcher.getControllerForCommand("cmd_copy");
if (controller && controller.isCommandEnabled("cmd_copy"))
couldCopy = true;
if (liberator.mode != modes.VISUAL) {
if (couldCopy) {
if ((liberator.mode == modes.TEXTAREA ||
(modes.extended & modes.TEXTAREA))
&& !options["insertmode"])
modes.set(modes.VISUAL, modes.TEXTAREA);
else if (liberator.mode == modes.CARET)
modes.set(modes.VISUAL, modes.CARET);
}
}
// XXX: disabled, as i think automatically starting visual caret mode does more harm than help
// else
// {
// if (!couldCopy && modes.extended & modes.CARET)
// liberator.mode = modes.CARET;
// }
},
/**
* The global escape key handler. This is called in ALL modes.
*/
onEscape: function () {
if (modes.passNextKey) // We allow <Esc> in passAllKeys
return;
// always clear the commandline. Even if we are in
// NORMAL mode, we might have a commandline visible,
// e.g. after pressing 'n' to show the last search
// again.
commandline.clear();
switch (liberator.mode) {
case modes.NORMAL:
// clear any selection made
let selection = Buffer.focusedWindow.getSelection();
try { // a simple if (selection) does not seem to work
selection.collapseToStart();
} catch (e) {}
// also clear any focus rectangle
if (liberator.focus)
liberator.focus.blur();
// select only one message in Muttator
if (liberator.has("mail") && !config.isComposeWindow) {
let i = gDBView.selection.currentIndex;
if (i == -1 && gDBView.rowCount >= 0)
i = 0;
gDBView.selection.select(i);
}
//modes.reset(); // TODO: Needed?
break;
case modes.VISUAL:
if (modes.extended & modes.TEXTAREA)
liberator.mode = modes.TEXTAREA;
else if (modes.extended & modes.CARET)
liberator.mode = modes.CARET;
break;
case modes.CARET:
// setting this option will trigger an observer which will
// take care of all other details like setting the NORMAL
// mode
options.setPref("accessibility.browsewithcaret", false);
break;
case modes.TEXTAREA:
// TODO: different behaviour for text areas and other input
// fields seems unnecessarily complicated. If the user
// likes Vi-mode then they probably like it for all input
// fields, if not they can enter it explicitly for only
// text areas. The mode name TEXTAREA is confusing and
// would be better replaced with something indicating that
// it's a Vi editing mode. Extended modes really need to be
// displayed too. --djk
function isInputField() {
let elem = liberator.focus;
return (elem instanceof HTMLInputElement && !/image/.test(elem.type));
}
if (options["insertmode"] || isInputField())
liberator.mode = modes.INSERT;
else
modes.reset();
break;
case modes.INSERT:
if ((modes.extended & modes.TEXTAREA))
liberator.mode = modes.TEXTAREA;
else
modes.reset();
break;
default: // HINTS, CUSTOM or COMMAND_LINE
modes.reset();
break;
}
// clear any command output, if we have any
modes.show();
},
// this keypress handler gets always called first, even if e.g.
// the commandline has focus
// TODO: ...help me...please...
onKeyPress: function (event) {
function isEscapeKey(key) key == "<Esc>" || key == "<C-[>";
function killEvent() {
event.preventDefault();
event.stopPropagation();
}
function updateCount(value) {
events._input.count = parseInt(value, 10);
if (isNaN(events._input.count))
events._input.count = null;
}
let key = events.toString(event);
if (!key)
return;
let url = typeof(buffer) != "undefined" ? buffer.URL : "";
if (modes.isRecording) {
if (key == "q" && liberator.mode != modes.INSERT && liberator.mode != modes.TEXTAREA) { // TODO: should not be hardcoded
modes.isRecording = false;
liberator.echomsg("Recorded macro '" + this._currentMacro + "'");
killEvent();
return;
}
else if (!mappings.hasMap(liberator.mode, this._input.buffer + key, url))
this._macros.set(this._currentMacro, this._macros.get(this._currentMacro) + key);
}
if (key == "<C-c>")
liberator.interrupted = true;
// feedingKeys needs to be separate from interrupted so
// we can differentiate between a recorded <C-c>
// interrupting whatever it's started and a real <C-c>
// interrupting our playback.
if (events.feedingKeys && !event.isMacro) {
if (key == "<C-c>") {
events.feedingKeys = false;
if (modes.isReplaying) {
modes.isReplaying = false;
this.setTimeout(function () { liberator.echomsg("Canceled playback of macro '" + this._lastMacro + "'"); }, 100);
}
}
else
events.duringFeed.push(event);
killEvent();
return;
}
try {
let stop = false;
let win = document.commandDispatcher.focusedWindow;
// special mode handling
if (modes.isMenuShown) { // menus have their own command handlers
stop = true;
} else if (modes.passNextKey) { // handle Escape-one-key mode ('i')
modes.passNextKey = false;
stop = true;
} else if (modes.passAllKeys) { // handle Escape-all-keys mode (Shift-Esc)
if (key == "<S-Esc>" || key == "<Insert>") // FIXME: Don't hardcode!
modes.passAllKeys = false;
// If we manage to get into command line mode while IGNOREKEYS, let the command line handle keys
if (liberator.mode == modes.COMMAND_LINE)
stop = false;
// If we are in the middle of a mapping, we never send the next key to the host app
else if (this._input.buffer)
stop = false;
// Respect "unignored" keys
else if (modes._passKeysExceptions == null || modes._passKeysExceptions.indexOf(key) < 0)
stop = true;
}
if (stop) {
this._input.buffer = "";
return;
}
stop = true; // set to false if we should NOT consume this event but let the host app handle it
// just forward event without checking any mappings when the MOW is open
if (liberator.mode == modes.COMMAND_LINE && (modes.extended & modes.OUTPUT_MULTILINE)) {
commandline.onMultilineOutputEvent(event);
throw killEvent();
}
// XXX: ugly hack for now pass certain keys to the host app as
// they are without beeping also fixes key navigation in combo
// boxes, submitting forms, etc.
// FIXME: breaks iabbr for now --mst
if (key in config.ignoreKeys && (config.ignoreKeys[key] & liberator.mode)) {
this._input.buffer = "";
return;
}
// TODO: handle middle click in content area
if (!isEscapeKey(key)) {
// custom mode...
if (liberator.mode == modes.CUSTOM) {
plugins.onEvent(event);
throw killEvent();
}
// All of these special cases for hint mode are driving
// me insane! -Kris
if (modes.extended & modes.HINTS) {
// under HINT mode, certain keys are redirected to hints.onEvent
if (key == "<Return>" || key == "<Tab>" || key == "<S-Tab>"
|| key == mappings.getMapLeader()
|| (key == "<BS>" && hints.previnput == "number")
|| (hints._isHintNumber(key) && !hints.escNumbers)) {
hints.onEvent(event);
this._input.buffer = "";
throw killEvent();
}
// others are left to generate the 'input' event or handled by the host app
return;
}
}
// FIXME (maybe): (is an ESC or C-] here): on HINTS mode, it enters
// into 'if (map && !skipMap) below. With that (or however) it
// triggers the onEscape part, where it resets mode. Here I just
// return true, with the effect that it also gets to there (for
// whatever reason). if that happens to be correct, well..
// XXX: why not just do that as well for HINTS mode actually?
if (liberator.mode == modes.CUSTOM)
return;
let inputStr = this._input.buffer + key;
let countStr = inputStr.match(/^[1-9][0-9]*|/)[0];
let candidateCommand = inputStr.substr(countStr.length);
let map = mappings[event.noremap ? "getDefault" : "get"](liberator.mode, candidateCommand, url);
let candidates = mappings.getCandidates(liberator.mode, candidateCommand, url);
if (candidates.length == 0 && !map) {
map = this._input.pendingMap;
this._input.pendingMap = null;
if (map && map.arg)
this._input.pendingArgMap = map;
}
// counts must be at the start of a complete mapping (10j -> go 10 lines down)
if (countStr && !candidateCommand) {
// no count for insert mode mappings
if (!modes.mainMode.count || modes.mainMode.input)
stop = false;
else
this._input.buffer = inputStr;
}
else if (this._input.pendingArgMap) {
this._input.buffer = "";
let map = this._input.pendingArgMap;
this._input.pendingArgMap = null;
if (!isEscapeKey(key)) {
if (modes.isReplaying && !this.waitForPageLoad())
return;
map.execute(null, this._input.count, key);
}
}
// only follow a map if there isn't a longer possible mapping
// (allows you to do :map z yy, when zz is a longer mapping than z)
else if (map && !event.skipmap && candidates.length == 0) {
this._input.pendingMap = null;
updateCount(countStr);
this._input.buffer = "";
if (map.arg) {
this._input.buffer = inputStr;
this._input.pendingArgMap = map;
}
else if (this._input.pendingMotionMap) {
if (!isEscapeKey(key))
this._input.pendingMotionMap.execute(candidateCommand, this._input.count, null);
this._input.pendingMotionMap = null;
}
// no count support for these commands yet
else if (map.motion) {
this._input.pendingMotionMap = map;
}
else {
if (modes.isReplaying && !this.waitForPageLoad())
throw killEvent();
let ret = map.execute(null, this._input.count);
if (map.route && ret)
stop = false;
}
}
else if (candidates.length > 0 && !event.skipmap) {
updateCount(countStr);
this._input.pendingMap = map;
this._input.buffer += key;
}
else { // if the key is neither a mapping nor the start of one
// the mode checking is necessary so that things like g<esc> do not beep
if (this._input.buffer != "" && !event.skipmap &&
(liberator.mode & (modes.INSERT | modes.COMMAND_LINE | modes.TEXTAREA)))
events.feedkeys(this._input.buffer, { noremap: true, skipmap: true });
this._input.buffer = "";
this._input.pendingArgMap = null;
this._input.pendingMotionMap = null;
this._input.pendingMap = null;
if (!isEscapeKey(key)) {
// allow key to be passed to the host app if we can't handle it
stop = false;
if (liberator.mode == modes.COMMAND_LINE) {
if (!(modes.extended & modes.INPUT_MULTILINE))
commandline.onEvent(event); // reroute event in command line mode
}
// beep on unrecognized keys
/*else if (!modes.mainMode.input)
liberator.beep();*/
}
}
if (stop)
killEvent();
}
catch (e) {
if (e !== undefined)
liberator.echoerr(e);
}
finally {
let motionMap = (this._input.pendingMotionMap && this._input.pendingMotionMap.names[0]) || "";
if (!(modes.extended & modes.HINTS))
statusline.updateField("input", motionMap + this._input.buffer);
}
},
// this is need for sites like msn.com which focus the input field on keydown
onKeyUpOrDown: function (event) {
if (modes.passNextKey || modes.passAllKeys || modes.isMenuShown || Events.isInputElemFocused())
return;
event.stopPropagation();
},
onPopupShown: function (event) {
if (event.originalTarget.localName == "tooltip" || event.originalTarget.id == "liberator-visualbell")
return;
modes.isMenuShown = true;
},
onPopupHidden: function () {
// gContextMenu is set to NULL, when a context menu is closed
if ((window.gContextMenu == null || !window.gContextMenu.shouldDisplay) && !this._activeMenubar)
modes.isMenuShown = false;
},
onDOMMenuBarActive: function () {
this._activeMenubar = true;
modes.isMenuShown = true;
},
onDOMMenuBarInactive: function () {
this._activeMenubar = false;
modes.isMenuShown = false;
},
onResize: function (event) {
if (window.fullScreen != this._fullscreen) {
this._fullscreen = window.fullScreen;
liberator.triggerObserver("fullscreen", this._fullscreen);
autocommands.trigger("Fullscreen", { state: this._fullscreen });
}
}
}, {
isInputElemFocused: function () {
let elem = liberator.focus;
return ((elem instanceof HTMLInputElement && !/image/.test(elem.type)) ||
elem instanceof HTMLTextAreaElement ||
elem instanceof HTMLObjectElement ||
elem instanceof HTMLEmbedElement);
}
}, {
commands: function () {
commands.add(["delmac[ros]"],
"Delete macros",
function (args) {
liberator.assert(!args.bang || !args.string, "Invalid argument");
if (args.bang)
events.deleteMacros();
else if (args.string)
events.deleteMacros(args.string);
else
liberator.echoerr("Argument required");
}, {
bang: true,
completer: function (context) completion.macro(context)
});
commands.add(["mac[ros]"],
"List all macros",
function (args) { completion.listCompleter("macro", args[0]); }, {
argCount: "?",
completer: function (context) completion.macro(context)
});
commands.add(["pl[ay]"],
"Replay a recorded macro",
function (args) { events.playMacro(args[0]); }, {
argCount: "1",
completer: function (context) completion.macro(context)
});
},
mappings: function () {
mappings.add(modes.all,
["<Esc>", "<C-[>"], "Focus content",
function () { events.onEscape(); });
// add the ":" mapping in all but insert mode mappings
mappings.add(modes.matchModes({ extended: false, input: false }),
[":"], "Enter command line mode",
function (count) { commandline.open("", count ? String(count) : "", modes.EX); }, {count: true});
// focus events
mappings.add([modes.NORMAL, modes.PLAYER, modes.VISUAL, modes.CARET],
["<Tab>"], "Advance keyboard focus",
function () { document.commandDispatcher.advanceFocus(); });
mappings.add([modes.NORMAL, modes.PLAYER, modes.VISUAL, modes.CARET, modes.INSERT, modes.TEXTAREA],
["<S-Tab>"], "Rewind keyboard focus",
function () { document.commandDispatcher.rewindFocus(); });
mappings.add(modes.all,
["<S-Esc>", "<Insert>"], "Temporarily ignore all " + config.name + " key bindings",
function () { modes.passAllKeys = !modes.passAllKeys; });
mappings.add([modes.NORMAL],
["i"], "Ignore next key and send it directly to the webpage",
function () { modes.passNextKey = true; });
mappings.add(modes.all,
["<Nop>"], "Do nothing",
function () { return; });
// macros
mappings.add([modes.NORMAL, modes.PLAYER, modes.MESSAGE],
["q"], "Record a key sequence into a macro",
function (arg) { events.startRecording(arg); },
{ arg: true });
mappings.add([modes.NORMAL, modes.PLAYER, modes.MESSAGE],
["@"], "Play a macro",
function (count, arg) {
if (count < 1) count = 1;
while (count-- && events.playMacro(arg))
;
},
{ arg: true, count: true });
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2009 by Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/**
* @class ModuleBase
* The base class for all modules.
*/
const ModuleBase = Class("ModuleBase", {
/**
* @property {[string]} A list of module prerequisites which
* must be initialized before this module is loaded.
*/
requires: [],
toString: function () "[module " + this.constructor.name + "]"
});
/**
* @constructor Module
*
* Constructs a new ModuleBase class and makes arrangements for its
* initialization. Arguments marked as optional must be either
* entirely elided, or they must have the exact type specified.
* Loading semantics are as follows:
*
* - A module is guaranteed not to be initialized before any of its
* prerequisites as listed in its {@see ModuleBase#requires} member.
* - A module is considered initialized once it's been instantiated,
* its {@see Class#init} method has been called, and its
* instance has been installed into the top-level {@see modules}
* object.
* - Once the module has been initialized, its module-dependent
* initialization functions will be called as described hereafter.
* @param {string} name The module's name as it will appear in the
* top-level {@see modules} object.
* @param {ModuleBase} base The base class for this module.
* @optional
* @param {Object} prototype The prototype for instances of this
* object. The object itself is copied and not used as a prototype
* directly.
* @param {Object} classProperties The class properties for the new
* module constructor.
* @optional
* @param {Object} moduleInit The module initialization functions
* for the new module. Each function is called as soon as the named module
* has been initialized, but after the module itself. The constructors are
* guaranteed to be called in the same order that the dependent modules
* were initialized.
* @optional
*
* @returns {function} The constructor for the resulting module.
*/
function Module(name, prototype, classProperties, moduleInit) {
var base = ModuleBase;
if (callable(prototype))
base = Array.splice(arguments, 1, 1)[0];
const module = Class(name, base, prototype, classProperties);
module.INIT = moduleInit || {};
module.requires = prototype.requires || [];
Module.list.push(module);
Module.constructors[name] = module;
return module;
}
Module.list = [];
Module.constructors = {};
window.addEventListener("load", function onload() {
window.removeEventListener("load", onload, false);
function dump(str) window.dump(String.replace(str, /\n?$/, "\n").replace(/^/m, Config.prototype.name.toLowerCase() + ": "));
const start = Date.now();
const deferredInit = { load: [] };
const seen = new Set();
const loaded = [];
function load(module, prereq) {
try {
if (module.name in modules)
return;
if (seen.has(module.name))
throw Error("Module dependency loop");
seen.add(module.name);
for (let dep of module.requires)
load(Module.constructors[dep], module.name);
dump("Load" + (isstring(prereq) ? " " + prereq + " dependency: " : ": ") + module.name);
modules[module.name] = module();
loaded.push(module.name);
function init(mod, module)
function () module.INIT[mod].call(modules[module.name], modules[mod]);
for (let mod of loaded) {
try {
if (mod in module.INIT)
init(mod, module)();
delete module.INIT[mod];
}
catch (e) {
if (modules.liberator)
liberator.echoerr(e);
}
}
for (let mod of Object.keys(module.INIT)) {
deferredInit[mod] = deferredInit[mod] || [];
deferredInit[mod].push(init(mod, module));
}
for (let fn of deferredInit[module.name] || [])
fn();
}
catch (e) {
dump("Loading " + (module && module.name) + ": " + e + "\n");
if (e.stack)
dump(e.stack);
}
}
Module.list.forEach(load);
deferredInit["load"].forEach(call);
for (let module of Module.list)
delete module.INIT;
dump("Loaded in " + (Date.now() - start) + "ms\n");
}, false);
window.addEventListener("unload", function onunload() {
window.removeEventListener("unload", onunload, false);
for (let [, mod] in iter(modules))
if (mod instanceof ModuleBase && "destroy" in mod)
mod.destroy();
}, false);
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2009 by Kris Maglione <maglione.k at Gmail>
// Copyright (c) 2009-2010 by Doug Kearns <dougkearns@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
// TODO:
// - fix Sanitize autocommand
// - add warning for TIMESPAN_EVERYTHING?
// - respect privacy.clearOnShutdown et al or recommend VimperatorLeave autocommand?
// - add support for :set sanitizeitems=all like 'eventignore'?
// - integrate with the Clear Private Data dialog?
const Sanitizer = Module("sanitizer", {
requires: ["liberator"],
init: function () {
const self = this;
liberator.loadScript("chrome://browser/content/sanitize.js", Sanitizer);
this.__proto__.__proto__ = new Sanitizer.Sanitizer; // Good enough.
Sanitizer.getClearRange = Sanitizer.Sanitizer.getClearRange; // XXX
self.prefDomain = "privacy.cpd.";
self.prefDomain2 = "extensions.liberator.privacy.cpd.";
},
// Largely ripped from from browser/base/content/sanitize.js so we can override
// the pref strategy without stepping on the global prefs namespace.
sanitize: function () {
const prefService = services.get("prefs");
let branch = prefService.getBranch(this.prefDomain);
let branch2 = prefService.getBranch(this.prefDomain2);
let errors = null;
function prefSet(name) {
try {
return branch.getBoolPref(name);
}
catch (e) {
return branch2.getBoolPref(name);
}
}
for (let itemName in this.items) {
let item = this.items[itemName];
if ("clear" in item && item.canClear && prefSet(itemName)) {
liberator.echomsg("Sanitizing " + itemName + " items...");
// Some of these clear() may raise exceptions (see bug #265028)
// to sanitize as much as possible, we catch and store them,
// rather than fail fast.
// Callers should check returned errors and give user feedback
// about items that could not be sanitized
try {
item.clear();
}
catch (e) {
if (!errors)
errors = {};
errors[itemName] = e;
liberator.echoerr("Error sanitizing " + itemName + ": " + e);
}
}
}
return errors;
},
get prefNames() util.Array.flatten([this.prefDomain, this.prefDomain2].map(options.allPrefs))
}, {
argToPref: function (arg) ["commandLine", "offlineApps", "siteSettings"].filter(function (pref) pref.toLowerCase() == arg)[0] || arg,
prefToArg: function (pref) pref.toLowerCase().replace(/.*\./, "")
}, {
commands: function () {
commands.add(["sa[nitize]"],
"Clear private data",
function (args) {
liberator.assert(!options['private'], "Cannot sanitize items in private mode");
let timespan = args["-timespan"] == undefined ? options["sanitizetimespan"] : args["-timespan"];
sanitizer.range = Sanitizer.getClearRange(timespan);
if (args.bang) {
liberator.assert(args.length == 0, "Trailing characters");
liberator.echomsg("Sanitizing all items in 'sanitizeitems'...");
let errors = sanitizer.sanitize();
if (errors) {
for (let item in errors)
liberator.echoerr("Error sanitizing " + item + ": " + errors[item]);
}
}
else {
liberator.assert(args.length > 0, "Argument required");
let items = [item for (item of args.map(Sanitizer.argToPref))];
for (let item of items) {
if (!options.get("sanitizeitems").isValidValue(item)) {
liberator.echoerr("Invalid data item: " + item);
return;
}
}
liberator.echomsg("Sanitizing " + args + " items...");
for (let item of items) {
if (sanitizer.canClearItem(item)) {
try {
sanitizer.clearItem(item);
}
catch (e) {
liberator.echoerr("Error sanitizing " + item + ": " + e);
}
}
else
liberator.echomsg("Cannot sanitize " + item);
}
}
},
{
argCount: "*", // FIXME: should be + and 0
bang: true,
completer: function (context) {
context.title = ["Privacy Item", "Description"];
context.completions = options.get("sanitizeitems").completer();
},
options: [
[["-timespan", "-t"],
commands.OPTION_INT,
function (arg) /^[0-4]$/.test(arg),
function () options.get("sanitizetimespan").completer()]
]
});
},
options: function () {
const self = this;
// add liberator-specific private items
[
{
name: "commandLine",
action: function () {
let stores = ["command", "search"];
if (self.range) {
stores.forEach(function (store) {
storage["history-" + store].mutate("filter", function (item) {
let timestamp = item.timestamp * 1000;
return timestamp < self.range[0] || timestamp > self.range[1];
});
});
}
else
stores.forEach(function (store) { storage["history-" + store].truncate(0); });
}
},
{
name: "macros",
action: function () { storage["macros"].clear(); }
},
{
name: "marks",
action: function () {
storage["local-marks"].clear();
storage["url-marks"].clear();
}
}
].forEach(function (item) {
let pref = self.prefDomain2 + item.name;
if (options.getPref(pref) == null)
options.setPref(pref, false);
self.items[item.name] = {
canClear: true,
clear: item.action
};
});
// call Sanitize autocommand
for (let [name, item] in Iterator(self.items)) {
let arg = Sanitizer.prefToArg(name);
if (item.clear) {
let func = item.clear;
item.clear = function () {
autocommands.trigger("Sanitize", { name: arg });
item.range = sanitizer.range;
func.call(item);
};
}
}
options.add(["sanitizeitems", "si"],
"The default list of private items to sanitize",
"stringlist", "cache,commandline,cookies,formdata,history,marks,sessions",
{
setter: function (values) {
for (let pref of sanitizer.prefNames) {
options.setPref(pref, false);
for (let value of this.parseValues(values)) {
if (Sanitizer.prefToArg(pref) == value) {
options.setPref(pref, true);
break;
}
}
}
return values;
},
getter: function () sanitizer.prefNames.filter(function (pref) options.getPref(pref)).map(Sanitizer.prefToArg).join(","),
completer: function (value) [
["cache", "Cache"],
["commandline", "Command-line history"],
["cookies", "Cookies"],
["downloads", "Download history"],
["formdata", "Saved form and search history"],
["history", "Browsing history"],
["macros", "Saved macros"],
["marks", "Local and URL marks"],
["offlineapps", "Offline website data"],
["passwords", "Saved passwords"],
["sessions", "Authenticated sessions"],
["sitesettings", "Site preferences"]
]
});
options.add(["sanitizetimespan", "sts"],
"The default sanitizer time span",
"number", 1,
{
setter: function (value) {
options.setPref("privacy.sanitize.timeSpan", value);
return value;
},
getter: function () options.getPref("privacy.sanitize.timeSpan", this.defaultValue),
completer: function (value) [
["0", "Everything"],
["1", "Last hour"],
["2", "Last two hours"],
["3", "Last four hours"],
["4", "Today"]
]
});
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const ConfigBase = Class(ModuleBase, {
/**
* @property {[["string", "string"]]} A sequence of names and descriptions
* of the autocommands available in this application. Primarily used
* for completion results.
*/
autocommands: [],
get browser() window.gBrowser,
get tabbrowser() window.gBrowser,
get browserModes() [modes.NORMAL],
/**
* @property {Object} Application specific defaults for option values. The
* property names must be the options' canonical names, and the values
* must be strings as entered via :set.
*/
defaults: { toolbars: "" },
/**
* @property {[["string", "string", "function"]]} An array of
* dialogs available via the :dialog command.
* [0] name - The name of the dialog, used as the first
* argument to :dialog.
* [1] description - A description of the dialog, used in
* command completion results for :dialog.
* [2] action - The function executed by :dialog.
*/
dialogs: [],
/**
* @property {string[]} A list of features available in this
* application. Used extensively in feature test macros. Use
* liberator.has(feature) to check for a feature's presence
* in this array.
*/
features: new Set,
guioptions: {},
hasTabbrowser: false,
/**
* @property {string} The name of the application that hosts the
* “liberated” application. E.g., "Firefox" or "Xulrunner".
*/
hostApplication: null,
/**
* @property {function} Called on liberator startup to allow for any
* arbitrary application-specific initialization code.
*/
init: function () {},
/**
* @property {Object} A map between key names for key events should be ignored,
* and a mask of the modes in which they should be ignored.
*/
ignoreKeys: {}, // XXX: be aware you can't put useful values in here, as "modes.NORMAL" etc. are not defined at this time
/**
* @property {string} The ID of the application's main XUL window.
*/
mainWindowId: document.documentElement.id,
/**
* @property {[[]]} An array of application specific mode specifications.
* The values of each mode are passed to modes.addMode during
* liberator startup.
*/
modes: [],
/**
* @property {string} The name of “liberated” application.
* Required.
*/
name: null,
/**
* @property {number} The height (px) that is available to the output
* window.
*/
get outputHeight() config.browser.mPanelContainer.boxObject.height,
/**
* @property {[string]} A list of extra scripts in the liberator or
* application namespaces which should be loaded before liberator
* initialization.
*/
scripts: [],
/**
* @property {Object} A list of toolbars which can be shown/hidden
* with :set toolbars
*/
toolbars: {},
/**
* @property {string} The leaf name of any temp files created by
* {@link io.createTempFile}.
*/
get tempFile() this.name.toLowerCase() + ".tmp",
updateTitlebar: function () {},
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
//xxx:
this.$$Namespace = function (prefix, uri) {
return "XMLList" in window ? Namespace(prefix, uri)
: {
prefix: prefix,
uri: uri,
toString: function () {
return this.uri;
},
};
}
const XHTML = $$Namespace("html", "http://www.w3.org/1999/xhtml");
const XUL = $$Namespace("xul", "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
const NS = $$Namespace("liberator", "http://vimperator.org/namespaces/liberator");
if ("XMLList" in window) eval("default xml namespace = XHTML");
delete this.$$Namespace;
const Util = Module("util", {
init: function () {
this.Array = Util.Array;
},
/**
* Returns a shallow copy of <b>obj</b>.
*
* @param {Object} obj
* @returns {Object}
*/
cloneObject: function cloneObject(obj) {
if (obj instanceof Array)
return obj.slice();
let newObj = {};
for (let [k, v] in Iterator(obj))
newObj[k] = v;
return newObj;
},
/**
* Clips a string to a given length. If the input string is longer
* than <b>length</b>, an ellipsis is appended.
*
* @param {string} str The string to truncate.
* @param {number} length The length of the returned string.
* @returns {string}
*/
clip: function clip(str, length) {
return str.length <= length ? str : str.substr(0, length - 3) + "...";
},
/**
* Compares two strings, case insensitively. Return values are as
* in String#localeCompare.
*
* @param {string} a
* @param {string} b
* @returns {number}
*/
compareIgnoreCase: function compareIgnoreCase(a, b) String.localeCompare(a.toLowerCase(), b.toLowerCase()),
/**
* Returns an object representing a Node's computed CSS style.
*
* @param {Node} node
* @returns {Object}
*/
computedStyle: function computedStyle(node) {
while ((node instanceof Text || node instanceof Comment) && node.parentNode)
node = node.parentNode;
return node.ownerDocument.defaultView.getComputedStyle(node, null);
},
/**
* Copies a string to the system clipboard. If <b>verbose</b> is specified
* the copied string is also echoed to the command line.
*
* @param {string} str
* @param {boolean} verbose
*/
copyToClipboard: function copyToClipboard(str, verbose) {
const clipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
clipboardHelper.copyString(str);
if (verbose)
liberator.echomsg("Copied text to clipboard: " + str);
},
/**
* Converts any arbitrary string into an URI object.
*
* @param {string} str
* @returns {Object}
*/
// FIXME: newURI needed too?
createURI: function createURI(str) {
const fixup = Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup);
return fixup.createFixupURI(str, fixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP);
},
/**
* Converts HTML special characters in <b>str</b> to the equivalent HTML
* entities.
*
* @param {string} str
* @returns {string}
*/
escapeHTML: function escapeHTML(str) {
// XXX: the following code is _much_ slower than a simple .replace()
// :history display went down from 2 to 1 second after changing
//
// var e = window.content.document.createElement("div");
// e.appendChild(window.content.document.createTextNode(str));
// return e.innerHTML;
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
},
/**
* Escapes Regular Expression special characters in <b>str</b>.
*
* @param {string} str
* @returns {string}
*/
escapeRegex: function escapeRegex(str) {
return str.replace(/([\\{}()[\].?*+])/g, "\\$1");
},
/**
* Escapes quotes, newline and tab characters in <b>str</b>. The returned
* string is delimited by <b>delimiter</b> or " if <b>delimiter</b> is not
* specified. {@see String#quote}.
*
* @param {string} str
* @param {string} delimiter
* @returns {string}
*/
escapeString: function escapeString(str, delimiter) {
if (delimiter == undefined)
delimiter = '"';
return delimiter + str.replace(/([\\'"])/g, "\\$1").replace("\n", "\\n", "g").replace("\t", "\\t", "g") + delimiter;
},
/**
* Returns an XPath union expression constructed from the specified node
* tests. An expression is built with node tests for both the null and
* XHTML namespaces. See {@link Buffer#evaluateXPath}.
*
* @param nodes {Array(string)}
* @returns {string}
*/
makeXPath: function makeXPath(nodes) {
return util.Array(nodes).map(function (node) [node, "xhtml:" + node]).flatten()
.map(function (node) "//" + node).join(" | ");
},
/**
* Memoize the lookup of a property in an object.
*
* @param {object} obj The object to alter.
* @param {string} key The name of the property to memoize.
* @param {function} getter A function of zero to two arguments which
* will return the property's value. <b>obj</b> is
* passed as the first argument, <b>key</b> as the
* second.
*/
memoize: function memoize(obj, key, getter) {
obj.__defineGetter__(key, function () {
delete obj[key];
obj[key] = getter(obj, key);
return obj[key];
});
},
/**
* Split a string on literal occurrences of a marker.
*
* Specifically this ignores occurrences preceded by a backslash, or
* contained within 'single' or "double" quotes.
*
* It assumes backslash escaping on strings, and will thus not count quotes
* that are preceded by a backslash or within other quotes as starting or
* ending quoted sections of the string.
*
* @param {string} str
* @param {RegExp} marker
*/
splitLiteral: function splitLiteral(str, marker) {
let results = [];
let resep = RegExp(/^(([^\\'"]|\\.|'([^\\']|\\.)*'|"([^\\"]|\\.)*")*?)/.source + marker.source);
let cont = true;
while (cont) {
cont = false;
str = str.replace(resep, function (match, before) {
cont = false;
if (before) {
results.push(before);
cont = true;
}
return "";
});
}
results.push(str);
return results;
},
/**
* Converts <b>bytes</b> to a pretty printed data size string.
*
* @param {number} bytes The number of bytes.
* @param {string} decimalPlaces The number of decimal places to use if
* <b>humanReadable</b> is true.
* @param {boolean} humanReadable Use byte multiples.
* @returns {string}
*/
formatBytes: function formatBytes(bytes, decimalPlaces, humanReadable) {
const unitVal = ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
let unitIndex = 0;
let tmpNum = parseInt(bytes, 10) || 0;
let strNum = [tmpNum + ""];
if (humanReadable) {
while (tmpNum >= 1024) {
tmpNum /= 1024;
if (++unitIndex > (unitVal.length - 1))
break;
}
let decPower = Math.pow(10, decimalPlaces);
strNum = ((Math.round(tmpNum * decPower) / decPower) + "").split(".", 2);
if (!strNum[1])
strNum[1] = "";
while (strNum[1].length < decimalPlaces) // pad with "0" to the desired decimalPlaces)
strNum[1] += "0";
}
for (let u = strNum[0].length - 3; u > 0; u -= 3) // make a 10000 a 10,000
strNum[0] = strNum[0].substr(0, u) + "," + strNum[0].substr(u);
if (unitIndex) // decimalPlaces only when > Bytes
strNum[0] += "." + strNum[1];
return strNum[0] + " " + unitVal[unitIndex];
},
exportHelp: function (path) {
const FILE = io.File(path);
const PATH = FILE.leafName.replace(/\..*/, "") + "/";
const TIME = Date.now();
let zip = services.create("zipWriter");
zip.open(FILE, io.MODE_CREATE | io.MODE_WRONLY | io.MODE_TRUNCATE);
function addURIEntry(file, uri)
zip.addEntryChannel(PATH + file, TIME, 9,
services.get("io").newChannel(uri, null, null), false);
function addDataEntry(file, data) // Inideal to an extreme.
addURIEntry(file, "data:text/plain;charset=UTF-8," + encodeURI(data));
let empty = util.Array.toObject(
"area base basefont br col frame hr img input isindex link meta param"
.split(" ").map(Array.concat));
let chrome = {};
for (let [file,] in Iterator(services.get("liberator:").FILE_MAP)) {
liberator.open("liberator://help/" + file);
events.waitForPageLoad();
let data = [
'<?xml version="1.0" encoding="UTF-8"?>\n',
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n',
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n'
];
function fix(node) {
switch(node.nodeType) {
case Node.ELEMENT_NODE:
if (node instanceof HTMLScriptElement)
return;
data.push("<"); data.push(node.localName);
if (node instanceof HTMLHtmlElement)
data.push(" xmlns=" + XHTML.uri.quote());
for (let { name: name, value: value } in util.Array.itervalues(node.attributes)) {
if (name == "liberator:highlight") {
name = "class";
value = "hl-" + value;
}
if (name == "href") {
if (value.indexOf("liberator://help-tag/") == 0)
value = services.get("io").newChannel(value, null, null).originalURI.path.substr(1);
if (!/[#\/]/.test(value))
value += ".xhtml";
}
if (name == "src" && value.indexOf(":") > 0) {
chrome[value] = value.replace(/.*\//, "");;
value = value.replace(/.*\//, "");
}
data.push(" ");
data.push(name);
data.push('="');
data.push(xml`${value}`.toString());
data.push('"')
}
if (node.localName in empty)
data.push(" />");
else {
data.push(">");
if (node instanceof HTMLHeadElement)
data.push(`<link rel="stylesheet" type="text/css" href="help.css"/>`/*toXMLString()*/);
Array.map(node.childNodes, arguments.callee);
data.push("</"); data.push(node.localName); data.push(">");
}
break;
case Node.TEXT_NODE:
data.push(xml`${node.textContent}`.toString());
}
}
fix(content.document.documentElement);
addDataEntry(file + ".xhtml", data.join(""));
}
let data = [h.selector.replace(/^\[.*?=(.*?)\]/, ".hl-$1").replace(/html\|/, "") +
"\t{" + h.value + "}"
for (h in highlight) if (/^Help|^Logo/.test(h.class))];
data = data.join("\n");
addDataEntry("help.css", data.replace(/chrome:[^ ")]+\//g, ""));
let re = /(chrome:[^ ");]+\/)([^ ");]+)/g;
while ((m = re.exec(data)))
chrome[m[0]] = m[2];
for (let [uri, leaf] in Iterator(chrome))
addURIEntry(leaf, uri);
zip.close();
},
/**
* Sends a synchronous or asynchronous HTTP request to <b>url</b> and
* returns the XMLHttpRequest object. If <b>callback</b> is specified the
* request is asynchronous and the <b>callback</b> is invoked with the
* object as its argument.
*
* @param {string} url
* @param {function(XMLHttpRequest)} callback
* @returns {XMLHttpRequest}
*/
httpGet: function httpGet(url, callback) {
try {
let xmlhttp = new XMLHttpRequest();
xmlhttp.mozBackgroundRequest = true;
if (callback) {
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4)
callback(xmlhttp);
};
}
xmlhttp.open("GET", url, !!callback);
xmlhttp.send(null);
return xmlhttp;
}
catch (e) {
// liberator.log("Error opening " + url + ": " + e);
return null;
}
},
/**
* Evaluates an XPath expression in the current or provided
* document. It provides the xhtml, xhtml2 and liberator XML
* namespaces. The result may be used as an iterator.
*
* @param {string} expression The XPath expression to evaluate.
* @param {Document} doc The document to evaluate the expression in.
* @default The current document.
* @param {Node} elem The context element.
* @default <b>doc</b>
* @param {boolean} asIterator Whether to return the results as an
* XPath iterator.
*/
evaluateXPath: function (expression, doc, elem, asIterator) {
if (!doc)
doc = window.content.document;
if (!elem)
elem = doc;
if (isarray(expression))
expression = util.makeXPath(expression);
let result = doc.evaluate(expression, elem,
function lookupNamespaceURI(prefix) {
return {
xhtml: "http://www.w3.org/1999/xhtml",
xhtml2: "http://www.w3.org/2002/06/xhtml2",
liberator: NS.uri
}[prefix] || null;
},
asIterator ? XPathResult.ORDERED_NODE_ITERATOR_TYPE : XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
result.__iterator__ = asIterator
? function () { let elem; while ((elem = this.iterateNext())) yield elem; }
: function () { for (let i = 0; i < this.snapshotLength; i++) yield this.snapshotItem(i); };
return result;
},
/**
* The identity function.
*
* @param {Object} k
* @returns {Object}
*/
identity: function identity(k) k,
/**
* Returns the intersection of two rectangles.
*
* @param {Object} r1
* @param {Object} r2
* @returns {Object}
*/
intersection: function (r1, r2) ({
get width() this.right - this.left,
get height() this.bottom - this.top,
left: Math.max(r1.left, r2.left),
right: Math.min(r1.right, r2.right),
top: Math.max(r1.top, r2.top),
bottom: Math.min(r1.bottom, r2.bottom)
}),
/**
* Returns the array that results from applying <b>func</b> to each
* property of <b>obj</b>.
*
* @param {Object} obj
* @param {function} func
* @returns {Array}
*/
map: function map(obj, func) {
let ary = [];
for (let i in Iterator(obj))
ary.push(func(i));
return ary;
},
/**
* Math utility methods.
* @singleton
*/
Math: {
/**
* Returns the specified <b>value</b> constrained to the range <b>min</b> -
* <b>max</b>.
*
* @param {number} value The value to constrain.
* @param {number} min The minimum constraint.
* @param {number} max The maximum constraint.
* @returns {number}
*/
constrain: function constrain(value, min, max) Math.min(Math.max(min, value), max)
},
/**
* Converts a URI string into a URI object.
*
* @param {string} uri
* @returns {nsIURI}
*/
// FIXME: createURI needed too?
newURI: function (uri) {
return services.get("io").newURI(uri, null, null);
},
/**
* Pretty print a JavaScript object. Use HTML markup to color certain items
* if <b>color</b> is true.
*
* @param {Object} object The object to pretty print.
* @param {boolean} color Whether the output should be colored.
* @returns {string}
*/
objectToString: function objectToString(object, color) {
if (object === null)
return "null\n";
if (typeof object != "object")
return false;
const NAMESPACES = util.Array.toObject([
[NS, 'liberator'],
[XHTML, 'html'],
[XUL, 'xul']
]);
if (object instanceof Element) {
let elem = object;
if (elem.nodeType == elem.TEXT_NODE)
return elem.data;
function namespaced(node) {
var ns = NAMESPACES[node.namespaceURI];
if (ns)
return ns + ":" + node.localName;
return node.localName.toLowerCase();
}
try {
let tag = xml`${`<${namespaced(elem)} `}${
template.map2(xml, elem.attributes,
function (a) xml`${namespaced(a)}=${template.highlight(a.value, true)}`, " ")}${
!elem.firstChild || /^\s*$/.test(elem.firstChild) && !elem.firstChild.nextSibling
? "/>" : `>...</${namespaced(elem)}>`}`;
return tag;
}
catch (e) {
return {}.toString.call(elem);
}
}
try { // for window.JSON
var obj = String(object);
}
catch (e) {
obj = "[Object]";
}
obj = template.highlightFilter(util.clip(obj, 150), "\n", !color ? function () "^J" : function () xml`<span highlight="NonText">^J</span>`);
let string = xml`<span highlight="Title Object">${obj}</span>::<br/>
`;
let keys = [];
try { // window.content often does not want to be queried with "var i in object"
let hasValue = !("__iterator__" in object);
if (modules.isPrototypeOf(object)) {
object = Iterator(object);
hasValue = false;
}
for (let i in object) {
let value = xml`<![CDATA[<no value>]]>`;
try {
value = object[i];
}
catch (e) {}
if (!hasValue) {
if (i instanceof Array && i.length == 2)
[i, value] = i;
else
var noVal = true;
}
value = template.highlight(value, true, 150);
let key = xml`<span highlight="Key">${i}</span>`;
if (!isNaN(i))
i = parseInt(i);
else if (/^[A-Z_]+$/.test(i))
i = "";
keys.push([i, xml`${key}${noVal ? "" : xml`: ${value}`}<br/>
`]);
}
}
catch (e) {}
function compare(a, b) {
if (!isNaN(a[0]) && !isNaN(b[0]))
return a[0] - b[0];
return String.localeCompare(a[0], b[0]);
}
xml["+="](string, template.map2(xml, keys.sort(compare), function (f) f[1]));
return string;
},
/**
* A generator that returns the values between <b>start</b> and <b>end</b>,
* in <b>step</b> increments.
*
* @param {number} start The interval's start value.
* @param {number} end The interval's end value.
* @param {boolean} step The value to step the range by. May be
* negative. @default 1
* @returns {Iterator(Object)}
*/
range: function range(start, end, step) {
if (!step)
step = 1;
if (step > 0) {
for (; start < end; start += step)
yield start;
}
else {
while (start > end)
yield start += step;
}
},
/**
* An interruptible generator that returns all values between <b>start</b>
* and <b>end</b>. The thread yields every <b>time</b> milliseconds.
*
* @param {number} start The interval's start value.
* @param {number} end The interval's end value.
* @param {number} time The time in milliseconds between thread yields.
* @returns {Iterator(Object)}
*/
interruptibleRange: function interruptibleRange(start, end, time) {
let endTime = Date.now() + time;
while (start < end) {
if (Date.now() > endTime) {
liberator.threadYield(true, true);
endTime = Date.now() + time;
}
yield start++;
}
},
/**
* Reads a string from the system clipboard.
*
* This is same as Firefox's readFromClipboard function, but is needed for
* apps like Thunderbird which do not provide it.
*
* @returns {string}
*/
readFromClipboard: function readFromClipboard() {
let str;
try {
const clipboard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
const transferable = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
transferable.addDataFlavor("text/unicode");
if (clipboard.supportsSelectionClipboard())
clipboard.getData(transferable, clipboard.kSelectionClipboard);
else
clipboard.getData(transferable, clipboard.kGlobalClipboard);
let data = {};
let dataLen = {};
transferable.getTransferData("text/unicode", data, dataLen);
if (data) {
data = data.value.QueryInterface(Ci.nsISupportsString);
str = data.data.substring(0, dataLen.value / 2);
}
}
catch (e) {}
return str;
},
/**
* Returns an array of URLs parsed from <b>str</b>.
*
* Given a string like 'google bla, www.osnews.com' return an array
* ['www.google.com/search?q=bla', 'www.osnews.com']
*
* @param {string} str
* @returns {string[]}
*/
stringToURLArray: function stringToURLArray(str) {
let urls;
if (options["urlseparator"])
urls = util.splitLiteral(str, RegExp("\\s*" + options["urlseparator"] + "\\s*"));
else
urls = [str];
return urls.map(function (url) {
url = url.trim();
if (!url)
return "";
if (url.substr(0, 5) != "file:") {
try {
// Try to find a matching file.
let file = io.File(url);
if (file.exists() && file.isReadable())
return services.get("io").newFileURI(file).spec;
}
catch (e) {}
}
// Look for a valid protocol
let proto = url.match(/^([-\w]+):/);
if (proto && Cc["@mozilla.org/network/protocol;1?name=" + proto[1]])
// Handle as URL, but remove spaces. Useful for copied/'p'asted URLs.
return url.replace(/\s*\n+\s*/g, "");
// Ok, not a valid proto. If it looks like URL-ish (foo.com/bar),
// let Gecko figure it out.
if (!/^(["']).*\1$/.test(url) && /[.\/]/.test(url) && !/^\.|\s/.test(url) ||
/^[\w-.]+:\d+(?:\/|$)/.test(url))
return url;
// TODO: it would be clearer if the appropriate call to
// getSearchURL was made based on whether or not the first word was
// indeed an SE alias rather than seeing if getSearchURL can
// process the call usefully and trying again if it fails
// check for a search engine match in the string, then try to
// search for the whole string in the default engine
let searchURL = bookmarks.getSearchURL(url, false) || bookmarks.getSearchURL(url, true);
if (searchURL)
return searchURL;
// Hmm. No defsearch? Let the host app deal with it, then.
return url;
}).filter(function(url, i) i === 0 || url);
},
/**
* Converts an string, TemplateXML object or E4X literal to a DOM node.
*
* @param {String|TemplateXML|xml} node
* @param {Document} doc
* @param {Object} nodes If present, nodes with the "key" attribute are
* stored here, keyed to the value thereof.
* @returns {Node|DocumentFragment}
*/
xmlToDom: function xmlToDom(node, doc, nodes) {
if (typeof node === "xml")
return this.xmlToDomForE4X(node, doc, nodes);
var dom = this.xmlToDomForTemplate(node, doc, nodes);
//xxx: change highlight's namespace
const str = "highlight";
var attr,
list = (dom.nodeType === 11 ? dom : dom.parentNode).querySelectorAll("[highlight]");
for (let node of list) {
attr = node.getAttribute(str);
node.removeAttribute(str);
node.setAttributeNS(NS, str, attr);
}
return dom;
},
/**
* Converts an E4X XML literal to a DOM node.
*
* @param {Node} node
* @param {Document} doc
* @param {Object} nodes
* @returns {Node}
* @deprecated
* @see util.xmlToDom
*/
xmlToDomForE4X: function xmlToDomForE4X(node, doc, nodes) {
if (node.length() != 1) {
let domnode = doc.createDocumentFragment();
for each (let child in node)
domnode.appendChild(arguments.callee(child, doc, nodes));
return domnode;
}
switch (node.nodeKind()) {
case "text":
return doc.createTextNode(String(node));
case "element":
let domnode = doc.createElementNS(node.namespace(), node.localName());
for each (let attr in node.attributes())
domnode.setAttributeNS(attr.name() == "highlight" ? NS.uri : attr.namespace(), attr.name(), String(attr));
for each (let child in node.children())
domnode.appendChild(arguments.callee(child, doc, nodes));
if (nodes && node.attribute("key"))
nodes[node.attribute("key")] = domnode;
return domnode;
default:
return null;
}
},
/**
* Converts an string of TemplateXML object to a DOM node.
*
* @param {String|TemplateXML} node
* @param {Document} doc
* @param {Object} nodes
* @returns {Node|DocumentFragment}
* @see util.xmlToDom
*/
xmlToDomForTemplate: function xmlToDomForTemplate(node, doc, nodes) {
var range = doc.createRange();
var fragment = range.createContextualFragment(
xml`<div xmlns:ns=${NS} xmlns:xul=${XUL} xmlns=${XHTML}>${node}</div>`.toString());
range.selectNodeContents(fragment.firstChild);
var dom = range.extractContents();
range.detach();
if (nodes) {
for (let elm of dom.querySelectorAll("[key]"))
nodes[elm.getAttribute("key")] = elm;
}
return dom.childNodes.length === 1 ? dom.childNodes[0] : dom;
},
/**
* encoding dom
*
* @param {Node|Range|Selection|Document} node
* @param {String} type example "text/plain", "text/html", "text/xml", "application/xhtml+xml" etc...
* @param {Number} flags nsIDocumentEncoder.OutputXXXX
* @returns {String}
*/
domToStr: let (Encoder = Components.Constructor("@mozilla.org/layout/documentEncoder;1?type=text/plain", "nsIDocumentEncoder", "init"))
function domToStr(node, type, flags) {
var doc, method;
if (node instanceof Document) {
doc = node;
node = null;
method = "setNode";
} else if (node instanceof Node) {
doc = node.ownerDocument;
method = "setNode";
} else if (node instanceof Range) {
doc = node.startContainer;
if (doc.ownerDocument) {
doc = doc.ownerDocument;
}
method = "setRange";
} else if (node instanceof Selection) {
// can not found document
if (node.rangeCount === 0) {
return "";
}
doc = node.getRangeAt(0).startContainer;
if (doc.ownerDocument) {
doc = doc.ownerDocument;
}
method = "setSelection";
} else {
return null;
}
var encoder = new Encoder(doc, type || "text/html", flags || 0);
encoder[method](node);
return encoder.encodeToString();
},
}, {
// TODO: Why don't we just push all util.BuiltinType up into modules? --djk
/**
* Array utility methods.
*/
Array: Class("Array", Array, {
init: function (ary) {
return {
__proto__: ary,
__iterator__: function () this.iteritems(),
__noSuchMethod__: function (meth, args) {
var res = util.Array[meth].apply(null, [this.__proto__].concat(args));
if (util.Array.isinstance(res))
return util.Array(res);
return res;
},
toString: function () this.__proto__.toString(),
concat: function () this.__proto__.concat.apply(this.__proto__, arguments),
map: function () this.__noSuchMethod__("map", Array.slice(arguments))
};
}
}, {
isinstance: function isinstance(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
},
/**
* Converts an array to an object. As in lisp, an assoc is an
* array of key-value pairs, which maps directly to an object,
* as such:
* [["a", "b"], ["c", "d"]] -> { a: "b", c: "d" }
*
* @param {Array[]} assoc
* @... {string} 0 - Key
* @... 1 - Value
*/
toObject: function toObject(assoc) {
let obj = {};
assoc.forEach(function ([k, v]) { obj[k] = v; });
return obj;
},
/**
* Compacts an array, removing all elements that are null or undefined:
* ["foo", null, "bar", undefined] -> ["foo", "bar"]
*
* @param {Array} ary
* @returns {Array}
*/
compact: function compact(ary) ary.filter(function (item) item != null),
/**
* Flattens an array, such that all elements of the array are
* joined into a single array:
* [["foo", ["bar"]], ["baz"], "quux"] -> ["foo", ["bar"], "baz", "quux"]
*
* @param {Array} ary
* @returns {Array}
*/
flatten: function flatten(ary) Array.prototype.concat.apply([], ary),
/**
* Returns an Iterator for an array's values.
*
* @param {Array} ary
* @returns {Iterator(Object)}
*/
itervalues: function itervalues(ary) {
let length = ary.length;
for (let i = 0; i < length; i++)
yield ary[i];
},
/**
* Returns an Iterator for an array's indices and values.
*
* @param {Array} ary
* @returns {Iterator([{number}, {Object}])}
*/
iteritems: function iteritems(ary) {
let length = ary.length;
for (let i = 0; i < length; i++)
yield [i, ary[i]];
},
/**
* Filters out all duplicates from an array. If
* <b>unsorted</b> is false, the array is sorted before
* duplicates are removed.
*
* @param {Array} ary
* @param {boolean} unsorted
* @returns {Array}
*/
uniq: function uniq(ary, unsorted) [...new Set(unsorted ? ary : ary.sort())],
})
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2008-2009 Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
(function () {
const modules = {};
const BASE = "liberator://template/chrome://liberator/content/"
modules.modules = modules;
const loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader);
function load(script) {
for (let [i, base] in Iterator(prefix)) {
try {
loader.loadSubScript(base + script, modules);
return;
}
catch (e) {
if (i + 1 < prefix.length)
continue;
if (Components.utils.reportError)
Components.utils.reportError(e);
dump("liberator: Error loading script " + script + ": " + e + "\n");
dump(e.stack + "\n");
}
}
}
let prefix = [BASE];
//Cu.import("resource://liberator/template-tag.js", modules);
loader.loadSubScript("resource://liberator/template-tag.js", modules);
// TODO: This list is much too long, we should try to minimize
// the number of required components for easier porting to new applications
["base.js",
"modules.js",
"abbreviations.js",
"autocommands.js",
"buffer.js",
"commandline.js",
"commands.js",
"completion.js",
"configbase.js",
"config.js",
"liberator.js",
"editor.js",
"events.js",
"finder.js",
"hints.js",
"io.js",
"javascript.js",
"mappings.js",
"marks.js",
"modes.js",
"options.js",
"services.js",
"statusline.js",
"style.js",
"template.js",
"util.js",
].forEach(load);
prefix.unshift("chrome://" + modules.Config.prototype.name.toLowerCase() + "/content/");
modules.Config.prototype.scripts.forEach(load);
})();
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* A class representing key mappings. Instances are created by the
* {@link Mappings} class.
*
* @param {number[]} modes The modes in which this mapping is active.
* @param {string[]} keys The key sequences which are bound to
* <b>action</b>.
* @param {string} description A short one line description of the key mapping.
* @param {function} action The action invoked by each key sequence.
* @param {Object} extraInfo An optional extra configuration hash. The
* following properties are supported.
* arg - see {@link Map#arg}
* count - see {@link Map#count}
* motion - see {@link Map#motion}
* route - see {@link Map#route}
* noremap - see {@link Map#noremap}
* rhs - see {@link Map#rhs}
* silent - see {@link Map#silent}
* matchingUrls - see {@link Map#matchingUrls}
* @optional
* @private
*/
const Map = Class("Map", {
init: function (modes, keys, description, action, extraInfo) {
modes = Array.concat(modes).map(function (m) isobject(m) ? m.mask : m);
this.modes = modes;
this.names = keys.map(events.canonicalKeys);
this.action = action;
this.description = description;
if (extraInfo)
update(this, extraInfo);
if (this.matchingUrls)
this.matchingUrls = this.matchingUrls instanceof RegExp ? this.matchingUrls
: RegExp(this.matchingUrls);
},
/** @property {number[]} All of the modes for which this mapping applies. */
modes: null,
/** @property {string[]} All of this mapping's names (key sequences). */
names: null,
/** @property {function (number)} The function called to execute this mapping. */
action: null,
/** @property {string} This mapping's description, as shown in :usage. */
description: "",
/** @property {boolean} Whether this mapping accepts an argument. */
arg: false,
/** @property {boolean} Whether this mapping accepts a count. */
count: false,
/**
* @property {boolean} Whether the mapping accepts a motion mapping
* as an argument.
*/
motion: false,
/**
* @property {boolean} Whether the mapping's key events should be
* propagated to the host application.
*/
// TODO: I'm not sure this is the best name but it reflects that which it replaced. --djk
route: false,
/** @property {boolean} Whether the RHS of the mapping should expand mappings recursively. */
noremap: false,
/** @property {boolean} Whether any output from the mapping should be echoed on the command line. */
silent: false,
/** @property {string} The literal RHS expansion of this mapping. */
rhs: null,
/** @property {RegExp} URL matching pattern for URL local mapping. */
matchingUrls: null,
/**
* @property {boolean} Specifies whether this is a user mapping. User
* mappings may be created by plugins, or directly by users. Users and
* plugin authors should create only user mappings.
*/
user: false,
/**
* Returns whether this mapping can be invoked by a key sequence matching
* <b>name</b>.
*
* @param {string} name The name to query.
* @returns {boolean}
*/
hasName: function (name) this.names.indexOf(name) >= 0,
/**
* Execute the action for this mapping.
*
* @param {string} motion The motion argument if accepted by this mapping.
* E.g. "w" for "dw"
* @param {number} count The associated count. E.g. "5" for "5j"
* @default -1
* @param {string} argument The normal argument if accepted by this
* mapping. E.g. "a" for "ma"
*/
execute: function (motion, count, argument) {
let args = [];
if (this.motion)
args.push(motion);
if (this.count)
args.push(count);
if (this.arg)
args.push(argument);
let self = this;
function repeat() self.action.apply(self, args);
if (this.names[0] != ".") // FIXME: Kludge.
mappings.repeat = repeat;
return liberator.trapErrors(repeat);
},
/**
* Returns true if same mapping.
*
* @param {Mapping}
* @returns {boolean}
*/
equals: function (map) {
return this.rhs == map.rhs && this.names[0] == map.names && this.matchingUrls == map.matchingUrls;
}
});
/**
* @instance mappings
*/
const Mappings = Module("mappings", {
requires: ["modes"],
init: function () {
this._main = []; // default mappings
this._user = []; // user created mappings
},
_matchingUrlsTest: function (map, patternOrUrl) {
if (!patternOrUrl)
return !map.matchingUrls;
if (patternOrUrl instanceof RegExp)
return map.matchingUrls && (patternOrUrl.toString() == map.matchingUrls.toString());
return !map.matchingUrls || map.matchingUrls.test(patternOrUrl);
},
_addMap: function (map) {
let where = map.user ? this._user : this._main;
map.modes.forEach(function (mode) {
if (!(mode in where))
where[mode] = [];
// URL local mappings should be searched first.
where[mode][map.matchingUrls ? 'unshift' : 'push'](map);
});
},
_getMap: function (mode, cmd, patternOrUrl, stack) {
let maps = stack[mode] || [];
for (let map of maps) {
if (map.hasName(cmd) && this._matchingUrlsTest(map, patternOrUrl))
return map;
}
return null;
},
_removeMap: function (mode, cmd, patternOrUrl) {
let maps = this._user[mode] || [];
let names;
for (let [i, map] in Iterator(maps)) {
if (!this._matchingUrlsTest(map, patternOrUrl))
continue;
for (let [j, name] in Iterator(map.names)) {
if (name == cmd) {
map.names.splice(j, 1);
if (map.names.length == 0)
maps.splice(i, 1);
return;
}
}
}
},
_expandLeader: function (keyString) keyString.replace(/<Leader>/gi, mappings.getMapLeader()),
// Return all mappings present in all @modes
_mappingsIterator: function (modes, stack) {
modes = modes.slice();
return (map for (map of stack[modes.shift()])
if (modes.every(function (mode) stack[mode].some(
function (m) map.equals(m)))))
},
// NOTE: just normal mode for now
/** @property {Iterator(Map)} @private */
__iterator__: function () this._mappingsIterator([modes.NORMAL], this._main),
// used by :mkvimperatorrc to save mappings
/**
* Returns a user-defined mappings iterator for the specified
* <b>mode</b>.
*
* @param {number} mode The mode to return mappings from.
* @returns {Iterator(Map)}
*/
getUserIterator: function (mode) this._mappingsIterator(mode, this._user),
addMode: function (mode) {
if (!(mode in this._user || mode in this._main)) {
this._main[mode] = [];
this._user[mode] = [];
}
},
/**
* Adds a new default key mapping.
*
* @param {number[]} modes The modes that this mapping applies to.
* @param {string[]} keys The key sequences which are bound to
* <b>action</b>.
* @param {string} description A description of the key mapping.
* @param {function} action The action invoked by each key sequence.
* @param {Object} extra An optional extra configuration hash.
* @optional
* @returns {Map}
*/
add: function (modes, keys, description, action, extra) {
let map = Map(modes, keys, description, action, extra);
this._addMap(map);
return map;
},
/**
* Adds a new user-defined key mapping.
*
* @param {number[]} modes The modes that this mapping applies to.
* @param {string[]} keys The key sequences which are bound to
* <b>action</b>.
* @param {string} description A description of the key mapping.
* @param {function} action The action invoked by each key sequence.
* @param {Object} extra An optional extra configuration hash (see
* {@link Map#extraInfo}).
* @optional
* @returns {Map}
*/
addUserMap: function (modes, keys, description, action, extra) {
keys = keys.map(this._expandLeader);
extra = extra || {};
extra.user = true;
let map = Map(modes, keys, description || "User defined mapping", action, extra);
// remove all old mappings to this key sequence
for (let name of map.names) {
for (let mode of map.modes)
this._removeMap(mode, name, map.matchingUrls);
}
this._addMap(map);
return map;
},
/**
* Returns the map from <b>mode</b> named <b>cmd</b>.
*
* @param {number} mode The mode to search.
* @param {string} cmd The map name to match.
* @param {RegExp|string} URL matching pattern or URL.
* @returns {Map}
*/
get: function (mode, cmd, patternOrUrl) {
mode = mode || modes.NORMAL;
return this._getMap(mode, cmd, patternOrUrl, this._user) || this._getMap(mode, cmd, patternOrUrl, this._main);
},
/**
* Returns the default map from <b>mode</b> named <b>cmd</b>.
*
* @param {number} mode The mode to search.
* @param {string} cmd The map name to match.
* @param {RegExp|string} URL matching pattern or URL.
* @returns {Map}
*/
getDefault: function (mode, cmd, patternOrUrl) {
mode = mode || modes.NORMAL;
return this._getMap(mode, cmd, patternOrUrl, this._main);
},
/**
* Returns an array of maps with names starting with but not equal to
* <b>prefix</b>.
*
* @param {number} mode The mode to search.
* @param {string} prefix The map prefix string to match.
* @param {RegExp|string} URL matching pattern or URL.
* @returns {Map[]}
*/
getCandidates: function (mode, prefix, patternOrUrl) {
let mappings = this._user[mode].concat(this._main[mode]);
let matches = [];
for (let map of mappings) {
if (!this._matchingUrlsTest(map, patternOrUrl))
continue;
for (let name of map.names) {
if (name.startsWith(prefix) && name.length > prefix.length) {
// for < only return a candidate if it doesn't look like a <c-x> mapping
if (prefix != "<" || !/^<.+>/.test(name))
matches.push(map);
}
}
}
return matches;
},
/*
* Returns the map leader string used to replace the special token
* "<Leader>" when user mappings are defined.
*
* @returns {string}
*/
// FIXME: property
getMapLeader: function () {
let leaderRef = liberator.variableReference("mapleader");
return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\";
},
/**
* Returns whether there is a user-defined mapping <b>cmd</b> for the
* specified <b>mode</b>.
*
* @param {number} mode The mode to search.
* @param {string} cmd The candidate key mapping.
* @param {RegExp|string} URL matching pattern or URL.
* @returns {boolean}
*/
hasMap:
function (mode, cmd, patternOrUrl)
let (self = this)
this._user[mode].some(function (map) map.hasName(cmd) && self._matchingUrlsTest(map, patternOrUrl)),
/**
* Remove the user-defined mapping named <b>cmd</b> for <b>mode</b>.
*
* @param {number} mode The mode to search.
* @param {string} cmd The map name to match.
* @param {RegExp|string} URL matching pattern or URL.
*/
remove: function (mode, cmd, patternOrUrl) {
this._removeMap(mode, cmd, patternOrUrl);
},
/**
* Remove all user-defined mappings for <b>mode</b>.
*
* @param {number} mode The mode to remove all mappings from.
*/
removeAll: function (mode) {
this._user[mode] = [];
},
/**
* Lists all user-defined mappings matching <b>filter</b> for the
* specified <b>modes</b>.
*
* @param {number[]} modes An array of modes to search.
* @param {string} filter The filter string to match.
* @param {RegExp|string} URL matching pattern or URL.
*/
list: function (modes, filter, urlPattern) {
let maps = this._mappingsIterator(modes, this._user);
if (filter)
maps = [map for (map of maps) if (map.names[0] == filter)];
if (urlPattern)
maps = [map for (map of maps) if (this._matchingUrlsTest(map, urlPattern))];
// build results
let displayMaps = [];
for (map of maps) {
let modes = "";
map.modes.forEach(function (mode) {
for (let m in modules.modes.mainModes)
if (mode == m.mask)// && modeSign.indexOf(m.char) == -1)
//modeSign += (modeSign ? "" : ",") + m.name;
modes += (modes ? ", " : "") + m.name;
});
let option = xml``;
var add = function (lhs, rhs) xml`${lhs}${rhs}`;
if (map.silent)
option = add(option, xml`<span highlight="Keyword">silent</span>`);
if (map.noremap) {
if (map.silent)
option = add(option, `, `);
option = add(option, xml`<span highlight="Keyword">noremap</span>`);
}
displayMaps.push([map.names, map.rhs || "function () { ... }", modes, option, map.matchingUrls]);
}
if (displayMaps.length == 0) {
liberator.echomsg("No mapping found");
return;
}
let list = template.tabular([{ header: "Mapping", highlight: "Mapping" }, "Expression", { header: "Modes", highlight: "ModeMsg" }, "Options", "URLs"], displayMaps);
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}
}, {
}, {
commands: function () {
function addMapCommands(ch, modes, modeDescription) {
// 0 args -> list all maps
// 1 arg -> list the maps starting with args
// 2 args -> map arg1 to arg*
function map(args, modes, noremap) {
let urls = args['-urls'];
if (!args.length) {
mappings.list(modes, null, urls && RegExp(urls));
return;
}
let [lhs, rhs] = args;
if (!rhs) // list the mapping
mappings.list(modes, mappings._expandLeader(lhs), urls && RegExp(urls));
else {
// this matches Vim's behaviour
if (/^<Nop>$/i.test(rhs))
noremap = true;
mappings.addUserMap(modes, [lhs],
"User defined mapping",
function (count) { events.feedkeys((count || "") + this.rhs, this.noremap, this.silent); },
{
count: true,
rhs: events.canonicalKeys(mappings._expandLeader(rhs)),
noremap: !!noremap,
silent: "<silent>" in args,
matchingUrls: urls
});
}
}
modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";
// :map, :noremap => NORMAL + VISUAL modes
function isMultiMode(map, cmd) {
return map.modes.indexOf(modules.modes.NORMAL) >= 0
&& map.modes.indexOf(modules.modes.VISUAL) >= 0
&& /^[nv](nore)?map$/.test(cmd);
}
function regexpValidator(expr) {
try {
RegExp(expr);
return true;
}
catch (e) {}
return false;
}
function urlsCompleter (modes, current) {
return function () {
let completions = util.Array.uniq([
m.matchingUrls.source
for (m in mappings.getUserIterator(modes))
if (m.matchingUrls)
]).map(function (re) [re, re]);
if (current) {
if (buffer.URL)
completions.unshift([util.escapeRegex(buffer.URL), "Current buffer URL"]);
if (content.document && content.document.domain)
completions.unshift([util.escapeRegex(content.document.domain), "Current buffer domain"]);
}
return completions;
};
}
const opts = {
completer: function (context, args) completion.userMapping(context, args, modes),
options: [
[["<silent>", "<Silent>"], commands.OPTION_NOARG],
[["-urls", "-u"], commands.OPTION_STRING, regexpValidator, urlsCompleter(modes, true)],
],
literal: 1,
serial: function () {
function options (map) {
let opts = {};
if (map.silent)
opts["<silent>"] = null;
if (map.matchingUrls)
opts["-urls"] = map.matchingUrls.source;
return opts;
}
let noremap = this.name.indexOf("noremap") > -1;
return [
{
command: this.name,
options: options(map),
arguments: [map.names[0]],
literalArg: map.rhs
}
for (map in mappings._mappingsIterator(modes, mappings._user))
if (map.rhs && map.noremap == noremap && !isMultiMode(map, this.name))
];
}
};
commands.add([ch ? ch + "m[ap]" : "map"],
"Map a key sequence" + modeDescription,
function (args) { map(args, modes, false); },
opts);
commands.add([ch + "no[remap]"],
"Map a key sequence without remapping keys" + modeDescription,
function (args) { map(args, modes, true); },
opts);
commands.add([ch + "mapc[lear]"],
"Remove all mappings" + modeDescription,
function () { modes.forEach(function (mode) { mappings.removeAll(mode); }); },
{ argCount: "0" });
commands.add([ch + "unm[ap]"],
"Remove a mapping" + modeDescription,
function (args) {
let lhs = events.canonicalKeys(args[0]);
let urls = args["-urls"] && RegExp(args["-urls"]);
let found = false;
for (let mode of modes) {
if (mappings.hasMap(mode, lhs, urls)) {
mappings.remove(mode, lhs, urls);
found = true;
}
}
if (!found)
liberator.echoerr("No such mapping: " + lhs);
},
{
argCount: "1",
options: [
[["-urls", "-u"], commands.OPTION_STRING, regexpValidator, urlsCompleter(modes)],
],
completer: function (context, args) completion.userMapping(context, args, modes)
});
}
addMapCommands("", [modes.NORMAL, modes.VISUAL], "");
for (let mode in modes.mainModes)
if (mode.char && !commands.get(mode.char + "map"))
addMapCommands(mode.char,
[m.mask for (m in modes.mainModes) if (m.char == mode.char)],
[mode.disp.toLowerCase()]);
},
completion: function () {
JavaScript.setCompleter(this.get,
[
null,
function (context, obj, args) {
let mode = args[0];
return [
[name, map.description]
for (map of mappings._user[mode].concat(mappings._main[mode]))
for (name of map.names)];
}
]);
completion.userMapping = function userMapping(context, args, modes) {
// FIXME: have we decided on a 'standard' way to handle this clash? --djk
modes = modes || [modules.modes.NORMAL];
let urls = args["-urls"] && RegExp(args["-urls"]);
if (args.completeArg == 0) {
let maps = [
[m.names[0], ""]
for (m in mappings.getUserIterator(modes))
if (mappings._matchingUrlsTest(m, urls))
];
context.completions = maps;
}
};
},
modes: function () {
for (let mode in modes) {
this._main[mode] = [];
this._user[mode] = [];
}
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
// Do NOT create instances of this class yourself, use the helper method
// commands.add() instead
/**
* A class representing Ex commands. Instances are created by
* the {@link Command} class.
*
* @param {string[]} specs The names by which this command can be invoked.
* These are specified in the form "com[mand]" where "com" is a unique
* command name prefix.
* @param {string} description A short one line description of the command.
* @param {function} action The action invoked by this command when executed.
* @param {Object} extraInfo An optional extra configuration hash. The
* following properties are supported.
* argCount - see {@link Command#argCount}
* bang - see {@link Command#bang}
* completer - see {@link Command#completer}
* count - see {@link Command#count}
* heredoc - see {@link Command#heredoc}
* literal - see {@link Command#literal}
* options - see {@link Command#options}
* serial - see {@link Command#serial}
* privateData - see {@link Command#privateData}
* @optional
* @private
*/
const Command = Class("Command", {
requires: ["config"],
init: function (specs, description, action, extraInfo) {
specs = Array.concat(specs); // XXX
let parsedSpecs = Command.parseSpecs(specs);
if (!parsedSpecs.every(function (specs) specs.every(Command.validateName)))
throw Error("Invalid command name");
this.specs = specs;
this.shortNames = parsedSpecs.reduce(function(r,c){c[1]&&r.push(c[1]);return r;}, []);
this.longNames = parsedSpecs.map(function (n) n[0]);
this.name = this.longNames[0];
this.names = parsedSpecs.reduce(function(r,c) r.concat(c), []);
this.description = description;
this.action = action;
if (extraInfo)
update(this, extraInfo);
},
/**
* Execute this command.
*
* @param {string} args The args to be parsed and passed to
* {@link #action}.
* @param {boolean} bang Whether this command was executed with a trailing
* bang.
* @deprecated
* @param {number} count Whether this command was executed with a leading
* count.
* @deprecated
* @param {Object} modifiers Any modifiers to be passed to {@link #action}.
*/
execute: function (args, bang, count, modifiers) {
// XXX
bang = !!bang;
count = (count === undefined) ? null : count;
modifiers = modifiers || {};
let cmd = this;
function exec(args) {
// FIXME: Move to parseCommand?
args = cmd.parseArgs(args, null, { count: count, bang: bang });
if (!args)
return;
if (args.subCmd)
cmd = args.subCmd;
liberator.trapErrors(cmd.action, cmd, args, modifiers);
}
if (this.hereDoc) {
let matches = args.match(/(.*)<<\s*(\S+)$/);
if (matches && matches[2]) {
commandline.inputMultiline(RegExp("^" + matches[2] + "$", "m"),
function (args) { exec(matches[1] + "\n" + args); });
return;
}
}
exec(args);
},
/**
* Returns whether this command may be invoked via <b>name</b>.
*
* @param {string} name The candidate name.
* @returns {boolean}
*/
hasName: function (name) {
for (let spec of this.specs) {
let fullName = spec.replace(/\[(\w+)]$/, "$1");
let index = spec.indexOf("[");
let min = index == -1 ? fullName.length : index;
if (fullName.startsWith(name) && name.length >= min)
return true;
}
return false;
},
/**
* A helper function to parse an argument string.
*
* @param {string} args The argument string to parse.
* @param {CompletionContext} complete A completion context.
* Non-null when the arguments are being parsed for completion
* purposes.
* @param {Object} extra Extra keys to be spliced into the
* returned Args object.
* @returns {Args}
* @see Commands#parseArgs
*/
parseArgs: function (args, complete, extra) commands.parseArgs(args, this.options, this.subCommands, this.argCount, false, this.literal, complete, extra),
/**
* @property {string[]} All of this command's name specs. e.g., "com[mand]"
*/
specs: null,
/** @property {string[]} All of this command's short names, e.g., "com" */
shortNames: null,
/**
* @property {string[]} All of this command's long names, e.g., "command"
*/
longNames: null,
/** @property {string} The command's canonical name. */
name: null,
/** @property {string[]} All of this command's long and short names. */
names: null,
/** @property {string} This command's description, as shown in :usage */
description: "",
/**
* @property {function (Args)} The function called to execute this command.
*/
action: null,
/**
* @property {string} This command's argument count spec.
* @see Commands#parseArguments
*/
argCount: 0,
/**
* @property {function (CompletionContext, Args)} This command's completer.
* @see CompletionContext
*/
completer: null,
/** @property {boolean} Whether this command accepts a here document. */
hereDoc: false,
/**
* @property {Array} The options this command takes.
* @see Commands@parseArguments
*/
options: [],
/**
* @property {Array} The sub-commands this command takes.
*/
subCommands: [],
/**
* @property {boolean} Whether this command may be called with a bang,
* e.g., :com!
*/
bang: false,
/**
* @property {boolean} Whether this command may be called with a count,
* e.g., :12bdel
*/
count: false,
/**
* @property {boolean} At what index this command's literal arguments
* begin. For instance, with a value of 2, all arguments starting with
* the third are parsed as a single string, with all quoting characters
* passed literally. This is especially useful for commands which take
* key mappings or Ex command lines as arguments.
*/
literal: null,
/**
* @property {function} Should return an array of <b>Object</b>s suitable
* to be passed to {@link Commands#commandToString}, one for each past
* invocation which should be restored on subsequent @liberator
* startups.
*/
serial: null,
/**
* @property {boolean} When true, invocations of this command
* may contain private data which should be purged from
* saved histories when clearing private data.
*/
privateData: false,
/**
* @property {boolean} Specifies whether this is a user command. User
* commands may be created by plugins, or directly by users, and,
* unlike basic commands, may be overwritten. Users and plugin authors
* should create only user commands.
*/
user: false,
/**
* @property {string} For commands defined via :command, contains the Ex
* command line to be executed upon invocation.
*/
replacementText: null
}, {
// TODO: do we really need more than longNames as a convenience anyway?
/**
* Converts command name abbreviation specs of the form
* 'shortname[optional-tail]' to short and long versions:
* ["abc[def]", "ghijkl"] -> [["abcdef", "abc"], ["ghijlk"]]
*
* @param {Array} specs An array of command name specs to parse.
* @returns {Array}
*/
parseSpecs: function parseSpecs(specs) {
return specs.map(function (spec) {
let [, head, tail] = spec.match(/([^[]+)(?:\[(.*)])?/);
return tail ? [head + tail, head] : [head];
});
},
/**
* Validate command name
*
* @param {string} command name
* @returns {boolean}
*/
validateName: function (name) {
return /^(!|[a-zA-Z][a-zA-Z\d]*)$/.test(name);
}
});
/**
* @instance commands
*/
const ArgType = Struct("description", "parse");
const Commands = Module("commands", {
init: function () {
this._exCommands = [];
},
// FIXME: remove later, when our option handler is better
/**
* @property {number} The option argument is unspecified. Any argument
* is accepted and caller is responsible for parsing the return
* value.
* @final
*/
OPTION_ANY: 0,
/**
* @property {number} The option doesn't accept an argument.
* @final
*/
OPTION_NOARG: 1,
/**
* @property {number} The option accepts a boolean argument.
* @final
*/
OPTION_BOOL: 2,
/**
* @property {number} The option accepts a string argument.
* @final
*/
OPTION_STRING: 3,
/**
* @property {number} The option accepts an integer argument.
* @final
*/
OPTION_INT: 4,
/**
* @property {number} The option accepts a float argument.
* @final
*/
OPTION_FLOAT: 5,
/**
* @property {number} The option accepts a string list argument.
* E.g. "foo,bar"
* @final
*/
OPTION_LIST: 6,
/**
* @property Indicates that no count was specified for this
* command invocation.
* @final
*/
COUNT_NONE: null,
/**
* @property {number} Indicates that the full buffer range (1,$) was
* specified for this command invocation.
* @final
*/
// FIXME: this isn't a count at all
COUNT_ALL: -2, // :%...
/** @property {Iterator(Command)} @private */
__iterator__: function () {
let sorted = this._exCommands.sort(function (a, b) a.name > b.name);
return util.Array.itervalues(sorted);
},
/** @property {string} The last executed Ex command line. */
repeat: null,
_addCommand: function (command, replace) {
if (this._exCommands.some(function (c) c.hasName(command.name))) {
if (command.user && replace)
commands.removeUserCommand(command.name);
else {
liberator.echomsg("Command '" + command.name + "' already exists, NOT replacing existing command. Use ! to override.");
return false;
}
}
this._exCommands.push(command);
return command;
},
/**
* Adds a new default command.
*
* @param {string[]} names The names by which this command can be
* invoked. The first name specified is the command's canonical
* name.
* @param {string} description A description of the command.
* @param {function} action The action invoked by this command.
* @param {Object} extra An optional extra configuration hash.
* @optional
* @returns {Command}
*/
add: function (names, description, action, extra) {
return this._addCommand(Command(names, description, action, extra), false);
},
/**
* Adds a new user-defined command.
*
* @param {string[]} names The names by which this command can be
* invoked. The first name specified is the command's canonical
* name.
* @param {string} description A description of the command.
* @param {function} action The action invoked by this command.
* @param {Object} extra An optional extra configuration hash.
* @param {boolean} replace Overwrite an existing command with the same
* canonical name.
* @returns {Command}
*/
addUserCommand: function (names, description, action, extra, replace) {
extra = extra || {};
extra.user = true;
description = description || "User defined command";
return this._addCommand(Command(names, description, action, extra), replace);
},
/**
* Returns the specified command invocation object serialized to
* an executable Ex command string.
*
* @param {Object} args The command invocation object.
* @returns {string}
*/
commandToString: function (args) {
let res = [args.command + (args.bang ? "!" : "")];
function quote(str) Commands.quoteArg[/[\s"'\\]|^$/.test(str) ? '"' : ""](str);
for (let [opt, val] in Iterator(args.options || {})) {
let chr = /^-.$/.test(opt) ? " " : "=";
if (val != null)
opt += chr + quote(val);
res.push(opt);
}
for (let [, arg] in Iterator(args.arguments || []))
res.push(quote(arg));
let str = args.literalArg;
if (str)
res.push(/\n/.test(str) ? "<<EOF\n" + str.replace(/\n$/, "") + "\nEOF" : str);
return res.join(" ");
},
/**
* Returns the command with matching <b>name</b>.
*
* @param {string} name The name of the command to return. This can be
* any of the command's names.
* @returns {Command}
*/
get: function (name) {
return this._exCommands.filter(function (cmd) cmd.hasName(name))[0] || null;
},
/**
* Returns the user-defined command with matching <b>name</b>.
*
* @param {string} name The name of the command to return. This can be
* any of the command's names.
* @returns {Command}
*/
getUserCommand: function (name) {
return this._exCommands.filter(function (cmd) cmd.user && cmd.hasName(name))[0] || null;
},
/**
* Returns all user-defined commands.
*
* @returns {Command[]}
*/
getUserCommands: function () {
return this._exCommands.filter(function (cmd) cmd.user);
},
// TODO: should it handle comments?
// : it might be nice to be able to specify that certain quoting
// should be disabled E.g. backslash without having to resort to
// using literal etc.
// : error messages should be configurable or else we can ditch
// Vim compatibility but it actually gives useful messages
// sometimes rather than just "Invalid arg"
// : I'm not sure documenting the returned object here, and
// elsewhere, as type Args rather than simply Object makes sense,
// especially since it is further augmented for use in
// Command#action etc.
/**
* Parses <b>str</b> for options and plain arguments.
*
* The returned <b>Args</b> object is an augmented array of arguments.
* Any key/value pairs of <b>extra</b> will be available and the
* following additional properties:
* -opt - the value of the option -opt if specified
* string - the original argument string <b>str</b>
* literalArg - any trailing literal argument
*
* Quoting rules:
* '-quoted strings - only ' and \ itself are escaped
* "-quoted strings - also ", \n and \t are translated
* non-quoted strings - everything is taken literally apart from "\
* " and "\\"
*
* @param {string} str The Ex command-line string to parse. E.g.
* "-x=foo -opt=bar arg1 arg2"
* @param {Array} options The options accepted. These are specified as
* an array [names, type, validator, completions, multiple].
* names - an array of option names. The first name is the
* canonical option name.
* type - the option's value type. This is one of:
* (@link Commands#OPTION_NOARG),
* (@link Commands#OPTION_STRING),
* (@link Commands#OPTION_BOOL),
* (@link Commands#OPTION_INT),
* (@link Commands#OPTION_FLOAT),
* (@link Commands#OPTION_LIST),
* (@link Commands#OPTION_ANY)
* validator - a validator function
* completer - a list of completions, or a completion function
* multiple - whether this option can be specified multiple times
* E.g.
* options = [[["-force"], OPTION_NOARG],
* [["-fullscreen", "-f"], OPTION_BOOL],
* [["-language"], OPTION_STRING, validateFunc, ["perl", "ruby"]],
* [["-speed"], OPTION_INT],
* [["-acceleration"], OPTION_FLOAT],
* [["-accessories"], OPTION_LIST, null, ["foo", "bar"], true],
* [["-other"], OPTION_ANY]];
* @param {Array} subCommands The sub-commands accepted. These are Command instance
* see @link Command
* @param {string} argCount The number of arguments accepted.
* "0": no arguments
* "1": exactly one argument
* "+": one or more arguments
* "*": zero or more arguments (default if unspecified)
* "?": zero or one arguments
* @param {boolean} allowUnknownOptions Whether unspecified options
* should cause an error.
* @param {number} literal The index at which any literal arg begins.
* See {@link Command#literal}.
* @param {CompletionContext} complete The relevant completion context
* when the args are being parsed for completion.
* @param {Object} extra Extra keys to be spliced into the returned
* Args object.
* @returns {Args}
*/
parseArgs: function (str, options, subCommands, argCount, allowUnknownOptions, literal, complete, extra) {
function getNextArg(str) {
let [count, arg, quote] = Commands.parseArg(str);
if (quote == "\\" && !complete)
return [,,,"Trailing \\"];
if (quote && !complete)
return [,,,"Missing quote: " + quote];
return [count, arg, quote];
}
if (!options)
options = [];
if (!subCommands)
subCommands = [];
if (!argCount)
argCount = "*";
if (!extra)
extra = {};
var args = []; // parsed options
args.__iterator__ = function () util.Array.iteritems(this);
args.string = str; // for access to the unparsed string
args.literalArg = "";
var argPosition = []; // argument's starting position
// FIXME!
for (let [k, v] in Iterator(extra)) {
switch (k) {
case "count":
case "bang":
case "subCmd":
args[k] = v;
break;
case "opts":
for (let [optKey, optValue] in Iterator(v))
args[optKey] = optValue;
break;
}
}
var invalid = false;
// FIXME: best way to specify these requirements?
var onlyArgumentsRemaining = allowUnknownOptions || (options.length == 0 && subCommands.length == 0) || false; // after a -- has been found
var arg = null;
var count = 0; // the length of the argument
var i = 0;
var completeOpts;
// XXX
function matchOpts(arg) {
// Push possible option matches into completions
if (complete && !onlyArgumentsRemaining)
completeOpts = [[opt[0], opt[0][0]] for (opt of options) if (!(opt[0][0] in args))];
}
function resetCompletions() {
completeOpts = null;
args.completeArg = null;
args.completeOpt = null;
args.completeFilter = null;
args.completeStart = i;
args.quote = Commands.complQuote[""];
}
if (complete) {
resetCompletions();
matchOpts("");
args.completeArg = 0;
}
function echoerr(error) {
if (complete)
complete.message = error;
else
liberator.echoerr(error);
}
outer:
while (i < str.length || complete) {
// skip whitespace
while (/\s/.test(str[i]) && i < str.length)
i++;
if (i == str.length && !complete)
break;
if (complete)
resetCompletions();
var sub = str.substr(i);
if ((!onlyArgumentsRemaining) && /^--(\s|$)/.test(sub)) {
onlyArgumentsRemaining = true;
i += 2;
continue;
}
var optname = "";
if (!onlyArgumentsRemaining) {
for (let opt of options) {
for (let optname of opt[0]) {
if (sub.startsWith(optname)) {
invalid = false;
arg = null;
quote = null;
count = 0;
let sep = sub[optname.length];
if (sep == "=" || /\s/.test(sep) && opt[1] != this.OPTION_NOARG) {
[count, arg, quote, error] = getNextArg(sub.substr(optname.length + 1));
liberator.assert(!error, error);
// if we add the argument to an option after a space, it MUST not be empty
if (sep != "=" && !quote && arg.length == 0)
arg = null;
count++; // to compensate the "=" character
}
else if (!/\s/.test(sep) && sep != undefined) // this isn't really an option as it has trailing characters, parse it as an argument
invalid = true;
let context = null;
if (!complete && quote) {
liberator.echoerr("Invalid argument for option: " + optname);
return null;
}
if (!invalid) {
if (complete && count > 0) {
args.completeStart += optname.length + 1;
args.completeOpt = opt;
args.completeFilter = arg;
args.quote = Commands.complQuote[quote] || Commands.complQuote[""];
}
let type = Commands.argTypes[opt[1]];
if (type && (!complete || arg != null)) {
let orig = arg;
arg = type.parse(arg);
if (arg == null || (typeof arg == "number" && isNaN(arg))) {
if (!complete || orig != "" || args.completeStart != str.length)
echoerr("Invalid argument for " + type.description + " option: " + optname);
if (complete)
complete.highlight(args.completeStart, count - 1, "SPELLCHECK");
else
return null;
}
}
// we have a validator function
if (typeof opt[2] == "function") {
if (opt[2].call(this, arg) == false) {
echoerr("Invalid argument for option: " + optname);
if (complete)
complete.highlight(args.completeStart, count - 1, "SPELLCHECK");
else
return null;
}
}
// option allowed multiple times
if (!!opt[4])
args[opt[0][0]] = (args[opt[0][0]] || []).concat(arg);
else
args[opt[0][0]] = opt[1] == this.OPTION_NOARG || arg;
i += optname.length + count;
if (i == str.length)
break outer;
continue outer;
}
// if it is invalid, just fall through and try the next argument
}
}
}
}
matchOpts(sub);
if (complete) {
if (argCount == "0" || args.length > 0 && (/[1?]/.test(argCount)))
complete.highlight(i, sub.length, "SPELLCHECK");
}
if (args.length == literal) {
if (complete)
args.completeArg = args.length;
args.literalArg = sub;
args.push(sub);
args.quote = null;
argPosition.push(i);
break;
}
// if not an option, treat this token as an argument
let [count, arg, quote, error] = getNextArg(sub);
liberator.assert(!error, error);
if (complete) {
args.quote = Commands.complQuote[quote] || Commands.complQuote[""];
args.completeFilter = arg || "";
}
else if (count == -1) {
liberator.echoerr("Error parsing arguments: " + arg);
return null;
} // if /^\s*-/ is NOT TRUE, "-" be quoted.
else if (!onlyArgumentsRemaining && /^-/.test(arg) && /^\s*-/.test(sub)) {
liberator.echoerr("Invalid option: " + arg);
return null;
}
else if (!onlyArgumentsRemaining) {
let [cmdCount, cmdName, cmdBang, cmdArg] = commands.parseCommand(sub);
if (cmdName) {
for (let subCmd of subCommands) {
if (subCmd.hasName(cmdName)) {
let subExtra = {
count: cmdCount,
bang: cmdBang,
subCmd: subCmd,
opts: extra.opts || {}
};
for (let opt of options) {
if (opt[0][0] in args)
subExtra.opts[opt[0][0]] = args[opt[0][0]];
}
// delegate parsing to the sub-command
return subCmd.parseArgs(sub.substr(count), null, subExtra);
}
}
}
}
if (arg != null) {
args.push(arg);
argPosition.push(i);
}
if (complete)
args.completeArg = args.length - 1;
i += count;
if (count <= 0 || i == str.length)
break;
}
if (complete) {
if (subCommands.length && !args.completeOpt) {
complete.fork("subCmds", argPosition[0], completion, "ex", subCommands);
// don't any more if sub-command arguments are completing
if (complete.contexts[complete.name + "/subCmds/args"])
return;
}
if (args.completeOpt) {
let opt = args.completeOpt;
let context = complete.fork(opt[0][0], args.completeStart);
context.filter = args.completeFilter;
if (typeof opt[3] == "function")
var compl = opt[3](context, args);
else {
if (opt[1] === commands.OPTION_LIST) {
let [, prefix] = context.filter.match(/^(.*,)[^,]*$/) || [];
if (prefix)
context.advance(prefix.length);
}
compl = opt[3] || [];
}
context.title = [opt[0][0]];
context.quote = args.quote;
context.completions = compl;
}
complete.advance(args.completeStart);
complete.title = ["Options"];
if (completeOpts)
complete.completions = completeOpts;
}
// check for correct number of arguments
if (args.length == 0 && /^[1+]$/.test(argCount) ||
literal != null && /[1+]/.test(argCount) && !/\S/.test(args.literalArg || "")) {
if (!complete) {
liberator.echoerr("Argument required");
return null;
}
}
else if (args.length == 1 && (argCount == "0") ||
args.length > 1 && /^[01?]$/.test(argCount)) {
echoerr("Trailing characters");
return null;
}
return args;
},
/**
* Parses a complete Ex command.
*
* The parsed string is returned as an Array like
* [count, command, bang, args]:
* count - any count specified
* command - the Ex command name
* bang - whether the special "bang" version was called
* args - the commands full argument string
* E.g. ":2foo! bar" -> [2, "foo", true, "bar"]
*
* @param {string} str The Ex command line string.
* @returns {Array}
*/
// FIXME: why does this return an Array rather than Object?
parseCommand: function (str) {
// remove comments
str.replace(/\s*".*$/, "");
// 0 - count, 1 - cmd, 2 - special, 3 - args
let matches = str.match(/^[:\s]*(\d+|%)?([a-zA-Z][a-zA-Z\d]*|!)(!)?(?:\s*(.*?))?$/);
//var matches = str.match(/^:*(\d+|%)?([a-zA-Z]+|!)(!)?(?:\s*(.*?)\s*)?$/);
if (!matches)
return [null, null, null, null];
let [, count, cmd, special, args] = matches;
// parse count
if (count)
count = count == "%" ? this.COUNT_ALL : parseInt(count, 10);
else
count = this.COUNT_NONE;
return [count, cmd, !!special, args || ""];
},
/** @property */
get complQuote() Commands.complQuote,
/** @property */
get quoteArg() Commands.quoteArg, // XXX: better somewhere else?
/**
* Remove the user-defined command with matching <b>name</b>.
*
* @param {string} name The name of the command to remove. This can be
* any of the command's names.
*/
removeUserCommand: function (name) {
this._exCommands = this._exCommands.filter(function (cmd) !(cmd.user && cmd.hasName(name)));
},
// FIXME: still belong here? Also used for autocommand parameters.
/**
* Returns a string with all tokens in <b>string</b> matching "<key>"
* replaced with "value". Where "key" is a property of the specified
* <b>tokens</b> object and "value" is the corresponding value. The
* <lt> token can be used to include a literal "<" in the returned
* string. Any tokens prefixed with "q-" will be quoted except for
* <q-lt> which is treated like <lt>.
*
* @param {string} str The string with tokens to replace.
* @param {Object} tokens A map object whose keys are replaced with its
* values.
* @returns {string}
*/
replaceTokens: function replaceTokens(str, tokens) {
return str.replace(/<((?:q-)?)([a-zA-Z]+)?>/g, function (match, quote, token) {
if (token == "lt") // Don't quote, as in Vim (but, why so in Vim? You'd think people wouldn't say <q-lt> if they didn't want it)
return "<";
let res = tokens[token];
if (res == undefined) // Ignore anything undefined
res = "<" + token + ">";
if (quote && typeof res != "number")
return Commands.quoteArg['"'](res);
return res;
});
}
}, {
QUOTE_STYLE: "rc-ish",
// returns [count, parsed_argument]
parseArg: function (str) {
let arg = "";
let quote = null;
let len = str.length;
while (str.length && !/^\s/.test(str)) {
let res;
switch (Commands.QUOTE_STYLE) {
case "vim-sucks":
if (res = str.match(/^()((?:[^\\\s]|\\.)+)((?:\\$)?)/))
arg += res[2].replace(/\\(.)/g, "$1");
break;
case "vimperator":
if ((res = str.match(/^()((?:[^\\\s"']|\\.)+)((?:\\$)?)/)))
arg += res[2].replace(/\\(.)/g, "$1");
else if ((res = str.match(/^(")((?:[^\\"]|\\.)*)("?)/)))
arg += eval(res[0] + (res[3] ? "" : '"'));
else if ((res = str.match(/^(')((?:[^\\']|\\.)*)('?)/)))
arg += res[2].replace(/\\(.)/g, function (n0, n1) /[\\']/.test(n1) ? n1 : n0);
break;
case "rc-ish":
if ((res = str.match(/^()((?:[^\\\s"']|\\.)+)((?:\\$)?)/)))
arg += res[2].replace(/\\(.)/g, "$1");
else if ((res = str.match(/^(")((?:[^\\"]|\\.)*)("?)/)))
arg += eval(res[0] + (res[3] ? "" : '"'));
else if ((res = str.match(/^(')((?:[^']|'')*)('?)/)))
arg += res[2].replace("''", "'", "g");
break;
case "pythonesque":
if ((res = str.match(/^()((?:[^\\\s"']|\\.)+)((?:\\$)?)/)))
arg += res[2].replace(/\\(.)/g, "$1");
else if ((res = str.match(/^(""")((?:.?.?[^"])*)((?:""")?)/)))
arg += res[2];
else if ((res = str.match(/^(")((?:[^\\"]|\\.)*)("?)/)))
arg += eval(res[0] + (res[3] ? "" : '"'));
else if ((res = str.match(/^(')((?:[^\\']|\\.)*)('?)/)))
arg += res[2].replace(/\\(.)/g, function (n0, n1) /[\\']/.test(n1) ? n1 : n0);
break;
}
if (!res)
break;
if (!res[3])
quote = res[1];
if (!res[1])
quote = res[3];
str = str.substr(res[0].length);
}
return [len - str.length, arg, quote];
}
}, {
mappings: function () {
mappings.add(config.browserModes,
["@:"], "Repeat the last Ex command",
function (count) {
if (commands.repeat) {
for (let i in util.interruptibleRange(0, Math.max(count, 1), 100))
liberator.execute(commands.repeat);
}
else
liberator.echoerr("No previous command line");
},
{ count: true });
},
completion: function () {
JavaScript.setCompleter(this.get, [function () ([c.name, c.description] for (c in commands))]);
completion.command = function command(context, subCmds) {
context.keys = { text: "longNames", description: "description" };
if (subCmds) {
context.title = ["Sub command"];
context.completions = subCmds;
} else {
context.title = ["Command"];
context.completions = [k for (k in commands)];
}
};
// provides completions for ex commands, including their arguments
completion.ex = function ex(context, subCmds) {
// if there is no space between the command name and the cursor
// then get completions of the command name
let [count, cmd, bang, args] = commands.parseCommand(context.filter);
let [, prefix, junk] = context.filter.match(/^(:*\d*)\w*(.?)/) || [];
context.advance(prefix.length);
if (!junk) {
completion.command(context, subCmds);
return;
}
// highlight non-existent commands
let command = Commands.prototype.get.call(subCmds ? {_exCommands: subCmds} : commands, cmd);
if (!command) {
if (!subCmds)
context.highlight(0, cmd ? cmd.length : context.filter.length, "SPELLCHECK");
return;
}
// dynamically get completions as specified with the command's completer function
[prefix] = context.filter.match(/^(?:\w*[\s!]|!)\s*/);
let cmdContext = context.fork(cmd, prefix.length);
let argContext = context.fork("args", prefix.length);
args = command.parseArgs(cmdContext.filter, argContext, { count: count, bang: bang });
if (args) {
// FIXME: Move to parseCommand
args.count = count;
args.bang = bang;
if (!args.completeOpt && command.completer) {
cmdContext.advance(args.completeStart);
cmdContext.quote = args.quote;
cmdContext.filter = args.completeFilter;
try {
let compObject = command.completer.call(command, cmdContext, args);
if (compObject instanceof Array) // for now at least, let completion functions return arrays instead of objects
compObject = { start: compObject[0], items: compObject[1] };
if (compObject != null) {
cmdContext.advance(compObject.start);
cmdContext.filterFunc = null;
cmdContext.completions = compObject.items;
}
}
catch (e) {
liberator.echoerr(e);
}
}
}
};
completion.userCommand = function userCommand(context) {
context.title = ["User Command", "Definition"];
context.completions = [
[command.name, command.replacementText || "function () { ... }"]
for (command of commands.getUserCommands())
];
};
},
commands: function () {
function userCommand(args, modifiers) {
let tokens = {
args: this.argCount && args.string,
bang: this.bang && args.bang ? "!" : "",
count: this.count && args.count
};
liberator.execute(commands.replaceTokens(this.replacementText, tokens));
}
// TODO: offer completion.ex?
// : make this config specific
var completeOptionMap = {
abbreviation: "abbreviation", altstyle: "alternateStyleSheet",
bookmark: "bookmark", buffer: "buffer", color: "colorScheme",
command: "command", dialog: "dialog", dir: "directory",
environment: "environment", event: "autocmdEvent", file: "file",
help: "help", highlight: "highlightGroup", history: "history",
javascript: "javascript", macro: "macro", mapping: "userMapping",
menu: "menuItem", option: "option", preference: "preference",
search: "search", shellcmd: "shellCommand", sidebar: "sidebar",
url: "url", usercommand: "userCommand"
};
// TODO: Vim allows commands to be defined without {rep} if there are {attr}s
// specified - useful?
commands.add(["com[mand]"],
"List and define commands",
function (args) {
let cmd = args[0];
liberator.assert(Command.validateName(cmd), "Invalid command name: " + cmd);
if (args.literalArg) {
let nargsOpt = args["-nargs"] || "0";
let bangOpt = "-bang" in args;
let countOpt = "-count" in args;
let descriptionOpt = args["-description"] || "User-defined command";
let completeOpt = args["-complete"];
let completeFunc = null; // default to no completion for user commands
if (completeOpt) {
if (/^custom,/.test(completeOpt)) {
completeOpt = completeOpt.substr(7);
completeFunc = function () {
try {
var completer = liberator.eval(completeOpt);
if (!(completer instanceof Function))
throw new TypeError("User-defined custom completer " + completeOpt.quote() + " is not a function");
}
catch (e) {
liberator.echoerr("Unknown function: " + completeOpt);
return undefined;
}
return completer.apply(this, Array.slice(arguments));
};
}
else
completeFunc = function (context) completion[completeOptionMap[completeOpt]](context);
}
let added = commands.addUserCommand([cmd],
descriptionOpt,
userCommand, {
argCount: nargsOpt,
bang: bangOpt,
count: countOpt,
completer: completeFunc,
replacementText: args.literalArg
}, args.bang);
if (!added)
liberator.echoerr("Command '" + cmd + "' already exists: Add ! to replace it");
}
else {
function completerToString(completer) {
if (completer)
return [k for ([k, v] in Iterator(completeOptionMap)) if (completer == completion[v])][0] || "custom";
else
return "";
}
// TODO: using an array comprehension here generates flakey results across repeated calls
// : perhaps we shouldn't allow options in a list call but just ignore them for now
// : No, array comprehensions are fine, generator statements aren't. --Kris
let cmds = commands._exCommands.filter(function (c) c.user && (!cmd || c.name.match("^" + cmd)));
if (cmds.length > 0) {
let str = template.tabular(["", "Name", "Args", "Range", "Complete", "Definition"],
([cmd.bang ? "!" : " ",
cmd.name,
cmd.argCount,
cmd.count ? "0c" : "",
completerToString(cmd.completer),
cmd.replacementText || "function () { ... }"]
for ([, cmd] in Iterator(cmds))));
commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}
else
liberator.echomsg("No user-defined commands found");
}
}, {
bang: true,
completer: function (context, args) {
if (args.completeArg == 0)
completion.userCommand(context);
else
completion.ex(context);
},
options: [
[["-nargs"], commands.OPTION_STRING,
function (arg) /^[01*?+]$/.test(arg),
[["0", "No arguments are allowed (default)"],
["1", "One argument is allowed"],
["*", "Zero or more arguments are allowed"],
["?", "Zero or one argument is allowed"],
["+", "One or more arguments is allowed"]]],
[["-bang"], commands.OPTION_NOARG],
[["-count"], commands.OPTION_NOARG],
[["-description"], commands.OPTION_STRING],
[["-complete"], commands.OPTION_STRING,
function (arg) arg in completeOptionMap || /custom,\w+/.test(arg),
function (context) [[k, ""] for ([k, v] in Iterator(completeOptionMap))]]
],
literal: 1,
serial: function () [ {
command: this.name,
bang: true,
options: util.Array.toObject(
[[v, typeof cmd[k] == "boolean" ? null : cmd[k]]
// FIXME: this map is expressed multiple times
for ([k, v] in Iterator({ argCount: "-nargs", bang: "-bang", count: "-count", description: "-description" }))
// FIXME: add support for default values to parseArgs
if (k in cmd && cmd[k] != "0" && cmd[k] != "User-defined command")]),
arguments: [cmd.name],
literalArg: cmd.replacementText
}
for ([k, cmd] in Iterator(commands._exCommands))
if (cmd.user && cmd.replacementText)
]
});
commands.add(["comc[lear]"],
"Delete all user-defined commands",
function () {
commands.getUserCommands().forEach(function (cmd) { commands.removeUserCommand(cmd.name); });
},
{ argCount: "0" });
commands.add(["delc[ommand]"],
"Delete the specified user-defined command",
function (args) {
let name = args[0];
if (commands.get(name))
commands.removeUserCommand(name);
else
liberator.echoerr("No such user-defined command: " + name);
}, {
argCount: "1",
completer: function (context) completion.userCommand(context)
});
}
});
(function () {
Commands.quoteMap = {
"\n": "n",
"\t": "t"
};
function quote(q, list) {
let re = RegExp("[" + list + "]", "g");
return function (str) q + String.replace(str, re, function ($0) $0 in Commands.quoteMap ? Commands.quoteMap[$0] : ("\\" + $0)) + q;
};
function vimSingleQuote(s)
s.replace(/'/g, "''");
Commands.complQuote = { // FIXME
'"': ['"', quote("", '\n\t"\\\\'), '"'],
"'": ["'", vimSingleQuote, "'"],
"": ["", quote("", "\\\\'\" "), ""]
};
Commands.quoteArg = {
'"': quote('"', '\n\t"\\\\'),
"'": vimSingleQuote,
"": quote("", "\\\\'\" ")
};
Commands.parseBool = function (arg) {
if (/^(true|1|on)$/i.test(arg))
return true;
if (/^(false|0|off)$/i.test(arg))
return false;
return NaN;
};
Commands.argTypes = [
null,
ArgType("no arg", function (arg) !arg || null),
ArgType("boolean", Commands.parseBool),
ArgType("string", function (val) val),
ArgType("int", parseInt),
ArgType("float", parseFloat),
ArgType("list", function (arg) arg && arg.split(/\s*,\s*/))
];
})();
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2009 by Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
function array(obj) {
if (isgenerator(obj))
obj = [k for (k in obj)];
else if (obj.length)
obj = Array.slice(obj);
return util.Array(obj);
}
function allkeys(obj) {
for(; obj; obj = obj.__proto__)
for (let prop of Object.getOwnPropertyNames(obj))
yield prop;
}
function keys(obj) {
for (let prop of Object.getOwnPropertyNames(obj))
yield prop;
}
function values(obj) {
for (var k of Object.keys(obj))
yield obj[k];
}
function foreach(iter, fn, self) {
for (let val in iter)
fn.call(self, val);
}
function dict(ary) {
var obj = {};
for (var i = 0; i < ary.length; i++) {
var val = ary[i];
obj[val[0]] = val[1];
}
return obj;
}
function iter(obj) {
if (obj instanceof Ci.nsISimpleEnumerator)
return (function () {
while (obj.hasMoreElements())
yield obj.getNext();
})();
if (isinstance(obj, [Ci.nsIStringEnumerator, Ci.nsIUTF8StringEnumerator]))
return (function () {
while (obj.hasMore())
yield obj.getNext();
})();
if (isinstance(obj, Ci.nsIDOMNodeIterator))
return (function () {
try {
while (true)
yield obj.nextNode();
}
catch (e) {}
})();
if (isinstance(obj, [HTMLCollection, NodeList]))
return (node for (node of obj));
if ((typeof NamedNodeMap !== "undefined" && obj instanceof NamedNodeMap) ||
(typeof MozNamedAttrMap !== "undefined" && obj instanceof MozNamedAttrMap))
return (function () {
for (let i = 0, len = obj.length; i < len; ++i)
yield [obj[i].name, obj[i]];
})();
return Iterator(obj);
}
function issubclass(targ, src) {
return src === targ ||
targ && typeof targ === "function" && targ.prototype instanceof src;
}
function isinstance(targ, src) {
const types = {
boolean: Boolean,
string: String,
function: Function,
number: Number
}
src = Array.concat(src);
for (var i = 0; i < src.length; i++) {
if (targ instanceof src[i])
return true;
var type = types[typeof targ];
if (type && issubclass(src[i], type))
return true;
}
return false;
}
function isobject(obj) {
return typeof obj === "object" && obj != null;
}
/**
* Returns true if and only if its sole argument is an
* instance of the builtin Array type. The array may come from
* any window, frame, namespace, or execution context, which
* is not the case when using (obj instanceof Array).
*/
function isarray(val) {
return Object.prototype.toString.call(val) == "[object Array]";
}
/**
* Returns true if and only if its sole argument is an
* instance of the builtin Generator type. This includes
* functions containing the 'yield' statement and generator
* statements such as (x for (x in obj)).
*/
function isgenerator(val) {
return Object.prototype.toString.call(val) == "[object Generator]";
}
/**
* Returns true if and only if its sole argument is a String,
* as defined by the builtin type. May be constructed via
* String(foo) or new String(foo) from any window, frame,
* namespace, or execution context, which is not the case when
* using (obj instanceof String) or (typeof obj == "string").
*/
function isstring(val) {
return Object.prototype.toString.call(val) == "[object String]";
}
/**
* Returns true if and only if its sole argument may be called
* as a function. This includes classes and function objects.
*/
function callable(val) {
return typeof val === "function";
}
function call(fn, context, ...args) {
fn.apply(context, args);
return fn;
}
/**
* Curries a function to the given number of arguments. Each
* call of the resulting function returns a new function. When
* a call does not contain enough arguments to satisfy the
* required number, the resulting function is another curried
* function with previous arguments accumulated.
*
* function foo(a, b, c) [a, b, c].join(" ");
* curry(foo)(1, 2, 3) -> "1 2 3";
* curry(foo)(4)(5, 6) -> "4 5 6";
* curry(foo)(7)(8)(9) -> "7 8 9";
*
* @param {function} fn The function to curry.
* @param {integer} length The number of arguments expected.
* @default fn.length
* @optional
* @param {object} self The 'this' value for the returned function. When
* omitted, the value of 'this' from the first call to the function is
* preserved.
* @optional
*/
function curry(fn, length, self, acc) {
if (length == null)
length = fn.length;
if (length == 0)
return fn;
// Close over function with 'this'
function close(self, fn) function () fn.apply(self, Array.slice(arguments));
if (acc == null)
acc = [];
return function () {
let args = acc.concat(Array.slice(arguments));
// The curried result should preserve 'this'
if (arguments.length == 0)
return close(self || this, arguments.callee);
if (args.length >= length)
return fn.apply(self || this, args);
return curry(fn, length, self || this, args);
};
}
/**
* Updates an object with the properties of another object. Getters
* and setters are copied as expected. Moreover, any function
* properties receive new 'supercall' and 'superapply' properties,
* which will call the identically named function in target's
* prototype.
*
* let a = { foo: function (arg) "bar " + arg }
* let b = { __proto__: a }
* update(b, { foo: function () arguments.callee.supercall(this, "baz") });
*
* a.foo("foo") -> "bar foo"
* b.foo() -> "bar baz"
*
* @param {Object} target The object to update.
* @param {Object} src The source object from which to update target.
* May be provided multiple times.
* @returns {Object} Returns its updated first argument.
*/
function update(target, ...sources) {
for (let src of sources) {
if (!src)
continue;
foreach(keys(src), function (k) {
let desc = Object.getOwnPropertyDescriptor(src, k);
Object.defineProperty(target, k, desc);
if (("value" in desc) && callable(desc.value)) {
let v = desc.value,
proto = Object.getPrototypeOf(target);
if (proto && (k in proto) && callable(proto[k])) {
v.superapply = function superapply(self, args) {
return proto[k].apply(self, args);
};
v.supercall = function supercall(self, ...args) {
return v.superapply(self, args);
};
} else
v.superapply = v.supercall = function dummy() {};
}
});
}
return target;
}
/**
* Extends a subclass with a superclass. The subclass's
* prototype is replaced with a new object, which inherits
* from the superclass's prototype, {@see update}d with the
* members of 'overrides'.
*
* @param {function} subclass
* @param {function} superclass
* @param {Object} overrides @optional
*/
function extend(subclass, superclass, overrides) {
subclass.prototype = {};
update(subclass.prototype, overrides);
// This is unduly expensive. Unfortunately necessary since
// we apparently can't rely on the presence of the
// debugger to enumerate properties when we have
// __iterators__ attached to prototypes.
subclass.prototype.__proto__ = superclass.prototype;
subclass.superclass = superclass.prototype;
subclass.prototype.constructor = subclass;
subclass.prototype.__class__ = subclass;
if (superclass.prototype.constructor === Object.prototype.constructor)
superclass.prototype.constructor = superclass;
}
/**
* @constructor Class
*
* Constructs a new Class. Arguments marked as optional must be
* either entirely elided, or they must have the exact type
* specified.
*
* @param {string} name The class's as it will appear when toString
* is called, as well as in stack traces.
* @optional
* @param {function} base The base class for this module. May be any
* callable object.
* @optional
* @default Class
* @param {Object} prototype The prototype for instances of this
* object. The object itself is copied and not used as a prototype
* directly.
* @param {Object} classProperties The class properties for the new
* module constructor. More than one may be provided.
* @optional
*
* @returns {function} The constructor for the resulting class.
*/
function Class() {
function constructor() {
let self = {
__proto__: Constructor.prototype,
constructor: Constructor,
get closure() {
delete this.closure;
function closure(fn) function () fn.apply(self, arguments);
for (let k in this)
if (!this.__lookupGetter__(k) && callable(this[k]))
closure[k] = closure(self[k]);
return this.closure = closure;
}
};
var res = self.init.apply(self, arguments);
return res !== undefined ? res : self;
}
var args = Array.slice(arguments);
if (isstring(args[0]))
var name = args.shift();
var superclass = Class;
if (callable(args[0]))
superclass = args.shift();
var Constructor = eval("(function " + (name || superclass.name).replace(/\W/g, "_") +
String.substr(constructor, 20) + ")");
Constructor.__proto__ = superclass;
if (!("init" in superclass.prototype) && !("init" in args[0])) {
var superc = superclass;
superclass = function Shim() {};
extend(superclass, superc, {
init: superc
});
}
extend(Constructor, superclass, args[0]);
update(Constructor, args[1]);
args = args.slice(2);
Array.forEach(args, function (obj) {
if (callable(obj))
obj = obj.prototype;
update(Constructor.prototype, obj);
});
return Constructor;
}
Class.toString = function () "[class " + this.constructor.name + "]",
Class.prototype = {
/**
* Initializes new instances of this class. Called automatically
* when new instances are created.
*/
init: function () {},
toString: function () "[instance " + this.constructor.name + "]",
/**
* Exactly like {@see nsIDOMWindow#setTimeout}, except that it
* preserves the value of 'this' on invocation of 'callback'.
*
* @param {function} callback The function to call after 'timeout'
* @param {number} timeout The timeout, in seconds, to wait
* before calling 'callback'.
* @returns {integer} The ID of this timeout, to be passed to
* {@see nsIDOMWindow#clearTimeout}.
*/
setTimeout: function (callback, timeout) {
const self = this;
function target() callback.call(self);
return window.setTimeout(target, timeout);
}
};
/**
* @class Struct
*
* Creates a new Struct constructor, used for creating objects with
* a fixed set of named members. Each argument should be the name of
* a member in the resulting objects. These names will correspond to
* the arguments passed to the resultant constructor. Instances of
* the new struct may be treated very much like arrays, and provide
* many of the same methods.
*
* const Point = Struct("x", "y", "z");
* let p1 = Point(x, y, z);
*
* @returns {function} The constructor for the new Struct.
*/
function Struct(...args) {
const Struct = Class("Struct", StructBase, {
length: args.length,
members: args
});
args.forEach(function (name, i) {
Object.defineProperty(Struct.prototype, name, {
get: function () this[i],
set: function (val) { this[i] = val },
enumerable: true,
});
});
return Struct;
}
const StructBase = Class("StructBase", {
init: function (...args) {
for (var i = 0, len = args.length; i < len; ++i)
if (args[i] != null)
this[i] = args[i];
},
clone: function clone() this.constructor.apply(null, this.slice()),
// Iterator over our named members
__iterator__: function () {
let self = this;
return ([k, self[i]] for ([i, k] in Iterator(self.members)))
}
}, {
/**
* Sets a lazily constructed default value for a member of
* the struct. The value is constructed once, the first time
* it is accessed and memoized thereafter.
*
* @param {string} key The name of the member for which to
* provide the default value.
* @param {function} val The function which is to generate
* the default value.
*/
defaultValue: function (key, val) {
let proto = this.prototype;
let i = proto.members.indexOf(key);
if (i === -1)
return;
Object.defineProperty(this.prototype, i, {
get: function () {
if (this === proto)
return;
var value = val.call(this);
Object.defineProperty(this, i, {
value: value,
writable: true
});
return value;
},
set: function (value) {
if (this === proto)
return;
Object.defineProperty(this, i, {
value: value,
writable: true,
})
},
});
}
});
// Add no-sideeffect array methods. Can't set new Array() as the prototype or
// get length() won't work.
for (let k in values(["concat", "every", "filter", "forEach", "indexOf", "join", "lastIndexOf",
"map", "reduce", "reduceRight", "reverse", "slice", "some", "sort"]))
StructBase.prototype[k] = Array.prototype[k];
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
Cu.import("resource://gre/modules/XPCOMUtils.jsm", modules);
Cu.import("resource://gre/modules/AddonManager.jsm")
const plugins = { __proto__: modules };
const userContext = { __proto__: modules };
const EVAL_ERROR = "__liberator_eval_error";
const EVAL_RESULT = "__liberator_eval_result";
const EVAL_STRING = "__liberator_eval_string";
// Move elsewhere?
const Storage = Module("storage", {
requires: ["services"],
init: function () {
Cu.import("resource://liberator/storage.jsm", this);
modules.Timer = this.Timer; // Fix me, please.
try {
let infoPath = services.create("file");
infoPath.initWithPath(File.expandPath(IO.runtimePath.replace(/,.*/, "")));
infoPath.append("info");
infoPath.append(liberator.profileName);
this.storage.infoPath = infoPath;
}
catch (e) {}
return this.storage;
}
});
function Runnable(self, func, args) {
return {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIRunnable]),
run: function () { func.apply(self, args); }
};
}
const FailedAssertion = Class("FailedAssertion", Error, {
init: function (message) {
this.message = message;
}
});
const Liberator = Module("liberator", {
requires: ["config", "services"],
init: function () {
window.liberator = this;
this.observers = {};
this.modules = modules;
// NOTE: services.get("profile").selectedProfile.name doesn't return
// what you might expect. It returns the last _actively_ selected
// profile (i.e. via the Profile Manager or -P option) rather than the
// current profile. These will differ if the current process was run
// without explicitly selecting a profile.
/** @property {string} The name of the current user profile. */
this.profileName = services.get("dirsvc").get("ProfD", Ci.nsIFile).leafName.replace(/^.+?\./, "");
let platform = Liberator.getPlatformFeature()
config.features.add(platform);
if (/^Win(32|64)$/.test(platform))
config.features.add('Windows');
if (AddonManager) {
let self = this;
self._extensions = [];
AddonManager.getAddonsByTypes(["extension"], function (e) self._extensions = e);
this.onEnabled = this.onEnabling = this.onDisabled = this.onDisabling = this.onInstalled =
this.onInstalling = this.onUninstalled = this.onUninstalling =
function () AddonManager.getAddonsByTypes(["extension"], function (e) self._extensions = e);
AddonManager.addAddonListener(this);
}
},
destroy: function () {
autocommands.trigger(config.name + "LeavePre", {});
storage.saveAll();
liberator.triggerObserver("shutdown", null);
liberator.log("All liberator modules destroyed");
autocommands.trigger(config.name + "Leave", {});
},
/**
* @property {number} The current main mode.
* @see modes#mainModes
*/
get mode() modes.main,
set mode(value) modes.main = value,
get menuItems() Liberator.getMenuItems(),
/** @property {Element} The currently focused element. */
get focus() document.commandDispatcher.focusedElement,
// TODO: Do away with this getter when support for 1.9.x is dropped
get extensions() {
return this._extensions.map(function (e) ({
id: e.id,
name: e.name,
description: e.description,
enabled: e.isActive,
icon: e.iconURL,
options: e.optionsURL,
version: e.version,
original: e
}));
},
getExtension: function (name) this.extensions.filter(function (e) e.name == name)[0],
// Global constants
CURRENT_TAB: [],
NEW_TAB: [],
NEW_BACKGROUND_TAB: [],
NEW_WINDOW: [],
NEW_PRIVATE_WINDOW: [],
forceNewTab: false,
forceNewWindow: false,
forceNewPrivateWindow: false,
/** @property {string} The Liberator version string. */
version: "###VERSION### (created: ###DATE###)", // these VERSION and DATE tokens are replaced by the Makefile
/**
* @property {Object} The map of command-line options. These are
* specified in the argument to the host application's -{config.name}
* option. E.g. $ firefox -vimperator '+u=/tmp/rcfile ++noplugin'
* Supported options:
* +u=RCFILE Use RCFILE instead of .vimperatorrc.
* ++noplugin Don't load plugins.
*/
commandLineOptions: {
/** @property Whether plugin loading should be prevented. */
noPlugins: false,
/** @property An RC file to use rather than the default. */
rcFile: null,
/** @property An Ex command to run before any initialization is performed. */
preCommands: null,
/** @property An Ex command to run after all initialization has been performed. */
postCommands: null
},
registerObserver: function (type, callback) {
if (!(type in this.observers))
this.observers[type] = [];
this.observers[type].push(callback);
},
unregisterObserver: function (type, callback) {
if (type in this.observers)
this.observers[type] = this.observers[type].filter(function (c) c != callback);
},
// TODO: "zoom": if the zoom value of the current buffer changed
triggerObserver: function (type) {
let args = Array.slice(arguments, 1);
for (let func of this.observers[type] || [])
func.apply(null, args);
},
/**
* Triggers the application bell to notify the user of an error. The
* bell may be either audible or visual depending on the value of the
* 'visualbell' option.
*/
beep: function () {
// FIXME: popups clear the command line
if (options["visualbell"]) {
// flash the visual bell
let popup = document.getElementById("liberator-visualbell");
let win = config.visualbellWindow;
let rect = win.getBoundingClientRect();
let width = rect.right - rect.left;
let height = rect.bottom - rect.top;
// NOTE: this doesn't seem to work in FF3 with full box dimensions
popup.openPopup(win, "overlap", 1, 1, false, false);
popup.sizeTo(width - 2, height - 2);
setTimeout(function () { popup.hidePopup(); }, 20);
}
else {
let soundService = Cc["@mozilla.org/sound;1"].getService(Ci.nsISound);
soundService.beep();
}
return false; // so you can do: if (...) return liberator.beep();
},
/**
* Creates a new thread.
*/
newThread: function () services.get("threadManager").newThread(0),
/**
* Calls a function asynchronously on a new thread.
*
* @param {nsIThread} thread The thread to call the function on. If no
* thread is specified a new one is created.
* @optional
* @param {Object} self The 'this' object used when executing the
* function.
* @param {function} func The function to execute.
*
*/
callAsync: function (thread, self, func) {
thread = thread || services.get("threadManager").newThread(0);
thread.dispatch(Runnable(self, func, Array.slice(arguments, 3)), thread.DISPATCH_NORMAL);
},
/**
* Calls a function synchronously on a new thread.
*
* NOTE: Be sure to call GUI related methods like alert() or dump()
* ONLY in the main thread.
*
* @param {nsIThread} thread The thread to call the function on. If no
* thread is specified a new one is created.
* @optional
* @param {function} func The function to execute.
*/
callFunctionInThread: function (thread, func) {
thread = thread || services.get("threadManager").newThread(0);
// DISPATCH_SYNC is necessary, otherwise strange things will happen
thread.dispatch(Runnable(null, func, Array.slice(arguments, 2)), thread.DISPATCH_SYNC);
},
/**
* Prints a message to the console. If <b>msg</b> is an object it is
* pretty printed.
*
* NOTE: the "browser.dom.window.dump.enabled" preference needs to be
* set.
*
* @param {string|Object} msg The message to print.
*/
dump: function () {
let msg = Array.map(arguments, function (msg) {
if (typeof msg == "object")
msg = util.objectToString(msg);
return msg;
}).join(", ");
msg = String.replace(msg, /\n?$/, "\n");
window.dump(msg.replace(/^./gm, ("config" in modules && config.name.toLowerCase()) + ": $&"));
},
/**
* Outputs a plain message to the command line.
*
* @param {string} str The message to output.
* @param {number} flags These control the multiline message behaviour.
* See {@link CommandLine#echo}.
*/
echo: function (str, flags) {
commandline.echo(str, commandline.HL_NORMAL, flags);
},
/**
* Outputs an error message to the command line.
*
* @param {string|Error} str The message to output.
* @param {number} flags These control the multiline message behavior.
* See {@link CommandLine#echo}.
* @param {string} prefix The prefix of error message.
*/
echoerr: function (str, flags, prefix) {
try {
flags |= commandline.APPEND_TO_MESSAGES | commandline.DISALLOW_MULTILINE | commandline.FORCE_SINGLELINE;
if (typeof str == "object" && "echoerr" in str)
str = str.echoerr;
if (options["errorbells"])
liberator.beep();
commandline.echo((prefix || "") + str, commandline.HL_ERRORMSG, flags);
// For errors, also print the stack trace to our :messages list
if (str instanceof Error) {
let stackTrace = xml``;
let stackItems = new Error().stack.split('\n');
// ignore the first element intenationally!
stackTrace = template.map2(xml, stackItems.slice(1), function (stackItema) {
let atIndex = stackItem.lastIndexOf("@");
if (n === 0 || atIndex < 0)
return "";
let stackLocation = stackItem.substring(atIndex + 1);
let stackArguments = stackItem.substring(0, atIndex);
if (stackArguments)
stackArguments = " - " + stackArguments;
return xml`<span style="font-weight: normal">  xxx at </span>${stackLocation}<span style="font-weight: normal">${stackArguments}</span><br/>`;
});
commandline.messages.add({str: stackTrace, highlight: commandline.HL_ERRORMSG});
}
} catch (e) {
// if for some reason, echoerr fails, log this information at least to
// the console!
liberator.dump(str);
}
},
/**
* Outputs an information message to the command line.
*
* @param {string} str The message to output.
* @param {number} flags These control the multiline message behavior.
* See {@link CommandLine#echo}.
*/
echomsg: function (str, flags) {
flags |= commandline.APPEND_TO_MESSAGES | commandline.DISALLOW_MULTILINE | commandline.FORCE_SINGLELINE;
commandline.echo(str, commandline.HL_INFOMSG, flags);
},
/**
* Loads and executes the script referenced by <b>uri</b> in the scope
* of the <b>context</b> object.
*
* @param {string} uri The URI of the script to load. Should be a local
* chrome:, file:, or resource: URL.
* @param {Object} context The context object into which the script
* should be loaded.
*/
loadScript: function (uri, context) {
if (options.expandtemplate) {
var prefix = "liberator://template/";
if (uri.lastIndexOf(prefix, 0) === -1)
uri = prefix + uri;
}
services.get("scriptloader").loadSubScript(uri, context, "UTF-8");
},
eval: function (str, context) {
try {
if (!context)
context = userContext;
if (options.expandtemplate) {
var obj = new Object;
Cu.import("resource://liberator/template.js", obj);
str = obj.convert(str);
}
context[EVAL_ERROR] = null;
context[EVAL_STRING] = str;
context[EVAL_RESULT] = null;
this.loadScript("chrome://liberator/content/eval.js", context);
if (context[EVAL_ERROR]) {
try {
context[EVAL_ERROR].fileName = io.sourcing.file;
context[EVAL_ERROR].lineNumber += io.sourcing.line;
}
catch (e) {}
throw context[EVAL_ERROR];
}
return context[EVAL_RESULT];
}
finally {
delete context[EVAL_ERROR];
delete context[EVAL_RESULT];
delete context[EVAL_STRING];
}
},
// partial sixth level expression evaluation
// TODO: what is that really needed for, and where could it be used?
// Or should it be removed? (c) Viktor
// Better name? See other liberator.eval()
// I agree, the name is confusing, and so is the
// description --Kris
evalExpression: function (string) {
string = string.toString().trim();
let matches = null;
// String
if ((matches = string.match(/^(['"])([^\1]*?[^\\]?)\1/))) {
return matches[2].toString();
}
// Number
else if ((matches = string.match(/^(\d+)$/)))
return parseInt(matches[1], 10);
let reference = this.variableReference(string);
if (!reference[0])
this.echoerr("Undefined variable: " + string);
else
return reference[0][reference[1]];
return null;
},
/**
* Execute an Ex command string. E.g. ":zoom 300".
*
* @param {string} str The command to execute.
* @param {Object} modifiers Any modifiers to be passed to
* {@link Command#action}.
* @param {boolean} silent Whether the command should be echoed on the
* command line.
*/
execute: function (str, modifiers, silent) {
// skip comments and blank lines
if (/^\s*("|$)/.test(str))
return;
modifiers = modifiers || {};
let err = null;
let [count, cmd, special, args] = commands.parseCommand(str.replace(/^'(.*)'$/, "$1"));
let command = commands.get(cmd);
if (command === null) {
err = "Not a " + config.name.toLowerCase() + " command: " + str;
liberator.focusContent();
}
else if (command.action === null)
err = "Internal error: command.action === null"; // TODO: need to perform this test? -- djk
else if (count != null && !command.count)
err = "No range allowed";
else if (special && !command.bang)
err = "No ! allowed";
liberator.assert(!err, err);
if (!silent)
commandline.command = str.replace(/^\s*:\s*/, "");
command.execute(args, special, count, modifiers);
},
/**
* Focuses the content window.
*
* @param {boolean} clearFocusedElement Remove focus from any focused
* element.
*/
focusContent: function (clearFocusedElement) {
if (window != services.get("ww").activeWindow)
return;
let elem = config.mainWidget || window.content;
// TODO: make more generic
try {
if (this.has("tabs")) {
// select top most frame in a frameset
let frame = buffer.localStore.focusedFrame;
if (frame && frame.top == window.content)
elem = frame;
}
}
catch (e) {}
if (clearFocusedElement && liberator.focus)
liberator.focus.blur();
if (elem && elem != liberator.focus)
elem.focus();
},
/**
* Returns whether this Liberator extension supports <b>feature</b>.
*
* @param {string} feature The feature name.
* @returns {boolean}
*/
has: function (feature) config.features.has(feature),
/**
* Returns whether the host application has the specified extension
* installed.
*
* @param {string} name The extension name.
* @returns {boolean}
*/
hasExtension: function (name) {
return this._extensions.some(function (e) e.name == name);
},
/**
* Returns the URL of the specified help <b>topic</b> if it exists.
*
* @param {string} topic The help topic to lookup.
* @param {boolean} unchunked Whether to search the unchunked help page.
* @returns {string}
*/
findHelp: function (topic, unchunked) {
if (topic in services.get("liberator:").FILE_MAP)
return topic;
unchunked = !!unchunked;
let items = completion._runCompleter("help", topic, null, unchunked).items;
let partialMatch = null;
function format(item) item.description + "#" + encodeURIComponent(item.text);
for (let item of items) {
if (item.text == topic)
return format(item);
else if (!partialMatch && topic)
partialMatch = item;
}
if (partialMatch)
return format(partialMatch);
return null;
},
/**
* @private
* Initialize the help system.
*/
initHelp: function () {
let namespaces = [config.name.toLowerCase(), "liberator"];
services.get("liberator:").init({});
let tagMap = services.get("liberator:").HELP_TAGS;
let fileMap = services.get("liberator:").FILE_MAP;
let overlayMap = services.get("liberator:").OVERLAY_MAP;
// Left as an XPCOM instantiation so it can easilly be moved
// into XPCOM code.
function XSLTProcessor(sheet) {
let xslt = Cc["@mozilla.org/document-transformer;1?type=xslt"].createInstance(Ci.nsIXSLTProcessor);
xslt.importStylesheet(util.httpGet(sheet).responseXML);
return xslt;
}
// Find help and overlay files with the given name.
function findHelpFile(file) {
let result = [];
for (let namespace of namespaces) {
let url = ["chrome://", namespace, "/locale/", file, ".xml"].join("");
let res = util.httpGet(url);
if (res) {
if (res.responseXML.documentElement.localName == "document")
fileMap[file] = url;
if (res.responseXML.documentElement.localName == "overlay")
overlayMap[file] = url;
result.push(res.responseXML);
}
}
return result;
}
// Find the tags in the document.
function addTags(file, doc) {
doc = XSLT.transformToDocument(doc);
for (let elem in util.evaluateXPath("//xhtml:a/@id", doc))
tagMap[elem.value] = file;
}
const XSLT = XSLTProcessor("chrome://liberator/content/help-single.xsl");
// Scrape the list of help files from all.xml
// Always process main and overlay files, since XSLTProcessor and
// XMLHttpRequest don't allow access to chrome documents.
tagMap.all = "all";
let files = findHelpFile("all").map(function (doc)
[f.value for (f in util.evaluateXPath(
"//liberator:include/@href", doc))]);
// Scrape the tags from the rest of the help files.
util.Array.flatten(files).forEach(function (file) {
findHelpFile(file).forEach(function (doc) {
addTags(file, doc);
});
});
// Process plugin help entries.
let lang = options.getPref("general.useragent.locale", "en-US");
const ps = new DOMParser;
const encoder = Cc["@mozilla.org/layout/documentEncoder;1?type=text/xml"].getService(Ci.nsIDocumentEncoder);
encoder.init(document, "text/xml", 0);
body = xml.map([con for ([,con] in Iterator(plugins.contexts))], function (context) {
try { // debug
var info = context.INFO;
if (!info) return "";
var div = ps.parseFromString(xml`<div xmlns=${XHTML}>${info}</div>`, "text/xml").documentElement;
var list = div.querySelectorAll("plugin");
var res = {};
for (var i = 0, j = list.length; i < j; i++) {
var info = list[i];
var value = info.getAttribute("lang") || "";
res[i] = res[value] = info;
}
var info = res[lang] || res[lang.split("-", 2).shift()] || res[0];
if (!info) return "";
encoder.setNode(info);
return xml`<h2 xmlns=${NS.uri} tag=${info.getAttribute("name") + '-plugin'}>${
info.getAttribute("summary")}</h2>${xml.raw`${encoder.encodeToString()}`}`;
} catch (ex) {
Cu.reportError(ex);
alert(ex);
}
});
let help = '<?xml version="1.0"?>\n' +
'<?xml-stylesheet type="text/xsl" href="chrome://liberator/content/help.xsl"?>\n' +
'<!DOCTYPE document SYSTEM "chrome://liberator/content/liberator.dtd">' +
xml`<document xmlns=${NS}
name="plugins" title=${config.name + " Plugins"}>
<h1 tag="using-plugins">Using Plugins</h1>
${body}
</document>`.toString();
fileMap["plugins"] = function () ['text/xml;charset=UTF-8', help];
addTags("plugins", util.httpGet("liberator://help/plugins").responseXML);
},
/**
* Opens the help page containing the specified <b>topic</b> if it
* exists.
*
* @param {string} topic The help topic to open.
* @param {boolean} unchunked Whether to use the unchunked help page.
* @returns {string}
*/
help: function (topic, unchunked) {
if (!topic) {
let helpFile = unchunked ? "all" : options["helpfile"];
if (helpFile in services.get("liberator:").FILE_MAP)
liberator.open("liberator://help/" + helpFile, { from: "help" });
else
liberator.echomsg("Sorry, help file " + helpFile.quote() + " not found");
return;
}
let page = this.findHelp(topic, unchunked);
liberator.assert(page != null, "Sorry, no help for: " + topic);
liberator.open("liberator://help/" + page, { from: "help" });
if (!options["activate"] || options.get("activate").has("all", "help"))
content.postMessage("fragmentChange", "*");
},
/**
* The map of global variables.
*
* These are set and accessed with the "g:" prefix.
*/
globalVariables: {},
loadPlugins: function () {
function sourceDirectory(dir) {
liberator.assert(dir.isReadable(), "Cannot read directory: " + dir.path);
liberator.log("Sourcing plugin directory: " + dir.path + "...");
dir.readDirectory(true).forEach(function (file) {
if (file.isFile() && /\.(js|vimp)$/i.test(file.path) && !(file.path in liberator.pluginFiles)) {
try {
io.source(file.path, false);
liberator.pluginFiles[file.path] = true;
}
catch (e) {
liberator.echoerr(e);
}
}
else if (file.isDirectory())
sourceDirectory(file);
});
}
let dirs = io.getRuntimeDirectories("plugin");
if (dirs.length == 0) {
liberator.log("No user plugin directory found");
return;
}
liberator.log('Searching for "plugin/**/*.{js,vimp}" in "'
+ [dir.path.replace(/.plugin$/, "") for (dir of dirs)].join(",") + '"');
dirs.forEach(function (dir) {
liberator.log("Searching for \"" + (dir.path + "/**/*.{js,vimp}") + "\"", 3);
sourceDirectory(dir);
});
},
/**
* Logs a message to the JavaScript error console.
*
* @param {string|Object} msg The message to print.
*/
log: function (msg) {
if (typeof msg == "object")
msg = Cc["@mozilla.org/feed-unescapehtml;1"]
.getService(Ci.nsIScriptableUnescapeHTML)
.unescape(util.objectToString(msg, false).value);
services.get("console").logStringMessage(config.name.toLowerCase() + ": " + msg);
},
/**
* Opens one or more URLs. Returns true when load was initiated, or
* false on error.
*
* @param {string|string[]} urls Either a URL string or an array of URLs.
* The array can look like this:
* ["url1", "url2", "url3", ...]
* or:
* [["url1", postdata1], ["url2", postdata2], ...]
* @param {number|Object} where If ommited, CURRENT_TAB is assumed but NEW_TAB
* is set when liberator.forceNewTab is true.
* @param {boolean} force Don't prompt whether to open more than 20
* tabs.
* @returns {boolean}
*/
open: function (urls, params, force) {
// convert the string to an array of converted URLs
// -> see util.stringToURLArray for more details
//
// This is strange. And counterintuitive. Is it really
// necessary? --Kris
if (typeof urls == "string") {
// rather switch to the tab instead of opening a new url in case of "12: Tab Title" like "urls"
if (liberator.has("tabs")) {
let matches = urls.match(/^(\d+):/);
if (matches) {
tabs.select(parseInt(matches[1], 10) - 1, false, true); // make it zero-based
return;
}
}
urls = util.stringToURLArray(urls);
}
if (urls.length > 20 && !force) {
commandline.input("This will open " + urls.length + " new tabs. Would you like to continue? (yes/[no]) ",
function (resp) {
if (resp && resp.match(/^y(es)?$/i))
liberator.open(urls, params, true);
});
return;
}
let flags = 0;
params = params || {};
if (params instanceof Array)
params = { where: params };
for (let [opt, flag] in Iterator({ replace: "REPLACE_HISTORY", hide: "BYPASS_HISTORY" }))
if (params[opt])
flags |= Ci.nsIWebNavigation["LOAD_FLAGS_" + flag];
let where = params.where || liberator.CURRENT_TAB;
if (liberator.forceNewTab)
where = liberator.NEW_TAB;
else if (liberator.forceNewWindow)
where = liberator.NEW_WINDOW;
else if (liberator.forceNewPrivateWindow)
where = liberator.NEW_PRIVATE_WINDOW;
if ("from" in params && liberator.has("tabs")) {
if (!('where' in params) && options["newtab"] && options.get("newtab").has("all", params.from))
where = liberator.NEW_TAB;
if (options["activate"] && !options.get("activate").has("all", params.from)) {
if (where == liberator.NEW_TAB)
where = liberator.NEW_BACKGROUND_TAB;
else if (where == liberator.NEW_BACKGROUND_TAB)
where = liberator.NEW_TAB;
}
}
if (urls.length == 0)
return;
let browser = config.browser;
let urlTasks = [];
function open(urls, where) {
if (!browser) {
urlTasks.push(urls);
return;
}
try {
let url = "", postdata;
if (typeof urls === "string")
url = urls;
else
[url, postdata] = Array.concat(urls);
if (!url)
url = window.BROWSER_NEW_TAB_URL || "about:blank";
// decide where to load the first url
switch (where) {
case liberator.CURRENT_TAB:
browser.loadURIWithFlags(url, flags, null, null, postdata);
break;
case liberator.NEW_BACKGROUND_TAB:
case liberator.NEW_TAB:
if (!liberator.has("tabs")) {
open(urls, liberator.NEW_WINDOW);
return;
}
options.withContext(function () {
options.setPref("browser.tabs.loadInBackground", true);
browser.loadOneTab(url, null, null, postdata, where == liberator.NEW_BACKGROUND_TAB);
});
break;
case liberator.NEW_PRIVATE_WINDOW:
case liberator.NEW_WINDOW:
let sa = Cc["@mozilla.org/supports-array;1"].createInstance(Ci.nsISupportsArray);
let wuri = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
wuri.data = url;
sa.AppendElement(wuri);
sa.AppendElement(null); // charset
sa.AppendElement(null); // referrerURI
sa.AppendElement(postdata);
sa.AppendElement(null); // allowThirdPartyFixup
let features = "chrome,dialog=no,all" + (where === liberator.NEW_PRIVATE_WINDOW ? ",private" : "");
let win = services.get("ww").openWindow(window, "chrome://browser/content/browser.xul", null, features, sa);
browser = null;
win.addEventListener("load", function onload(aEvent) {
win.removeEventListener("load", onload, false);
browser = win.getBrowser();
for (let url of urlTasks)
open(url, liberator.NEW_BACKGROUND_TAB);
urlTasks = [];
}, false);
break;
}
}
catch (e) {}
}
for (let url of urls) {
open(url, where);
where = liberator.NEW_BACKGROUND_TAB;
}
},
pluginFiles: {},
// namespace for plugins/scripts. Actually (only) the active plugin must/can set a
// v.plugins.mode = <str> string to show on v.modes.CUSTOM
// v.plugins.stop = <func> hooked on a v.modes.reset()
// v.plugins.onEvent = <func> function triggered, on keypresses (unless <esc>) (see events.js)
plugins: plugins,
/**
* Quit the host application, no matter how many tabs/windows are open.
*
* @param {boolean} saveSession If true the current session will be
* saved and restored when the host application is restarted.
* @param {boolean} force Forcibly quit irrespective of whether all
* windows could be closed individually.
*/
quit: function (saveSession, force) {
// TODO: Use safeSetPref?
if (saveSession)
options.setPref("browser.startup.page", 3); // start with saved session
else
options.setPref("browser.startup.page", 1); // start with default homepage session
if (force)
services.get("startup").quit(Ci.nsIAppStartup.eForceQuit);
else
window.goQuitApplication();
},
/*
* Tests a condition and throws a FailedAssertion error on
* failure.
*
* @param {boolean} condition The condition to test.
* @param {string} message The message to present to the
* user on failure.
*/
assert: function (condition, message) {
if (!condition)
throw new FailedAssertion(message);
},
/**
* Traps errors in the called function, possibly reporting them.
*
* @param {function} func The function to call
* @param {object} self The 'this' object for the function.
*/
trapErrors: function (func, self) {
try {
return func.apply(self || this, Array.slice(arguments, 2));
}
catch (e) {
if (e instanceof FailedAssertion) {
if (e.message)
liberator.echoerr(e.message);
else
liberator.beep();
}
else
liberator.echoerr(e);
return undefined;
}
},
/**
* Reports an error to both the console and the host application's
* Error Console.
*
* @param {Object} error The error object.
*/
/*reportError: function (error) {
if (Cu.reportError)
Cu.reportError(error);
try {
let obj = {
toString: function () String(error),
stack: <>{String.replace(error.stack || Error().stack, /^/mg, "\t")}</>
};
for (let [k, v] in Iterator(error)) {
if (!(k in obj))
obj[k] = v;
}
if (liberator.storeErrors) {
let errors = storage.newArray("errors", { store: false });
errors.toString = function () [String(v[0]) + "\n" + v[1] for ([k, v] in this)].join("\n\n");
errors.push([new Date, obj + obj.stack]);
}
liberator.dump(String(error));
liberator.dump(obj);
liberator.dump("");
}
catch (e) { window.dump(e); }
},*/
/**
* Restart the host application.
*/
restart: function () {
// notify all windows that an application quit has been requested.
var cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool);
services.get("obs").notifyObservers(cancelQuit, "quit-application-requested", null);
// something aborted the quit process.
if (cancelQuit.data)
return;
// notify all windows that an application quit has been granted.
services.get("obs").notifyObservers(null, "quit-application-granted", null);
// enumerate all windows and call shutdown handlers
let windows = services.get("wm").getEnumerator(null);
while (windows.hasMoreElements()) {
let win = windows.getNext();
if (("tryToClose" in win) && !win.tryToClose())
return;
}
services.get("startup").quit(Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eAttemptQuit);
},
/**
* Parses a Liberator command-line string i.e. the value of the
* -liberator command-line option.
*
* @param {string} cmdline The string to parse for command-line
* options.
* @returns {Object}
* @see Commands#parseArgs
*/
parseCommandLine: function (cmdline) {
const options = [
[["+u"], commands.OPTIONS_STRING],
[["++noplugin"], commands.OPTIONS_NOARG],
[["++cmd"], commands.OPTIONS_STRING, null, null, true],
[["+c"], commands.OPTIONS_STRING, null, null, true]
];
return commands.parseArgs(cmdline, options, [], "*");
},
sleep: function (delay) {
let mainThread = services.get("threadManager").mainThread;
let end = Date.now() + delay;
while (Date.now() < end)
mainThread.processNextEvent(true);
return true;
},
callInMainThread: function (callback, self) {
let mainThread = services.get("threadManager").mainThread;
if (!services.get("threadManager").isMainThread)
mainThread.dispatch({ run: callback.call(self) }, mainThread.DISPATCH_NORMAL);
else
callback.call(self);
},
threadYield: function (flush, interruptable) {
let mainThread = services.get("threadManager").mainThread;
liberator.interrupted = false;
do {
mainThread.processNextEvent(!flush);
if (liberator.interrupted)
throw new Error("Interrupted");
}
while (flush === true && mainThread.hasPendingEvents());
},
variableReference: function (string) {
if (!string)
return [null, null, null];
let matches = string.match(/^([bwtglsv]):(\w+)/);
if (matches) { // Variable
// Other variables should be implemented
if (matches[1] == "g") {
if (matches[2] in this.globalVariables)
return [this.globalVariables, matches[2], matches[1]];
else
return [null, matches[2], matches[1]];
}
}
else { // Global variable
if (string in this.globalVariables)
return [this.globalVariables, string, "g"];
else
return [null, string, "g"];
}
throw Error("What the fuck?");
},
/**
* @property {Window[]} Returns an array of all the host application's
* open windows.
*/
get windows() {
let windows = [];
let enumerator = services.get("wm").getEnumerator("navigator:browser");
while (enumerator.hasMoreElements())
windows.push(enumerator.getNext());
return windows;
}
}, {
// return the platform normalized to Vim values
getPlatformFeature: function () {
let platform = navigator.platform;
return /^Mac/.test(platform) ? "MacUnix" :
platform == "Win32" ? "Win32" :
platform == "Win64" ? "Win64" :
"Unix";
},
// TODO: move this
getMenuItems: function () {
function addChildren(node, parent) {
for (let item of node.childNodes) {
if (item.childNodes.length == 0 && item.localName == "menuitem"
&& !/rdf:http:/.test(item.getAttribute("label"))) { // FIXME
item.fullMenuPath = parent + item.getAttribute("label");
items.push(item);
}
else {
let path = parent;
if (item.localName == "menu")
path += item.getAttribute("label") + ".";
addChildren(item, path);
}
}
}
let items = [];
addChildren(document.getElementById(config.toolbars["menu"][0][0]), "");
return items;
},
}, {
// Only general options are added here, which are valid for all liberator extensions
options: function () {
options.add(["errorbells", "eb"],
"Ring the bell when an error message is displayed",
"boolean", false);
options.add(["exrc", "ex"],
"Allow reading of an RC file in the current directory",
"boolean", false);
options.add(["fullscreen", "fs"],
"Show the current window fullscreen",
"boolean", false, {
setter: function (value) window.fullScreen = value,
getter: function () window.fullScreen
});
options.add(["helpfile", "hf"],
"Name of the main help file",
"string", "intro");
options.add(["loadplugins", "lpl"],
"Load plugin scripts when starting up",
"boolean", true);
// TODO: Is this vimperator only? Otherwise fix for Muttator
options.add(["scrollbars", "sb"],
"Show scrollbars in the content window when needed",
"boolean", true, {
setter: function (value) {
if (value)
styles.removeSheet(true, "scrollbars");
else // Use [orient="horizontal"] if you only want to change the horizontal scrollbars
styles.addSheet(true, "scrollbars", "*", "html|html > xul|scrollbar { visibility: collapse !important; }", true);
return value;
}
});
options.add(["smallicons", "si"],
"Show small or normal size icons in the main toolbar",
"boolean", true, {
setter: function (value) {
try {
let mainToolbar = config.mainToolbar;
mainToolbar.setAttribute("iconsize", value ? "small" : "large");
} catch (e) { }
return value;
},
getter: function () {
try {
let mainToolbar = config.mainToolbar;
return mainToolbar.getAttribute("iconsize") == "small";
} catch (e) {
return false;
}
}
});
options.add(["titlestring"],
"Change the title of the window",
"string", config.defaults.titlestring || config.hostApplication,
{
setter: function (value) {
let win = document.documentElement;
if (liberator.has("privatebrowsing")) {
let oldValue = win.getAttribute("titlemodifier_normal");
let suffix = win.getAttribute("titlemodifier_privatebrowsing").substr(oldValue.length);
win.setAttribute("titlemodifier_normal", value);
win.setAttribute("titlemodifier_privatebrowsing", value + suffix);
if (window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsILoadContext)
.usePrivateBrowsing) {
win.setAttribute("titlemodifier", value + suffix);
}
else
win.setAttribute("titlemodifier", value);
}
else
win.setAttribute("titlemodifier", value);
config.updateTitlebar();
return value;
}
});
options.add(["toolbars", "gui"],
"Show or hide toolbars",
"stringlist", config.defaults.toolbars || "", {
setter: function (values) {
let toolbars = config.toolbars || {};
// a set of actions with the the name of the element as the object's keys
// and the collapsed state for the values
// Used in order to avoid multiple collapse/uncollapse actions
// for values like :set gui=none,tabs
let actions = {};
for (let action of this.parseValues(values)) {
if (action === "all" || action === "none") {
for (let [name, toolbar] in Iterator(toolbars)) {
for (let id of toolbar[0] || [])
actions[id] = action === "none";
}
} else {
let toolbarName = action.replace(/^(no|inv)/, "");
let toolbar = toolbars[toolbarName];
if (toolbar) {
for (let id of toolbar[0] || []) {
let elem = document.getElementById(id);
if (!elem)
continue;
let collapsed = false;
if (action.startsWith("no"))
collapsed = true;
else if (action.startsWith("inv")) {
if (typeof(actions[id]) === "boolean")
collapsed = !actions[id];
else {
let hidingAttribute = elem.getAttribute("type") === "menubar" ? "autohide" : "collapsed";
collapsed = !(elem.getAttribute(hidingAttribute) === "true");
}
}
else
collapsed = false;
actions[id] = collapsed; // add the action, or change an existing action
}
}
}
}
// finally we can just execute the actions
for (let [id, collapsed] in Iterator(actions)) {
let elem = document.getElementById(id);
if (!elem)
continue;
// Firefox4 added this helper function, which does more than
// just collapsing elements (like showing or hiding the menu button when the menu is hidden/shown)
if (window.setToolbarVisibility)
window.setToolbarVisibility(elem, !collapsed);
else if (elem.getAttribute("type") == "menubar")
elem.setAttribute("autohide", collapsed);
else
elem.collapsed = collapsed;
// HACK: prevent the tab-bar from redisplaying when 'toolbars' option has 'notabs'
// @see http://code.google.com/p/vimperator-labs/issues/detail?id=520
if (id == "TabsToolbar" && config.tabbrowser.mTabContainer.updateVisibility)
config.tabbrowser.mTabContainer.updateVisibility = function () { };
}
return ""; // we need this value, otherwise "inv" options won't work. Maybe we should just make this a local option
},
getter: function() {
let toolbars = config.toolbars || {};
let values = [];
for (let [name, toolbar] in Iterator(toolbars)) {
let elem = document.getElementById(toolbar[0]);
if (elem) {
let hidingAttribute = elem.getAttribute("type") == "menubar" ? "autohide" : "collapsed";
values.push(elem.getAttribute(hidingAttribute) == "true" ? "no" + name : name);
}
}
return this.joinValues(values);
},
completer: function (context) {
let toolbars = config.toolbars || {};
let completions = [["all", "Show all toolbars"],
["none", "Hide all toolbars"]];
for (let [name, toolbar] in Iterator(toolbars)) {
let elem = document.getElementById(toolbar[0][0]);
if (elem) {
let hidingAttribute = elem.getAttribute("type") == "menubar" ? "autohide" : "collapsed";
completions.push([elem.getAttribute(hidingAttribute) == "true" ? name : "no" + name,
(elem.getAttribute(hidingAttribute) == "true" ? "Show " : "Hide ") + toolbar[1]]);
}
}
context.completions = completions;
context.compare = CompletionContext.Sort.unsorted;
return completions;
},
validator: function (value) {
let toolbars = config.toolbars || {};
// "ne" is a simple hack, since in the next line val.replace() makes "ne" out from "none"
let values = ["all", "ne"].concat([toolbar for each([toolbar, ] in Iterator(toolbars))]);
return value.every(function(val) values.indexOf(val.replace(/^(no|inv)/, "")) >= 0);
}
});
options.add(["verbose", "vbs"],
"Define which info messages are displayed",
"number", 1,
{ validator: function (value) value >= 0 && value <= 15 });
options.add(["visualbell", "vb"],
"Use visual bell instead of beeping on errors",
"boolean", false,
{
setter: function (value) {
options.safeSetPref("accessibility.typeaheadfind.enablesound", !value,
"See 'visualbell' option");
return value;
}
});
},
mappings: function () {
mappings.add(modes.all, ["<F1>"],
"Open the help page",
function () { liberator.help(); });
if (liberator.has("session")) {
mappings.add([modes.NORMAL], ["ZQ"],
"Quit and don't save the session",
function () { liberator.quit(false); });
}
mappings.add([modes.NORMAL], ["ZZ"],
"Quit and save the session",
function () { liberator.quit(true); });
},
commands: function () {
commands.add(["addo[ns]"],
"Manage available Extensions and Themes",
function () { liberator.open("about:addons", { from: "addons" }); },
{ argCount: "0" });
commands.add(["beep"],
"Play a system beep", // Play? Wrong word. Implies some kind of musicality. --Kris
function () { liberator.beep(); },
{ argCount: "0" });
commands.add(["dia[log]"],
"Open a " + config.name + " dialog",
function (args) {
let arg = args[0];
try {
// TODO: why are these sorts of properties arrays? --djk
let dialogs = config.dialogs;
for (let dialog of dialogs) {
if (util.compareIgnoreCase(arg, dialog[0]) == 0) {
dialog[2]();
return;
}
}
liberator.echoerr("Invalid argument: " + arg);
}
catch (e) {
liberator.echoerr("Error opening " + arg.quote() + ": " + e);
}
}, {
argCount: "1",
bang: true,
completer: function (context) {
context.ignoreCase = true;
return completion.dialog(context);
}
});
commands.add(["em[enu]"],
"Execute the specified menu item from the command line",
function (args) {
let arg = args.literalArg;
let items = Liberator.getMenuItems();
liberator.assert(items.some(function (i) i.fullMenuPath == arg),
"Menu not found: " + arg);
for (let [, item] in Iterator(items)) {
if (item.fullMenuPath == arg)
item.doCommand();
}
}, {
argCount: "1",
completer: function (context) completion.menuItem(context),
literal: 0
});
commands.add(["exe[cute]"],
"Execute the argument as an Ex command",
// FIXME: this should evaluate each arg separately then join
// with " " before executing.
// E.g. :execute "source" io.getRCFile().path
// Need to fix commands.parseArgs which currently strips the quotes
// from quoted args
function (args) {
try {
let cmd = liberator.eval(args.string);
liberator.execute(cmd, null, true);
}
catch (e) {
liberator.echoerr(e);
}
});
commands.add(["exta[dd]"],
"Install an extension",
function (args) {
let file = io.File(args[0]);
if (file.exists() && file.isReadable() && file.isFile())
AddonManager.getInstallForFile(file, function (a) a.install());
else {
if (file.exists() && file.isDirectory())
liberator.echoerr("Cannot install a directory: " + file.path);
liberator.echoerr("Cannot open file: " + file.path);
}
}, {
argCount: "1",
completer: function (context) {
context.filters.push(function ({ item: f }) f.isDirectory() || /\.xpi$/.test(f.leafName));
completion.file(context);
}
});
// TODO: handle extension dependencies
[
{
name: "extde[lete]",
description: "Uninstall an extension",
action: "uninstallItem"
},
{
name: "exte[nable]",
description: "Enable an extension",
action: "enableItem",
filter: function ({ item: e }) (!e.enabled || (e.original && e.original.userDisabled))
},
{
name: "extd[isable]",
description: "Disable an extension",
action: "disableItem",
filter: function ({ item: e }) (e.enabled || (e.original && !e.original.userDisabled))
}
].forEach(function (command) {
commands.add([command.name],
command.description,
function (args) {
let name = args[0];
function action(e) {
if (command.action == "uninstallItem")
e.original.uninstall();
else
e.original.userDisabled = command.action == "disableItem";
};
if (args.bang)
liberator.extensions.forEach(function (e) { action(e); });
else {
liberator.assert(name, "Argument required");
let extension = liberator.getExtension(name);
if (extension)
action(extension);
else
liberator.echoerr("Invalid argument");
}
}, {
argCount: "?", // FIXME: should be "1"
bang: true,
completer: function (context) {
completion.extension(context);
if (command.filter)
context.filters.push(command.filter);
},
literal: 0
});
});
commands.add(["exto[ptions]", "extp[references]"],
"Open an extension's preference dialog",
function (args) {
let extension = liberator.getExtension(args[0]);
liberator.assert(extension && extension.options, "Invalid argument");
if (args.bang)
window.openDialog(extension.options, "_blank", "chrome,toolbar");
else
liberator.open(extension.options, { from: "extoptions" });
}, {
argCount: "1",
bang: true,
completer: function (context) {
completion.extension(context);
context.filters.push(function ({ item: e }) e.options);
},
literal: 0
});
// TODO: maybe indicate pending status too?
commands.add(["extens[ions]"],
"List available extensions",
function (args) {
let filter = args[0] || "";
let extensions = liberator.extensions.filter(function (e) e.name.indexOf(filter) >= 0);
if (extensions.length > 0) {
let list = template.tabular(
["Name", "Version", "Status", "Description"],
([template.icon(e, e.name),
e.version,
e.enabled ? xml`<span highlight="Enabled">enabled</span>`
: xml`<span highlight="Disabled">disabled</span>`,
e.description] for ([, e] in Iterator(extensions)))
);
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}
else {
if (filter)
liberator.echoerr("No matching extensions for: " + filter);
else
liberator.echoerr("No extensions installed");
}
},
{ argCount: "?" });
[
{
name: "h[elp]",
description: "Open the help page"
}, {
name: "helpa[ll]",
description: "Open the single unchunked help page"
}
].forEach(function (command) {
let unchunked = command.name == "helpa[ll]";
commands.add([command.name],
command.description,
function (args) {
liberator.assert(!args.bang, "Don't panic!");
liberator.help(args.literalArg, unchunked);
}, {
argCount: "?",
bang: true,
completer: function (context) completion.help(context, unchunked),
literal: 0
});
});
commands.add(["javas[cript]", "js"],
"Run a JavaScript command through eval()",
function (args) {
if (args.bang) { // open JavaScript console
liberator.open("chrome://global/content/console.xul",
{ from: "javascript" });
}
else {
try {
liberator.eval(args.string);
}
catch (e) {
liberator.echoerr(e);
}
}
}, {
bang: true,
completer: function (context) completion.javascript(context),
hereDoc: true,
literal: 0
});
commands.add(["loadplugins", "lpl"],
"Load all plugins immediately",
function () { liberator.loadPlugins(); },
{ argCount: "0" });
commands.add(["norm[al]"],
"Execute Normal mode commands",
function (args) { events.feedkeys(args.string, args.bang); },
{
argCount: "+",
bang: true
});
commands.add(["q[uit]"],
liberator.has("tabs") ? "Quit current tab" : "Quit application",
function (args) {
if (liberator.has("tabs"))
tabs.remove(config.browser.mCurrentTab, 1, false, 1);
else
liberator.quit(false, args.bang);
}, {
argCount: "0",
bang: true
});
commands.add(["res[tart]"],
"Force " + config.name + " to restart",
function () { liberator.restart(); },
{ argCount: "0" });
commands.add(["time"],
"Profile a piece of code or run a command multiple times",
function (args) {
let count = args.count;
let special = args.bang;
args = args.string;
if (args[0] == ":")
var method = function () liberator.execute(args, null, true);
else
method = liberator.eval("(function () {" + args + "})");
try {
if (count > 1) {
let each, eachUnits, totalUnits;
let total = 0;
for (let i in util.interruptibleRange(0, count, 500)) {
let now = Date.now();
method();
total += Date.now() - now;
}
if (special)
return;
if (total / count >= 100) {
each = total / 1000.0 / count;
eachUnits = "sec";
}
else {
each = total / count;
eachUnits = "msec";
}
if (total >= 100) {
total = total / 1000.0;
totalUnits = "sec";
}
else
totalUnits = "msec";
let str = template.genericOutput("Code execution summary",
xml`<table>
<tr><td>Executed:</td><td align="right"><span class="times-executed">${count}</span></td><td>times</td></tr>
<tr><td>Average time:</td><td align="right"><span class="time-average">${each.toFixed(2)}</span></td><td>${eachUnits}</td></tr>
<tr><td>Total time:</td><td align="right"><span class="time-total">${total.toFixed(2)}</span></td><td>${totalUnits}</td></tr>
</table>`);
commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}
else {
let beforeTime = Date.now();
method();
if (special)
return;
let afterTime = Date.now();
if (afterTime - beforeTime >= 100)
liberator.echo("Total time: " + ((afterTime - beforeTime) / 1000.0).toFixed(2) + " sec");
else
liberator.echo("Total time: " + (afterTime - beforeTime) + " msec");
}
}
catch (e) {
liberator.echoerr(e);
}
}, {
argCount: "+",
bang: true,
completer: function (context) {
if (/^:/.test(context.filter))
return completion.ex(context);
else
return completion.javascript(context);
},
count: true,
literal: 0
});
commands.add(["verb[ose]"],
"Execute a command with 'verbose' set",
function (args) {
let vbs = options.get("verbose");
let value = vbs.value;
let setFrom = vbs.setFrom;
try {
vbs.set(args.count || 1);
vbs.setFrom = null;
liberator.execute(args[0], null, true);
}
finally {
vbs.set(value);
vbs.setFrom = setFrom;
}
}, {
argCount: "+",
completer: function (context) completion.ex(context),
count: true,
literal: 0
});
commands.add(["ve[rsion]"],
"Show version information",
function (args) {
if (args.bang)
liberator.open("about:");
else
liberator.echo(template.tabular([{ header: "Version Information", style: "font-weight: bold; padding-left: 2ex", colspan: 2 }],
[[config.name + ":", liberator.version],
[config.hostApplication + ":", navigator.userAgent]]));
}, {
argCount: "0",
bang: true
});
commands.add(["us[age]"],
"List all commands, mappings and options with a short description",
function (args) {
let usage = {
mappings: function() template.table2(xml, "Mappings", [[item.name || item.names[0], item.description] for (item in mappings)].sort()),
commands: function() template.table2(xml, "Commands", [[item.name || item.names[0], item.description] for (item in commands)]),
options: function() template.table2(xml, "Options", [[item.name || item.names[0], item.description] for (item in options)])
}
if (args[0] && !usage[args[0]])
return void liberator.echoerr("No usage information for: " + args[0]);
if (args[0])
var usage = template.genericOutput(config.name + " Usage", usage[args[0]]());
else
var usage = template.genericOutput(config.name + " Usage", xml`${ usage["mappings"]() }<br/>${ usage["commands"]() }<br/>${ usage["options"]()}`);
liberator.echo(usage, commandline.FORCE_MULTILINE);
}, {
argCount: "?",
bang: false,
completer: function (context) {
context.title = ["Usage Item"];
context.compare = CompletionContext.Sort.unsorted;
context.completions = [["mappings", "All key bindings"],
["commands", "All ex-commands"],
["options", "All options"]];
}
});
},
completion: function () {
completion.dialog = function dialog(context) {
context.title = ["Dialog"];
context.completions = config.dialogs;
};
completion.extension = function extension(context) {
context.title = ["Extension"];
context.anchored = false;
context.keys = { text: "name", description: "description", icon: "icon" },
context.completions = liberator.extensions;
};
completion.help = function help(context, unchunked) {
context.title = ["Help"];
context.anchored = false;
context.completions = services.get("liberator:").HELP_TAGS;
if (unchunked)
context.keys = { text: 0, description: function () "all" };
};
completion.menuItem = function menuItem(context) {
context.title = ["Menu Path", "Label"];
context.anchored = false;
context.keys = { text: "fullMenuPath", description: function (item) item.getAttribute("label") };
context.completions = liberator.menuItems;
};
completion.toolbar = function toolbar(context) {
let toolbox = document.getElementById("navigator-toolbox");
context.title = ["Toolbar"];
context.keys = { text: function (item) item.getAttribute("toolbarname"), description: function () "" };
context.completions = util.evaluateXPath("./*[@toolbarname]", document, toolbox);
};
completion.window = function window(context) {
context.title = ["Window", "Title"]
context.keys = { text: function (win) liberator.windows.indexOf(win) + 1, description: function (win) win.document.title };
context.completions = liberator.windows;
};
},
load: function () {
liberator.triggerObserver("load");
liberator.log("All modules loaded");
services.add("commandLineHandler", "@mozilla.org/commandlinehandler/general-startup;1?type=" + config.name.toLowerCase());
let commandline = services.get("commandLineHandler").optionValue;
if (commandline) {
let args = liberator.parseCommandLine(commandline);
liberator.commandLineOptions.rcFile = args["+u"];
liberator.commandLineOptions.noPlugins = "++noplugin" in args;
liberator.commandLineOptions.postCommands = args["+c"];
liberator.commandLineOptions.preCommands = args["++cmd"];
liberator.log("Command-line options: " + util.objectToString(liberator.commandLineOptions));
}
// first time intro message
const firstTime = "extensions." + config.name.toLowerCase() + ".firsttime";
if (options.getPref(firstTime, true)) {
setTimeout(function () {
liberator.help();
options.setPref(firstTime, false);
}, 1000);
}
// always start in normal mode
modes.reset();
if (liberator.commandLineOptions.preCommands)
liberator.commandLineOptions.preCommands.forEach(function (cmd) {
liberator.execute(cmd);
});
// finally, read the RC file and source plugins
// make sourcing asynchronous, otherwise commands that open new tabs won't work
setTimeout(function () {
let extensionName = config.name.toUpperCase();
let init = services.get("environment").get(extensionName + "_INIT");
let rcFile = io.getRCFile("~");
if (liberator.commandLineOptions.rcFile) {
let filename = liberator.commandLineOptions.rcFile;
if (!/^(NONE|NORC)$/.test(filename))
io.source(io.File(filename).path, false); // let io.source handle any read failure like Vim
}
else {
if (init)
liberator.execute(init);
else {
if (rcFile) {
io.source(rcFile.path, true);
services.get("environment").set("MY_" + extensionName + "RC", rcFile.path);
}
else
liberator.log("No user RC file found");
}
if (options["exrc"] && !liberator.commandLineOptions.rcFile) {
let localRCFile = io.getRCFile(io.getCurrentDirectory().path);
if (localRCFile && !localRCFile.equals(rcFile))
io.source(localRCFile.path, true);
}
}
if (liberator.commandLineOptions.rcFile == "NONE" || liberator.commandLineOptions.noPlugins)
options["loadplugins"] = false;
if (options["loadplugins"])
liberator.loadPlugins();
liberator.initHelp();
// after sourcing the initialization files, this function will set
// all gui options to their default values, if they have not been
// set before by any RC file
// TODO: Let options specify themselves whether they need to be set at startup!
for (let option in options) {
if (!option.hasChanged && ["popups", "smallicons", "titlestring", "toolbars"].indexOf(option.name) >= 0)
option.value = option.defaultValue; // call setter
}
if (liberator.commandLineOptions.postCommands)
liberator.commandLineOptions.postCommands.forEach(function (cmd) {
liberator.execute(cmd);
});
liberator.triggerObserver("enter", null);
autocommands.trigger(config.name + "Enter", {});
}, 0);
statusline.update();
liberator.log(config.name + " fully initialized");
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2009 by Kris Maglione <kris@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
function checkFragment() {
document.title = document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "title")[0].textContent;
var frag = document.location.hash.substr(1);
var elem = document.getElementById(frag);
if (elem)
window.content.scrollTo(0, window.content.scrollY + elem.getBoundingClientRect().top - 10); // 10px context
}
document.addEventListener("load", checkFragment, true);
window.addEventListener("message", function (event) {
if (event.data == "fragmentChange")
checkFragment();
}, true);
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
// do NOT create instances of this class yourself, use the helper method
// options.add() instead
/**
* A class representing configuration options. Instances are created by the
* {@link Options} class.
*
* @param {string[]} names The names by which this option is identified.
* @param {string} description A short one line description of the option.
* @param {string} type The option's value data type (see {@link Option#type}).
* @param {string} defaultValue The default value for this option.
* @param {Object} extraInfo An optional extra configuration hash. The
* following properties are supported.
* scope - see {@link Option#scope}
* setter - see {@link Option#setter}
* getter - see {@link Option#getter}
* completer - see {@link Option#completer}
* validator - see {@link Option#validator}
* checkHas - see {@link Option#checkHas}
* @optional
* @private
*/
const Option = Class("Option", {
init: function (names, description, type, defaultValue, extraInfo) {
this.name = names[0];
this.names = names;
this.type = type;
this.description = description;
if (arguments.length > 3)
this.defaultValue = defaultValue;
if (extraInfo)
update(this, extraInfo);
// add no{option} variant of boolean {option} to this.names
if (this.type == "boolean")
this.names = array([name, "no" + name] for (name in values(names))).flatten().__proto__;
if (this.globalValue == undefined)
this.globalValue = this.defaultValue;
},
/** @property {value} The option's global value. @see #scope */
get globalValue() options.store.get(this.name),
set globalValue(val) { options.store.set(this.name, val); },
/**
* Returns <b>value</b> as an array of parsed values if the option type is
* "charlist" or "stringlist" or else unchanged.
*
* @param {value} value The option value.
* @returns {value|string[]}
*/
parseValues: function (value) {
if (this.type == "stringlist")
return (value === "") ? [] : value.split(",");
if (this.type == "charlist")
return Array.slice(value);
return value;
},
/**
* Returns <b>values</b> packed in the appropriate format for the option
* type.
*
* @param {value|string[]} values The option value.
* @returns {value}
*/
joinValues: function (values) {
if (this.type == "stringlist")
return values.join(",");
if (this.type == "charlist")
return values.join("");
return values;
},
/** @property {value|string[]} The option value or array of values. */
get values() this.parseValues(this.value),
set values(values) this.setValues(values, this.scope),
/**
* Returns the option's value as an array of parsed values if the option
* type is "charlist" or "stringlist" or else the simple value.
*
* @param {number} scope The scope to return these values from (see
* {@link Option#scope}).
* @returns {value|string[]}
*/
getValues: function (scope) this.parseValues(this.get(scope)),
/**
* Sets the option's value from an array of values if the option type is
* "charlist" or "stringlist" or else the simple value.
*
* @param {number} scope The scope to apply these values to (see
* {@link Option#scope}).
*/
setValues: function (values, scope) {
this.set(this.joinValues(values), scope || this.scope);
},
/**
* Returns the value of the option in the specified <b>scope</b>. The
* (@link Option#getter) callback, if it exists, is invoked with this value
* before it is returned.
*
* @param {number} scope The scope to return this value from (see
* {@link Option#scope}).
* @returns {value}
*/
get: function (scope) {
if (scope) {
if ((scope & this.scope) == 0) // option doesn't exist in this scope
return null;
}
else
scope = this.scope;
// Options with a custom getter are always responsible for returning a meaningful value
if (this.getter)
return liberator.trapErrors(this.getter, this, value);
let value;
if (liberator.has("tabs") && (scope & Option.SCOPE_LOCAL))
value = tabs.options[this.name];
if ((scope & Option.SCOPE_GLOBAL) && (value == undefined))
value = this.globalValue;
return value;
},
/**
* Sets the option value to <b>newValue</b> for the specified <b>scope</b>.
* The (@link Option#setter) callback, if it exists, is invoked with
* <b>newValue</b>.
*
* @param {value} newValue The option's new value.
* @param {number} scope The scope to apply this value to (see
* {@link Option#scope}).
*/
set: function (newValue, scope) {
scope = scope || this.scope;
if ((scope & this.scope) == 0) // option doesn't exist in this scope
return;
if (this.setter)
newValue = liberator.trapErrors(this.setter, this, newValue);
if (liberator.has("tabs") && (scope & Option.SCOPE_LOCAL))
tabs.options[this.name] = newValue;
if ((scope & Option.SCOPE_GLOBAL) && newValue != this.globalValue)
this.globalValue = newValue;
this.hasChanged = true;
},
/**
* @property {value} The option's current value. The option's local value,
* or if no local value is set, this is equal to the
* (@link #globalValue).
*/
get value() this.get(),
set value(val) this.set(val),
/**
* Returns whether the option value contains one or more of the specified
* arguments.
*
* @returns {boolean}
*/
has: function () {
let self = this;
let test = function (val) values.indexOf(val) >= 0;
if (this.checkHas)
test = function (val) values.some(function (value) self.checkHas(value, val));
let values = this.values;
// return whether some argument matches
return Array.some(arguments, function (val) test(val));
},
/**
* Returns whether this option is identified by <b>name</b>.
*
* @param {string} name
* @returns {boolean}
*/
hasName: function (name) this.names.indexOf(name) >= 0,
/**
* Returns whether the specified <b>values</b> are valid for this option.
* @see Option#validator
*/
isValidValue: function (values) this.validator(values),
/**
* Resets the option to its default value.
*/
reset: function () {
this.value = this.defaultValue;
},
/**
* Sets the option's value using the specified set <b>operator</b>.
*
* @param {string} operator The set operator.
* @param {value|string[]} values The value (or values) to apply.
* @param {number} scope The scope to apply this value to (see
* {@link #scope}).
* @param {boolean} invert Whether this is an invert boolean operation.
*/
op: function (operator, values, scope, invert) {
let newValue = null;
let self = this;
switch (this.type) {
case "boolean":
if (operator != "=")
break;
if (invert)
newValue = !this.value;
else
newValue = values;
break;
case "number":
// TODO: support floats? Validators need updating.
if (!/^[+-]?(?:0x[0-9a-f]+|0[0-7]+|0|[1-9]\d*)$/i.test(values))
return "Number required after := " + this.name + "=" + values;
let value = parseInt(values/* deduce radix */);
switch (operator) {
case "+":
newValue = this.value + value;
break;
case "-":
newValue = this.value - value;
break;
case "^":
newValue = this.value * value;
break;
case "=":
newValue = value;
break;
}
break;
case "charlist":
case "stringlist":
values = Array.concat(values);
switch (operator) {
case "+":
newValue = util.Array.uniq(Array.concat(this.values, values), true);
break;
case "^":
// NOTE: Vim doesn't prepend if there's a match in the current value
newValue = util.Array.uniq(Array.concat(values, this.values), true);
break;
case "-":
newValue = this.values.filter(function (item) values.indexOf(item) == -1);
break;
case "=":
newValue = values;
if (invert) {
let keepValues = this.values.filter(function (item) values.indexOf(item) == -1);
let addValues = values.filter(function (item) self.values.indexOf(item) == -1);
newValue = addValues.concat(keepValues);
}
break;
}
break;
case "string":
switch (operator) {
case "+":
newValue = this.value + values;
break;
case "-":
newValue = this.value.replace(values, "");
break;
case "^":
newValue = values + this.value;
break;
case "=":
newValue = values;
break;
}
break;
default:
return "Internal error: option type `" + this.type + "' not supported";
}
if (newValue == null)
return "Operator " + operator + " not supported for option type " + this.type;
if (!this.isValidValue(newValue))
return "Invalid argument: " + values;
this.setValues(newValue, scope);
return null;
},
// Properties {{{2
/** @property {string} The option's canonical name. */
name: null,
/** @property {string[]} All names by which this option is identified. */
names: null,
/**
* @property {string} The option's data type. One of:
* "boolean" - Boolean E.g. true
* "number" - Integer E.g. 1
* "string" - String E.g. "Vimperator"
* "charlist" - Character list E.g. "rb"
* "stringlist" - String list E.g. "homepage,quickmark,tabopen,paste"
*/
type: null,
/**
* @property {number} The scope of the option. This can be local, global,
* or both.
* @see Option#SCOPE_LOCAL
* @see Option#SCOPE_GLOBAL
* @see Option#SCOPE_BOTH
*/
scope: 1, // Option.SCOPE_GLOBAL // XXX set to BOTH by default someday? - kstep
/**
* @property {string} This option's description, as shown in :usage.
*/
description: "",
/**
* @property {value} The option's default value. This value will be used
* unless the option is explicitly set either interactively or in an RC
* file or plugin.
*/
defaultValue: null,
/**
* @property {function} The function called when the option value is set.
*/
setter: null,
/**
* @property {function} The function called when the option value is read.
*/
getter: null,
/**
* @property {function(CompletionContext, Args)} This option's completer.
* @see CompletionContext
*/
completer: null,
/**
* @property {function} The function called to validate the option's value
* when set.
*/
validator: function () {
if (this.completer)
return Option.validateCompleter.apply(this, arguments);
return true;
},
/**
* @property The function called to determine whether the option already
* contains a specified value.
* @see #has
*/
checkHas: null,
/**
* @property {boolean} Set to true whenever the option is first set. This
* is useful to see whether it was changed from its default value
* interactively or by some RC file.
*/
hasChanged: false,
/**
* @property {nsIFile} The script in which this option was last set. null
* implies an interactive command.
*/
setFrom: null
}, {
/**
* @property {number} Global option scope.
* @final
*/
SCOPE_GLOBAL: 1,
/**
* @property {number} Local option scope. Options in this scope only
* apply to the current tab/buffer.
* @final
*/
SCOPE_LOCAL: 2,
/**
* @property {number} Both local and global option scope.
* @final
*/
SCOPE_BOTH: 3,
// TODO: Run this by default?
/**
* Validates the specified <b>values</b> against values generated by the
* option's completer function.
*
* @param {value|string[]} values The value or array of values to validate.
* @returns {boolean}
*/
validateCompleter: function (values) {
let context = CompletionContext("");
let res = context.fork("", 0, this, this.completer);
if (!res)
res = context.allItems.items.map(function (item) [item.text]);
return Array.concat(values).every(function (value) res.some(function (item) item[0] == value));
}
});
/**
* @instance options
*/
const Options = Module("options", {
requires: ["config", "highlight", "storage"],
init: function () {
this._optionHash = {};
this._prefContexts = [];
for (let pref of this.allPrefs(Options.OLD_SAVED)) {
let saved = Options.SAVED + pref.substr(Options.OLD_SAVED.length)
if (!this.getPref(saved))
this.setPref(saved, this.getPref(pref));
this.resetPref(pref);
}
// Host application preferences which need to be changed to work well with
//
// Work around the popup blocker
// TODO: Make this work like safeSetPref
var popupAllowedEvents = this._loadPreference("dom.popup_allowed_events", "change click dblclick mouseup reset submit");
if (!/keypress/.test(popupAllowedEvents)) {
this._storePreference("dom.popup_allowed_events", popupAllowedEvents + " keypress");
liberator.registerObserver("shutdown", function () {
if (this._loadPreference("dom.popup_allowed_events", "") == popupAllowedEvents + " keypress")
this._storePreference("dom.popup_allowed_events", popupAllowedEvents);
});
}
function optionObserver(key, event, option) {
// Trigger any setters.
let opt = options.get(option);
if (event == "change" && opt)
opt.set(opt.globalValue, Option.SCOPE_GLOBAL);
}
storage.newMap("options", { store: false });
storage.addObserver("options", optionObserver, window);
this.prefObserver.register();
},
destroy: function () {
this.prefObserver.unregister();
},
/** @property {Iterator(Option)} @private */
__iterator__: function () {
let sorted = [o for ([i, o] in Iterator(this._optionHash))].sort(function (a, b) String.localeCompare(a.name, b.name));
return (v for (v of sorted));
},
/** @property {Object} Observes preference value changes. */
prefObserver: {
register: function () {
// better way to monitor all changes?
this._branch = services.get("prefs").getBranch("").QueryInterface(Ci.nsIPrefBranch2);
this._branch.addObserver("", this, false);
},
unregister: function () {
if (this._branch)
this._branch.removeObserver("", this);
},
observe: function (subject, topic, data) {
if (topic != "nsPref:changed")
return;
// subject is the nsIPrefBranch we're observing (after appropriate QI)
// data is the name of the pref that's been changed (relative to subject)
switch (data) {
case "accessibility.browsewithcaret":
let value = options.getPref("accessibility.browsewithcaret", false);
liberator.mode = value ? modes.CARET : modes.NORMAL;
break;
}
}
},
/**
* Adds a new option.
*
* @param {string[]} names All names for the option.
* @param {string} description A description of the option.
* @param {string} type The option type (see {@link Option#type}).
* @param {value} defaultValue The option's default value.
* @param {Object} extra An optional extra configuration hash (see
* {@link Map#extraInfo}).
* @optional
* @returns {Option} Returns the instace of Option, if the option was created.
*/
add: function (names, description, type, defaultValue, extraInfo) {
if (!extraInfo)
extraInfo = {};
let option = Option(names, description, type, defaultValue, extraInfo);
if (!option)
return false;
if (option.name in this._optionHash) {
// never replace for now
liberator.echomsg("Option '" + names[0].quote() + "' already exists, NOT replacing existing option.");
return false;
}
// quickly access options with options["wildmode"]:
this.__defineGetter__(option.name, function () option.value);
this.__defineSetter__(option.name, function (value) { option.value = value; });
this._optionHash[option.name] = option;
return option;
},
/**
* Returns the names of all preferences.
*
* @param {string} branch The branch in which to search preferences.
* @default ""
*/
allPrefs: function (branch) services.get("prefs").getChildList(branch || "", { value: 0 }),
/**
* Returns the option with <b>name</b> in the specified <b>scope</b>.
*
* @param {string} name The option's name.
* @param {number} scope The option's scope (see {@link Option#scope}).
* @optional
* @returns {Option} The matching option.
*/
get: function (name, scope) {
if (!scope)
scope = Option.SCOPE_BOTH;
if (name in this._optionHash)
return (this._optionHash[name].scope & scope) && this._optionHash[name];
for (let opt in options) {
if (opt.hasName(name))
return (opt.scope & scope) && opt;
}
return null;
},
/**
* Lists all options in <b>scope</b> or only those with changed values
* if <b>onlyNonDefault</b> is specified.
*
* @param {boolean} onlyNonDefault Limit the list to prefs with a
* non-default value.
* @param {number} scope Only list options in this scope (see
* {@link Option#scope}).
*/
list: function (onlyNonDefault, scope) {
if (!scope)
scope = Option.SCOPE_BOTH;
function opts(opt) {
for (let opt in options) {
let option = {
isDefault: opt.value == opt.defaultValue,
name: opt.name,
default: opt.defaultValue,
pre: "\u00a0\u00a0", // Unicode nonbreaking space.
value: xml``
};
if (onlyNonDefault && option.isDefault)
continue;
if (!(opt.scope & scope))
continue;
if (opt.type == "boolean") {
if (!opt.value)
option.pre = "no";
option.default = (option.default ? "" : "no") + opt.name;
}
else
option.value = xml`=${template.highlight(opt.value)}`;
yield option;
}
};
let list = template.options("Options", opts());
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
},
/**
* Lists all preferences matching <b>filter</b> or only those with
* changed values if <b>onlyNonDefault</b> is specified.
*
* @param {boolean} onlyNonDefault Limit the list to prefs with a
* non-default value.
* @param {string} filter The list filter. A null filter lists all
* prefs.
* @optional
*/
listPrefs: function (onlyNonDefault, filter) {
if (!filter)
filter = "";
let prefArray = options.allPrefs();
prefArray.sort();
function prefs() {
for (let pref of prefArray) {
let userValue = services.get("prefs").prefHasUserValue(pref);
if (onlyNonDefault && !userValue || pref.indexOf(filter) == -1)
continue;
value = options.getPref(pref);
let option = {
isDefault: !userValue,
default: options._loadPreference(pref, null, true),
value: xml`${template.highlight(value, true, 100)}`,
name: pref,
pre: "\u00a0\u00a0" // Unicode nonbreaking space.
};
yield option;
}
};
let list = template.options(config.hostApplication + " Options", prefs());
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
},
/**
* Parses a :set command's argument string.
*
* @param {string} args The :set command's argument string.
* @param {Object} modifiers A hash of parsing modifiers. These are:
* scope - see {@link Option#scope}
* @optional
* @returns {Object} The parsed command object.
*/
parseOpt: function parseOpt(args, modifiers) {
let ret = {};
let matches, prefix, postfix, valueGiven;
[matches, prefix, ret.name, postfix, valueGiven, ret.operator, ret.value] =
args.match(/^\s*(no|inv)?([a-z_]*)([?&!])?\s*(([-+^]?)=(.*))?\s*$/) || [];
ret.args = args;
ret.onlyNonDefault = false; // used for :set to print non-default options
if (!args) {
ret.name = "all";
ret.onlyNonDefault = true;
}
if (matches)
ret.option = options.get(ret.name, ret.scope);
ret.prefix = prefix;
ret.postfix = postfix;
ret.all = (ret.name == "all");
ret.get = (ret.all || postfix == "?" || (ret.option && ret.option.type != "boolean" && !valueGiven));
ret.invert = (prefix == "inv" || postfix == "!");
ret.reset = (postfix == "&");
ret.unsetBoolean = (prefix == "no");
ret.scope = modifiers && modifiers.scope;
if (!ret.option)
return ret;
if (ret.value === undefined)
ret.value = "";
ret.optionValue = ret.option.get(ret.scope);
ret.optionValues = ret.option.getValues(ret.scope);
ret.values = ret.option.parseValues(ret.value);
return ret;
},
/**
* Remove the option with matching <b>name</b>.
*
* @param {string} name The name of the option to remove. This can be
* any of the options's names.
*/
remove: function (name) {
for each (let option in this._optionHash) {
if (option.hasName(name))
delete this._optionHash[option.name];
}
},
/** @property {Object} The options store. */
get store() storage.options,
/**
* Returns the value of the preference <b>name</b>.
*
* @param {string} name The preference name.
* @param {value} forcedDefault The default value for this
* preference. Used for internal liberator preferences.
*/
getPref: function (name, forcedDefault) {
return this._loadPreference(name, forcedDefault);
},
/**
* Sets the preference <b>name</b> to </b>value</b> but warns the user
* if the value is changed from its default.
*
* @param {string} name The preference name.
* @param {value} value The new preference value.
*/
// FIXME: Well it used to. I'm looking at you mst! --djk
safeSetPref: function (name, value, message) {
let val = this._loadPreference(name, null, false);
let def = this._loadPreference(name, null, true);
let lib = this._loadPreference(Options.SAVED + name);
if (lib == null && val != def || val != lib) {
let msg = "Warning: setting preference " + name + ", but it's changed from its default value.";
if (message)
msg += " " + message;
liberator.echomsg(msg);
}
this._storePreference(name, value);
this._storePreference(Options.SAVED + name, value);
},
/**
* Sets the preference <b>name</b> to </b>value</b>.
*
* @param {string} name The preference name.
* @param {value} value The new preference value.
*/
setPref: function (name, value) {
this._storePreference(name, value);
},
/**
* Resets the preference <b>name</b> to its default value.
*
* @param {string} name The preference name.
*/
resetPref: function (name) {
try {
services.get("prefs").clearUserPref(name);
}
catch (e) {
// ignore - thrown if not a user set value
}
},
/**
* Toggles the value of the boolean preference <b>name</b>.
*
* @param {string} name The preference name.
*/
invertPref: function (name) {
if (services.get("prefs").getPrefType(name) == Ci.nsIPrefBranch.PREF_BOOL)
this.setPref(name, !this.getPref(name));
else
liberator.echoerr("Trailing characters: " + name + "!");
},
/**
* Pushes a new preference context onto the context stack.
*
* @see #withContext
*/
pushContext: function () {
this._prefContexts.push({});
},
/**
* Pops the top preference context from the stack.
*
* @see #withContext
*/
popContext: function () {
for (let [k, v] in Iterator(this._prefContexts.pop()))
this._storePreference(k, v);
},
/**
* Executes <b>func</b> with a new preference context. When <b>func</b>
* returns, the context is popped and any preferences set via
* {@link #setPref} or {@link #invertPref} are restored to their
* previous values.
*
* @param {function} func The function to call.
* @param {Object} func The 'this' object with which to call <b>func</b>
* @see #pushContext
* @see #popContext
*/
withContext: function (func, self) {
try {
this.pushContext();
return func.call(self);
}
finally {
this.popContext();
}
},
_storePreference: function (name, value) {
if (this._prefContexts.length) {
let val = this._loadPreference(name, null);
if (val != null)
this._prefContexts[this._prefContexts.length - 1][name] = val;
}
let type = services.get("prefs").getPrefType(name);
switch (typeof value) {
case "string":
if (type == Ci.nsIPrefBranch.PREF_INVALID || type == Ci.nsIPrefBranch.PREF_STRING) {
let supportString = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
supportString.data = value;
services.get("prefs").setComplexValue(name, Ci.nsISupportsString, supportString);
}
else if (type == Ci.nsIPrefBranch.PREF_INT)
liberator.echoerr("Number required after =: " + name + "=" + value);
else
liberator.echoerr("Invalid argument: " + name + "=" + value);
break;
case "number":
if (type == Ci.nsIPrefBranch.PREF_INVALID || type == Ci.nsIPrefBranch.PREF_INT)
services.get("prefs").setIntPref(name, value);
else
liberator.echoerr("Invalid argument: " + name + "=" + value);
break;
case "boolean":
if (type == Ci.nsIPrefBranch.PREF_INVALID || type == Ci.nsIPrefBranch.PREF_BOOL)
services.get("prefs").setBoolPref(name, value);
else if (type == Ci.nsIPrefBranch.PREF_INT)
liberator.echoerr("Number required after =: " + name + "=" + value);
else
liberator.echoerr("Invalid argument: " + name + "=" + value);
break;
default:
liberator.echoerr("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")");
}
},
_loadPreference: function (name, forcedDefault, defaultBranch) {
let defaultValue = null; // XXX
if (forcedDefault != null) // this argument sets defaults for non-user settable options (like extensions.history.comp_history)
defaultValue = forcedDefault;
let branch = defaultBranch ? services.get("prefs").getDefaultBranch("") : services.get("prefs");
let type = services.get("prefs").getPrefType(name);
try {
switch (type) {
case Ci.nsIPrefBranch.PREF_STRING:
let value = branch.getComplexValue(name, Ci.nsISupportsString).data;
// try in case it's a localized string (will throw an exception if not)
if (!services.get("prefs").prefIsLocked(name) && !services.get("prefs").prefHasUserValue(name) &&
RegExp("chrome://.+/locale/.+\\.properties").test(value))
value = branch.getComplexValue(name, Ci.nsIPrefLocalizedString).data;
return value;
case Ci.nsIPrefBranch.PREF_INT:
return branch.getIntPref(name);
case Ci.nsIPrefBranch.PREF_BOOL:
return branch.getBoolPref(name);
default:
return defaultValue;
}
}
catch (e) {
return defaultValue;
}
}
}, {
SAVED: "extensions.liberator.saved.",
OLD_SAVED: "liberator.saved."
}, {
commandline: function () {
// TODO: maybe reset in .destroy()?
// TODO: move to buffer.js
// we have our own typeahead find implementation
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=348187
options.safeSetPref("accessibility.typeaheadfind.autostart", false);
options.safeSetPref("accessibility.typeaheadfind", false); // actually the above setting should do it, but has no effect in Firefox
},
commands: function () {
function setAction(args, modifiers) {
let bang = args.bang;
if (!args.length)
args[0] = "";
for (let [, arg] in args) {
if (bang) {
let onlyNonDefault = false;
let reset = false;
let invertBoolean = false;
if (args[0] == "") {
var name = "all";
onlyNonDefault = true;
}
else {
var [matches, name, postfix, valueGiven, operator, value] =
arg.match(/^\s*?([a-zA-Z0-9\.\-_{}]+)([?&!])?\s*(([-+^]?)=(.*))?\s*$/);
reset = (postfix == "&");
invertBoolean = (postfix == "!");
}
if (name == "all" && reset)
commandline.input("Warning: Resetting all preferences may make " + config.hostApplication + " unusable. Continue (yes/[no]): ",
function (resp) {
if (resp == "yes")
for (let pref in values(options.allPrefs()))
options.resetPref(pref);
},
{ promptHighlight: "WarningMsg" });
else if (name == "all")
options.listPrefs(onlyNonDefault, "");
else if (reset)
options.resetPref(name);
else if (invertBoolean)
options.invertPref(name);
else if (valueGiven) {
switch (value) {
case undefined:
value = "";
break;
case "true":
value = true;
break;
case "false":
value = false;
break;
default:
if (/^[+-]?\d+$/.test(value))
value = parseInt(value, 10);
}
options.setPref(name, value);
}
else
options.listPrefs(onlyNonDefault, name);
return;
}
let opt = options.parseOpt(arg, modifiers);
liberator.assert(opt, "Error parsing :set command: " + arg);
let option = opt.option;
liberator.assert(option != null || opt.all,
"Unknown option: " + opt.name);
// reset a variable to its default value
if (opt.reset) {
if (opt.all) {
for (let option in options)
option.reset();
}
else {
option.setFrom = modifiers.setFrom || null;
option.reset();
}
}
// read access
else if (opt.get) {
if (opt.all)
options.list(opt.onlyNonDefault, opt.scope);
else {
if (option.type == "boolean")
var msg = (opt.optionValue ? " " : "no") + option.name;
else
msg = " " + option.name + "=" + opt.optionValue;
if (options["verbose"] > 0 && option.setFrom)
msg += "\n Last set from " + option.setFrom.path;
// FIXME: Message highlight group wrapping messes up the indent up for multi-arg verbose :set queries
liberator.echo(xml`<span highlight="CmdOutput">${msg}</span>`);
}
}
// write access
// NOTE: the behavior is generally Vim compatible but could be
// improved. i.e. Vim's behavior is pretty sloppy to no real benefit
else {
option.setFrom = modifiers.setFrom || null;
if (option.type == "boolean") {
if (opt.unsetBoolean) {
opt.values = false;
} else {
switch (opt.value) {
case "":
case "true":
opt.values = true;
break;
case "false":
opt.values = false;
break;
default:
return liberator.echoerr("Invalid argument: " + arg);
}
}
}
let res = opt.option.op(opt.operator || "=", opt.values, opt.scope, opt.invert);
if (res)
liberator.echoerr(res);
}
}
}
function setCompleter(context, args, modifiers) {
let filter = context.filter;
if (args.bang) { // list completions for about:config entries
if (filter[filter.length - 1] == "=") {
context.advance(filter.length);
filter = filter.substr(0, filter.length - 1);
context.completions = [
[options._loadPreference(filter, null, false), "Current Value"],
[options._loadPreference(filter, null, true), "Default Value"]
].filter(function ([k]) k != null);
return null;
}
return completion.preference(context);
}
let opt = options.parseOpt(filter, modifiers);
let prefix = opt.prefix;
if (context.filter.indexOf("=") == -1) {
if (prefix)
context.filters.push(function ({ item: opt }) opt.type == "boolean" || prefix == "inv" && opt.values instanceof Array);
return completion.option(context, opt.scope);
}
else if (prefix == "no")
return null;
let option = opt.option;
context.advance(context.filter.indexOf("=") + 1);
if (!option) {
context.message = "No such option: " + opt.name;
context.highlight(0, name.length, "SPELLCHECK");
}
if (opt.get || opt.reset || !option || prefix)
return null;
context.fork("default", 0, this, function (context) {
context.title = ["Extra Completions"];
let completions = [
[option.value, "Current value"],
[option.defaultValue, "Default value"]
];
if (option.type == "boolean") {
completions.push([!option.value, "Inverted current value"]);
context.completions = completions;
} else {
context.completions = completions.filter(function (f) f[0] != "");
}
});
return context.fork("values", 0, completion, "optionValue", opt.name, opt.operator);
}
commands.add(["let"],
"Set or list a variable",
function (args) {
args = args.string;
if (!args) {
var hasRow = false;
let str =
xml`<table>
${
template.map2(xml, liberator.globalVariables, function ([i, value]) {
let prefix = typeof value == "number" ? "#" :
typeof value == "function" ? "*" :
" ";
if (!hasRow) hasRow = true;
return xml`<tr>
<td style="width: 200px;">${i}</td>
<td>${prefix}${value}</td>
</tr>`;
})
}
</table>`;
if (hasRow)
liberator.echo(str, commandline.FORCE_MULTILINE);
else
liberator.echomsg("No variables found");
return;
}
// 1 - type, 2 - name, 3 - +-., 4 - expr
let matches = args.match(/([$@&])?([\w:]+)\s*([-+.])?=\s*(.+)/);
if (matches) {
let [, type, name, stuff, expr] = matches;
if (!type) {
let reference = liberator.variableReference(name);
liberator.assert(reference[0] || !stuff, "Undefined variable: " + name);
expr = liberator.evalExpression(expr);
liberator.assert(expr !== undefined, "Invalid expression: " + expr);
if (!reference[0]) {
if (reference[2] == "g")
reference[0] = liberator.globalVariables;
else
return; // for now
}
if (stuff) {
if (stuff == "+")
reference[0][reference[1]] += expr;
else if (stuff == "-")
reference[0][reference[1]] -= expr;
else if (stuff == ".")
reference[0][reference[1]] += expr.toString();
}
else
reference[0][reference[1]] = expr;
}
}
// 1 - name
else if ((matches = args.match(/^\s*([\w:]+)\s*$/))) {
let reference = liberator.variableReference(matches[1]);
liberator.assert(reference[0], "Undefined variable: " + matches[1]);
let value = reference[0][reference[1]];
let prefix = typeof value == "number" ? "#" :
typeof value == "function" ? "*" :
" ";
liberator.echo(reference[1] + "\t\t" + prefix + value);
}
},
{
literal: 0
}
);
commands.add(["setl[ocal]"],
"Set local option",
function (args, modifiers) {
modifiers.scope = Option.SCOPE_LOCAL;
setAction(args, modifiers);
},
{
bang: true,
count: true,
completer: function (context, args) {
return setCompleter(context, args, { scope: Option.SCOPE_LOCAL });
},
literal: 0
}
);
commands.add(["setg[lobal]"],
"Set global option",
function (args, modifiers) {
modifiers.scope = Option.SCOPE_GLOBAL;
setAction(args, modifiers);
},
{
bang: true,
count: true,
completer: function (context, args) {
return setCompleter(context, args, { scope: Option.SCOPE_GLOBAL });
},
literal: 0
}
);
commands.add(["se[t]"],
"Set an option",
function (args, modifiers) { setAction(args, modifiers); },
{
bang: true,
completer: function (context, args) {
return setCompleter(context, args);
},
serial: function () [
{
command: this.name,
arguments: [opt.type == "boolean" ? (opt.value ? "" : "no") + opt.name
: opt.name + "=" + opt.value]
}
for (opt in options)
if (!opt.getter && opt.value != opt.defaultValue && (opt.scope & Option.SCOPE_GLOBAL))
]
});
commands.add(["unl[et]"],
"Delete a variable",
function (args) {
for (let [, name] in args) {
let reference = liberator.variableReference(name);
if (!reference[0]) {
if (!args.bang)
liberator.echoerr("No such variable: " + name);
return;
}
delete reference[0][reference[1]];
}
},
{
argCount: "+",
bang: true
});
},
completion: function () {
JavaScript.setCompleter(this.get, [function () ([o.name, o.description] for (o in options))]);
JavaScript.setCompleter([this.getPref, this.safeSetPref, this.setPref, this.resetPref, this.invertPref],
[function () options.allPrefs().map(function (pref) [pref, ""])]);
completion.option = function option(context, scope) {
context.title = ["Option"];
context.keys = { text: "names", description: "description" };
context.completions = options;
if (scope)
context.filters.push(function ({ item: opt }) opt.scope & scope);
};
completion.optionValue = function (context, name, op, curValue) {
let opt = options.get(name);
let completer = opt.completer;
if (!completer)
return;
let curValues = curValue != null ? opt.parseValues(curValue) : opt.values;
let newValues = opt.parseValues(context.filter);
let len = context.filter.length;
switch (opt.type) {
case "boolean":
completer = function () [["true", ""], ["false", ""]];
break;
case "stringlist":
let target = newValues.pop();
len = target ? target.length : 0;
break;
case "charlist":
len = 0;
break;
}
// TODO: Highlight when invalid
context.advance(context.filter.length - len);
context.title = ["Option Value"];
let completions = completer(context);
if (!completions)
return;
// Not Vim compatible, but is a significant enough improvement
// that it's worth breaking compatibility.
if (newValues instanceof Array) {
completions = completions.filter(function (val) newValues.indexOf(val[0]) == -1);
switch (op) {
case "+":
completions = completions.filter(function (val) curValues.indexOf(val[0]) == -1);
break;
case "-":
completions = completions.filter(function (val) curValues.indexOf(val[0]) > -1);
break;
}
}
context.completions = completions;
};
completion.preference = function preference(context) {
context.anchored = false;
context.title = [config.hostApplication + " Preference", "Value"];
context.keys = { text: function (item) item, description: function (item) options.getPref(item) };
context.completions = options.allPrefs();
};
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
// TODO: Clean this up.
const JavaScript = Module("javascript", {
init: function () {
this._stack = [];
this._functions = [];
this._top = {}; // The element on the top of the stack.
this._last = ""; // The last opening char pushed onto the stack.
this._lastNonwhite = ""; // Last non-whitespace character we saw.
this._lastChar = ""; // Last character we saw, used for \ escaping quotes.
this._str = "";
this._lastIdx = 0;
this._cacheKey = null;
},
get completers() JavaScript.completers, // For backward compatibility
// Some object members are only accessible as function calls
getKey: function (obj, key) {
try {
return obj[key];
}
catch (e) {
return undefined;
}
},
iter: function iter(obj, toplevel) {
toplevel = !!toplevel;
let seen = {};
try {
let orig = obj;
function iterObj(obj, toplevel) {
function isXPCNativeWrapper(obj) isobject(obj) && XPCNativeWrapper.unwrap(obj) !== obj
if (isXPCNativeWrapper(obj)) {
if (toplevel) {
yield {get wrappedJSObject() 0};
}
// according to http://getfirebug.com/wiki/index.php/Using_win.wrappedJSObject
// using a wrappedJSObject itself is safe, as potential functions are always
// run in page context, not in chrome context.
// However, as we really need to make sure, values coming
// from content scope are never used in unsecured eval(),
// we dissallow unwrapping objects for now, unless the user
// uses an (undocumented) option 'unwrapjsobjects'
else if (options["inspectcontentobjects"]) {
obj = obj.wrappedJSObject;
}
}
if (toplevel)
yield obj;
else
for (let o = obj.__proto__; o; o = o.__proto__)
yield o;
}
for (let obj in iterObj(orig, toplevel)) {
for (let k of Object.getOwnPropertyNames(obj)) {
let name = "|" + k;
if (name in seen)
continue;
seen[name] = 1;
yield [k, this.getKey(orig, k)];
}
}
}
catch (ex) {
// TODO: report error?
}
},
// Search the object for strings starting with @key.
// If @last is defined, key is a quoted string, it's
// wrapped in @last after @offset characters are sliced
// off of it and it's quoted.
objectKeys: function objectKeys(obj, toplevel) {
// Things we can dereference
if (["object", "string", "function"].indexOf(typeof obj) == -1)
return [];
if (!obj)
return [];
let completions;
if (modules.isPrototypeOf(obj))
completions = [v for (v in Iterator(obj))];
else {
completions = [k for (k in this.iter(obj, toplevel))];
if (!toplevel)
completions = util.Array.uniq(completions, true);
}
// Add keys for sorting later.
// Numbers are parsed to ints.
// Constants, which should be unsorted, are found and marked null.
completions.forEach(function (item) {
let key = item[0];
if (!isNaN(key))
key = parseInt(key);
else if (/^[A-Z_][A-Z0-9_]*$/.test(key))
key = "";
item.key = key;
});
return completions;
},
eval: function eval(arg, key, tmp) {
let cache = this.context.cache.eval;
let context = this.context.cache.evalContext;
if (!key)
key = arg;
if (key in cache)
return cache[key];
context[JavaScript.EVAL_TMP] = tmp;
try {
return cache[key] = liberator.eval(arg, context);
}
catch (e) {
return null;
}
finally {
delete context[JavaScript.EVAL_TMP];
}
},
// Get an element from the stack. If @frame is negative,
// count from the top of the stack, otherwise, the bottom.
// If @nth is provided, return the @mth value of element @type
// of the stack entry at @frame.
_get: function (frame, nth, type) {
let a = this._stack[frame >= 0 ? frame : this._stack.length + frame];
if (type != null)
a = a[type];
if (nth == null)
return a;
return a[a.length - nth - 1];
},
// Push and pop the stack, maintaining references to 'top' and 'last'.
_push: function push(arg) {
this._top = {
offset: this._i,
char: arg,
statements: [this._i],
dots: [],
fullStatements: [],
comma: [],
functions: []
};
this._last = this._top.char;
this._stack.push(this._top);
},
_pop: function pop(arg) {
if (this._top.char != arg) {
this.context.highlight(this._top.offset, this._i - this._top.offset, "SPELLCHECK");
this.context.highlight(this._top.offset, 1, "FIND");
throw new Error("Invalid JS");
}
if (this._i == this.context.caret - 1)
this.context.highlight(this._top.offset, 1, "FIND");
// The closing character of this stack frame will have pushed a new
// statement, leaving us with an empty statement. This doesn't matter,
// now, as we simply throw away the frame when we pop it, but it may later.
if (this._top.statements[this._top.statements.length - 1] == this._i)
this._top.statements.pop();
this._top = this._get(-2);
this._last = this._top.char;
let ret = this._stack.pop();
return ret;
},
_buildStack: function (filter) {
let self = this;
// Todo: Fix these one-letter variable names.
this._i = 0;
this._c = ""; // Current index and character, respectively.
// Reuse the old stack.
if (this._str && filter.substr(0, this._str.length) == this._str) {
this._i = this._str.length;
if (this.popStatement)
this._top.statements.pop();
}
else {
this._stack = [];
this._functions = [];
this._push("#root");
}
// Build a parse stack, discarding entries as opening characters
// match closing characters. The stack is walked from the top entry
// and down as many levels as it takes us to figure out what it is
// that we're completing.
this._str = filter;
let length = this._str.length;
for (; this._i < length; this._lastChar = this._c, this._i++) {
this._c = this._str[this._i];
if (this._last == '"' || this._last == "'" || this._last == "/") {
if (this._lastChar == "\\") { // Escape. Skip the next char, whatever it may be.
this._c = "";
this._i++;
}
else if (this._c == this._last)
this._pop(this._c);
} else if (this._last === "`") {
if (this._lastChar == "\\") { // Escape. Skip the next char, whatever it may be.
this._c = "";
this._i++;
}
else if (this._c == "`") {
this._pop("`");
this._pop("``");
} else if (this._c === "{" && this._lastChar === "$") {
this._pop("`");
this._push("{");
}
} else {
// A word character following a non-word character, or simply a non-word
// character. Start a new statement.
if (/[a-zA-Z_$]/.test(this._c) && !/[\w$]/.test(this._lastChar) || !/[\w\s$]/.test(this._c))
this._top.statements.push(this._i);
// A "." or a "[" dereferences the last "statement" and effectively
// joins it to this logical statement.
if ((this._c == "." || this._c == "[") && /[\w$\])"']/.test(this._lastNonwhite)
|| this._lastNonwhite == "." && /[a-zA-Z_$]/.test(this._c))
this._top.statements.pop();
switch (this._c) {
case "(":
// Function call, or if/while/for/...
if (/[\w$]/.test(this._lastNonwhite)) {
this._functions.push(this._i);
this._top.functions.push(this._i);
this._top.statements.pop();
}
case '"':
case "'":
case "/":
case "{":
this._push(this._c);
break;
case "[":
this._push(this._c);
break;
case ".":
this._top.dots.push(this._i);
break;
case ")": this._pop("("); break;
case "]": this._pop("["); break;
case "}": this._pop("{"); // Fallthrough
if (this._last === "``") {
this._push("`");
break;
}
case ";":
this._top.fullStatements.push(this._i);
break;
case ",":
this._top.comma.push(this._i);
break;
case "`":
this._push("``");
this._push("`");
break;
}
if (/\S/.test(this._c))
this._lastNonwhite = this._c;
}
}
this.popStatement = false;
if (!/[\w$]/.test(this._lastChar) && this._lastNonwhite != ".") {
this.popStatement = true;
this._top.statements.push(this._i);
}
this._lastIdx = this._i;
},
// Don't eval any function calls unless the user presses tab.
_checkFunction: function (start, end, key) {
let res = this._functions.some(function (idx) idx >= start && idx < end);
if (!res || this.context.tabPressed || key in this.cache.eval)
return false;
this.context.waitingForTab = true;
return true;
},
// For each DOT in a statement, prefix it with TMP, eval it,
// and save the result back to TMP. The point of this is to
// cache the entire path through an object chain, mainly in
// the presence of function calls. There are drawbacks. For
// instance, if the value of a variable changes in the course
// of inputting a command (let foo=bar; frob(foo); foo=foo.bar; ...),
// we'll still use the old value. But, it's worth it.
_getObj: function (frame, stop) {
let statement = this._get(frame, 0, "statements") || 0; // Current statement.
let prev = statement;
let obj;
let cacheKey;
for (let dot of this._get(frame).dots.concat(stop)) {
if (dot < statement)
continue;
if (dot > stop || dot <= prev)
break;
let s = this._str.substring(prev, dot);
if (prev != statement)
s = JavaScript.EVAL_TMP + "." + s;
cacheKey = this._str.substring(statement, dot);
if (this._checkFunction(prev, dot, cacheKey))
return [];
prev = dot + 1;
obj = this.eval(s, cacheKey, obj);
}
return [[obj, cacheKey]];
},
_getObjKey: function (frame) {
let dot = this._get(frame, 0, "dots") || -1; // Last dot in frame.
let statement = this._get(frame, 0, "statements") || 0; // Current statement.
let end = (frame == -1 ? this._lastIdx : this._get(frame + 1).offset);
this._cacheKey = null;
let obj = [[this.cache.evalContext, "Local Variables"],
[userContext, "Global Variables"],
[modules, "modules"],
[window, "window"]]; // Default objects;
// Is this an object dereference?
if (dot < statement) // No.
dot = statement - 1;
else // Yes. Set the object to the string before the dot.
obj = this._getObj(frame, dot);
let [, space, key] = this._str.substring(dot + 1, end).match(/^(\s*)(.*)/);
return [dot + 1 + space.length, obj, key];
},
_fill: function (context, obj, name, compl, anchored, key, last, offset) {
context.title = [name];
context.anchored = anchored;
context.filter = key;
context.itemCache = context.parent.itemCache;
context.key = name;
if (last != null)
context.quote = [last, function (text) util.escapeString(text.substr(offset), ""), last];
else // We're not looking for a quoted string, so filter out anything that's not a valid identifier
context.filters.push(function (item) /^[a-zA-Z_$][\w$]*$/.test(item.text));
compl.call(self, context, obj);
},
_complete: function (objects, key, compl, string, last) {
const self = this;
let orig = compl;
if (!compl) {
compl = function (context, obj, recurse) {
context.process = [null, function highlight(item, v) template.highlight(v, true)];
// Sort in a logical fashion for object keys:
// Numbers are sorted as numbers, rather than strings, and appear first.
// Constants are unsorted, and appear before other non-null strings.
// Other strings are sorted in the default manner.
let compare = context.compare;
function isnan(item) item != '' && isNaN(item);
context.compare = function (a, b) {
if (!isnan(a.item.key) && !isnan(b.item.key))
return a.item.key - b.item.key;
return isnan(b.item.key) - isnan(a.item.key) || compare(a, b);
};
if (!context.anchored) // We've already listed anchored matches, so don't list them again here.
context.filters.push(function (item) util.compareIgnoreCase(item.text.substr(0, this.filter.length), this.filter));
if (obj == self.cache.evalContext)
context.regenerate = true;
context.generate = function () self.objectKeys(obj, !recurse);
};
}
// TODO: Make this a generic completion helper function.
let filter = key + (string || "");
for (let obj of objects) {
this.context.fork(obj[1], this._top.offset, this, this._fill,
obj[0], obj[1], compl,
true, filter, last, key.length);
}
if (orig)
return;
for (let obj of objects) {
let name = obj[1] + " (prototypes)";
this.context.fork(name, this._top.offset, this, this._fill,
obj[0], name, function (a, b) compl(a, b, true),
true, filter, last, key.length);
}
for (let obj of objects) {
let name = obj[1] + " (substrings)";
this.context.fork(name, this._top.offset, this, this._fill,
obj[0], name, compl,
false, filter, last, key.length);
}
for (let obj of objects) {
let name = obj[1] + " (prototype substrings)";
this.context.fork(name, this._top.offset, this, this._fill,
obj[0], name, function (a, b) compl(a, b, true),
false, filter, last, key.length);
}
},
_getKey: function () {
if (this._last == "")
return "";
// After the opening [ upto the opening ", plus '' to take care of any operators before it
let key = this._str.substring(this._get(-2, 0, "statements"), this._get(-1, null, "offset")) + "''";
// Now eval the key, to process any referenced variables.
return this.eval(key);
},
get cache() this.context.cache,
complete: function _complete(context) {
const self = this;
this.context = context;
try {
this._buildStack.call(this, context.filter);
}
catch (e) {
if (e.message != "Invalid JS")
liberator.echoerr(e);
this._lastIdx = 0;
return null;
}
this.context.getCache("eval", Object);
this.context.getCache("evalContext", function () Object.create(userContext));
// Okay, have parse stack. Figure out what we're completing.
// Find any complete statements that we can eval before we eval our object.
// This allows for things like: let doc = window.content.document; let elem = doc.createElement...; elem.<Tab>
let prev = 0;
for (let v of this._get(0).fullStatements) {
let key = this._str.substring(prev, v + 1);
if (this._checkFunction(prev, v, key))
return null;
this.eval(key);
prev = v + 1;
}
// In a string. Check if we're dereferencing an object.
// Otherwise, do nothing.
if (this._last == "'" || this._last == '"' || this._last == "`") {
//
// str = "foo[bar + 'baz"
// obj = "foo"
// key = "bar + ''"
//
// The top of the stack is the sting we're completing.
// Wrap it in its delimiters and eval it to process escape sequences.
let string = this._str.substring(this._get(-1).offset + 1, this._lastIdx);
string = eval(this._last + string + this._last);
// Is this an object accessor?
if (this._get(-2).char == "[") { // Are we inside of []?
// Stack:
// [-1]: "...
// [-2]: [...
// [-3]: base statement
// Yes. If the [ starts at the beginning of a logical
// statement, we're in an array literal, and we're done.
if (this._get(-3, 0, "statements") == this._get(-2).offset)
return null;
// Beginning of the statement upto the opening [
let obj = this._getObj(-3, this._get(-2).offset);
return this._complete(obj, this._getKey(), null, string, this._last);
}
// Is this a function call?
if (this._get(-2).char == "(") {
// Stack:
// [-1]: "...
// [-2]: (...
// [-3]: base statement
// Does the opening "(" mark a function call?
if (this._get(-3, 0, "functions") != this._get(-2).offset)
return null; // No. We're done.
let [offset, obj, func] = this._getObjKey(-3);
if (!obj.length)
return null;
obj = obj.slice(0, 1);
try {
var completer = obj[0][0][func].liberatorCompleter;
}
catch (e) {}
if (!completer)
completer = JavaScript.completers[func];
if (!completer)
return null;
// Split up the arguments
let prev = this._get(-2).offset;
let args = [];
let i = 0;
for (let idx of this._get(-2).comma) {
let arg = this._str.substring(prev + 1, idx);
prev = idx;
util.memoize(args, i, function () self.eval(arg));
++i;
}
let key = this._getKey();
args.push(key + string);
var compl = function (context, obj) {
let res = completer.call(self, context, func, obj, args);
if (res)
context.completions = res;
};
obj[0][1] += "." + func + "(... [" + args.length + "]";
return this._complete(obj, key, compl, string, this._last);
}
// In a string that's not an obj key or a function arg.
// Nothing to do.
return null;
}
//
// str = "foo.bar.baz"
// obj = "foo.bar"
// key = "baz"
//
// str = "foo"
// obj = [modules, window]
// key = "foo"
//
let [offset, obj, key] = this._getObjKey(-1);
// Wait for a keypress before completing the default objects.
if (!this.context.tabPressed && key == "" && obj.length > 1) {
this.context.waitingForTab = true;
this.context.message = "Waiting for key press";
return null;
}
if (!/^(?:[a-zA-Z_$][\w$]*)?$/.test(key))
return null; // Not a word. Forget it. Can this even happen?
try { // FIXME
var o = this._top.offset;
this._top.offset = offset;
return this._complete(obj, key);
}
finally {
this._top.offset = o;
}
return null;
}
}, {
EVAL_TMP: "__liberator_eval_tmp",
/**
* A map of argument completion functions for named methods. The
* signature and specification of the completion function
* are fairly complex and yet undocumented.
*
* @see JavaScript.setCompleter
*/
completers: {},
/**
* Installs argument string completers for a set of functions.
* The second argument is an array of functions (or null
* values), each corresponding the argument of the same index.
* Each provided completion function receives as arguments a
* CompletionContext, the 'this' object of the method, and an
* array of values for the preceding arguments.
*
* It is important to note that values in the arguments array
* provided to the completers are lazily evaluated the first
* time they are accessed, so they should be accessed
* judiciously.
*
* @param {function|function[]} funcs The functions for which to
* install the completers.
* @param {function[]} completers An array of completer
* functions.
*/
setCompleter: function (funcs, completers) {
funcs = Array.concat(funcs);
for (let func of funcs) {
func.liberatorCompleter = function (context, func, obj, args) {
let completer = completers[args.length - 1];
if (!completer)
return [];
return completer.call(this, context, obj, args);
};
}
}
}, {
completion: function () {
completion.javascript = this.closure.complete;
completion.javascriptCompleter = JavaScript; // Backwards compatibility.
},
options: function () {
options.add(["inspectcontentobjects"],
"Allow completion of JavaScript objects coming from web content. POSSIBLY INSECURE!",
"boolean", false);
options.add(["expandtemplate"],
"Expand TemplateLiteral",
"boolean", !("XMLList" in window));
}
})
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/** @instance hints */
const Hints = Module("hints", {
requires: ["config"],
init: function () {
this._hintMode = null;
this._submode = ""; // used for extended mode, can be "o", "t", "y", etc.
this._hintString = ""; // the typed string part of the hint is in this string
this._hintNumber = 0; // only the numerical part of the hint
this._usedTabKey = false; // when we used <Tab> to select an element
this._prevInput = ""; // record previous user input type, "text" || "number"
this._extendedhintCount = null; // for the count argument of Mode#action (extended hint only)
this._pageHints = [];
this._validHints = []; // store the indices of the "hints" array with valid elements
this._tabNavigation = {}; // for navigating between valid hints when TAB key is pressed
this._activeTimeout = null; // needed for hinttimeout > 0
this._canUpdate = false;
// keep track of the documents which we generated the hints for
// this._docs = { doc: document, start: start_index in hints[], end: end_index in hints[] }
this._docs = [];
const Mode = Hints.Mode;
Mode.defaultValue("tags", function () function () options.hinttags);
function extended() options.extendedhinttags;
function images() "//*[@src]";
this._hintModes = {
";": Mode("Focus hint", function (elem) buffer.focusElement(elem), extended),
"?": Mode("Show information for hint", function (elem) buffer.showElementInfo(elem), extended),
s: Mode("Save link", function (elem) buffer.saveLink(elem, true)),
S: Mode("Save object", function (elem) buffer.saveLink(elem, true), images),
a: Mode("Save link with prompt", function (elem) buffer.saveLink(elem, false)),
A: Mode("Save object with prompt", function (elem) buffer.saveLink(elem, false), images),
f: Mode("Focus frame", function (elem) Buffer.focusedWindow = elem.ownerDocument.defaultView, function () util.makeXPath(["body"])),
o: Mode("Follow hint", function (elem) buffer.followLink(elem, liberator.CURRENT_TAB)),
t: Mode("Follow hint in a new tab", function (elem) buffer.followLink(elem, liberator.NEW_TAB)),
b: Mode("Follow hint in a background tab", function (elem) buffer.followLink(elem, liberator.NEW_BACKGROUND_TAB)),
w: Mode("Follow hint in a new window", function (elem) buffer.followLink(elem, liberator.NEW_WINDOW), extended),
F: Mode("Open multiple hints in tabs", followAndReshow),
O: Mode("Generate an ':open URL' using hint", function (elem, loc) commandline.open("", "open " + loc, modes.EX)),
T: Mode("Generate a ':tabopen URL' using hint", function (elem, loc) commandline.open("", "tabopen " + loc, modes.EX)),
W: Mode("Generate a ':winopen URL' using hint", function (elem, loc) commandline.open("", "winopen " + loc, modes.EX)),
v: Mode("View hint source", function (elem, loc) buffer.viewSource(loc, false), extended),
V: Mode("View hint source in external editor", function (elem, loc) buffer.viewSource(loc, true), extended),
y: Mode("Yank hint location", function (elem, loc) util.copyToClipboard(loc, true)),
Y: Mode("Yank hint description", function (elem) util.copyToClipboard(elem.textContent || "", true), extended),
c: Mode("Open context menu", function (elem) buffer.openContextMenu(elem), extended),
i: Mode("Show media object", function (elem) liberator.open(elem.src), images),
I: Mode("Show media object in a new tab", function (elem) liberator.open(elem.src, liberator.NEW_TAB), images),
x: Mode("Show hint's title or alt text", function (elem) liberator.echo(elem.title ? "title: " + elem.title : "alt: " + elem.alt), function() "//*[@title or @alt]")
};
/**
* Follows the specified hint and then reshows all hints. Used to open
* multiple hints in succession.
*
* @param {Node} elem The selected hint.
*/
function followAndReshow(elem) {
buffer.followLink(elem, liberator.NEW_BACKGROUND_TAB);
// TODO: Maybe we find a *simple* way to keep the hints displayed rather than
// showing them again, or is this short flash actually needed as a "usability
// feature"? --mst
hints.show("F");
}
},
/**
* Reset hints, so that they can be cleanly used again.
*/
_reset: function () {
statusline.updateField("input", "");
this._hintString = "";
this._hintNumber = 0;
this._usedTabKey = false;
this._prevInput = "";
this._pageHints = [];
this._validHints = [];
this._tabNavigation = {};
this._canUpdate = false;
this._docs = [];
hints.escNumbers = false;
if (this._activeTimeout)
clearTimeout(this._activeTimeout);
this._activeTimeout = null;
},
/**
* Display the current status to the user.
*/
_updateStatusline: function () {
statusline.updateField("input", (hints.escNumbers ? mappings.getMapLeader() : "") + (this._hintNumber ? this._num2chars(this._hintNumber) : ""));
},
/**
* Get a hint for "input", "textarea" and "select".
*
* Tries to use <label>s if possible but does not try to guess that a
* neighbouring element might look like a label. Only called by
* {@link #_generate}.
*
* If it finds a hint it returns it, if the hint is not the caption of the
* element it will return showText=true.
*
* @param {Object} elem The element used to generate hint text.
* @param {Document} doc The containing document.
*
* @returns [text, showText]
*/
_getInputHint: function (elem, doc) {
// <input type="submit|button|reset"/> Always use the value
// <input type="radio|checkbox"/> Use the value if it is not numeric or label or name
// <input type="password"/> Never use the value, use label or name
// <input type="text|file"/> <textarea/> Use value if set or label or name
// <input type="image"/> Use the alt text if present (showText) or label or name
// <input type="hidden"/> Never gets here
// <select/> Use the text of the selected item or label or name
let type = elem.type;
if (elem instanceof HTMLInputElement && /(submit|button|reset)/.test(type))
return [elem.value, false];
else {
for (let option of options["hintinputs"].split(",")) {
switch (option) {
case "value":
if (elem instanceof HTMLSelectElement) {
if (elem.selectedIndex >= 0)
return [elem.item(elem.selectedIndex).text.toLowerCase(), false];
}
else if (type == "image") {
if (elem.alt)
return [elem.alt.toLowerCase(), true];
}
else if (elem.value && type != "password") {
// radio's and checkboxes often use internal ids as values - maybe make this an option too...
if (! ((type == "radio" || type == "checkbox") && !isNaN(elem.value)))
return [elem.value.toLowerCase(), (type == "radio" || type == "checkbox")];
}
break;
case "label":
if (elem.id) {
// TODO: (possibly) do some guess work for label-like objects
let label = util.evaluateXPath(["label[@for=" + elem.id.quote() + "]"], doc).snapshotItem(0);
if (label)
return [label.textContent.toLowerCase(), true];
}
break;
case "name":
return [elem.name.toLowerCase(), true];
}
}
}
return ["", false];
},
/**
* Gets the actual offset of an imagemap area.
*
* Only called by {@link #_generate}.
*
* @param {Object} elem The <area> element.
* @param {number} leftPos The left offset of the image.
* @param {number} topPos The top offset of the image.
* @returns [leftPos, topPos] The updated offsets.
*/
_getAreaOffset: function (elem, leftPos, topPos) {
try {
// Need to add the offset to the area element.
// Always try to find the top-left point, as per liberator default.
let shape = elem.getAttribute("shape").toLowerCase();
let coordStr = elem.getAttribute("coords");
// Technically it should be only commas, but hey
coordStr = coordStr.replace(/\s+[;,]\s+/g, ",").replace(/\s+/g, ",");
let coords = coordStr.split(",").map(Number);
if ((shape == "rect" || shape == "rectangle") && coords.length == 4) {
leftPos += coords[0];
topPos += coords[1];
}
else if (shape == "circle" && coords.length == 3) {
leftPos += coords[0] - coords[2] / Math.sqrt(2);
topPos += coords[1] - coords[2] / Math.sqrt(2);
}
else if ((shape == "poly" || shape == "polygon") && coords.length % 2 == 0) {
let leftBound = Infinity;
let topBound = Infinity;
// First find the top-left corner of the bounding rectangle (offset from image topleft can be noticably suboptimal)
for (let i = 0; i < coords.length; i += 2) {
leftBound = Math.min(coords[i], leftBound);
topBound = Math.min(coords[i + 1], topBound);
}
let curTop = null;
let curLeft = null;
let curDist = Infinity;
// Then find the closest vertex. (we could generalise to nearest point on an edge, but I doubt there is a need)
for (let i = 0; i < coords.length; i += 2) {
let leftOffset = coords[i] - leftBound;
let topOffset = coords[i + 1] - topBound;
let dist = Math.sqrt(leftOffset * leftOffset + topOffset * topOffset);
if (dist < curDist) {
curDist = dist;
curLeft = coords[i];
curTop = coords[i + 1];
}
}
// If we found a satisfactory offset, let's use it.
if (curDist < Infinity)
return [leftPos + curLeft, topPos + curTop];
}
}
catch (e) {} // badly formed document, or shape == "default" in which case we don't move the hint
return [leftPos, topPos];
},
// the containing block offsets with respect to the viewport
_getContainerOffsets: function (doc) {
try {
var body = doc.body || doc.documentElement;
} catch (e) {
return [null, null];
}
// TODO: getComputedStyle returns null for Facebook channel_iframe doc - probable Gecko bug.
let style = util.computedStyle(body);
if (style && /^(absolute|fixed|relative)$/.test(style.position)) {
let rect = body.getClientRects()[0];
return [-rect.left, -rect.top];
}
else
return [doc.defaultView.scrollX, doc.defaultView.scrollY];
},
/**
* Returns true if element is visible.
*
* Only called by {@link #_generate}.
*/
_isVisible: function (elem, screen) {
let doc = elem.ownerDocument;
let win = doc.defaultView;
// TODO: for iframes, this calculation is wrong
let rect = elem.getBoundingClientRect();
if (!rect || rect.top > screen.bottom || rect.bottom < screen.top || rect.left > screen.right || rect.right < screen.left)
return false;
rect = elem.getClientRects()[0];
if (!rect)
return false;
let computedStyle = doc.defaultView.getComputedStyle(elem, null);
if (computedStyle.getPropertyValue("visibility") != "visible" || computedStyle.getPropertyValue("display") == "none")
return false;
return true;
},
/**
* Generate the hints in a window.
*
* Pushes the hints into the pageHints object, but does not display them.
*
* @param {Window} win The window for which to generate hints.
* @default config.browser.contentWindow
*/
_generate: function (win, screen) {
if (!win)
win = config.browser.contentWindow;
if (!screen)
screen = {top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth};
let doc = win.document;
let baseNodeAbsolute = util.xmlToDom(xml`<span highlight="Hint"/>`, doc);
let res = util.evaluateXPath(this._hintMode.tags(), doc, null, true);
let fragment = util.xmlToDom(xml`<div highlight="hints" style="position:fixed;top:0;left:0px;"/>`, doc);
let pageHints = this._pageHints;
let start = this._pageHints.length;
let elem;
let that = this;
function makeHint (elem) {
let rect = elem.getClientRects()[0];
let hint = { elem: elem, showText: false };
if (elem instanceof HTMLInputElement || elem instanceof HTMLSelectElement || elem instanceof HTMLTextAreaElement)
[hint.text, hint.showText] = that._getInputHint(elem, doc);
else
hint.text = elem.textContent.toLowerCase();
hint.span = baseNodeAbsolute.cloneNode(true);
let leftPos = rect.left > screen.left ? rect.left : screen.left;
let topPos = rect.top > screen.top ? rect.top : screen.top;
if (elem instanceof HTMLAreaElement)
[leftPos, topPos] = that._getAreaOffset(elem, leftPos, topPos);
hint.span.style.left = leftPos + "px";
hint.span.style.top = topPos + "px";
fragment.appendChild(hint.span);
pageHints[pageHints.length] = hint;
}
while (elem = res.iterateNext()) {
let rect = elem.getBoundingClientRect();
// If the rect has a zero dimension, it may contain
// floated children. In that case, the children's rects
// are most probably where the hints should be at.
if (rect.width == 0 || rect.height == 0) {
let hasFloatChild = false;
for (let i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeType != 1) // nodeType 1: elem_NODE
continue;
// getComputedStyle returns null, if the owner frame is not visible.
let computedStyle = doc.defaultView.getComputedStyle(elem.childNodes[i], null);
if (computedStyle && computedStyle.getPropertyValue('float') != 'none'
&& this._isVisible(elem.childNodes[i], screen)) {
makeHint(elem.childNodes[i]);
hasFloatChild = true;
break;
}
}
if (hasFloatChild)
continue;
}
if (this._isVisible(elem, screen))
makeHint(elem);
}
let body = (doc instanceof XULDocument) ?
doc.documentElement :
doc.body || util.evaluateXPath(["body"], doc).snapshotItem(0);
if (body) {
body.appendChild(fragment);
this._docs.push({ doc: doc, start: start, end: this._pageHints.length - 1 });
}
// also _generate hints for frames
for (let frame in util.Array.itervalues(win.frames)) {
elem = frame.frameElement;
if (!this._isVisible(elem, screen)) continue;
let rect = elem.getBoundingClientRect();
this._generate(frame,{
top : Math.max(0, screen.top - rect.top),
left : Math.max(0, screen.left - rect.left),
bottom : Math.min(frame.innerHeight, screen.bottom - rect.top),
right : Math.min(frame.innerWidth, screen.right - rect.left)
});
}
return true;
},
/**
* Update the activeHint.
*
* By default highlights it green instead of yellow.
*
* @param {number} newId The hint to make active.
* @param {number} oldId The currently active hint.
*/
_showActiveHint: function (newId, oldId) {
let oldElem = this._validHints[oldId - 1];
if (oldElem)
this._setClass(oldElem, false);
let newElem = this._validHints[newId - 1];
if (newElem)
this._setClass(newElem, true);
},
/**
* Toggle the highlight of a hint.
*
* @param {Object} elem The element to toggle.
* @param {boolean} active Whether it is the currently active hint or not.
*/
_setClass: function (elem, active) {
let prefix = (elem.getAttributeNS(NS.uri, "class") || "") + " ";
if (active)
elem.setAttributeNS(NS.uri, "highlight", prefix + "HintActive");
else
elem.setAttributeNS(NS.uri, "highlight", prefix + "HintElem");
},
/**
* Display the hints in pageHints that are still valid.
*/
_showHints: function () {
let hintnum = 1;
let validHint = this._hintMatcher(this._hintString.toLowerCase());
let activeHint = this._hintNumber || 1;
this._validHints = [];
this._tabNavigation = {};
let firstHint = null;
let lastHint = null;
let prevHint = null;
let activeHintChars = this._num2chars(activeHint);
for (let { doc, start, end } of this._docs) {
if (!(doc instanceof Node))
continue;
let [offsetX, offsetY] = this._getContainerOffsets(doc);
if (offsetX === null && offsetY === null)
continue;
inner:
for (let i in (util.interruptibleRange(start, end + 1, 500))) {
let hint = this._pageHints[i];
let valid = validHint(hint.text);
let hintnumchars = this._num2chars(hintnum);
let display = valid && (
this._hintNumber == 0 ||
hintnumchars.indexOf(String(activeHintChars)) == 0
);
hint.span.style.display = (display ? "" : "none");
if (hint.imgSpan)
hint.imgSpan.style.display = (display ? "" : "none");
if (!valid || !display) {
hint.elem.removeAttributeNS(NS.uri, "highlight");
if (valid) {
this._validHints.push(hint.elem);
hintnum++;
}
continue inner;
}
if (hint.text == "" && hint.elem.firstChild && hint.elem.firstChild instanceof HTMLImageElement) {
if (!hint.imgSpan) {
let rect = hint.elem.firstChild.getBoundingClientRect();
if (!rect)
continue;
hint.imgSpan = util.xmlToDom(xml`<span highlight="Hint" liberator:class="HintImage" xmlns:liberator=${NS}/>`, doc);
hint.imgSpan.style.left = (rect.left + offsetX) + "px";
hint.imgSpan.style.top = (rect.top + offsetY) + "px";
hint.imgSpan.style.width = (rect.right - rect.left) + "px";
hint.imgSpan.style.height = (rect.bottom - rect.top) + "px";
hint.span.parentNode.appendChild(hint.imgSpan);
}
this._setClass(hint.imgSpan, activeHint == hintnum);
}
hint.span.setAttribute("number", hint.showText ? hintnumchars + ": " + hint.text.substr(0, 50) : hintnumchars);
if (hint.imgSpan)
hint.imgSpan.setAttribute("number", hintnumchars);
else
this._setClass(hint.elem, activeHint == hintnum);
this._validHints.push(hint.elem);
// Set up tab navigation for valid hints
firstHint = (firstHint ) ? firstHint : hintnum ;
lastHint = hintnum;
prevHint = (prevHint) ? prevHint : hintnum;
this._tabNavigation[hintnum] = {prev: prevHint, next:prevHint};
this._tabNavigation[prevHint].next = hintnum;
prevHint = hintnum;
hintnum++;
}
}
this._tabNavigation[firstHint].prev = lastHint;
this._tabNavigation[lastHint].next = firstHint;
if (config.browser.markupDocumentViewer.authorStyleDisabled) {
let css = [];
// FIXME: Broken for imgspans.
for (let { doc } of this._docs) {
for (let elem in util.evaluateXPath(" {//*[@liberator:highlight and @number]", doc)) {
let group = elem.getAttributeNS(NS.uri, "highlight");
css.push(highlight.selector(group) + "[number=" + elem.getAttribute("number").quote() + "] { " + elem.style.cssText + " }");
}
}
styles.addSheet(true, "hint-positions", "*", css.join("\n"));
}
return true;
},
/**
* Remove all hints from the document, and reset the completions.
*
* Lingers on the active hint briefly to confirm the selection to the user.
*
* @param {number} timeout The number of milliseconds before the active
* hint disappears.
*/
_removeHints: function (timeout) {
let firstElem = this._validHints[0] || null;
for (let { doc, start, end } of this._docs) {
if (!(doc instanceof Node))
continue;
let result = util.evaluateXPath("//*[@liberator:highlight='hints']", doc, null, true);
let hints = new Array();
let elem;
// Lucas de Vries: Deleting elements while iterating creates
// problems, therefore store the items in a temporary array first.
while (elem = result.iterateNext())
hints.push(elem);
while (elem = hints.pop())
elem.parentNode.removeChild(elem);
for (let i in util.range(start, end + 1)) {
let hint = this._pageHints[i];
if (!timeout || hint.elem != firstElem)
hint.elem.removeAttributeNS(NS.uri, "highlight");
}
// animate the disappearance of the first hint
if (timeout && firstElem)
setTimeout(function () { firstElem.removeAttributeNS(NS.uri, "highlight"); }, timeout);
}
styles.removeSheet(true, "hint-positions");
this._reset();
},
_num2chars: function (num) {
let hintchars = options["hintchars"];
let chars = "";
let base = hintchars.length;
do {
chars = hintchars[((num % base))] + chars;
num = Math.floor(num / base);
} while (num > 0);
return chars;
},
_chars2num: function (chars) {
let num = 0;
let hintchars = options["hintchars"];
let base = hintchars.length;
for (let i = 0, l = chars.length; i < l; ++i) {
num = base * num + hintchars.indexOf(chars[i]);
}
return num;
},
_isHintNumber: function (key) options["hintchars"].indexOf(key) >= 0,
/**
* Finish hinting.
*
* Called when there are one or zero hints in order to possibly activate it
* and, if activated, to clean up the rest of the hinting system.
*
* @param {boolean} followFirst Whether to force the following of the first
* link (when 'followhints' is 1 or 2)
*
*/
_processHints: function (followFirst) {
if (this._validHints.length == 0) {
liberator.beep();
return false;
}
// This "followhints" option is *too* confusing. For me, and
// presumably for users, too. --Kris
if (options["followhints"] > 0) {
if (!followFirst)
return false; // no return hit; don't examine uniqueness
// OK. return hit. But there's more than one hint, and
// there's no tab-selected current link. Do not follow in mode 2
liberator.assert(options["followhints"] != 2 || this._validHints.length == 1 || this._hintNumber)
}
if (!followFirst) {
let firstHref = this._validHints[0].getAttribute("href") || null;
if (firstHref) {
if (this._validHints.some(function (e) e.getAttribute("href") != firstHref))
return false;
}
else if (this._validHints.length > 1)
return false;
}
let timeout = followFirst || events.feedingKeys ? 0 : 500;
let activeIndex = (this._hintNumber ? this._hintNumber - 1 : 0);
let elem = this._validHints[activeIndex];
this._removeHints(timeout);
if (timeout == 0)
// force a possible mode change, based on whether an input field has focus
events.onFocusChange();
this.setTimeout(function () {
if (modes.extended & modes.HINTS)
modes.reset();
this._hintMode.action(elem, elem.href || "", this._extendedhintCount);
}, timeout);
return true;
},
_checkUnique: function () {
if (this._hintNumber == 0)
return;
liberator.assert(this._hintNumber <= this._validHints.length);
// if we write a numeric part like 3, but we have 45 hints, only follow
// the hint after a timeout, as the user might have wanted to follow link 34
if (this._hintNumber > 0 && this._hintNumber * options["hintchars"].length <= this._validHints.length) {
let timeout = options["hinttimeout"];
if (timeout > 0)
this._activeTimeout = this.setTimeout(function () { this._processHints(true); }, timeout);
}
else // we have a unique hint
this._processHints(true);
},
/**
* Handle user input.
*
* Will update the filter on displayed hints and follow the final hint if
* necessary.
*
* @param {Event} event The keypress event.
*/
_onInput: function (event) {
this._prevInput = "text";
// clear any timeout which might be active after pressing a number
if (this._activeTimeout) {
clearTimeout(this._activeTimeout);
this._activeTimeout = null;
}
this._hintNumber = 0;
this._hintString = commandline.command;
this._updateStatusline();
this._showHints();
if (this._validHints.length == 1)
this._processHints(false);
},
/**
* Get the hintMatcher according to user preference.
*
* @param {string} hintString The currently typed hint.
* @returns {hintMatcher}
*/
_hintMatcher: function (hintString) { //{{{
/**
* Divide a string by a regular expression.
*
* @param {RegExp|string} pat The pattern to split on.
* @param {string} str The string to split.
* @returns {Array(string)} The lowercased splits of the splitting.
*/
function tokenize(pat, str) str.split(pat).map(String.toLowerCase);
/**
* Get a hint matcher for hintmatching=contains
*
* The hintMatcher expects the user input to be space delimited and it
* returns true if each set of characters typed can be found, in any
* order, in the link.
*
* @param {string} hintString The string typed by the user.
* @returns {function(String):boolean} A function that takes the text
* of a hint and returns true if all the (space-delimited) sets of
* characters typed by the user can be found in it.
*/
function containsMatcher(hintString) { //{{{
let tokens = tokenize(/\s+/, hintString);
return function (linkText) {
linkText = linkText.toLowerCase();
return tokens.every(function (token) indexOf(linkText, token) >= 0);
};
} //}}}
/**
* Get a hintMatcher for hintmatching=firstletters|wordstartswith
*
* The hintMatcher will look for any division of the user input that
* would match the first letters of words. It will always only match
* words in order.
*
* @param {string} hintString The string typed by the user.
* @param {boolean} allowWordOverleaping Whether to allow non-contiguous
* words to match.
* @returns {function(String):boolean} A function that will filter only
* hints that match as above.
*/
function wordStartsWithMatcher(hintString, allowWordOverleaping) { //{{{
let hintStrings = tokenize(/\s+/, hintString);
let wordSplitRegex = RegExp(options["wordseparators"]);
/**
* Match a set of characters to the start of words.
*
* What the **** does this do? --Kris
* This function matches hintStrings like 'hekho' to links
* like 'Hey Kris, how are you?' -> [HE]y [K]ris [HO]w are you
* --Daniel
*
* @param {string} chars The characters to match.
* @param {Array(string)} words The words to match them against.
* @param {boolean} allowWordOverleaping Whether words may be
* skipped during matching.
* @returns {boolean} Whether a match can be found.
*/
function charsAtBeginningOfWords(chars, words, allowWordOverleaping) {
function charMatches(charIdx, chars, wordIdx, words, inWordIdx, allowWordOverleaping) {
let matches = (chars[charIdx] == words[wordIdx][inWordIdx]);
if ((matches == false && allowWordOverleaping) || words[wordIdx].length == 0) {
let nextWordIdx = wordIdx + 1;
if (nextWordIdx == words.length)
return false;
return charMatches(charIdx, chars, nextWordIdx, words, 0, allowWordOverleaping);
}
if (matches) {
let nextCharIdx = charIdx + 1;
if (nextCharIdx == chars.length)
return true;
let nextWordIdx = wordIdx + 1;
let beyondLastWord = (nextWordIdx == words.length);
let charMatched = false;
if (beyondLastWord == false)
charMatched = charMatches(nextCharIdx, chars, nextWordIdx, words, 0, allowWordOverleaping);
if (charMatched)
return true;
if (charMatched == false || beyondLastWord == true) {
let nextInWordIdx = inWordIdx + 1;
if (nextInWordIdx == words[wordIdx].length)
return false;
return charMatches(nextCharIdx, chars, wordIdx, words, nextInWordIdx, allowWordOverleaping);
}
}
return false;
}
return charMatches(0, chars, 0, words, 0, allowWordOverleaping);
}
/**
* Check whether the array of strings all exist at the start of the
* words.
*
* i.e. ['ro', 'e'] would match ['rollover', 'effect']
*
* The matches must be in order, and, if allowWordOverleaping is
* false, contiguous.
*
* @param {Array(string)} strings The strings to search for.
* @param {Array(string)} words The words to search in.
* @param {boolean} allowWordOverleaping Whether matches may be
* non-contiguous.
* @returns {boolean} Whether all the strings matched.
*/
function stringsAtBeginningOfWords(strings, words, allowWordOverleaping) {
let strIdx = 0;
for (let word of words) {
if (word.length == 0)
continue;
let str = strings[strIdx];
if (str.length == 0 || indexOf(word, str) == 0)
strIdx++;
else if (!allowWordOverleaping)
return false;
if (strIdx == strings.length)
return true;
}
for (; strIdx < strings.length; strIdx++) {
if (strings[strIdx].length != 0)
return false;
}
return true;
}
return function (linkText) {
if (hintStrings.length == 1 && hintStrings[0].length == 0)
return true;
let words = tokenize(wordSplitRegex, linkText);
if (hintStrings.length == 1)
return charsAtBeginningOfWords(hintStrings[0], words, allowWordOverleaping);
else
return stringsAtBeginningOfWords(hintStrings, words, allowWordOverleaping);
};
} //}}}
let indexOf = String.indexOf;
if (options.get("hintmatching").has("transliterated"))
indexOf = Hints.indexOf;
switch (options.get("hintmatching").values[0]) {
case "contains" : return containsMatcher(hintString);
case "wordstartswith": return wordStartsWithMatcher(hintString, /*allowWordOverleaping=*/ true);
case "firstletters" : return wordStartsWithMatcher(hintString, /*allowWordOverleaping=*/ false);
case "custom" : return liberator.plugins.customHintMatcher(hintString);
default : liberator.echoerr("Invalid hintmatching type: " + hintMatching);
}
return null;
}, //}}}
/**
* Creates a new hint mode.
*
* @param {string} mode The letter that identifies this mode.
* @param {string} prompt The description to display to the user
* about this mode.
* @param {function(Node)} action The function to be called with the
* element that matches.
* @param {function():string} tags The function that returns an
* XPath expression to decide which elements can be hinted (the
* default returns options.hinttags).
* @optional
*/
addMode: function (mode, prompt, action, tags) {
this._hintModes[mode] = Hints.Mode.apply(Hints.Mode, Array.slice(arguments, 1));
},
/**
* Updates the display of hints.
*
* @param {string} minor Which hint mode to use.
* @param {string} filter The filter to use.
* @param {Object} win The window in which we are showing hints.
*/
show: function (minor, filter, win) {
this._hintMode = this._hintModes[minor];
liberator.assert(this._hintMode);
commandline.input(this._hintMode.prompt, null, { onChange: this.closure._onInput });
modes.extended = modes.HINTS;
this._submode = minor;
this._hintString = filter || "";
this._hintNumber = 0;
this._usedTabKey = false;
this._prevInput = "";
this._canUpdate = false;
this._generate(win);
// get all keys from the input queue
liberator.threadYield(true);
this._canUpdate = true;
this._showHints();
if (this._validHints.length == 0) {
liberator.beep();
modes.reset();
}
else if (this._validHints.length == 1)
this._processHints(false);
else // Ticket #185
this._checkUnique();
},
/**
* start an extended hint mode
*
* @param {string} filter The filter to use.
* @param {Object} win The window in which we are showing hints.
*/
startExtendedHint: function (filter, win) {
commandline.input(";",
function onSubmit (str) {
if (str in hints._hintModes)
setTimeout(function(){ hints.show(str, filter, win); }, 0);
}, {
promptHighlight: "Normal",
completer: function (context) {
context.compare = function () 0;
context.completions = [[k, v.prompt] for ([k, v] in Iterator(hints._hintModes))];
},
onChange: function (str) {
if (str in hints._hintModes) {
hints.show(str, filter, win);
if (commandline._completionList.visible())
commandline._completionList.hide();
}
},
});
},
/**
* Cancel all hinting.
*/
hide: function () {
this._removeHints(0);
},
/**
* Handle a hint mode event.
*
* @param {Event} event The event to handle.
*/
onEvent: function (event) {
let key = events.toString(event);
let followFirst = false;
// clear any timeout which might be active after pressing a number
if (this._activeTimeout) {
clearTimeout(this._activeTimeout);
this._activeTimeout = null;
}
switch (key) {
case "<Return>":
followFirst = true;
break;
case "<Tab>":
case "<S-Tab>":
this._usedTabKey = true;
if (this._hintNumber == 0)
this._hintNumber = 1;
let oldId = this._hintNumber;
if (key == "<Tab>")
this._hintNumber = this._tabNavigation[this._hintNumber].next;
else
this._hintNumber = this._tabNavigation[this._hintNumber].prev;
this._showActiveHint(this._hintNumber, oldId);
this._updateStatusline();
return;
case "<BS>":
if (this._hintNumber > 0 && !this._usedTabKey) {
this._hintNumber = Math.floor(this._hintNumber / 10);
if (this._hintNumber == 0)
this._prevInput = "text";
}
else {
this._usedTabKey = false;
this._hintNumber = 0;
liberator.beep();
return;
}
break;
case mappings.getMapLeader():
hints.escNumbers = !hints.escNumbers;
if (hints.escNumbers && this._usedTabKey) // this._hintNumber not used normally, but someone may wants to toggle
this._hintNumber = 0; // <tab>s ? this._reset. Prevent to show numbers not entered.
this._updateStatusline();
return;
default:
if (this._isHintNumber(key)) {
this._prevInput = "number";
let oldHintNumber = this._hintNumber;
if (this._hintNumber == 0 || this._usedTabKey) {
this._usedTabKey = false;
this._hintNumber = this._chars2num(key);
}
else
this._hintNumber = this._chars2num(this._num2chars(this._hintNumber) + key);
this._updateStatusline();
if (!this._canUpdate)
return;
if (this._docs.length == 0) {
this._generate();
this._showHints();
}
this._showActiveHint(this._hintNumber, oldHintNumber || 1);
liberator.assert(this._hintNumber != 0);
this._checkUnique();
}
}
this._updateStatusline();
if (this._canUpdate) {
if (this._docs.length == 0 && this._hintString.length > 0)
this._generate();
this._showHints();
this._processHints(followFirst);
}
}
// FIXME: add resize support
// window.addEventListener("resize", onResize, null);
// function onResize(event)
// {
// if (event)
// doc = event.originalTarget;
// else
// doc = window.content.document;
// }
//}}}
}, {
indexOf: (function () {
const table = [
[0x00c0, 0x00c6, ["A"]],
[0x00c7, 0x00c7, ["C"]],
[0x00c8, 0x00cb, ["E"]],
[0x00cc, 0x00cf, ["I"]],
[0x00d1, 0x00d1, ["N"]],
[0x00d2, 0x00d6, ["O"]],
[0x00d8, 0x00d8, ["O"]],
[0x00d9, 0x00dc, ["U"]],
[0x00dd, 0x00dd, ["Y"]],
[0x00e0, 0x00e6, ["a"]],
[0x00e7, 0x00e7, ["c"]],
[0x00e8, 0x00eb, ["e"]],
[0x00ec, 0x00ef, ["i"]],
[0x00f1, 0x00f1, ["n"]],
[0x00f2, 0x00f6, ["o"]],
[0x00f8, 0x00f8, ["o"]],
[0x00f9, 0x00fc, ["u"]],
[0x00fd, 0x00fd, ["y"]],
[0x00ff, 0x00ff, ["y"]],
[0x0100, 0x0105, ["A", "a"]],
[0x0106, 0x010d, ["C", "c"]],
[0x010e, 0x0111, ["D", "d"]],
[0x0112, 0x011b, ["E", "e"]],
[0x011c, 0x0123, ["G", "g"]],
[0x0124, 0x0127, ["H", "h"]],
[0x0128, 0x0130, ["I", "i"]],
[0x0132, 0x0133, ["IJ", "ij"]],
[0x0134, 0x0135, ["J", "j"]],
[0x0136, 0x0136, ["K", "k"]],
[0x0139, 0x0142, ["L", "l"]],
[0x0143, 0x0148, ["N", "n"]],
[0x0149, 0x0149, ["n"]],
[0x014c, 0x0151, ["O", "o"]],
[0x0152, 0x0153, ["OE", "oe"]],
[0x0154, 0x0159, ["R", "r"]],
[0x015a, 0x0161, ["S", "s"]],
[0x0162, 0x0167, ["T", "t"]],
[0x0168, 0x0173, ["U", "u"]],
[0x0174, 0x0175, ["W", "w"]],
[0x0176, 0x0178, ["Y", "y", "Y"]],
[0x0179, 0x017e, ["Z", "z"]],
[0x0180, 0x0183, ["b", "B", "B", "b"]],
[0x0187, 0x0188, ["C", "c"]],
[0x0189, 0x0189, ["D"]],
[0x018a, 0x0192, ["D", "D", "d", "F", "f"]],
[0x0193, 0x0194, ["G"]],
[0x0197, 0x019b, ["I", "K", "k", "l", "l"]],
[0x019d, 0x01a1, ["N", "n", "O", "O", "o"]],
[0x01a4, 0x01a5, ["P", "p"]],
[0x01ab, 0x01ab, ["t"]],
[0x01ac, 0x01b0, ["T", "t", "T", "U", "u"]],
[0x01b2, 0x01d2, ["V", "Y", "y", "Z", "z", "D", "L", "N", "A", "a", "I", "i", "O", "o"]],
[0x01d3, 0x01dc, ["U", "u"]],
[0x01de, 0x01e1, ["A", "a"]],
[0x01e2, 0x01e3, ["AE", "ae"]],
[0x01e4, 0x01ed, ["G", "g", "G", "g", "K", "k", "O", "o", "O", "o"]],
[0x01f0, 0x01f5, ["j", "D", "G", "g"]],
[0x01fa, 0x01fb, ["A", "a"]],
[0x01fc, 0x01fd, ["AE", "ae"]],
[0x01fe, 0x0217, ["O", "o", "A", "a", "A", "a", "E", "e", "E", "e", "I", "i", "I", "i", "O", "o", "O", "o", "R", "r", "R", "r", "U", "u", "U", "u"]],
[0x0253, 0x0257, ["b", "c", "d", "d"]],
[0x0260, 0x0269, ["g", "h", "h", "i", "i"]],
[0x026b, 0x0273, ["l", "l", "l", "l", "m", "n", "n"]],
[0x027c, 0x028b, ["r", "r", "r", "r", "s", "t", "u", "u", "v"]],
[0x0290, 0x0291, ["z"]],
[0x029d, 0x02a0, ["j", "q"]],
[0x1e00, 0x1e09, ["A", "a", "B", "b", "B", "b", "B", "b", "C", "c"]],
[0x1e0a, 0x1e13, ["D", "d"]],
[0x1e14, 0x1e1d, ["E", "e"]],
[0x1e1e, 0x1e21, ["F", "f", "G", "g"]],
[0x1e22, 0x1e2b, ["H", "h"]],
[0x1e2c, 0x1e8f, ["I", "i", "I", "i", "K", "k", "K", "k", "K", "k", "L", "l", "L", "l", "L", "l", "L", "l", "M", "m", "M", "m", "M", "m", "N", "n", "N", "n", "N", "n", "N", "n", "O", "o", "O", "o", "O", "o", "O", "o", "P", "p", "P", "p", "R", "r", "R", "r", "R", "r", "R", "r", "S", "s", "S", "s", "S", "s", "S", "s", "S", "s", "T", "t", "T", "t", "T", "t", "T", "t", "U", "u", "U", "u", "U", "u", "U", "u", "U", "u", "V", "v", "V", "v", "W", "w", "W", "w", "W", "w", "W", "w", "W", "w", "X", "x", "X", "x", "Y", "y"]],
[0x1e90, 0x1e9a, ["Z", "z", "Z", "z", "Z", "z", "h", "t", "w", "y", "a"]],
[0x1ea0, 0x1eb7, ["A", "a"]],
[0x1eb8, 0x1ec7, ["E", "e"]],
[0x1ec8, 0x1ecb, ["I", "i"]],
[0x1ecc, 0x1ee3, ["O", "o"]],
[0x1ee4, 0x1ef1, ["U", "u"]],
[0x1ef2, 0x1ef9, ["Y", "y"]],
[0x2071, 0x2071, ["i"]],
[0x207f, 0x207f, ["n"]],
[0x249c, 0x24b5, "a"],
[0x24b6, 0x24cf, "A"],
[0x24d0, 0x24e9, "a"],
[0xfb00, 0xfb06, ["ff", "fi", "fl", "ffi", "ffl", "st", "st"]],
[0xff21, 0xff3a, "A"],
[0xff41, 0xff5a, "a"],
].map(function (a) {
if (typeof a[2] == "string")
a[3] = function (chr) String.fromCharCode(this[2].charCodeAt(0) + chr - this[0]);
else
a[3] = function (chr) this[2][(chr - this[0]) % this[2].length];
return a;
});
function translate(chr) {
var m, c = chr.charCodeAt(0);
var n = table.length;
var i = 0;
while (n) {
m = Math.floor(n / 2);
var t = table[i + m];
if (c >= t[0] && c <= t[1])
return t[3](c);
if (c < t[0] || m == 0)
n = m;
else {
i += m;
n = n - m;
}
}
return chr;
}
return function indexOf(dest, src) {
var end = dest.length - src.length;
if (src.length == 0)
return 0;
outer:
for (var i = 0; i < end; i++) {
var j = i;
for (var k = 0; k < src.length;) {
var s = translate(dest[j++]);
for (var l = 0; l < s.length; l++, k++) {
if (s[l] != src[k])
continue outer;
if (k == src.length - 1)
return i;
}
}
}
return -1;
}
})(),
Mode: Struct("prompt", "action", "tags")
}, {
mappings: function () {
var myModes = config.browserModes;
mappings.add(myModes, ["f"],
"Start QuickHint mode",
function () { hints.show("o"); });
// At the moment, "F" calls
// buffer.followLink(clicked_element, DO_WHAT_FIREFOX_DOES_WITH_CNTRL_CLICK)
// It is not clear that it shouldn't be:
// buffer.followLink(clicked_element, !DO_WHAT_FIREFOX_DOES_WITH_CNTRL_CLICK)
// In fact, it might be nice if there was a "dual" to F (like H and
// gH, except that gF is already taken). --tpp
//
// Likewise, it might be nice to have a liberator.NEW_FOREGROUND_TAB
// and then make liberator.NEW_TAB always do what a Ctrl+Click
// does. --tpp
mappings.add(myModes, ["F"],
"Start QuickHint mode, but open link in a new tab",
function () { hints.show(options.getPref("browser.tabs.loadInBackground") ? "b" : "t"); });
mappings.add(myModes, [";"],
"Start an extended hint mode",
function (count) {
hints._extendedhintCount = count;
hints.startExtendedHint();
}, { count: true });
},
options: function () {
const DEFAULT_HINTTAGS =
util.makeXPath(["input[not(@type='hidden')]", "a", "area", "iframe", "textarea", "button", "select"])
+ " | //*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @role='link'or @role='button' or @role='checkbox' or @role='combobox' or @role='listbox' or @role='listitem' or @role='menuitem' or @role='menuitemcheckbox' or @role='menuitemradio' or @role='option' or @role='radio' or @role='scrollbar' or @role='slider' or @role='spinbutton' or @role='tab' or @role='textbox' or @role='treeitem' or @tabindex]"
+ (config.name == "Muttator" ?
" | //xhtml:div[@class='wrappedsender']/xhtml:div[contains(@class,'link')]" :
"");
function checkXPath(val) {
try {
util.evaluateXPath(val, document.implementation.createDocument("", "", null));
return true;
}
catch (e) {
return false;
}
}
options.add(["extendedhinttags", "eht"],
"XPath string of hintable elements activated by ';'",
"string", DEFAULT_HINTTAGS,
{ validator: checkXPath, scope: Option.SCOPE_BOTH });
options.add(["hinttags", "ht"],
"XPath string of hintable elements activated by 'f' and 'F'",
"string", DEFAULT_HINTTAGS,
{ validator: checkXPath, scope: Option.SCOPE_BOTH });
options.add(["hinttimeout", "hto"],
"Timeout before automatically following a non-unique numerical hint",
"number", 0,
{ validator: function (value) value >= 0 });
options.add(["followhints", "fh"],
// FIXME: this description isn't very clear but I can't think of a
// better one right now.
"Change the behaviour of <Return> in hint mode",
"number", 0,
{
completer: function () [
["0", "Follow the first hint as soon as typed text uniquely identifies it. Follow the selected hint on <Return>."],
["1", "Follow the selected hint on <Return>."],
["2", "Follow the selected hint on <Return> only it's been <Tab>-selected."]
]
});
options.add(["hintmatching", "hm"],
"How links are matched",
"stringlist", "contains",
{
completer: function (context) [
["contains", "The typed characters are split on whitespace. The resulting groups must all appear in the hint."],
["wordstartswith", "The typed characters are split on whitespace. The resulting groups must all match the beginings of words, in order."],
["firstletters", "Behaves like wordstartswith, but all groups much match a sequence of words."],
["custom", "Delegate to a custom function: liberator.plugins.customHintMatcher(hintString)"],
["transliterated", "When true, special latin characters are translated to their ascii equivalent (e.g., \u00e9 -> e)"]
]
});
options.add(["hintchars", "hc"],
"What characters to use for labeling hints",
"string", "0123456789", // TODO: Change to charlist
{
setter: function (value) {
if (modes.extended & modes.HINTS)
hints._showHints();
return value;
},
completer: function (context) [
["0123456789", "Numbers only"],
["hjklasdf", "Home row"],
["hjklasdfgyuiopqwertnmzxcvb", "Smart order"],
["abcdefghijklmnopqrstuvwxyz", "Alphabetically ordered"],
],
validator: function (arg) {
let prev;
let list = arg.split("");
list.sort();
let ret = list.some(function (n) prev == (prev=n));
return !ret && arg.length > 1;
}
});
options.add(["wordseparators", "wsp"],
"How words are split for hintmatching",
"string", '[.,!?:;/"^$%&?()[\\]{}<>#*+|=~ _-]');
options.add(["hintinputs", "hin"],
"How text input fields are hinted",
"stringlist", "label,value",
{
completer: function (context) [
["value", "Match against the value contained by the input field"],
["label", "Match against the value of a label for the input field, if one can be found"],
["name", "Match against the name of an input field, only if neither a name or value could be found."]
]
});
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
// TODO: proper backwards search - implement our own component?
// : implement our own highlighter?
// : <ESC> should cancel search highlighting in 'incsearch' mode and jump
// back to the presearch page location - can probably use the same
// solution as marks
// : 'linksearch' searches should highlight link matches only
// : changing any search settings should also update the search state including highlighting
// : incremental searches shouldn't permanently update search modifiers
//
// TODO: Clean up this rat's nest. --Kris
/**
* @instance finder
*/
const Finder = Module("finder", {
requires: ["config"],
init: function () {
const self = this;
this._found = false; // true if the last search was successful
this._backwards = false; // currently searching backwards
this._searchString = ""; // current search string (without modifiers)
this._searchPattern = ""; // current search string (includes modifiers)
this._lastSearchPattern = ""; // the last searched pattern (includes modifiers)
this._lastSearchString = ""; // the last searched string (without modifiers)
this._lastSearchBackwards = false; // like "backwards", but for the last search, so if you cancel a search with <esc> this is not set
this._caseSensitive = false; // search string is case sensitive
this._linksOnly = false; // search is limited to link text only
},
// set searchString, searchPattern, caseSensitive, linksOnly
_processUserPattern: function (pattern) {
//// strip off pattern terminator and offset
//if (backwards)
// pattern = pattern.replace(/\?.*/, "");
//else
// pattern = pattern.replace(/\/.*/, "");
this._searchPattern = pattern;
// links only search - \l wins if both modifiers specified
if (/\\l/.test(pattern))
this._linksOnly = true;
else if (/\L/.test(pattern))
this._linksOnly = false;
else if (options["linksearch"])
this._linksOnly = true;
else
this._linksOnly = false;
// strip links-only modifiers
pattern = pattern.replace(/(\\)?\\[lL]/g, function ($0, $1) { return $1 ? $0 : ""; });
// case sensitivity - \c wins if both modifiers specified
if (/\c/.test(pattern))
this._caseSensitive = false;
else if (/\C/.test(pattern))
this._caseSensitive = true;
else if (options["ignorecase"] && options["smartcase"] && /[A-Z]/.test(pattern))
this._caseSensitive = true;
else if (options["ignorecase"])
this._caseSensitive = false;
else
this._caseSensitive = true;
// strip case-sensitive modifiers
pattern = pattern.replace(/(\\)?\\[cC]/g, function ($0, $1) { return $1 ? $0 : ""; });
// remove any modifier escape \
pattern = pattern.replace(/\\(\\[cClL])/g, "$1");
this._searchString = pattern;
},
/**
* Called when the search dialog is requested.
*
* @param {number} mode The search mode, either modes.SEARCH_FORWARD or
* modes.SEARCH_BACKWARD.
* @default modes.SEARCH_FORWARD
*/
openPrompt: function (mode) {
this._backwards = mode == modes.SEARCH_BACKWARD;
//commandline.open(this._backwards ? "Find backwards" : "Find", "", mode);
commandline.input(this._backwards ? "Find backwards" : "Find", this.closure.onSubmit, {
onChange: function() { if (options["incsearch"]) finder.find(commandline.command) }
});
//modes.extended = mode;
// TODO: focus the top of the currently visible screen
},
// TODO: backwards seems impossible i fear
/**
* Searches the current buffer for <b>str</b>.
*
* @param {string} str The string to find.
* @see Bug537013 https://bugzilla.mozilla.org/show_bug.cgi?id=537013
*/
find: Services.vc.compare(Services.appinfo.version, "24.0") > 0 ?
function (str) {
let fastFind = config.browser.getFindBar();
this._processUserPattern(str);
fastFind._typeAheadCaseSensitive = this._caseSensitive;
fastFind._typeAheadLinksOnly = this._linksOnly;
let result = fastFind._find(str);
} :
// FIXME: remove when minVersion > 24
function (str) {
let fastFind = config.browser.fastFind;
this._processUserPattern(str);
fastFind.caseSensitive = this._caseSensitive;
let result = fastFind.find(this._searchString, this._linksOnly);
this._displayFindResult(result, this._backwards);
},
/**
* Searches the current buffer again for the most recently used search
* string.
*
* @param {boolean} reverse Whether to search forwards or backwards.
* @default false
* @see Bug537013 https://bugzilla.mozilla.org/show_bug.cgi?id=537013
*/
findAgain: Services.vc.compare(Services.appinfo.version, "24.0") > 0 ?
function (reverse) {
let fastFind = config.browser.getFindBar();
if (fastFind._findField.value != this._lastSearchString)
this.find(this._lastSearchString);
let backwards = reverse ? !this._lastSearchBackwards : this._lastSearchBackwards;
fastFind._typeAheadLinksOnly = this._linksOnly;
let result = fastFind._findAgain(backwards);
this._displayFindResult(result, backwards);
} :
// FIXME: remove when minVersion > 24
function (reverse) {
// This hack is needed to make n/N work with the correct string, if
// we typed /foo<esc> after the original search. Since searchString is
// readonly we have to call find() again to update it.
if (config.browser.fastFind.searchString != this._lastSearchString)
this.find(this._lastSearchString);
let backwards = reverse ? !this._lastSearchBackwards : this._lastSearchBackwards;
let result = config.browser.fastFind.findAgain(backwards, this._linksOnly);
this._displayFindResult(result, backwards);
},
_displayFindResult: function(result, backwards) {
if (result == Ci.nsITypeAheadFind.FIND_NOTFOUND) {
liberator.echoerr("Pattern not found: " + this._searchString, commandline.FORCE_SINGLELINE);
}
else if (result == Ci.nsITypeAheadFind.FIND_WRAPPED) {
let msg = backwards ? "Search hit TOP, continuing at BOTTOM" : "Search hit BOTTOM, continuing at TOP";
commandline.echo(msg, commandline.HL_WARNINGMSG, commandline.APPEND_TO_MESSAGES | commandline.FORCE_SINGLELINE);
}
else {
liberator.echomsg("Found pattern: " + this._searchString);
}
},
/**
* Called when the user types a key in the search dialog. Triggers a
* search attempt if 'incsearch' is set.
*
* @param {string} str The search string.
*/
/*onKeyPress: function (str) {
if (options["incsearch"])
this.find(str);
},*/
/**
* Called when the <Enter> key is pressed to trigger a search.
*
* @param {string} str The search string.
* @param {boolean} forcedBackward Whether to search forwards or
* backwards. This overrides the direction set in
* (@link #openPrompt).
* @default false
*/
onSubmit: function (str, forcedBackward) {
if (typeof forcedBackward === "boolean")
this._backwards = forcedBackward;
if (str)
var pattern = str;
else {
liberator.assert(this._lastSearchPattern, "No previous search pattern");
pattern = this._lastSearchPattern;
}
this.clear();
// liberator.log('inc: ' + options["incsearch"] + ' sea:' + this._searchPattern + ' pat:' + pattern);
if (!options["incsearch"] /*|| !str || !this._found */|| this._searchPattern != pattern) {
// prevent any current match from matching again
if (!window.content.getSelection().isCollapsed)
window.content.getSelection().getRangeAt(0).collapse(this._backwards);
this.find(pattern);
}
// focus links after searching, so the user can just hit <Enter> another time to follow the link
// This has to be done async, because the mode reset after onSubmit would
// clear the focus
let elem = Services.vc.compare(Services.appinfo.version, "24.0") > 0 ?
config.browser.getFindBar()._foundLinkRef.get() :
config.browser.fastFind.foundLink; // FIXME: remove when minVersion > 24
this.setTimeout(function() {
if (elem)
elem.focus();
// fm.moveFocus(elem.ownerDocument.defaultView, null, Ci.nsIFocusManager.MOVEFOCUS_CARET, Ci.nsIFocusManager.FLAG_NOSCROLL);*/
}, 0);
this._lastSearchBackwards = this._backwards;
this._lastSearchPattern = pattern;
this._lastSearchString = this._searchString;
// TODO: move to find() when reverse incremental searching is kludged in
// need to find again for reverse searching
if (this._backwards)
this.setTimeout(function () { this.findAgain(false); }, 0);
if (options["hlsearch"])
this.highlight(this._searchString);
},
/**
* Highlights all occurances of <b>str</b> in the buffer.
*
* @param {string} str The string to highlight.
*/
highlight: function (str) {
// FIXME: Thunderbird incompatible
if (config.name == "Muttator")
return;
if (window.gFindBar) {
window.gFindBar._setCaseSensitivity(this._caseSensitive);
window.gFindBar._highlightDoc(false);
window.gFindBar._highlightDoc(true, str);
}
},
/**
* Clears all search highlighting.
*/
clear: function () {
// FIXME: Thunderbird incompatible
if (config.name == "Muttator")
return;
if (window.gFindBar)
window.gFindBar._highlightDoc(false);
}
}, {
}, {
commands: function () {
// TODO: Remove in favor of :set nohlsearch?
commands.add(["noh[lsearch]"],
"Remove the search highlighting",
function () { finder.clear(); },
{ argCount: "0" });
},
mappings: function () {
var myModes = config.browserModes;
myModes = myModes.concat([modes.CARET]);
mappings.add(myModes,
["/"], "Search forward for a pattern",
function () { finder.openPrompt(modes.SEARCH_FORWARD); });
mappings.add(myModes,
["?"], "Search backwards for a pattern",
function () { finder.openPrompt(modes.SEARCH_BACKWARD); });
mappings.add(myModes,
["n"], "Find next",
function () { finder.findAgain(false); });
mappings.add(myModes,
["N"], "Find previous",
function () { finder.findAgain(true); });
mappings.add(myModes.concat([modes.CARET, modes.TEXTAREA]), ["*"],
"Find word under cursor",
function () {
this._found = false;
finder.onSubmit(buffer.getCurrentWord(), false);
});
mappings.add(myModes.concat([modes.CARET, modes.TEXTAREA]), ["#"],
"Find word under cursor backwards",
function () {
this._found = false;
finder.onSubmit(buffer.getCurrentWord(), true);
});
},
options: function () {
options.add(["hlsearch", "hls"],
"Highlight previous search pattern matches",
"boolean", true, {
setter: function (value) {
try {
if (value)
finder.highlight();
else
finder.clear();
}
catch (e) {}
return value;
}
});
options.add(["ignorecase", "ic"],
"Ignore case in search patterns",
"boolean", true);
options.add(["incsearch", "is"],
"Show where the search pattern matches as it is typed",
"boolean", true);
options.add(["linksearch", "lks"],
"Limit the search to hyperlink text",
"boolean", false);
options.add(["smartcase", "scs"],
"Override the 'ignorecase' option if the pattern contains uppercase characters",
"boolean", true);
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* Cached XPCOM services and classes.
*
* @constructor
*/
const Services = Module("services", {
init: function () {
this.classes = {};
this.jsm = window.Services;
this.services = {
"autoCompleteSearch": {
class_: "@mozilla.org/autocomplete/search;1?name=history",
iface: Ci.nsIAutoCompleteSearch
},
"bookmarks": {
class_: "@mozilla.org/browser/nav-bookmarks-service;1",
iface: Ci.nsINavBookmarksService
},
"liberator:": {
class_: "@mozilla.org/network/protocol;1?name=liberator"
},
"debugger": {
class_: "@mozilla.org/js/jsd/debugger-service;1",
iface: Ci.jsdIDebuggerService
},
"environment": {
class_: "@mozilla.org/process/environment;1",
iface: Ci.nsIEnvironment
},
"favicon": {
class_: "@mozilla.org/browser/favicon-service;1",
iface: Ci.nsIFaviconService
},
"history": {
class_: "@mozilla.org/browser/nav-history-service;1",
iface: [Ci.nsINavHistoryService, Ci.nsIBrowserHistory]
},
"privateBrowsing": {
class_: "@mozilla.org/privatebrowsing;1",
iface: Ci.nsIPrivateBrowsingService
},
"profile": {
class_: "@mozilla.org/toolkit/profile-service;1",
iface: Ci.nsIToolkitProfileService
},
"rdf": {
class_: "@mozilla.org/rdf/rdf-service;1",
iface: Ci.nsIRDFService
},
"sessionStore": {
class_: "@mozilla.org/browser/sessionstore;1",
iface: Ci.nsISessionStore
},
"threadManager": {
class_: "@mozilla.org/thread-manager;1",
iface: Ci.nsIThreadManager
},
"UUID": {
class_: "@mozilla.org/uuid-generator;1",
iface: Ci.nsIUUIDGenerator
},
"textToSubURI": {
class_: "@mozilla.org/intl/texttosuburi;1",
iface: Ci.nsITextToSubURI
},
};
this.addClass("file", "@mozilla.org/file/local;1", Ci.nsILocalFile);
this.addClass("file:", "@mozilla.org/network/protocol;1?name=file", Ci.nsIFileProtocolHandler);
this.addClass("find", "@mozilla.org/embedcomp/rangefind;1", Ci.nsIFind);
this.addClass("process", "@mozilla.org/process/util;1", Ci.nsIProcess);
this.addClass("timer", "@mozilla.org/timer;1", Ci.nsITimer);
},
_create: function (classes, ifaces, meth) {
try {
let res = Cc[classes][meth || "getService"]();
if (!ifaces)
return res.wrappedJSObject;
ifaces = Array.concat(ifaces);
ifaces.forEach(function (iface) res.QueryInterface(iface));
return res;
}
catch (e) {
// liberator.log() is not defined at this time, so just dump any error
dump("Service creation failed for '" + classes + "': " + e + "\n");
return null;
}
},
/**
* Adds a new XPCOM service to the cache.
*
* @param {string} name The service's cache key.
* @param {string} class The class's contract ID.
* @param {nsISupports|nsISupports[]} ifaces The interface or array of
* interfaces implemented by this service.
* @param {string} meth The name of the function used to instanciate
* the service.
*/
add: function (name, class_, ifaces, meth) {
this.services[name] = {"class_": class_, "iface": ifaces, "meth": meth};
},
/**
* Adds a new XPCOM class to the cache.
*
* @param {string} name The class's cache key.
* @param {string} class The class's contract ID.
* @param {nsISupports|nsISupports[]} ifaces The interface or array of
* interfaces implemented by this class.
*/
addClass: function (name, class_, ifaces) {
const self = this;
return this.classes[name] = function () self._create(class_, ifaces, "createInstance");
},
/**
* Returns the cached service with the specified name.
*
* @param {string} name The service's cache key.
*/
get: function (name) {
if (this.jsm.hasOwnProperty(name))
return this.jsm[name];
if (!this.services.hasOwnProperty(name))
throw Error("Could not get service: " + name);
if (!this.services[name]["reference"]) {
var currentService = this.services[name];
this.services[name]["reference"] = this._create(currentService["class_"], currentService["iface"], currentService["meth"]);
}
return this.services[name]["reference"];
},
/**
* Returns a new instance of the cached class with the specified name.
*
* @param {string} name The class's cache key.
*/
create: function (name) this.classes[name]()
},
window.Services,
{
completion: function () {
JavaScript.setCompleter(this.get, [
function () Object.keys(services.jsm).concat(Object.keys(services.services)).map(function(key) [key, ""])
]);
JavaScript.setCompleter(this.create, [function () [[c, ""] for (c in services.classes)]]);
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2008-2009 by Kris Maglione <maglione.k at Gmail>
// Copyright (c) 2008-2010 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* @constant
* @property {string} The default highlighting rules. They have the
* form:
* rule ::= selector space space+ css
* selector ::= group
* | group "," css-selector
* | group "," css-selector "," scope
* group ::= groupname
* | groupname css-selector
*/
// <css>
Highlights.prototype.CSS = `
Boolean color: red;
Function color: navy;
Null color: blue;
Number color: blue;
Object color: maroon;
String color: green;
Mapping color: magenta;
Key font-weight: bold;
Enabled color: green;
Disabled color: red;
Normal color: black; background: white;
ErrorMsg color: white; background: red; font-weight: bold;
InfoMsg color: magenta; background: white;
ModeMsg color: white; background: green; border-radius: 1px; padding: 0px 5px;
MoreMsg color: green; background: white;
WarningMsg color: red; background: white;
Message white-space: normal; min-width: 100%; padding-left: 2em; text-indent: -2em; display: block;
NonText color: blue; min-height: 16px; padding-left: 2px;
Preview color: gray;
Prompt background: url("chrome://liberator/skin/prompt.png"); width: 10px; background-position: center; background-repeat: no-repeat;
PromptText color: white; background: purple;
CmdOutput white-space: pre;
CmdLine background: white; color: black; transition: all 0.25s;
CmdLine>* font-family: monospace;
ContentSeparator border-top: 1px dotted gray; display: -moz-box;
CompGroup
CompGroup:not(:first-of-type) margin-top: 1ex;
CompTitle font-weight: bold; background: linear-gradient(to top, #DBDBDB 19%, #D9D9D9, #E7E7E7 100%);
CompTitle>* color: #333; border-top: 1px solid gray; border-bottom: 1px solid #BBB; padding: 1px 0.5ex; text-shadow: 1px 1px 0px #E0E0E0;
CompMsg font-style: italic; margin-left: 16px;
CompItem
CompItem[selected] background: #FFEC8B; box-shadow: 0px 0px 1px #CC0;
CompItem>* height: 18px; min-height: 18px; padding: 0 0.5ex;
CompIcon width: 16px; min-width: 16px; display: inline-block; margin-right: .5ex;
CompIcon>img max-width: 16px; max-height: 16px; vertical-align: middle;
CompResult width: 500px; max-width: 500px; overflow: hidden;
CompDesc width: 500px; max-width: 500px; color: gray;
Indicator color: blue;
Filter border-radius: 2px; background: #ffec8b; border: 1px solid orange;
Keyword color: red;
Tag color: blue;
LineNr color: orange; background: white;
Question color: green; background: white; font-weight: bold;
StatusLine color: gray; background: transparent; font-weight: normal;
TabNumber font-weight: bold; margin: 0px; padding-right: .3ex;
Title color: magenta; background: white; font-weight: bold;
URL text-decoration: none; color: green;
URL:hover text-decoration: underline; cursor: pointer;
FrameIndicator,,* {
background-color: red;
opacity: 0.5;
z-index: 999;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
Bell border: none; background-color: black;
Hint,,* {
font-family: monospace;
font-size: 10px;
font-weight: bold;
text-transform: uppercase;
color: white;
background-color: red;
border-color: ButtonShadow;
border-width: 0px;
border-style: solid;
padding: 0px 1px 0px 1px;
}
Hint::after,,* content: attr(number);
HintElem,,* background-color: yellow; color: black;
HintActive,,* background-color: #88FF00; color: black;
HintImage,,* opacity: .5;
Help font-size: 8pt; line-height: 1.4em; font-family: -moz-fixed;
HelpArg color: #6A97D4;
HelpOptionalArg color: #6A97D4;
HelpBody display: block; margin: 1em auto; max-width: 100ex;
HelpBorder,*,liberator://help/* border-color: silver; border-width: 0px; border-style: solid;
HelpCode display: block; white-space: pre; margin-left: 2em; font-family: Terminus, Fixed, monospace;
HelpDefault margin-right: 1ex; white-space: pre;
HelpDescription display: block;
HelpEm,html|em,liberator://help/* font-weight: bold; font-style: normal;
HelpEx display: inline-block; color: #527BBD; font-weight: bold;
HelpExample display: block; margin: 1em 0;
HelpExample::before content: "Example: "; font-weight: bold;
HelpInfo display: block; width: 20em; margin-left: auto;
HelpInfoLabel display: inline-block; width: 6em; color: magenta; font-weight: bold; vertical-align: text-top;
HelpInfoValue display: inline-block; width: 14em; text-decoration: none; vertical-align: text-top;
HelpItem display: block; margin: 1em 1em 1em 10em; clear: both;
HelpKey color: #102663;
HelpLink,html|a,liberator://help/* text-decoration: none;
HelpLink[href]:hover text-decoration: underline;
HelpList,html|ul,liberator://help/* display: block; list-style: outside disc;
HelpOrderedList,html|ol,liberator://help/* display: block; list-style: outside decimal;
HelpListItem,html|li,liberator://help/* display: list-item;
HelpNote color: red; font-weight: bold;
HelpOpt color: #106326;
HelpOptInfo display: inline-block; margin-bottom: 1ex;
HelpParagraph,html|p,liberator://help/* display: block; margin: 1em 0em;
HelpParagraph:first-child margin-top: 0;
HelpSpec display: block; margin-left: -10em; float: left; clear: left; color: #FF00FF;
HelpString display: inline-block; color: green; font-weight: normal; vertical-align: text-top;
HelpString::before content: '"';
HelpString::after content: '"';
HelpHead,html|h1,liberator://help/* {
display: block;
margin: 1em 0;
padding-bottom: .2ex;
border-bottom-width: 1px;
font-size: 2em;
font-weight: bold;
color: #527BBD;
clear: both;
}
HelpSubhead,html|h2,liberator://help/* {
display: block;
margin: 1em 0;
padding-bottom: .2ex;
border-bottom-width: 1px;
font-size: 1.2em;
font-weight: bold;
color: #527BBD;
clear: both;
}
HelpSubsubhead,html|h3,liberator://help/* {
display: block;
margin: 1em 0;
padding-bottom: .2ex;
font-size: 1.1em;
font-weight: bold;
color: #527BBD;
clear: both;
}
HelpTOC
HelpTOC>ol ol margin-left: -1em;
HelpTab,html|dl,liberator://help/* display: table; width: 100%; margin: 1em 0; border-bottom-width: 1px; border-top-width: 1px; padding: .5ex 0; table-layout: fixed;
HelpTabColumn,html|column,liberator://help/* display: table-column;
HelpTabColumn:first-child width: 25%;
HelpTabTitle,html|dt,liberator://help/* display: table-cell; padding: .1ex 1ex; font-weight: bold;
HelpTabDescription,html|dd,liberator://help/* display: table-cell; padding: .1ex 1ex; border-width: 0px;
HelpTabRow,html|dl>html|tr,liberator://help/* display: table-row;
HelpTag display: inline-block; color: #999; margin-left: 1ex; font-size: 8pt; font-weight: bold;
HelpTags display: block; float: right; clear: right;
HelpTopic color: #102663;
HelpType margin-right: 2ex;
HelpWarning color: red; font-weight: bold;
Logo
`;
/**
* A class to manage highlighting rules. The parameters are the
* standard parameters for any {@link Storage} object.
*
* @author Kris Maglione <maglione.k@gmail.com>
*/
function Highlights(name, store) {
let self = this;
let highlight = {};
let styles = storage.styles;
const Highlight = Struct("class", "selector", "filter", "default", "value", "base");
Highlight.defaultValue("filter", function ()
this.base ? this.base.filter :
["chrome://liberator/*",
"liberator:*",
"file://*"].concat(config.styleableChrome).join(","));
Highlight.defaultValue("selector", function () self.selector(this.class));
Highlight.defaultValue("value", function () this.default);
Highlight.defaultValue("base", function () {
let base = this.class.match(/^(\w*)/)[0];
return base != this.class && base in highlight ? highlight[base] : null;
});
Highlight.prototype.toString = function () "Highlight(" + this.class + ")\n\t" + [k + ": " + util.escapeString(v || "undefined") for ([k, v] in this)].join("\n\t");
function keys() [k for ([k, v] in Iterator(highlight))].sort();
this.__iterator__ = function () (highlight[v] for (v of keys()));
this.get = function (k) highlight[k];
this.set = function (key, newStyle, force, append) {
let [, class_, selectors] = key.match(/^([a-zA-Z_-]+)(.*)/);
if (!(class_ in highlight))
return "Unknown highlight keyword: " + class_;
let style = highlight[key] || Highlight(key);
styles.removeSheet(true, style.selector);
if (append)
newStyle = (style.value || "").replace(/;?\s*$/, "; " + newStyle);
if (/^\s*$/.test(newStyle))
newStyle = null;
if (newStyle == null) {
if (style.default == null) {
delete highlight[style.class];
styles.removeSheet(true, style.selector);
return null;
}
newStyle = style.default;
force = true;
}
let css = newStyle.replace(/(?:!\s*important\s*)?(?:;?\s*$|;)/g, "!important;")
.replace(";!important;", ";", "g"); // Seeming Spidermonkey bug
if (!/^\s*(?:!\s*important\s*)?;*\s*$/.test(css)) {
css = style.selector + " { " + css + " }";
let error = styles.addSheet(true, "highlight:" + style.class, style.filter, css, true);
if (error)
return error;
}
style.value = newStyle;
highlight[style.class] = style;
return null;
};
/**
* Gets a CSS selector given a highlight group.
*
* @param {string} class
*/
this.selector = function (class_) {
let [, hl, rest] = class_.match(/^(\w*)(.*)/);
let pattern = "[liberator|highlight~=" + hl + "]"
if (highlight[hl] && highlight[hl].class != class_)
pattern = highlight[hl].selector;
return pattern + rest;
};
/**
* Clears all highlighting rules. Rules with default values are
* reset.
*/
this.clear = function () {
for (let [k, v] in Iterator(highlight))
this.set(k, null, true);
};
/**
* Bulk loads new CSS rules.
*
* @param {string} css The rules to load. See {@link Highlights#css}.
*/
this.loadCSS = function (css) {
css.replace(/^(\s*\S*\s+)\{((?:.|\n)*?)\}\s*$/gm, function (_, _1, _2) _1 + " " + _2.replace(/\n\s*/g, " "))
.split("\n").filter(function (s) /\S/.test(s))
.forEach(function (style) {
style = Highlight.apply(Highlight, Array.slice(style.match(/^\s*((?:[^,\s]|\s\S)+)(?:,((?:[^,\s]|\s\S)+)?)?(?:,((?:[^,\s]|\s\S)+))?\s*(.*)$/), 1));
if (/^[>+ ]/.test(style.selector))
style.selector = self.selector(style.class) + style.selector;
let old = highlight[style.class];
highlight[style.class] = style;
if (old && old.value != old.default)
style.value = old.value;
});
for (let [class_, hl] in Iterator(highlight)) {
if (hl.value == hl.default)
this.set(class_);
}
};
this.loadCSS(this.CSS);
}
/**
* Manages named and unnamed user style sheets, which apply to both
* chrome and content pages. The parameters are the standard
* parameters for any {@link Storage} object.
*
* @author Kris Maglione <maglione.k@gmail.com>
*/
function Styles(name, store) {
// Can't reference liberator or Components inside Styles --
// they're members of the window object, which disappear
// with this window.
const self = this;
const util = modules.util;
const sleep = liberator.sleep;
const storage = modules.storage;
const ios = services.get("io");
const sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
const namespace = "@namespace html " + XHTML.uri.quote() + ";\n" +
"@namespace xul " + XUL.uri.quote() + ";\n" +
"@namespace liberator " + NS.uri.quote() + ";\n";
const Sheet = Struct("name", "id", "sites", "css", "system", "agent");
Sheet.prototype.__defineGetter__("fullCSS", function wrapCSS() {
let filter = this.sites;
let css = this.css;
if (filter[0] == "*")
return namespace + css;
let selectors = filter.map(function (part) (/[*]$/.test(part) ? "url-prefix" :
/[\/:]/.test(part) ? "url"
: "domain")
+ '("' + part.replace(/"/g, "%22").replace(/[*]$/, "") + '")')
.join(", ");
return namespace + "/* Liberator style #" + this.id + " */ @-moz-document " + selectors + "{\n" + css + "\n}\n";
});
Sheet.prototype.__defineGetter__("enabled", function () this._enabled);
Sheet.prototype.__defineSetter__("enabled", function (on) {
this._enabled = Boolean(on);
if (on) {
self.registerSheet(cssUri(this.fullCSS));
if (this.agent)
self.registerSheet(cssUri(this.fullCSS), true);
}
else {
self.unregisterSheet(cssUri(this.fullCSS));
self.unregisterSheet(cssUri(this.fullCSS), true);
}
});
let cssUri = function (css) "chrome-data:text/css," + window.encodeURIComponent(css);
let userSheets = [];
let systemSheets = [];
let userNames = {};
let systemNames = {};
let id = 0;
this.__iterator__ = function () Iterator(userSheets.concat(systemSheets));
this.__defineGetter__("systemSheets", function () Iterator(systemSheets));
this.__defineGetter__("userSheets", function () Iterator(userSheets));
this.__defineGetter__("systemNames", function () Iterator(systemNames));
this.__defineGetter__("userNames", function () Iterator(userNames));
/**
* Add a new style sheet.
*
* @param {boolean} system Declares whether this is a system or
* user sheet. System sheets are used internally by
* @liberator.
* @param {string} name The name given to the style sheet by
* which it may be later referenced.
* @param {string} filter The sites to which this sheet will
* apply. Can be a domain name or a URL. Any URL ending in
* "*" is matched as a prefix.
* @param {string} css The CSS to be applied.
*/
this.addSheet = function (system, name, filter, css, agent) {
let sheets = system ? systemSheets : userSheets;
let names = system ? systemNames : userNames;
if (name && name in names)
this.removeSheet(system, name);
let sheet = Sheet(name, id++, filter.split(",").filter(util.identity), String(css), system, agent);
try {
sheet.enabled = true;
}
catch (e) {
return e.echoerr || e;
}
sheets.push(sheet);
if (name)
names[name] = sheet;
return null;
};
/**
* Get a sheet with a given name or index.
*
* @param {boolean} system
* @param {string or number} sheet The sheet to retrieve. Strings indicate
* sheet names, while numbers indicate indices.
*/
this.get = function get(system, sheet) {
let sheets = system ? systemSheets : userSheets;
let names = system ? systemNames : userNames;
if (typeof sheet === "number")
return sheets[sheet];
return names[sheet];
};
/**
* Find sheets matching the parameters. See {@link #addSheet}
* for parameters.
*
* @param {boolean} system
* @param {string} name
* @param {string} filter
* @param {string} css
* @param {number} index
*/
this.findSheets = function (system, name, filter, css, index) {
let sheets = system ? systemSheets : userSheets;
let names = system ? systemNames : userNames;
// Grossly inefficient.
let matches = [k for ([k, v] in Iterator(sheets))];
if (index)
matches = String(index).split(",").filter(function (i) i in sheets);
if (name)
matches = matches.filter(function (i) sheets[i] == names[name]);
if (css)
matches = matches.filter(function (i) sheets[i].css == css);
if (filter)
matches = matches.filter(function (i) sheets[i].sites.indexOf(filter) >= 0);
return matches.map(function (i) sheets[i]);
};
/**
* Remove a style sheet. See {@link #addSheet} for parameters.
* In cases where <b>filter</b> is supplied, the given filters
* are removed from matching sheets. If any remain, the sheet is
* left in place.
*
* @param {boolean} system
* @param {string} name
* @param {string} filter
* @param {string} css
* @param {number} index
*/
this.removeSheet = function (system, name, filter, css, index) {
let self = this;
if (arguments.length == 1) {
var matches = [system];
system = matches[0].system;
}
let sheets = system ? systemSheets : userSheets;
let names = system ? systemNames : userNames;
if (filter && filter.indexOf(",") > -1)
return filter.split(",").reduce(
function (n, f) n + self.removeSheet(system, name, f, index), 0);
if (filter == undefined)
filter = "";
if (!matches)
matches = this.findSheets(system, name, filter, css, index);
if (matches.length == 0)
return null;
for (let sheet of matches.reverse()) {
sheet.enabled = false;
if (name)
delete names[name];
if (sheets.indexOf(sheet) > -1)
sheets.splice(sheets.indexOf(sheet), 1);
/* Re-add if we're only changing the site filter. */
if (filter) {
let sites = sheet.sites.filter(function (f) f != filter);
if (sites.length)
this.addSheet(system, name, sites.join(","), css, sheet.agent);
}
}
return matches.length;
};
/**
* Register a user style sheet at the given URI.
*
* @param {string} uri The URI of the sheet to register.
* @param {boolean} agent If true, sheet is registered as an agent sheet.
* @param {boolean} reload Whether to reload any sheets that are
* already registered.
*/
this.registerSheet = function (uri, agent, reload) {
if (reload)
this.unregisterSheet(uri, agent);
uri = ios.newURI(uri, null, null);
if (reload || !sss.sheetRegistered(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET))
sss.loadAndRegisterSheet(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET);
};
/**
* Unregister a sheet at the given URI.
*
* @param {string} uri The URI of the sheet to unregister.
*/
this.unregisterSheet = function (uri, agent) {
uri = ios.newURI(uri, null, null);
if (sss.sheetRegistered(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET))
sss.unregisterSheet(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET);
};
}
Module("styles", {
requires: ["config", "liberator", "storage", "util"],
init: function () {
let (array = util.Array) {
update(Styles.prototype, {
get sites() array([v.sites for ([k, v] in this.userSheets)]).flatten().uniq().__proto__,
completeSite: function (context, content) {
context.anchored = false;
try {
context.fork("current", 0, this, function (context) {
context.title = ["Current Site"];
context.completions = [
[content.location.host, "Current Host"],
[content.location.href, "Current URL"]
];
});
}
catch (e) {}
context.fork("others", 0, this, function (context) {
context.title = ["Site"];
context.completions = [[s, ""] for (s of styles.sites)];
});
}
});
}
return storage.newObject("styles", Styles, { store: false });
}
}, {
}, {
commands: function () {
commands.add(["sty[le]"],
"Add or list user styles",
function (args) {
let [filter, css] = args;
let name = args["-name"];
if (!css) {
let list = Array.concat([i for (i in styles.userNames)],
[i for (i in styles.userSheets) if (!i[1].name)]);
let str = template.tabular([{ header: "", style: "min-width: 1em; text-align: center; font-weight: bold;", highlight: "Disabled" }, "Name", "Filter", "CSS"],
([sheet.enabled ? "" : "\u00d7",
key,
sheet.sites.join(","),
sheet.css]
for ([key, sheet] of list)
if ((!filter || sheet.sites.indexOf(filter) >= 0) && (!name || sheet.name == name))));
commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
}
else {
if ("-append" in args) {
let sheet = styles.get(false, name);
if (sheet) {
filter = sheet.sites.concat(filter).join(",");
css = sheet.css + " " + css;
}
}
let err = styles.addSheet(false, name, filter, css);
if (err)
liberator.echoerr(err);
}
},
{
bang: true,
completer: function (context, args) {
let compl = [];
if (args.completeArg == 0)
styles.completeSite(context, content);
else if (args.completeArg == 1) {
let sheet = styles.get(false, args["-name"]);
if (sheet)
context.completions = [[sheet.css.replace(/\n+/g, " "), "Current Value"]];
}
},
hereDoc: true,
literal: 1,
options: [[["-name", "-n"], commands.OPTION_STRING, null, function () [[k, v.css] for ([k, v] in Iterator(styles.userNames))]],
[["-append", "-a"], commands.OPTION_NOARG]],
serial: function () [
{
command: this.name,
bang: true,
options: sty.name ? { "-name": sty.name } : {},
arguments: [sty.sites.join(",")],
literalArg: sty.css
} for ([k, sty] in styles.userSheets)
]
});
[
{
name: ["stylee[nable]", "stye[nable]"],
desc: "Enable a user style sheet",
action: function (sheet) sheet.enabled = true,
filter: function (sheet) !sheet.enabled
},
{
name: ["styled[isable]", "styd[isable]"],
desc: "Disable a user style sheet",
action: function (sheet) sheet.enabled = false,
filter: function (sheet) sheet.enabled
},
{
name: ["stylet[oggle]", "styt[oggle]"],
desc: "Toggle a user style sheet",
action: function (sheet) sheet.enabled = !sheet.enabled
},
{
name: ["dels[tyle]"],
desc: "Remove a user style sheet",
action: function (sheet) styles.removeSheet(sheet)
}
].forEach(function (cmd) {
commands.add(cmd.name, cmd.desc,
function (args) {
styles.findSheets(false, args["-name"], args[0], args.literalArg, args["-index"])
.forEach(cmd.action);
},
{
completer: function (context) { context.completions = styles.sites.map(function (site) [site, ""]); },
literal: 1,
options: [[["-index", "-i"], commands.OPTION_INT, null,
function (context) {
context.compare = CompletionContext.Sort.number;
return [[i, `${sheet.sites.join(",")}: ${sheet.css.replace("\n", "\\n")}`]
for ([i, sheet] in styles.userSheets)
if (!cmd.filter || cmd.filter(sheet))];
}],
[["-name", "-n"], commands.OPTION_STRING, null,
function () [[name, sheet.css]
for ([name, sheet] in Iterator(styles.userNames))
if (!cmd.filter || cmd.filter(sheet))]]]
});
});
},
completion: function () {
JavaScript.setCompleter(["get", "addSheet", "removeSheet", "findSheets"].map(function (m) styles[m]),
[ // Prototype: (system, name, filter, css, index)
null,
function (context, obj, args) args[0] ? styles.systemNames : styles.userNames,
function (context, obj, args) styles.completeSite(context, content),
null,
function (context, obj, args) args[0] ? styles.systemSheets : styles.userSheets
]);
}
});
Module("highlight", {
requires: ["config", "styles"],
init: function () {
const self = storage.newObject("highlight", Highlights, { store: false });
if (self.CSS != Highlights.prototype.CSS) {
self.CSS = Highlights.prototype.CSS;
self.loadCSS(self.CSS);
}
return self;
}
}, {
}, {
commands: function () {
commands.add(["colo[rscheme]"],
"Load a color scheme",
function (args) {
let scheme = args[0];
if (scheme == "default")
highlight.clear();
else
liberator.assert(io.sourceFromRuntimePath(["colors/" + scheme + ".vimp"]),
"No such color scheme: " + scheme);
autocommands.trigger("ColorScheme", { name: scheme });
},
{
argCount: "1",
completer: function (context) {
context.title = ["Extra Completions"];
context.completions = [
["default", "Clear all highlights"]
];
context.fork("colorScheme", 0, completion, "colorScheme");
}
});
commands.add(["hi[ghlight]"],
"Set the style of certain display elements",
function (args) {
let style = `
;
display: inline-block !important;
position: static !important;
margin: 0px !important; padding: 0px !important;
width: 3em !important; min-width: 3em !important; max-width: 3em !important;
height: 1em !important; min-height: 1em !important; max-height: 1em !important;
overflow: hidden !important;
`;
let clear = args[0] == "clear";
if (clear)
args.shift();
let [key, css] = args;
liberator.assert(!(clear && css), "Trailing characters");
if (!css && !clear) {
// List matching keys
let str = template.tabular(["Key", { header: "Sample", style: "text-align: center" }, "CSS"],
([h.class,
xml`<span style=${h.value + style}>XXX</span>`,
template.highlightRegexp(h.value, /\b[-\w]+(?=:)/g, function (str) xml`<span style="font-weight: bold;">${str}</span>`)]
for (h in highlight)
if (!key || h.class.indexOf(key) > -1)));
commandline.echo(str, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
return;
}
if (!key && clear)
highlight.clear();
else {
let error = highlight.set(key, css, clear, "-append" in args);
if (error)
liberator.echoerr(error);
}
},
{
// TODO: add this as a standard highlight completion function?
completer: function (context, args) {
// Complete a highlight group on :hi clear ...
if (args.completeArg > 0 && args[0] == "clear")
args.completeArg = args.completeArg > 1 ? -1 : 0;
if (args.completeArg == 0)
context.completions = [[v.class, v.value] for (v in highlight)];
else if (args.completeArg == 1) {
let hl = highlight.get(args[0]);
if (hl)
context.completions = [[hl.value.replace(/\n+/g, " "), "Current Value"], [hl.default || "", "Default Value"]];
}
},
hereDoc: true,
literal: 1,
options: [[["-append", "-a"], commands.OPTION_NOARG]],
serial: function () [
{
command: this.name,
arguments: [v.class],
literalArg: v.value
}
for (v in highlight)
if (v.value != v.default)
]
});
},
completion: function () {
completion.colorScheme = function colorScheme(context) {
context.title = ["Color Scheme", "Runtime Path"];
context.keys = { text: function (f) f.leafName.replace(/\.vimp$/, ""), description: ".parent.path" };
context.completions = util.Array.flatten(
io.getRuntimeDirectories("colors").map(
function (dir) dir.readDirectory().filter(
function (file) /\.vimp$/.test(file.leafName))))
};
completion.highlightGroup = function highlightGroup(context) {
context.title = ["Highlight Group", "Value"];
context.completions = [[v.class, v.value] for (v in highlight)];
};
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
/**
* @instance quickmarks
*/
const QuickMarks = Module("quickmarks", {
requires: ["config", "storage"],
init: function () {
this._qmarks = storage.newMap("quickmarks", { store: true, privateData: true });
},
/**
* Adds a new quickmark with name <b>qmark</b> referencing
* the URL <b>location</b>. Any existing quickmark with the same name
* will be replaced.
*
* @param {string} qmark The name of the quickmark {A-Z}.
* @param {string} location The URL accessed by this quickmark.
*/
add: function add(qmark, location) {
this._qmarks.set(qmark, location);
liberator.echomsg("Added QuickMark '" + qmark + "': " + location);
},
/**
* Deletes the specified quickmarks. The <b>filter</b> is a list of
* quickmarks and ranges are supported. Eg. "ab c d e-k".
*
* @param {string} filter The list of quickmarks to delete.
*
*/
remove: function remove(filter) {
let pattern = RegExp("[" + filter.replace(/\s+/g, "") + "]");
for (let [qmark, ] in this._qmarks) {
if (pattern.test(qmark))
this._qmarks.remove(qmark);
}
},
/**
* Removes all quickmarks.
*/
removeAll: function removeAll() {
this._qmarks.clear();
},
/**
* Opens the URL referenced by the specified <b>qmark</b>.
*
* @param {string} qmark The quickmark to open.
* @param {number} where A constant describing where to open the page.
* See {@link Liberator#open}.
*/
jumpTo: function jumpTo(qmark, where) {
let url = this._qmarks.get(qmark);
if (url)
liberator.open(url, where);
else
liberator.echoerr("QuickMark not set: " + qmark);
},
/**
* Lists all quickmarks matching <b>filter</b> in the message window.
*
* @param {string} filter The list of quickmarks to display. Eg. "abc"
* Ranges are not supported.
*/
// FIXME: filter should match that of quickmarks.remove or vice versa
list: function list(filter) {
let marks = [k for ([k, v] in this._qmarks)];
let lowercaseMarks = marks.filter(function (x) /[a-z]/.test(x)).sort();
let uppercaseMarks = marks.filter(function (x) /[A-Z]/.test(x)).sort();
let numberMarks = marks.filter(function (x) /[0-9]/.test(x)).sort();
marks = Array.concat(lowercaseMarks, uppercaseMarks, numberMarks);
liberator.assert(marks.length > 0, "No QuickMarks set");
if (filter.length > 0) {
marks = marks.filter(function (qmark) filter.indexOf(qmark) >= 0);
liberator.assert(marks.length >= 0, "No matching QuickMarks for: " + filter);
}
let items = [[mark, this._qmarks.get(mark)] for (mark of marks)];
template.genericTable(items, { title: ["QuickMark", "URL"] });
}
}, {
}, {
commands: function () {
commands.add(["delqm[arks]"],
"Delete the specified QuickMarks",
function (args) {
// TODO: finish arg parsing - we really need a proper way to do this. :)
// assert(args.bang ^ args.string)
liberator.assert( args.bang || args.string, "Argument required");
liberator.assert(!args.bang || !args.string, "Invalid argument");
if (args.bang)
quickmarks.removeAll();
else
quickmarks.remove(args.string);
},
{
bang: true,
completer: function (context) {
context.title = ["QuickMark", "URL"];
context.completions = quickmarks._qmarks;
}
});
commands.add(["qma[rk]"],
"Mark a URL with a letter for quick access",
function (args) {
let matches = args.string.match(/^([a-zA-Z0-9])(?:\s+(.+))?$/);
if (!matches)
liberator.echoerr("Trailing characters");
else if (!matches[2])
quickmarks.add(matches[1], buffer.URL);
else
quickmarks.add(matches[1], matches[2]);
},
{ argCount: "+" });
commands.add(["qmarks"],
"Show all QuickMarks",
function (args) {
args = args.string;
// ignore invalid qmark characters unless there are no valid qmark chars
liberator.assert(!args || /[a-zA-Z0-9]/.test(args), "No matching QuickMarks for: " + args);
let filter = args.replace(/[^a-zA-Z0-9]/g, "");
quickmarks.list(filter);
});
},
mappings: function () {
var myModes = config.browserModes;
mappings.add(myModes,
["go"], "Jump to a QuickMark",
function (arg) { quickmarks.jumpTo(arg, liberator.CURRENT_TAB); },
{ arg: true });
mappings.add(myModes,
["gn"], "Jump to a QuickMark in a new tab",
function (arg) {
quickmarks.jumpTo(arg,
options.get("activate").has("all", "quickmark") ?
liberator.NEW_TAB : liberator.NEW_BACKGROUND_TAB);
},
{ arg: true });
mappings.add(myModes,
["M"], "Add new QuickMark for current URL",
function (arg) {
liberator.assert(/^[a-zA-Z0-9]$/.test(arg));
quickmarks.add(arg, buffer.URL);
},
{ arg: true });
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const History = Module("history", {
requires: ["config"],
get format() bookmarks.format,
get service() services.get("history"),
get: function get(filter, maxItems) {
// no query parameters will get all history
let query = services.get("history").getNewQuery();
let options = services.get("history").getNewQueryOptions();
if (typeof filter == "string")
filter = { searchTerms: filter };
for (let [k, v] in Iterator(filter))
query[k] = v;
options.sortingMode = options.SORT_BY_DATE_DESCENDING;
options.resultType = options.RESULTS_AS_URI;
if (maxItems > 0)
options.maxResults = maxItems;
// execute the query
let root = services.get("history").executeQuery(query, options).root;
root.containerOpen = true;
let items = util.map(util.range(0, root.childCount), function (i) {
let node = root.getChild(i);
return {
url: node.uri,
title: node.title,
icon: node.icon,
};
});
root.containerOpen = false; // close a container after using it!
return items;
},
get session() {
let sh = window.getWebNavigation().sessionHistory;
let obj = [];
obj.index = sh.index;
obj.__iterator__ = function () util.Array.iteritems(this);
for (let i in util.range(0, sh.count)) {
obj[i] = { index: i, __proto__: sh.getEntryAtIndex(i, false) };
util.memoize(obj[i], "icon", function (obj) bookmarks.getFavicon(obj.URI));
}
return obj;
},
// TODO: better names
stepTo: function stepTo(steps) {
let start = 0;
let end = window.getWebNavigation().sessionHistory.count - 1;
let current = window.getWebNavigation().sessionHistory.index;
if (current == start && steps < 0 || current == end && steps > 0)
liberator.beep();
else {
let index = util.Math.constrain(current + steps, start, end);
window.getWebNavigation().gotoIndex(index);
}
},
goToStart: function goToStart() {
let index = window.getWebNavigation().sessionHistory.index;
if (index > 0)
window.getWebNavigation().gotoIndex(0);
else
liberator.beep();
},
goToEnd: function goToEnd() {
let sh = window.getWebNavigation().sessionHistory;
let max = sh.count - 1;
if (sh.index < max)
window.getWebNavigation().gotoIndex(max);
else
liberator.beep();
},
// if openItems is true, open the matching history items in tabs rather than display
list: function list(filter, openItems, maxItems) {
// FIXME: returning here doesn't make sense
// Why the hell doesn't it make sense? --Kris
// See comment at bookmarks.list --djk
if (!openItems)
return completion.listCompleter("history", filter, maxItems, null, null, CompletionContext.Filter.textAndDescription);
let items = completion.runCompleter("history", filter, maxItems, null, null, CompletionContext.Filter.textAndDescription);
if (items.length)
return liberator.open(items.map(function (i) i.url), liberator.NEW_TAB);
if (filter.length > 0)
liberator.echoerr("No matching history items for: " + filter);
else
liberator.echoerr("No history set");
return null;
}
}, {
}, {
commands: function () {
commands.add(["ba[ck]"],
"Go back in the browser history",
function (args) {
let url = args.literalArg;
if (args.bang)
history.goToStart();
else {
if (url) {
let sh = history.session;
if (/^\d+(:|$)/.test(url) && sh.index - parseInt(url) in sh)
return void window.getWebNavigation().gotoIndex(sh.index - parseInt(url));
for (let [i, ent] in Iterator(sh.slice(0, sh.index).reverse()))
if (ent.URI.spec == url)
return void window.getWebNavigation().gotoIndex(i);
liberator.echoerr("URL not found in history: " + url);
}
else
history.stepTo(-Math.max(args.count, 1));
}
return null;
},
{
argCount: "?",
bang: true,
completer: function completer(context) {
let sh = history.session;
context.anchored = false;
context.compare = CompletionContext.Sort.unsorted;
context.filters = [CompletionContext.Filter.textDescription];
context.completions = sh.slice(0, sh.index).reverse();
context.keys = { text: function (item) (sh.index - item.index) + ": " + item.URI.spec, description: "title", icon: "icon" };
},
count: true,
literal: 0
});
commands.add(["fo[rward]", "fw"],
"Go forward in the browser history",
function (args) {
let url = args.literalArg;
if (args.bang)
history.goToEnd();
else {
if (url) {
let sh = history.session;
if (/^\d+(:|$)/.test(url) && sh.index + parseInt(url) in sh)
return void window.getWebNavigation().gotoIndex(sh.index + parseInt(url));
for (let [i, ent] in Iterator(sh.slice(sh.index + 1)))
if (ent.URI.spec == url)
return void window.getWebNavigation().gotoIndex(i);
liberator.echoerr("URL not found in history: " + url);
}
else
history.stepTo(Math.max(args.count, 1));
}
return null;
},
{
argCount: "?",
bang: true,
completer: function completer(context) {
let sh = history.session;
context.anchored = false;
context.compare = CompletionContext.Sort.unsorted;
context.filters = [CompletionContext.Filter.textDescription];
context.completions = sh.slice(sh.index + 1);
context.keys = { text: function (item) (item.index - sh.index) + ": " + item.URI.spec, description: "title", icon: "icon" };
},
count: true,
literal: 0
});
commands.add(["hist[ory]", "hs"],
"Show recently visited URLs",
function (args) {
if (args["-remove"]) {
let items = completion.runCompleter("history", args.join(" "), args["-max"] || 1000);
if (items.length == 0)
liberator.echoerr("No matching history items for: " + args.join(" "));
else {
var browserHistory = Components.classes["@mozilla.org/browser/nav-history-service;1"]
.getService(Components.interfaces.nsIBrowserHistory);
var urls = [];
items.map(function (i) { urls.push(makeURI(i.url)) });
browserHistory.removePages(urls, urls.length);
if (urls.length == 1)
liberator.echo("Removed history item " + urls[0].spec);
else
liberator.echo("Removed " + urls.length + " history items matching " + args.join(" "));
}
} else
history.list(args.join(" "), args.bang, args["-max"] || 1000);
}, {
bang: true,
completer: function (context, args) {
context.filter = args.join(" ");
context.filters = [CompletionContext.Filter.textAndDescription];
context.quote = null;
completion.history(context);
},
options: [[["-max", "-m"], commands.OPTION_INT],
[["-remove", "-r"], commands.OPTION_NOARG]]
});
},
completion: function () {
completion.history = function _history(context, maxItems) {
context.format = history.format;
context.title = ["History"];
context.compare = CompletionContext.Sort.unsorted;
if (context.maxItems == null)
context.maxItems = 100;
context.regenerate = true;
context.generate = function () history.get(context.filter, this.maxItems);
};
completion.addUrlCompleter("h", "History", completion.history);
},
mappings: function () {
var myModes = config.browserModes;
mappings.add(myModes,
["<C-o>"], "Go to an older position in the jump list",
function (count) { history.stepTo(-Math.max(count, 1)); },
{ count: true });
mappings.add(myModes,
["<C-i>"], "Go to a newer position in the jump list",
function (count) { history.stepTo(Math.max(count, 1)); },
{ count: true });
mappings.add(myModes,
["H", "<A-Left>", "<M-Left>"], "Go back in the browser history",
function (count) { history.stepTo(-Math.max(count, 1)); },
{ count: true });
mappings.add(myModes,
["L", "<A-Right>", "<M-Right>"], "Go forward in the browser history",
function (count) { history.stepTo(Math.max(count, 1)); },
{ count: true });
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
/** @scope modules */
// command names taken from:
// http://developer.mozilla.org/en/docs/Editor_Embedding_Guide
/** @instance editor */
const Editor = Module("editor", {
requires: ["config", "abbreviations"],
init: function () {
// store our last search with f, F, t or T
this._lastFindChar = null;
this._lastFindCharFunc = null;
this._visualMode = "";
},
line: function () {
let line = 1;
let text = Editor.getEditor().value;
for (let i = 0; i < Editor.getEditor().selectionStart; i++)
if (text[i] == "\n")
line++;
return line;
},
col: function () {
let col = 1;
let text = Editor.getEditor().value;
for (let i = 0; i < Editor.getEditor().selectionStart; i++) {
col++;
if (text[i] == "\n")
col = 1;
}
return col;
},
unselectText: function () {
let e = Editor.getEditor();
if (e instanceof Window) {
e.getSelection().collapseToStart();
} else {
// A error occurs if the element has been removed when "e.selectionStart" is executed.
try {
if (e && e.selectionEnd)
e.selectionEnd = e.selectionStart;
}
catch (e) {}
}
},
selectedText: function () {
let e = Editor.getEditor();
if (e instanceof Window)
return e.getSelection().toString();
let text = e.value;
return text.substring(e.selectionStart, e.selectionEnd);
},
pasteClipboard: function () {
if (liberator.has("Windows")) {
this.executeCommand("cmd_paste");
return;
}
// FIXME: #93 (<s-insert> in the bottom of a long textarea bounces up)
let elem = liberator.focus;
if (elem.setSelectionRange && util.readFromClipboard()) {
// readFromClipboard would return 'undefined' if not checked
// dunno about .setSelectionRange
// This is a hacky fix - but it works.
let curTop = elem.scrollTop;
let curLeft = elem.scrollLeft;
let rangeStart = elem.selectionStart; // caret position
let rangeEnd = elem.selectionEnd;
let tempStr1 = elem.value.substring(0, rangeStart);
let tempStr2 = util.readFromClipboard();
let tempStr3 = elem.value.substring(rangeEnd);
elem.value = tempStr1 + tempStr2 + tempStr3;
elem.selectionStart = rangeStart + tempStr2.length;
elem.selectionEnd = elem.selectionStart;
elem.scrollTop = curTop;
elem.scrollLeft = curLeft;
}
},
// count is optional, defaults to 1
executeCommand: function (cmd, count) {
let controller = Editor.getController(cmd);
if (!controller || !controller.supportsCommand(cmd) || !controller.isCommandEnabled(cmd)) {
liberator.beep();
return false;
}
if (typeof count != "number" || count < 1)
count = 1;
let didCommand = false;
while (count--) {
// some commands need this try/catch workaround, because a cmd_charPrevious triggered
// at the beginning of the textarea, would hang the doCommand()
// good thing is, we need this code anyway for proper beeping
try {
controller.doCommand(cmd);
didCommand = true;
}
catch (e) {
if (!didCommand)
liberator.beep();
return false;
}
}
return true;
},
// cmd = y, d, c
// motion = b, 0, gg, G, etc.
executeCommandWithMotion: function (cmd, motion, count) {
if (typeof count != "number" || count < 1)
count = 1;
if (cmd == motion) {
motion = "j";
count--;
}
modes.set(modes.VISUAL, modes.TEXTAREA);
switch (motion) {
case "j":
this.executeCommand("cmd_beginLine", 1);
this.executeCommand("cmd_selectLineNext", count + 1);
break;
case "k":
this.executeCommand("cmd_beginLine", 1);
this.executeCommand("cmd_lineNext", 1);
this.executeCommand("cmd_selectLinePrevious", count + 1);
break;
case "h":
this.executeCommand("cmd_selectCharPrevious", count);
break;
case "l":
this.executeCommand("cmd_selectCharNext", count);
break;
case "e":
case "w":
this.executeCommand("cmd_selectWordNext", count);
break;
case "b":
this.executeCommand("cmd_selectWordPrevious", count);
break;
case "0":
case "^":
this.executeCommand("cmd_selectBeginLine", 1);
break;
case "$":
this.executeCommand("cmd_selectEndLine", 1);
break;
case "gg":
this.executeCommand("cmd_endLine", 1);
this.executeCommand("cmd_selectTop", 1);
this.executeCommand("cmd_selectBeginLine", 1);
break;
case "G":
this.executeCommand("cmd_beginLine", 1);
this.executeCommand("cmd_selectBottom", 1);
this.executeCommand("cmd_selectEndLine", 1);
break;
default:
liberator.beep();
return false;
}
switch (cmd) {
case "d":
this.executeCommand("cmd_delete", 1);
// need to reset the mode as the visual selection changes it
modes.main = modes.TEXTAREA;
break;
case "c":
this.executeCommand("cmd_delete", 1);
modes.set(modes.INSERT, modes.TEXTAREA);
break;
case "y":
this.executeCommand("cmd_copy", 1);
this.unselectText();
break;
default:
liberator.beep();
return false;
}
return true;
},
// This function will move/select up to given "pos"
// Simple setSelectionRange() would be better, but we want to maintain the correct
// order of selectionStart/End (a Gecko bug always makes selectionStart <= selectionEnd)
// Use only for small movements!
moveToPosition: function (pos, forward, select) {
if (!select) {
Editor.getEditor().setSelectionRange(pos, pos);
return;
}
if (forward) {
if (pos <= Editor.getEditor().selectionEnd || pos > Editor.getEditor().value.length)
return;
do { // TODO: test code for endless loops
this.executeCommand("cmd_selectCharNext", 1);
}
while (Editor.getEditor().selectionEnd != pos);
}
else {
if (pos >= Editor.getEditor().selectionStart || pos < 0)
return;
do { // TODO: test code for endless loops
this.executeCommand("cmd_selectCharPrevious", 1);
}
while (Editor.getEditor().selectionStart != pos);
}
},
// returns the position of char
findCharForward: function (ch, count) {
if (!Editor.getEditor())
return -1;
this._lastFindChar = ch;
this._lastFindCharFunc = this.findCharForward;
let text = Editor.getEditor().value;
if (!typeof count == "number" || count < 1)
count = 1;
for (let i = Editor.getEditor().selectionEnd + 1; i < text.length; i++) {
if (text[i] == "\n")
break;
if (text[i] == ch)
count--;
if (count == 0)
return i + 1; // always position the cursor after the char
}
liberator.beep();
return -1;
},
// returns the position of char
findCharBackward: function (ch, count) {
if (!Editor.getEditor())
return -1;
this._lastFindChar = ch;
this._lastFindCharFunc = this.findCharBackward;
let text = Editor.getEditor().value;
if (!typeof count == "number" || count < 1)
count = 1;
for (let i = Editor.getEditor().selectionStart - 1; i >= 0; i--) {
if (text[i] == "\n")
break;
if (text[i] == ch)
count--;
if (count == 0)
return i;
}
liberator.beep();
return -1;
},
editFileExternally: function (path) {
// TODO: save return value in v:shell_error
let args = commands.parseArgs(options["editor"], [], [], "*", true);
liberator.assert(args.length >= 1, "No editor specified");
args.push(path);
io.run(io.expandPath(args.shift()), args, true);
},
// TODO: clean up with 2 functions for textboxes and currentEditor?
editFieldExternally: function (forceEditing, field) {
if (!options["editor"])
return;
let textBox = null, nsEditor = null;
if (Editor.windowIsEditable()) {
let win = document.commandDispatcher.focusedWindow;
nsEditor = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIEditingSession)
.getEditorForWindow(win);
nsEditor instanceof Ci.nsIPlaintextEditor;
nsEditor instanceof Ci.nsIHTMLEditor;
}
else {
if (field !== undefined) {
textBox = field; // if I reply 'yes', textBox.value == 'yes', so get the real value
} else {
textBox = liberator.focus;
}
}
if (!forceEditing && textBox && textBox.type == "password") {
commandline.input("Editing a password field externally will reveal the password. Would you like to continue? (yes/[no]): ",
function (resp) {
if (resp && resp.match(/^y(es)?$/i))
editor.editFieldExternally(true, textBox);
});
return;
}
let text = ""; // XXX
let isHTML = false;
if (textBox) {
text = textBox.value;
}
else if (nsEditor) {
isHTML = nsEditor.flags & Ci.nsIPlaintextEditor.eEditorPlaintextMask ? false : true;
text = isHTML ?
nsEditor.outputToString("text/html", Ci.nsIDocumentEncoder.OutputBodyOnly) :
nsEditor.outputToString("text/plain", Ci.nsIDocumentEncoder.OutpuFormatted);
}
else {
return;
}
let elem, oldBg, tmpBg;
try {
let res = io.withTempFiles(function (tmpfile) {
if (textBox) {
textBox.setAttribute("readonly", "true");
elem = textBox;
}
else if (nsEditor) {
nsEditor.flags |= Ci.nsIPlaintextEditor.eEditorReadonlyMask;
elem = nsEditor.rootElement;
}
oldBg = elem.style.backgroundColor;
tmpBg = "yellow";
elem.style.backgroundColor = "#bbbbbb";
if (!tmpfile.write(text))
throw Error("Input contains characters not valid in the current " +
"file encoding");
let lastUpdate = Date.now();
function update (force) {
if (force != true && tmpfile.lastModifiedTime <= lastUpdate)
return;
lastUpdate = Date.now();
let val = tmpfile.read();
if (textBox)
textBox.value = val;
else if (nsEditor) {
let wholeDocRange = nsEditor.document.createRange();
let rootNode = nsEditor.rootElement.QueryInterface(Ci.nsIDOMNode);
wholeDocRange.selectNodeContents(rootNode);
nsEditor.selection.addRange(wholeDocRange);
nsEditor.selection.deleteFromDocument();
if (isHTML) {
let doc = nsEditor.document;
let range = doc.createRange();
range.setStartAfter(doc.body);
doc.body.appendChild(range.createContextualFragment(val));
}
else {
nsEditor.insertText(val);
}
let lastChild = rootNode.lastChild;
while (lastChild.localName === "br" &&
(lastChild.hasAttribute("_moz_editor_bogus_node") || lastChild.hasAttribute("type"))) {
nsEditor.rootElement.removeChild(lastChild)
lastChild = rootNode.lastChild;
}
}
}
let timer = services.create("timer");
timer.initWithCallback({ notify: update }, 100, timer.TYPE_REPEATING_SLACK);
try {
this.editFileExternally(tmpfile.path);
}
finally {
timer.cancel();
}
update(true);
}, this);
if (res == false)
throw Error("Couldn't create temporary file");
}
catch (e) {
// Errors are unlikely, and our error messages won't
// likely be any more helpful than that given in the
// exception.
liberator.echoerr(e);
tmpBg = "red";
}
finally {
if (textBox)
textBox.removeAttribute("readonly");
else if (nsEditor)
nsEditor.flags &= ~Ci.nsIPlaintextEditor.eEditorReadonlyMask;
}
// blink the textbox after returning
if (elem) {
let colors = [tmpBg, oldBg, tmpBg, oldBg];
(function () {
elem.style.backgroundColor = colors.shift();
if (colors.length > 0)
setTimeout(arguments.callee, 100);
})();
}
return;
},
/**
* Expands an abbreviation in the currently active textbox.
*
* @param {string} filter The mode filter.
* @see #addAbbreviation
*/
expandAbbreviation: function (mode) {
let textbox = Editor.getEditor();
if (!textbox)
return false;
let text = textbox.value;
let currStart = textbox.selectionStart;
let currEnd = textbox.selectionEnd;
let foundWord = text.substring(0, currStart).replace(/.*[\s\n]/gm, '').match(RegExp('(' + abbreviations._match + ')$'));
if (!foundWord)
return true;
foundWord = foundWord[0];
let abbrev = abbreviations.get(mode, foundWord);
if (abbrev) {
let len = foundWord.length;
let abbrText = abbrev.text;
text = text.substring(0, currStart - len) + abbrText + text.substring(currStart);
textbox.value = text;
textbox.selectionStart = currStart - len + abbrText.length;
textbox.selectionEnd = currEnd - len + abbrText.length;
}
return true;
},
getVisualMode: function() {
return this._visualMode;
},
setVisualMode: function(value) {
this._visualMode = value;
modes.show();
}
}, {
getEditor: function () {
let e = liberator.focus;
if (!e || e.isContentEditable) {
e = document.commandDispatcher.focusedWindow;
if (!Editor.windowIsEditable(e))
return null;
} else if (config.isComposeWindow
&& document.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_DISCONNECTED
&& window.GetCurrentEditor) {
return window.GetCurrentEditor().document.defaultView;
}
return e;
},
getController: function (cmd) {
let ed = Editor.getEditor();
if (!ed || !ed.controllers)
return null;
return ed.controllers.getControllerForCommand(cmd || "cmd_beginLine");
},
windowIsEditable: function (win) {
if (!win)
win = document.commandDispatcher.focusedWindow;
if (!(win instanceof Window))
return false;
let editingSession = win
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIEditingSession);
return editingSession.windowIsEditable(win) &&
(win.document.designMode === "on" ||
(services.get("focus").getFocusedElementForWindow(win, true, {})||{}).isContentEditable);
}
}, {
mappings: function () {
var myModes = [modes.INSERT, modes.COMMAND_LINE];
// add mappings for commands like h,j,k,l,etc. in CARET, VISUAL and TEXTAREA mode
function addMovementMap(keys, hasCount, caretModeMethod, caretModeArg, textareaCommand, visualTextareaCommand) {
let extraInfo = {};
if (hasCount)
extraInfo.count = true;
mappings.add([modes.CARET], keys, "",
function (count) {
if (typeof count != "number" || count < 1)
count = 1;
let controller = buffer.selectionController;
while (count--)
controller[caretModeMethod](caretModeArg, false);
},
extraInfo);
mappings.add([modes.VISUAL], keys, "",
function (count) {
if (typeof count != "number" || count < 1 || !hasCount)
count = 1;
let controller = buffer.selectionController;
while (count--) {
if (modes.extended & modes.TEXTAREA) {
if (typeof visualTextareaCommand == "function")
visualTextareaCommand();
else
editor.executeCommand(visualTextareaCommand);
}
else
controller[caretModeMethod](caretModeArg, true);
}
},
extraInfo);
mappings.add([modes.TEXTAREA], keys, "",
function (count) {
if (typeof count != "number" || count < 1)
count = 1;
editor.executeCommand(textareaCommand, count);
},
extraInfo);
}
// add mappings for commands like i,a,s,c,etc. in TEXTAREA mode
function addBeginInsertModeMap(keys, commands) {
mappings.add([modes.TEXTAREA], keys, "",
function (count) {
commands.forEach(function (cmd)
editor.executeCommand(cmd, 1));
modes.set(modes.INSERT, modes.TEXTAREA);
});
}
function addMotionMap(key) {
mappings.add([modes.TEXTAREA], [key],
"Motion command",
function (motion, count) { editor.executeCommandWithMotion(key, motion, count); },
{ count: true, motion: true });
}
function selectPreviousLine() {
editor.executeCommand("cmd_selectLinePrevious");
if (editor.getVisualMode() == "LINE" && !editor.selectedText())
editor.executeCommand("cmd_selectLinePrevious");
}
function selectNextLine() {
editor.executeCommand("cmd_selectLineNext");
if (editor.getVisualMode() == "LINE" && !editor.selectedText())
editor.executeCommand("cmd_selectLineNext");
}
// KEYS COUNT CARET TEXTAREA VISUAL_TEXTAREA
addMovementMap(["k", "<Up>"], true, "lineMove", false, "cmd_linePrevious", selectPreviousLine);
addMovementMap(["j", "<Down>", "<Return>"], true, "lineMove", true, "cmd_lineNext", selectNextLine);
addMovementMap(["h", "<Left>", "<BS>"], true, "characterMove", false, "cmd_charPrevious", "cmd_selectCharPrevious");
addMovementMap(["l", "<Right>", "<Space>"], true, "characterMove", true, "cmd_charNext", "cmd_selectCharNext");
addMovementMap(["b", "B", "<C-Left>"], true, "wordMove", false, "cmd_wordPrevious", "cmd_selectWordPrevious");
addMovementMap(["w", "W", "e", "<C-Right>"], true, "wordMove", true, "cmd_wordNext", "cmd_selectWordNext");
addMovementMap(["<C-f>", "<PageDown>"], true, "pageMove", true, "cmd_movePageDown", "cmd_selectNextPage");
addMovementMap(["<C-b>", "<PageUp>"], true, "pageMove", false, "cmd_movePageUp", "cmd_selectPreviousPage");
addMovementMap(["gg", "<C-Home>"], false, "completeMove", false, "cmd_moveTop", "cmd_selectTop");
addMovementMap(["G", "<C-End>"], false, "completeMove", true, "cmd_moveBottom", "cmd_selectBottom");
addMovementMap(["0", "^", "<Home>"], false, "intraLineMove", false, "cmd_beginLine", "cmd_selectBeginLine");
addMovementMap(["$", "<End>"], false, "intraLineMove", true, "cmd_endLine" , "cmd_selectEndLine" );
addBeginInsertModeMap(["i", "<Insert>"], []);
addBeginInsertModeMap(["a"], ["cmd_charNext"]);
addBeginInsertModeMap(["I", "gI"], ["cmd_beginLine"]);
addBeginInsertModeMap(["A"], ["cmd_endLine"]);
addBeginInsertModeMap(["s"], ["cmd_deleteCharForward"]);
addBeginInsertModeMap(["S"], ["cmd_deleteToEndOfLine", "cmd_deleteToBeginningOfLine"]);
addBeginInsertModeMap(["C"], ["cmd_deleteToEndOfLine"]);
addMotionMap("d"); // delete
addMotionMap("c"); // change
addMotionMap("y"); // yank
// insert mode mappings
mappings.add([modes.INSERT],
["<C-w>"], "Delete previous word",
function () { editor.executeCommand("cmd_deleteWordBackward", 1); });
mappings.add([modes.COMMAND_LINE],
["<C-w>"], "Delete previous word",
function () {
// XXX Error occurs on doCommand, when completion's preview is available.
if (commandline._completions)
commandline._completions.previewClear();
editor.executeCommand("cmd_deleteWordBackward", 1);
});
mappings.add(myModes,
["<C-u>"], "Delete until beginning of current line",
function () {
// broken in FF3, deletes the whole line:
// editor.executeCommand("cmd_deleteToBeginningOfLine", 1);
editor.executeCommand("cmd_selectBeginLine", 1);
editor.executeCommand("cmd_delete", 1);
});
mappings.add(myModes,
["<C-k>"], "Delete until end of current line",
function () { editor.executeCommand("cmd_deleteToEndOfLine", 1); });
mappings.add(myModes,
["<C-a>"], "Move cursor to beginning of current line",
function () { editor.executeCommand("cmd_beginLine", 1); });
mappings.add(myModes,
["<C-e>"], "Move cursor to end of current line",
function () { editor.executeCommand("cmd_endLine", 1); });
mappings.add(myModes,
["<C-h>"], "Delete character to the left",
function () { editor.executeCommand("cmd_deleteCharBackward", 1); });
mappings.add(myModes,
["<C-d>"], "Delete character to the right",
function () { editor.executeCommand("cmd_deleteCharForward", 1); });
/*mappings.add(myModes,
["<C-Home>"], "Move cursor to beginning of text field",
function () { editor.executeCommand("cmd_moveTop", 1); });
mappings.add(myModes,
["<C-End>"], "Move cursor to end of text field",
function () { editor.executeCommand("cmd_moveBottom", 1); });*/
mappings.add(myModes,
["<S-Insert>"], "Insert clipboard/selection",
function () { editor.pasteClipboard(); });
mappings.add(modes.getCharModes("i"),
["<C-i>"], "Edit text field with an external editor",
function () { editor.editFieldExternally(); });
mappings.add([modes.INSERT],
["<C-t>"], "Edit text field in Vi mode",
function () { liberator.mode = modes.TEXTAREA; });
mappings.add([modes.INSERT],
["<Space>", "<Return>"], "Expand insert mode abbreviation",
function () { editor.expandAbbreviation(modes.INSERT); },
{ route: true });
mappings.add([modes.INSERT],
["<Tab>"], "Expand insert mode abbreviation",
function () { editor.expandAbbreviation(modes.INSERT); document.commandDispatcher.advanceFocus(); });
mappings.add([modes.INSERT],
["<C-]>", "<C-5>"], "Expand insert mode abbreviation",
function () { editor.expandAbbreviation(modes.INSERT); });
// textarea mode
mappings.add([modes.TEXTAREA],
["u"], "Undo",
function (count) {
editor.executeCommand("cmd_undo", count);
liberator.mode = modes.TEXTAREA;
},
{ count: true });
mappings.add([modes.TEXTAREA],
["<C-r>"], "Redo",
function (count) {
editor.executeCommand("cmd_redo", count);
liberator.mode = modes.TEXTAREA;
},
{ count: true });
mappings.add([modes.TEXTAREA],
["D"], "Delete the characters under the cursor until the end of the line",
function () { editor.executeCommand("cmd_deleteToEndOfLine"); });
mappings.add([modes.TEXTAREA],
["o"], "Open line below current",
function (count) {
editor.executeCommand("cmd_endLine", 1);
modes.set(modes.INSERT, modes.TEXTAREA);
events.feedkeys("<Return>");
});
mappings.add([modes.TEXTAREA],
["O"], "Open line above current",
function (count) {
editor.executeCommand("cmd_beginLine", 1);
modes.set(modes.INSERT, modes.TEXTAREA);
events.feedkeys("<Return>");
editor.executeCommand("cmd_linePrevious", 1);
});
mappings.add([modes.TEXTAREA],
["X"], "Delete character to the left",
function (count) { editor.executeCommand("cmd_deleteCharBackward", count); },
{ count: true });
mappings.add([modes.TEXTAREA],
["x"], "Delete character to the right",
function (count) { editor.executeCommand("cmd_deleteCharForward", count); },
{ count: true });
// visual mode
mappings.add([modes.CARET, modes.TEXTAREA],
["v"], "Start visual mode",
function (count) {
modes.set(modes.VISUAL, liberator.mode);
editor.setVisualMode("");
});
mappings.add([modes.VISUAL],
["v"], "End visual mode",
function (count) { events.onEscape(); });
mappings.add([modes.TEXTAREA],
["V"], "Start visual line mode",
function (count) {
//modes.set(modes.VISUAL, modes.TEXTAREA | modes.LINE);
modes.set(modes.VISUAL, liberator.mode);
editor.setVisualMode("LINE");
editor.executeCommand("cmd_beginLine", 1);
editor.executeCommand("cmd_selectLineNext", 1);
});
mappings.add([modes.VISUAL],
["c", "s"], "Change selected text",
function (count) {
liberator.assert(modes.extended & modes.TEXTAREA);
editor.executeCommand("cmd_cut");
modes.set(modes.INSERT, modes.TEXTAREA);
});
mappings.add([modes.VISUAL],
["d"], "Delete selected text",
function (count) {
if (modes.extended & modes.TEXTAREA) {
editor.executeCommand("cmd_cut");
modes.set(modes.TEXTAREA);
}
else
liberator.beep();
});
mappings.add([modes.VISUAL],
["y"], "Yank selected text",
function (count) {
if (modes.extended & modes.TEXTAREA) {
editor.executeCommand("cmd_copy");
modes.set(modes.TEXTAREA);
}
else {
util.copyToClipboard(buffer.getCurrentWord(), true);
}
});
mappings.add([modes.VISUAL, modes.TEXTAREA],
["p"], "Paste clipboard contents",
function (count) {
liberator.assert(!(modes.extended & modes.CARET));
if (!count)
count = 1;
while (count--)
editor.executeCommand("cmd_paste");
liberator.mode = modes.TEXTAREA;
});
// finding characters
mappings.add([modes.TEXTAREA, modes.VISUAL],
["f"], "Move to a character on the current line after the cursor",
function (count, arg) {
let pos = editor.findCharForward(arg, count);
if (pos >= 0)
editor.moveToPosition(pos, true, liberator.mode == modes.VISUAL);
},
{ arg: true, count: true });
mappings.add([modes.TEXTAREA, modes.VISUAL],
["F"], "Move to a charater on the current line before the cursor",
function (count, arg) {
let pos = editor.findCharBackward(arg, count);
if (pos >= 0)
editor.moveToPosition(pos, false, liberator.mode == modes.VISUAL);
},
{ arg: true, count: true });
mappings.add([modes.TEXTAREA, modes.VISUAL],
["t"], "Move before a character on the current line",
function (count, arg) {
let pos = editor.findCharForward(arg, count);
if (pos >= 0)
editor.moveToPosition(pos - 1, true, liberator.mode == modes.VISUAL);
},
{ arg: true, count: true });
mappings.add([modes.TEXTAREA, modes.VISUAL],
["T"], "Move before a character on the current line, backwards",
function (count, arg) {
let pos = editor.findCharBackward(arg, count);
if (pos >= 0)
editor.moveToPosition(pos + 1, false, liberator.mode == modes.VISUAL);
},
{ arg: true, count: true });
// textarea and visual mode
mappings.add([modes.TEXTAREA, modes.VISUAL],
["~"], "Switch case of the character under the cursor and move the cursor to the right",
function (count) {
if (modes.main == modes.VISUAL)
count = Editor.getEditor().selectionEnd - Editor.getEditor().selectionStart;
if (typeof count != "number" || count < 1)
count = 1;
while (count-- > 0) {
let text = Editor.getEditor().value;
let pos = Editor.getEditor().selectionStart;
liberator.assert(pos < text.length);
let chr = text[pos];
Editor.getEditor().value = text.substring(0, pos) +
(chr == chr.toLocaleLowerCase() ? chr.toLocaleUpperCase() : chr.toLocaleLowerCase()) +
text.substring(pos + 1);
editor.moveToPosition(pos + 1, true, false);
}
modes.set(modes.TEXTAREA);
},
{ count: true });
},
options: function () {
options.add(["editor"],
"Set the external text editor",
"string", "gvim -f");
options.add(["insertmode", "im"],
"Use Insert mode as the default for text areas",
"boolean", true);
}
});
// vim: set fdm=marker sw=4 ts=4 et:
| JavaScript |
window.onload=function(){
var offsetLeft=$('menu').offsetLeft;
Event.observe('menu', 'mousemove', function(event){
coordinateX=Event.pointerX(event)-offsetLeft;
$('slider').style.marginLeft=coordinateX-20+'px';
});
} | JavaScript |
/* Prototype JavaScript framework, version 1.6.0.2
* (c) 2005-2008 Sam Stephenson
*
* Prototype is freely distributable under the terms of an MIT-style license.
* For details, see the Prototype web site: http://www.prototypejs.org/
*
*--------------------------------------------------------------------------*/
var Prototype = {
Version: '1.6.0.2',
Browser: {
IE: !!(window.attachEvent && !window.opera),
Opera: !!window.opera,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
},
BrowserFeatures: {
XPath: !!document.evaluate,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
document.createElement('div').__proto__ &&
document.createElement('div').__proto__ !==
document.createElement('form').__proto__
},
ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
emptyFunction: function() { },
K: function(x) { return x }
};
if (Prototype.Browser.MobileSafari)
Prototype.BrowserFeatures.SpecificElementExtensions = false;
/* Based on Alex Arnell's inheritance implementation. */
var Class = {
create: function() {
var parent = null, properties = $A(arguments);
if (Object.isFunction(properties[0]))
parent = properties.shift();
function klass() {
this.initialize.apply(this, arguments);
}
Object.extend(klass, Class.Methods);
klass.superclass = parent;
klass.subclasses = [];
if (parent) {
var subclass = function() { };
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
parent.subclasses.push(klass);
}
for (var i = 0; i < properties.length; i++)
klass.addMethods(properties[i]);
if (!klass.prototype.initialize)
klass.prototype.initialize = Prototype.emptyFunction;
klass.prototype.constructor = klass;
return klass;
}
};
Class.Methods = {
addMethods: function(source) {
var ancestor = this.superclass && this.superclass.prototype;
var properties = Object.keys(source);
if (!Object.keys({ toString: true }).length)
properties.push("toString", "valueOf");
for (var i = 0, length = properties.length; i < length; i++) {
var property = properties[i], value = source[property];
if (ancestor && Object.isFunction(value) &&
value.argumentNames().first() == "$super") {
var method = value, value = Object.extend((function(m) {
return function() { return ancestor[m].apply(this, arguments) };
})(property).wrap(method), {
valueOf: function() { return method },
toString: function() { return method.toString() }
});
}
this.prototype[property] = value;
}
return this;
}
};
var Abstract = { };
Object.extend = function(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
};
Object.extend(Object, {
inspect: function(object) {
try {
if (Object.isUndefined(object)) return 'undefined';
if (object === null) return 'null';
return object.inspect ? object.inspect() : String(object);
} catch (e) {
if (e instanceof RangeError) return '...';
throw e;
}
},
toJSON: function(object) {
var type = typeof object;
switch (type) {
case 'undefined':
case 'function':
case 'unknown': return;
case 'boolean': return object.toString();
}
if (object === null) return 'null';
if (object.toJSON) return object.toJSON();
if (Object.isElement(object)) return;
var results = [];
for (var property in object) {
var value = Object.toJSON(object[property]);
if (!Object.isUndefined(value))
results.push(property.toJSON() + ': ' + value);
}
return '{' + results.join(', ') + '}';
},
toQueryString: function(object) {
return $H(object).toQueryString();
},
toHTML: function(object) {
return object && object.toHTML ? object.toHTML() : String.interpret(object);
},
keys: function(object) {
var keys = [];
for (var property in object)
keys.push(property);
return keys;
},
values: function(object) {
var values = [];
for (var property in object)
values.push(object[property]);
return values;
},
clone: function(object) {
return Object.extend({ }, object);
},
isElement: function(object) {
return object && object.nodeType == 1;
},
isArray: function(object) {
return object != null && typeof object == "object" &&
'splice' in object && 'join' in object;
},
isHash: function(object) {
return object instanceof Hash;
},
isFunction: function(object) {
return typeof object == "function";
},
isString: function(object) {
return typeof object == "string";
},
isNumber: function(object) {
return typeof object == "number";
},
isUndefined: function(object) {
return typeof object == "undefined";
}
});
Object.extend(Function.prototype, {
argumentNames: function() {
var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
return names.length == 1 && !names[0] ? [] : names;
},
bind: function() {
if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
},
bindAsEventListener: function() {
var __method = this, args = $A(arguments), object = args.shift();
return function(event) {
return __method.apply(object, [event || window.event].concat(args));
}
},
curry: function() {
if (!arguments.length) return this;
var __method = this, args = $A(arguments);
return function() {
return __method.apply(this, args.concat($A(arguments)));
}
},
delay: function() {
var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
return window.setTimeout(function() {
return __method.apply(__method, args);
}, timeout);
},
wrap: function(wrapper) {
var __method = this;
return function() {
return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
}
},
methodize: function() {
if (this._methodized) return this._methodized;
var __method = this;
return this._methodized = function() {
return __method.apply(null, [this].concat($A(arguments)));
};
}
});
Function.prototype.defer = Function.prototype.delay.curry(0.01);
Date.prototype.toJSON = function() {
return '"' + this.getUTCFullYear() + '-' +
(this.getUTCMonth() + 1).toPaddedString(2) + '-' +
this.getUTCDate().toPaddedString(2) + 'T' +
this.getUTCHours().toPaddedString(2) + ':' +
this.getUTCMinutes().toPaddedString(2) + ':' +
this.getUTCSeconds().toPaddedString(2) + 'Z"';
};
var Try = {
these: function() {
var returnValue;
for (var i = 0, length = arguments.length; i < length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) { }
}
return returnValue;
}
};
RegExp.prototype.match = RegExp.prototype.test;
RegExp.escape = function(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
/*--------------------------------------------------------------------------*/
var PeriodicalExecuter = Class.create({
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback();
},
registerCallback: function() {
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
execute: function() {
this.callback(this);
},
stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.execute();
} finally {
this.currentlyExecuting = false;
}
}
}
});
Object.extend(String, {
interpret: function(value) {
return value == null ? '' : String(value);
},
specialChar: {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'\\': '\\\\'
}
});
Object.extend(String.prototype, {
gsub: function(pattern, replacement) {
var result = '', source = this, match;
replacement = arguments.callee.prepareReplacement(replacement);
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
result += String.interpret(replacement(match));
source = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
}
}
return result;
},
sub: function(pattern, replacement, count) {
replacement = this.gsub.prepareReplacement(replacement);
count = Object.isUndefined(count) ? 1 : count;
return this.gsub(pattern, function(match) {
if (--count < 0) return match[0];
return replacement(match);
});
},
scan: function(pattern, iterator) {
this.gsub(pattern, iterator);
return String(this);
},
truncate: function(length, truncation) {
length = length || 30;
truncation = Object.isUndefined(truncation) ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) + truncation : String(this);
},
strip: function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
},
stripTags: function() {
return this.replace(/<\/?[^>]+>/gi, '');
},
stripScripts: function() {
return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
},
extractScripts: function() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
return (this.match(matchAll) || []).map(function(scriptTag) {
return (scriptTag.match(matchOne) || ['', ''])[1];
});
},
evalScripts: function() {
return this.extractScripts().map(function(script) { return eval(script) });
},
escapeHTML: function() {
var self = arguments.callee;
self.text.data = this;
return self.div.innerHTML;
},
unescapeHTML: function() {
var div = new Element('div');
div.innerHTML = this.stripTags();
return div.childNodes[0] ? (div.childNodes.length > 1 ?
$A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
div.childNodes[0].nodeValue) : '';
},
toQueryParams: function(separator) {
var match = this.strip().match(/([^?#]*)(#.*)?$/);
if (!match) return { };
return match[1].split(separator || '&').inject({ }, function(hash, pair) {
if ((pair = pair.split('='))[0]) {
var key = decodeURIComponent(pair.shift());
var value = pair.length > 1 ? pair.join('=') : pair[0];
if (value != undefined) value = decodeURIComponent(value);
if (key in hash) {
if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
hash[key].push(value);
}
else hash[key] = value;
}
return hash;
});
},
toArray: function() {
return this.split('');
},
succ: function() {
return this.slice(0, this.length - 1) +
String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
},
times: function(count) {
return count < 1 ? '' : new Array(count + 1).join(this);
},
camelize: function() {
var parts = this.split('-'), len = parts.length;
if (len == 1) return parts[0];
var camelized = this.charAt(0) == '-'
? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
: parts[0];
for (var i = 1; i < len; i++)
camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
return camelized;
},
capitalize: function() {
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
},
underscore: function() {
return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
},
dasherize: function() {
return this.gsub(/_/,'-');
},
inspect: function(useDoubleQuotes) {
var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
var character = String.specialChar[match[0]];
return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
});
if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
},
toJSON: function() {
return this.inspect(true);
},
unfilterJSON: function(filter) {
return this.sub(filter || Prototype.JSONFilter, '#{1}');
},
isJSON: function() {
var str = this;
if (str.blank()) return false;
str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
},
evalJSON: function(sanitize) {
var json = this.unfilterJSON();
try {
if (!sanitize || json.isJSON()) return eval('(' + json + ')');
} catch (e) { }
throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
},
include: function(pattern) {
return this.indexOf(pattern) > -1;
},
startsWith: function(pattern) {
return this.indexOf(pattern) === 0;
},
endsWith: function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
},
empty: function() {
return this == '';
},
blank: function() {
return /^\s*$/.test(this);
},
interpolate: function(object, pattern) {
return new Template(this, pattern).evaluate(object);
}
});
if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
escapeHTML: function() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
},
unescapeHTML: function() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
});
String.prototype.gsub.prepareReplacement = function(replacement) {
if (Object.isFunction(replacement)) return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };
};
String.prototype.parseQuery = String.prototype.toQueryParams;
Object.extend(String.prototype.escapeHTML, {
div: document.createElement('div'),
text: document.createTextNode('')
});
with (String.prototype.escapeHTML) div.appendChild(text);
var Template = Class.create({
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},
evaluate: function(object) {
if (Object.isFunction(object.toTemplateReplacements))
object = object.toTemplateReplacements();
return this.template.gsub(this.pattern, function(match) {
if (object == null) return '';
var before = match[1] || '';
if (before == '\\') return match[2];
var ctx = object, expr = match[3];
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
match = pattern.exec(expr);
if (match == null) return before;
while (match != null) {
var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
ctx = ctx[comp];
if (null == ctx || '' == match[3]) break;
expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
match = pattern.exec(expr);
}
return before + String.interpret(ctx);
});
}
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
var $break = { };
var Enumerable = {
each: function(iterator, context) {
var index = 0;
iterator = iterator.bind(context);
try {
this._each(function(value) {
iterator(value, index++);
});
} catch (e) {
if (e != $break) throw e;
}
return this;
},
eachSlice: function(number, iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var index = -number, slices = [], array = this.toArray();
while ((index += number) < array.length)
slices.push(array.slice(index, index+number));
return slices.collect(iterator, context);
},
all: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result = true;
this.each(function(value, index) {
result = result && !!iterator(value, index);
if (!result) throw $break;
});
return result;
},
any: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result = false;
this.each(function(value, index) {
if (result = !!iterator(value, index))
throw $break;
});
return result;
},
collect: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var results = [];
this.each(function(value, index) {
results.push(iterator(value, index));
});
return results;
},
detect: function(iterator, context) {
iterator = iterator.bind(context);
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
result = value;
throw $break;
}
});
return result;
},
findAll: function(iterator, context) {
iterator = iterator.bind(context);
var results = [];
this.each(function(value, index) {
if (iterator(value, index))
results.push(value);
});
return results;
},
grep: function(filter, iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var results = [];
if (Object.isString(filter))
filter = new RegExp(filter);
this.each(function(value, index) {
if (filter.match(value))
results.push(iterator(value, index));
});
return results;
},
include: function(object) {
if (Object.isFunction(this.indexOf))
if (this.indexOf(object) != -1) return true;
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
},
inGroupsOf: function(number, fillWith) {
fillWith = Object.isUndefined(fillWith) ? null : fillWith;
return this.eachSlice(number, function(slice) {
while(slice.length < number) slice.push(fillWith);
return slice;
});
},
inject: function(memo, iterator, context) {
iterator = iterator.bind(context);
this.each(function(value, index) {
memo = iterator(memo, value, index);
});
return memo;
},
invoke: function(method) {
var args = $A(arguments).slice(1);
return this.map(function(value) {
return value[method].apply(value, args);
});
},
max: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result;
this.each(function(value, index) {
value = iterator(value, index);
if (result == null || value >= result)
result = value;
});
return result;
},
min: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result;
this.each(function(value, index) {
value = iterator(value, index);
if (result == null || value < result)
result = value;
});
return result;
},
partition: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var trues = [], falses = [];
this.each(function(value, index) {
(iterator(value, index) ?
trues : falses).push(value);
});
return [trues, falses];
},
pluck: function(property) {
var results = [];
this.each(function(value) {
results.push(value[property]);
});
return results;
},
reject: function(iterator, context) {
iterator = iterator.bind(context);
var results = [];
this.each(function(value, index) {
if (!iterator(value, index))
results.push(value);
});
return results;
},
sortBy: function(iterator, context) {
iterator = iterator.bind(context);
return this.map(function(value, index) {
return {value: value, criteria: iterator(value, index)};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}).pluck('value');
},
toArray: function() {
return this.map();
},
zip: function() {
var iterator = Prototype.K, args = $A(arguments);
if (Object.isFunction(args.last()))
iterator = args.pop();
var collections = [this].concat(args).map($A);
return this.map(function(value, index) {
return iterator(collections.pluck(index));
});
},
size: function() {
return this.toArray().length;
},
inspect: function() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
};
Object.extend(Enumerable, {
map: Enumerable.collect,
find: Enumerable.detect,
select: Enumerable.findAll,
filter: Enumerable.findAll,
member: Enumerable.include,
entries: Enumerable.toArray,
every: Enumerable.all,
some: Enumerable.any
});
function $A(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
if (Prototype.Browser.WebKit) {
$A = function(iterable) {
if (!iterable) return [];
if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
iterable.toArray) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
};
}
Array.from = $A;
Object.extend(Array.prototype, Enumerable);
if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
Object.extend(Array.prototype, {
_each: function(iterator) {
for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
},
clear: function() {
this.length = 0;
return this;
},
first: function() {
return this[0];
},
last: function() {
return this[this.length - 1];
},
compact: function() {
return this.select(function(value) {
return value != null;
});
},
flatten: function() {
return this.inject([], function(array, value) {
return array.concat(Object.isArray(value) ?
value.flatten() : [value]);
});
},
without: function() {
var values = $A(arguments);
return this.select(function(value) {
return !values.include(value);
});
},
reverse: function(inline) {
return (inline !== false ? this : this.toArray())._reverse();
},
reduce: function() {
return this.length > 1 ? this : this[0];
},
uniq: function(sorted) {
return this.inject([], function(array, value, index) {
if (0 == index || (sorted ? array.last() != value : !array.include(value)))
array.push(value);
return array;
});
},
intersect: function(array) {
return this.uniq().findAll(function(item) {
return array.detect(function(value) { return item === value });
});
},
clone: function() {
return [].concat(this);
},
size: function() {
return this.length;
},
inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
},
toJSON: function() {
var results = [];
this.each(function(object) {
var value = Object.toJSON(object);
if (!Object.isUndefined(value)) results.push(value);
});
return '[' + results.join(', ') + ']';
}
});
// use native browser JS 1.6 implementation if available
if (Object.isFunction(Array.prototype.forEach))
Array.prototype._each = Array.prototype.forEach;
if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
i || (i = 0);
var length = this.length;
if (i < 0) i = length + i;
for (; i < length; i++)
if (this[i] === item) return i;
return -1;
};
if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
var n = this.slice(0, i).reverse().indexOf(item);
return (n < 0) ? n : i - n - 1;
};
Array.prototype.toArray = Array.prototype.clone;
function $w(string) {
if (!Object.isString(string)) return [];
string = string.strip();
return string ? string.split(/\s+/) : [];
}
if (Prototype.Browser.Opera){
Array.prototype.concat = function() {
var array = [];
for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
for (var i = 0, length = arguments.length; i < length; i++) {
if (Object.isArray(arguments[i])) {
for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
array.push(arguments[i][j]);
} else {
array.push(arguments[i]);
}
}
return array;
};
}
Object.extend(Number.prototype, {
toColorPart: function() {
return this.toPaddedString(2, 16);
},
succ: function() {
return this + 1;
},
times: function(iterator) {
$R(0, this, true).each(iterator);
return this;
},
toPaddedString: function(length, radix) {
var string = this.toString(radix || 10);
return '0'.times(length - string.length) + string;
},
toJSON: function() {
return isFinite(this) ? this.toString() : 'null';
}
});
$w('abs round ceil floor').each(function(method){
Number.prototype[method] = Math[method].methodize();
});
function $H(object) {
return new Hash(object);
};
var Hash = Class.create(Enumerable, (function() {
function toQueryPair(key, value) {
if (Object.isUndefined(value)) return key;
return key + '=' + encodeURIComponent(String.interpret(value));
}
return {
initialize: function(object) {
this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
},
_each: function(iterator) {
for (var key in this._object) {
var value = this._object[key], pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},
set: function(key, value) {
return this._object[key] = value;
},
get: function(key) {
return this._object[key];
},
unset: function(key) {
var value = this._object[key];
delete this._object[key];
return value;
},
toObject: function() {
return Object.clone(this._object);
},
keys: function() {
return this.pluck('key');
},
values: function() {
return this.pluck('value');
},
index: function(value) {
var match = this.detect(function(pair) {
return pair.value === value;
});
return match && match.key;
},
merge: function(object) {
return this.clone().update(object);
},
update: function(object) {
return new Hash(object).inject(this, function(result, pair) {
result.set(pair.key, pair.value);
return result;
});
},
toQueryString: function() {
return this.map(function(pair) {
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
if (Object.isArray(values))
return values.map(toQueryPair.curry(key)).join('&');
}
return toQueryPair(key, values);
}).join('&');
},
inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
},
toJSON: function() {
return Object.toJSON(this.toObject());
},
clone: function() {
return new Hash(this);
}
}
})());
Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;
var ObjectRange = Class.create(Enumerable, {
initialize: function(start, end, exclusive) {
this.start = start;
this.end = end;
this.exclusive = exclusive;
},
_each: function(iterator) {
var value = this.start;
while (this.include(value)) {
iterator(value);
value = value.succ();
}
},
include: function(value) {
if (value < this.start)
return false;
if (this.exclusive)
return value < this.end;
return value <= this.end;
}
});
var $R = function(start, end, exclusive) {
return new ObjectRange(start, end, exclusive);
};
var Ajax = {
getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false;
},
activeRequestCount: 0
};
Ajax.Responders = {
responders: [],
_each: function(iterator) {
this.responders._each(iterator);
},
register: function(responder) {
if (!this.include(responder))
this.responders.push(responder);
},
unregister: function(responder) {
this.responders = this.responders.without(responder);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (Object.isFunction(responder[callback])) {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) { }
}
});
}
};
Object.extend(Ajax.Responders, Enumerable);
Ajax.Responders.register({
onCreate: function() { Ajax.activeRequestCount++ },
onComplete: function() { Ajax.activeRequestCount-- }
});
Ajax.Base = Class.create({
initialize: function(options) {
this.options = {
method: 'post',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
encoding: 'UTF-8',
parameters: '',
evalJSON: true,
evalJS: true
};
Object.extend(this.options, options || { });
this.options.method = this.options.method.toLowerCase();
if (Object.isString(this.options.parameters))
this.options.parameters = this.options.parameters.toQueryParams();
else if (Object.isHash(this.options.parameters))
this.options.parameters = this.options.parameters.toObject();
}
});
Ajax.Request = Class.create(Ajax.Base, {
_complete: false,
initialize: function($super, url, options) {
$super(options);
this.transport = Ajax.getTransport();
this.request(url);
},
request: function(url) {
this.url = url;
this.method = this.options.method;
var params = Object.clone(this.options.parameters);
if (!['get', 'post'].include(this.method)) {
// simulate other verbs over post
params['_method'] = this.method;
this.method = 'post';
}
this.parameters = params;
if (params = Object.toQueryString(params)) {
// when GET, append parameters to URL
if (this.method == 'get')
this.url += (this.url.include('?') ? '&' : '?') + params;
else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
params += '&_=';
}
try {
var response = new Ajax.Response(this);
if (this.options.onCreate) this.options.onCreate(response);
Ajax.Responders.dispatch('onCreate', this, response);
this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
this.body = this.method == 'post' ? (this.options.postBody || params) : null;
this.transport.send(this.body);
/* Force Firefox to handle ready state 4 for synchronous requests */
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();
}
catch (e) {
this.dispatchException(e);
}
},
onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState > 1 && !((readyState == 4) && this._complete))
this.respondToReadyState(this.transport.readyState);
},
setRequestHeaders: function() {
var headers = {
'X-Requested-With': 'XMLHttpRequest',
'X-Prototype-Version': Prototype.Version,
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
};
if (this.method == 'post') {
headers['Content-type'] = this.options.contentType +
(this.options.encoding ? '; charset=' + this.options.encoding : '');
/* Force "Connection: close" for older Mozilla browsers to work
* around a bug where XMLHttpRequest sends an incorrect
* Content-length header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType &&
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
headers['Connection'] = 'close';
}
// user-defined headers
if (typeof this.options.requestHeaders == 'object') {
var extras = this.options.requestHeaders;
if (Object.isFunction(extras.push))
for (var i = 0, length = extras.length; i < length; i += 2)
headers[extras[i]] = extras[i+1];
else
$H(extras).each(function(pair) { headers[pair.key] = pair.value });
}
for (var name in headers)
this.transport.setRequestHeader(name, headers[name]);
},
success: function() {
var status = this.getStatus();
return !status || (status >= 200 && status < 300);
},
getStatus: function() {
try {
return this.transport.status || 0;
} catch (e) { return 0 }
},
respondToReadyState: function(readyState) {
var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
if (state == 'Complete') {
try {
this._complete = true;
(this.options['on' + response.status]
|| this.options['on' + (this.success() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
var contentType = response.getHeader('Content-type');
if (this.options.evalJS == 'force'
|| (this.options.evalJS && this.isSameOrigin() && contentType
&& contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
this.evalResponse();
}
try {
(this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
if (state == 'Complete') {
// avoid memory leak in MSIE: clean up
this.transport.onreadystatechange = Prototype.emptyFunction;
}
},
isSameOrigin: function() {
var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
protocol: location.protocol,
domain: document.domain,
port: location.port ? ':' + location.port : ''
}));
},
getHeader: function(name) {
try {
return this.transport.getResponseHeader(name) || null;
} catch (e) { return null }
},
evalResponse: function() {
try {
return eval((this.transport.responseText || '').unfilterJSON());
} catch (e) {
this.dispatchException(e);
}
},
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
}
});
Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Response = Class.create({
initialize: function(request){
this.request = request;
var transport = this.transport = request.transport,
readyState = this.readyState = transport.readyState;
if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
this.status = this.getStatus();
this.statusText = this.getStatusText();
this.responseText = String.interpret(transport.responseText);
this.headerJSON = this._getHeaderJSON();
}
if(readyState == 4) {
var xml = transport.responseXML;
this.responseXML = Object.isUndefined(xml) ? null : xml;
this.responseJSON = this._getResponseJSON();
}
},
status: 0,
statusText: '',
getStatus: Ajax.Request.prototype.getStatus,
getStatusText: function() {
try {
return this.transport.statusText || '';
} catch (e) { return '' }
},
getHeader: Ajax.Request.prototype.getHeader,
getAllHeaders: function() {
try {
return this.getAllResponseHeaders();
} catch (e) { return null }
},
getResponseHeader: function(name) {
return this.transport.getResponseHeader(name);
},
getAllResponseHeaders: function() {
return this.transport.getAllResponseHeaders();
},
_getHeaderJSON: function() {
var json = this.getHeader('X-JSON');
if (!json) return null;
json = decodeURIComponent(escape(json));
try {
return json.evalJSON(this.request.options.sanitizeJSON ||
!this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
},
_getResponseJSON: function() {
var options = this.request.options;
if (!options.evalJSON || (options.evalJSON != 'force' &&
!(this.getHeader('Content-type') || '').include('application/json')) ||
this.responseText.blank())
return null;
try {
return this.responseText.evalJSON(options.sanitizeJSON ||
!this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
}
});
Ajax.Updater = Class.create(Ajax.Request, {
initialize: function($super, container, url, options) {
this.container = {
success: (container.success || container),
failure: (container.failure || (container.success ? null : container))
};
options = Object.clone(options);
var onComplete = options.onComplete;
options.onComplete = (function(response, json) {
this.updateContent(response.responseText);
if (Object.isFunction(onComplete)) onComplete(response, json);
}).bind(this);
$super(url, options);
},
updateContent: function(responseText) {
var receiver = this.container[this.success() ? 'success' : 'failure'],
options = this.options;
if (!options.evalScripts) responseText = responseText.stripScripts();
if (receiver = $(receiver)) {
if (options.insertion) {
if (Object.isString(options.insertion)) {
var insertion = { }; insertion[options.insertion] = responseText;
receiver.insert(insertion);
}
else options.insertion(receiver, responseText);
}
else receiver.update(responseText);
}
}
});
Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
initialize: function($super, container, url, options) {
$super(options);
this.onComplete = this.options.onComplete;
this.frequency = (this.options.frequency || 2);
this.decay = (this.options.decay || 1);
this.updater = { };
this.container = container;
this.url = url;
this.start();
},
start: function() {
this.options.onComplete = this.updateComplete.bind(this);
this.onTimerEvent();
},
stop: function() {
this.updater.options.onComplete = undefined;
clearTimeout(this.timer);
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
},
updateComplete: function(response) {
if (this.options.decay) {
this.decay = (response.responseText == this.lastText ?
this.decay * this.options.decay : 1);
this.lastText = response.responseText;
}
this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
},
onTimerEvent: function() {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
if (Prototype.BrowserFeatures.XPath) {
document._getElementsByXPath = function(expression, parentElement) {
var results = [];
var query = document.evaluate(expression, $(parentElement) || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0, length = query.snapshotLength; i < length; i++)
results.push(Element.extend(query.snapshotItem(i)));
return results;
};
}
/*--------------------------------------------------------------------------*/
if (!window.Node) var Node = { };
if (!Node.ELEMENT_NODE) {
// DOM level 2 ECMAScript Language Binding
Object.extend(Node, {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12
});
}
(function() {
var element = this.Element;
this.Element = function(tagName, attributes) {
attributes = attributes || { };
tagName = tagName.toLowerCase();
var cache = Element.cache;
if (Prototype.Browser.IE && attributes.name) {
tagName = '<' + tagName + ' name="' + attributes.name + '">';
delete attributes.name;
return Element.writeAttribute(document.createElement(tagName), attributes);
}
if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
};
Object.extend(this.Element, element || { });
}).call(window);
Element.cache = { };
Element.Methods = {
visible: function(element) {
return $(element).style.display != 'none';
},
toggle: function(element) {
element = $(element);
Element[Element.visible(element) ? 'hide' : 'show'](element);
return element;
},
hide: function(element) {
$(element).style.display = 'none';
return element;
},
show: function(element) {
$(element).style.display = '';
return element;
},
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
return element;
},
update: function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) return element.update().insert(content);
content = Object.toHTML(content);
element.innerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
},
replace: function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
else if (!Object.isElement(content)) {
content = Object.toHTML(content);
var range = element.ownerDocument.createRange();
range.selectNode(element);
content.evalScripts.bind(content).defer();
content = range.createContextualFragment(content.stripScripts());
}
element.parentNode.replaceChild(content, element);
return element;
},
insert: function(element, insertions) {
element = $(element);
if (Object.isString(insertions) || Object.isNumber(insertions) ||
Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
insertions = {bottom:insertions};
var content, insert, tagName, childNodes;
for (var position in insertions) {
content = insertions[position];
position = position.toLowerCase();
insert = Element._insertionTranslations[position];
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
insert(element, content);
continue;
}
content = Object.toHTML(content);
tagName = ((position == 'before' || position == 'after')
? element.parentNode : element).tagName.toUpperCase();
childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
if (position == 'top' || position == 'after') childNodes.reverse();
childNodes.each(insert.curry(element));
content.evalScripts.bind(content).defer();
}
return element;
},
wrap: function(element, wrapper, attributes) {
element = $(element);
if (Object.isElement(wrapper))
$(wrapper).writeAttribute(attributes || { });
else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
else wrapper = new Element('div', wrapper);
if (element.parentNode)
element.parentNode.replaceChild(wrapper, element);
wrapper.appendChild(element);
return wrapper;
},
inspect: function(element) {
element = $(element);
var result = '<' + element.tagName.toLowerCase();
$H({'id': 'id', 'className': 'class'}).each(function(pair) {
var property = pair.first(), attribute = pair.last();
var value = (element[property] || '').toString();
if (value) result += ' ' + attribute + '=' + value.inspect(true);
});
return result + '>';
},
recursivelyCollect: function(element, property) {
element = $(element);
var elements = [];
while (element = element[property])
if (element.nodeType == 1)
elements.push(Element.extend(element));
return elements;
},
ancestors: function(element) {
return $(element).recursivelyCollect('parentNode');
},
descendants: function(element) {
return $(element).select("*");
},
firstDescendant: function(element) {
element = $(element).firstChild;
while (element && element.nodeType != 1) element = element.nextSibling;
return $(element);
},
immediateDescendants: function(element) {
if (!(element = $(element).firstChild)) return [];
while (element && element.nodeType != 1) element = element.nextSibling;
if (element) return [element].concat($(element).nextSiblings());
return [];
},
previousSiblings: function(element) {
return $(element).recursivelyCollect('previousSibling');
},
nextSiblings: function(element) {
return $(element).recursivelyCollect('nextSibling');
},
siblings: function(element) {
element = $(element);
return element.previousSiblings().reverse().concat(element.nextSiblings());
},
match: function(element, selector) {
if (Object.isString(selector))
selector = new Selector(selector);
return selector.match($(element));
},
up: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(element.parentNode);
var ancestors = element.ancestors();
return Object.isNumber(expression) ? ancestors[expression] :
Selector.findElement(ancestors, expression, index);
},
down: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return element.firstDescendant();
return Object.isNumber(expression) ? element.descendants()[expression] :
element.select(expression)[index || 0];
},
previous: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
var previousSiblings = element.previousSiblings();
return Object.isNumber(expression) ? previousSiblings[expression] :
Selector.findElement(previousSiblings, expression, index);
},
next: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
var nextSiblings = element.nextSiblings();
return Object.isNumber(expression) ? nextSiblings[expression] :
Selector.findElement(nextSiblings, expression, index);
},
select: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element, args);
},
adjacent: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element.parentNode, args).without(element);
},
identify: function(element) {
element = $(element);
var id = element.readAttribute('id'), self = arguments.callee;
if (id) return id;
do { id = 'anonymous_element_' + self.counter++ } while ($(id));
element.writeAttribute('id', id);
return id;
},
readAttribute: function(element, name) {
element = $(element);
if (Prototype.Browser.IE) {
var t = Element._attributeTranslations.read;
if (t.values[name]) return t.values[name](element, name);
if (t.names[name]) name = t.names[name];
if (name.include(':')) {
return (!element.attributes || !element.attributes[name]) ? null :
element.attributes[name].value;
}
}
return element.getAttribute(name);
},
writeAttribute: function(element, name, value) {
element = $(element);
var attributes = { }, t = Element._attributeTranslations.write;
if (typeof name == 'object') attributes = name;
else attributes[name] = Object.isUndefined(value) ? true : value;
for (var attr in attributes) {
name = t.names[attr] || attr;
value = attributes[attr];
if (t.values[attr]) name = t.values[attr](element, value);
if (value === false || value === null)
element.removeAttribute(name);
else if (value === true)
element.setAttribute(name, name);
else element.setAttribute(name, value);
}
return element;
},
getHeight: function(element) {
return $(element).getDimensions().height;
},
getWidth: function(element) {
return $(element).getDimensions().width;
},
classNames: function(element) {
return new Element.ClassNames(element);
},
hasClassName: function(element, className) {
if (!(element = $(element))) return;
var elementClassName = element.className;
return (elementClassName.length > 0 && (elementClassName == className ||
new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
},
addClassName: function(element, className) {
if (!(element = $(element))) return;
if (!element.hasClassName(className))
element.className += (element.className ? ' ' : '') + className;
return element;
},
removeClassName: function(element, className) {
if (!(element = $(element))) return;
element.className = element.className.replace(
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
return element;
},
toggleClassName: function(element, className) {
if (!(element = $(element))) return;
return element[element.hasClassName(className) ?
'removeClassName' : 'addClassName'](className);
},
// removes whitespace-only text node children
cleanWhitespace: function(element) {
element = $(element);
var node = element.firstChild;
while (node) {
var nextNode = node.nextSibling;
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
node = nextNode;
}
return element;
},
empty: function(element) {
return $(element).innerHTML.blank();
},
descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
var originalAncestor = ancestor;
if (element.compareDocumentPosition)
return (element.compareDocumentPosition(ancestor) & 8) === 8;
if (element.sourceIndex && !Prototype.Browser.Opera) {
var e = element.sourceIndex, a = ancestor.sourceIndex,
nextAncestor = ancestor.nextSibling;
if (!nextAncestor) {
do { ancestor = ancestor.parentNode; }
while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
}
if (nextAncestor && nextAncestor.sourceIndex)
return (e > a && e < nextAncestor.sourceIndex);
}
while (element = element.parentNode)
if (element == originalAncestor) return true;
return false;
},
scrollTo: function(element) {
element = $(element);
var pos = element.cumulativeOffset();
window.scrollTo(pos[0], pos[1]);
return element;
},
getStyle: function(element, style) {
element = $(element);
style = style == 'float' ? 'cssFloat' : style.camelize();
var value = element.style[style];
if (!value) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
}
if (style == 'opacity') return value ? parseFloat(value) : 1.0;
return value == 'auto' ? null : value;
},
getOpacity: function(element) {
return $(element).getStyle('opacity');
},
setStyle: function(element, styles) {
element = $(element);
var elementStyle = element.style, match;
if (Object.isString(styles)) {
element.style.cssText += ';' + styles;
return styles.include('opacity') ?
element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
}
for (var property in styles)
if (property == 'opacity') element.setOpacity(styles[property]);
else
elementStyle[(property == 'float' || property == 'cssFloat') ?
(Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
property] = styles[property];
return element;
},
setOpacity: function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
return element;
},
getDimensions: function(element) {
element = $(element);
var display = $(element).getStyle('display');
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
// so enable the element temporarily
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
var originalDisplay = els.display;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
makePositioned: function(element) {
element = $(element);
var pos = Element.getStyle(element, 'position');
if (pos == 'static' || !pos) {
element._madePositioned = true;
element.style.position = 'relative';
// Opera returns the offset relative to the positioning context, when an
// element is position relative but top and left have not been defined
if (window.opera) {
element.style.top = 0;
element.style.left = 0;
}
}
return element;
},
undoPositioned: function(element) {
element = $(element);
if (element._madePositioned) {
element._madePositioned = undefined;
element.style.position =
element.style.top =
element.style.left =
element.style.bottom =
element.style.right = '';
}
return element;
},
makeClipping: function(element) {
element = $(element);
if (element._overflow) return element;
element._overflow = Element.getStyle(element, 'overflow') || 'auto';
if (element._overflow !== 'hidden')
element.style.overflow = 'hidden';
return element;
},
undoClipping: function(element) {
element = $(element);
if (!element._overflow) return element;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
},
cumulativeOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return Element._returnOffset(valueL, valueT);
},
positionedOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
if (element.tagName == 'BODY') break;
var p = Element.getStyle(element, 'position');
if (p !== 'static') break;
}
} while (element);
return Element._returnOffset(valueL, valueT);
},
absolutize: function(element) {
element = $(element);
if (element.getStyle('position') == 'absolute') return;
// Position.prepare(); // To be done manually by Scripty when it needs it.
var offsets = element.positionedOffset();
var top = offsets[1];
var left = offsets[0];
var width = element.clientWidth;
var height = element.clientHeight;
element._originalLeft = left - parseFloat(element.style.left || 0);
element._originalTop = top - parseFloat(element.style.top || 0);
element._originalWidth = element.style.width;
element._originalHeight = element.style.height;
element.style.position = 'absolute';
element.style.top = top + 'px';
element.style.left = left + 'px';
element.style.width = width + 'px';
element.style.height = height + 'px';
return element;
},
relativize: function(element) {
element = $(element);
if (element.getStyle('position') == 'relative') return;
// Position.prepare(); // To be done manually by Scripty when it needs it.
element.style.position = 'relative';
var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
element.style.top = top + 'px';
element.style.left = left + 'px';
element.style.height = element._originalHeight;
element.style.width = element._originalWidth;
return element;
},
cumulativeScrollOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.scrollTop || 0;
valueL += element.scrollLeft || 0;
element = element.parentNode;
} while (element);
return Element._returnOffset(valueL, valueT);
},
getOffsetParent: function(element) {
if (element.offsetParent) return $(element.offsetParent);
if (element == document.body) return $(element);
while ((element = element.parentNode) && element != document.body)
if (Element.getStyle(element, 'position') != 'static')
return $(element);
return $(document.body);
},
viewportOffset: function(forElement) {
var valueT = 0, valueL = 0;
var element = forElement;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
// Safari fix
if (element.offsetParent == document.body &&
Element.getStyle(element, 'position') == 'absolute') break;
} while (element = element.offsetParent);
element = forElement;
do {
if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
valueT -= element.scrollTop || 0;
valueL -= element.scrollLeft || 0;
}
} while (element = element.parentNode);
return Element._returnOffset(valueL, valueT);
},
clonePosition: function(element, source) {
var options = Object.extend({
setLeft: true,
setTop: true,
setWidth: true,
setHeight: true,
offsetTop: 0,
offsetLeft: 0
}, arguments[2] || { });
// find page position of source
source = $(source);
var p = source.viewportOffset();
// find coordinate system to use
element = $(element);
var delta = [0, 0];
var parent = null;
// delta [0,0] will do fine with position: fixed elements,
// position:absolute needs offsetParent deltas
if (Element.getStyle(element, 'position') == 'absolute') {
parent = element.getOffsetParent();
delta = parent.viewportOffset();
}
// correct by body offsets (fixes Safari)
if (parent == document.body) {
delta[0] -= document.body.offsetLeft;
delta[1] -= document.body.offsetTop;
}
// set position
if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
if (options.setWidth) element.style.width = source.offsetWidth + 'px';
if (options.setHeight) element.style.height = source.offsetHeight + 'px';
return element;
}
};
Element.Methods.identify.counter = 1;
Object.extend(Element.Methods, {
getElementsBySelector: Element.Methods.select,
childElements: Element.Methods.immediateDescendants
});
Element._attributeTranslations = {
write: {
names: {
className: 'class',
htmlFor: 'for'
},
values: { }
}
};
if (Prototype.Browser.Opera) {
Element.Methods.getStyle = Element.Methods.getStyle.wrap(
function(proceed, element, style) {
switch (style) {
case 'left': case 'top': case 'right': case 'bottom':
if (proceed(element, 'position') === 'static') return null;
case 'height': case 'width':
// returns '0px' for hidden elements; we want it to return null
if (!Element.visible(element)) return null;
// returns the border-box dimensions rather than the content-box
// dimensions, so we subtract padding and borders from the value
var dim = parseInt(proceed(element, style), 10);
if (dim !== element['offset' + style.capitalize()])
return dim + 'px';
var properties;
if (style === 'height') {
properties = ['border-top-width', 'padding-top',
'padding-bottom', 'border-bottom-width'];
}
else {
properties = ['border-left-width', 'padding-left',
'padding-right', 'border-right-width'];
}
return properties.inject(dim, function(memo, property) {
var val = proceed(element, property);
return val === null ? memo : memo - parseInt(val, 10);
}) + 'px';
default: return proceed(element, style);
}
}
);
Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
function(proceed, element, attribute) {
if (attribute === 'title') return element.title;
return proceed(element, attribute);
}
);
}
else if (Prototype.Browser.IE) {
// IE doesn't report offsets correctly for static elements, so we change them
// to "relative" to get the values, then change them back.
Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
function(proceed, element) {
element = $(element);
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
element.setStyle({ position: 'relative' });
var value = proceed(element);
element.setStyle({ position: position });
return value;
}
);
$w('positionedOffset viewportOffset').each(function(method) {
Element.Methods[method] = Element.Methods[method].wrap(
function(proceed, element) {
element = $(element);
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
// Trigger hasLayout on the offset parent so that IE6 reports
// accurate offsetTop and offsetLeft values for position: fixed.
var offsetParent = element.getOffsetParent();
if (offsetParent && offsetParent.getStyle('position') === 'fixed')
offsetParent.setStyle({ zoom: 1 });
element.setStyle({ position: 'relative' });
var value = proceed(element);
element.setStyle({ position: position });
return value;
}
);
});
Element.Methods.getStyle = function(element, style) {
element = $(element);
style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
var value = element.style[style];
if (!value && element.currentStyle) value = element.currentStyle[style];
if (style == 'opacity') {
if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
if (value[1]) return parseFloat(value[1]) / 100;
return 1.0;
}
if (value == 'auto') {
if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
return element['offset' + style.capitalize()] + 'px';
return null;
}
return value;
};
Element.Methods.setOpacity = function(element, value) {
function stripAlpha(filter){
return filter.replace(/alpha\([^\)]*\)/gi,'');
}
element = $(element);
var currentStyle = element.currentStyle;
if ((currentStyle && !currentStyle.hasLayout) ||
(!currentStyle && element.style.zoom == 'normal'))
element.style.zoom = 1;
var filter = element.getStyle('filter'), style = element.style;
if (value == 1 || value === '') {
(filter = stripAlpha(filter)) ?
style.filter = filter : style.removeAttribute('filter');
return element;
} else if (value < 0.00001) value = 0;
style.filter = stripAlpha(filter) +
'alpha(opacity=' + (value * 100) + ')';
return element;
};
Element._attributeTranslations = {
read: {
names: {
'class': 'className',
'for': 'htmlFor'
},
values: {
_getAttr: function(element, attribute) {
return element.getAttribute(attribute, 2);
},
_getAttrNode: function(element, attribute) {
var node = element.getAttributeNode(attribute);
return node ? node.value : "";
},
_getEv: function(element, attribute) {
attribute = element.getAttribute(attribute);
return attribute ? attribute.toString().slice(23, -2) : null;
},
_flag: function(element, attribute) {
return $(element).hasAttribute(attribute) ? attribute : null;
},
style: function(element) {
return element.style.cssText.toLowerCase();
},
title: function(element) {
return element.title;
}
}
}
};
Element._attributeTranslations.write = {
names: Object.extend({
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing'
}, Element._attributeTranslations.read.names),
values: {
checked: function(element, value) {
element.checked = !!value;
},
style: function(element, value) {
element.style.cssText = value ? value : '';
}
}
};
Element._attributeTranslations.has = {};
$w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
'encType maxLength readOnly longDesc').each(function(attr) {
Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
Element._attributeTranslations.has[attr.toLowerCase()] = attr;
});
(function(v) {
Object.extend(v, {
href: v._getAttr,
src: v._getAttr,
type: v._getAttr,
action: v._getAttrNode,
disabled: v._flag,
checked: v._flag,
readonly: v._flag,
multiple: v._flag,
onload: v._getEv,
onunload: v._getEv,
onclick: v._getEv,
ondblclick: v._getEv,
onmousedown: v._getEv,
onmouseup: v._getEv,
onmouseover: v._getEv,
onmousemove: v._getEv,
onmouseout: v._getEv,
onfocus: v._getEv,
onblur: v._getEv,
onkeypress: v._getEv,
onkeydown: v._getEv,
onkeyup: v._getEv,
onsubmit: v._getEv,
onreset: v._getEv,
onselect: v._getEv,
onchange: v._getEv
});
})(Element._attributeTranslations.read.values);
}
else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
Element.Methods.setOpacity = function(element, value) {
element = $(element);
element.style.opacity = (value == 1) ? 0.999999 :
(value === '') ? '' : (value < 0.00001) ? 0 : value;
return element;
};
}
else if (Prototype.Browser.WebKit) {
Element.Methods.setOpacity = function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
if (value == 1)
if(element.tagName == 'IMG' && element.width) {
element.width++; element.width--;
} else try {
var n = document.createTextNode(' ');
element.appendChild(n);
element.removeChild(n);
} catch (e) { }
return element;
};
// Safari returns margins on body which is incorrect if the child is absolutely
// positioned. For performance reasons, redefine Element#cumulativeOffset for
// KHTML/WebKit only.
Element.Methods.cumulativeOffset = function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body)
if (Element.getStyle(element, 'position') == 'absolute') break;
element = element.offsetParent;
} while (element);
return Element._returnOffset(valueL, valueT);
};
}
if (Prototype.Browser.IE || Prototype.Browser.Opera) {
// IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
Element.Methods.update = function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) return element.update().insert(content);
content = Object.toHTML(content);
var tagName = element.tagName.toUpperCase();
if (tagName in Element._insertionTranslations.tags) {
$A(element.childNodes).each(function(node) { element.removeChild(node) });
Element._getContentFromAnonymousElement(tagName, content.stripScripts())
.each(function(node) { element.appendChild(node) });
}
else element.innerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
};
}
if ('outerHTML' in document.createElement('div')) {
Element.Methods.replace = function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
element.parentNode.replaceChild(content, element);
return element;
}
content = Object.toHTML(content);
var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
if (Element._insertionTranslations.tags[tagName]) {
var nextSibling = element.next();
var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
parent.removeChild(element);
if (nextSibling)
fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
else
fragments.each(function(node) { parent.appendChild(node) });
}
else element.outerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
};
}
Element._returnOffset = function(l, t) {
var result = [l, t];
result.left = l;
result.top = t;
return result;
};
Element._getContentFromAnonymousElement = function(tagName, html) {
var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
if (t) {
div.innerHTML = t[0] + html + t[1];
t[2].times(function() { div = div.firstChild });
} else div.innerHTML = html;
return $A(div.childNodes);
};
Element._insertionTranslations = {
before: function(element, node) {
element.parentNode.insertBefore(node, element);
},
top: function(element, node) {
element.insertBefore(node, element.firstChild);
},
bottom: function(element, node) {
element.appendChild(node);
},
after: function(element, node) {
element.parentNode.insertBefore(node, element.nextSibling);
},
tags: {
TABLE: ['<table>', '</table>', 1],
TBODY: ['<table><tbody>', '</tbody></table>', 2],
TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
SELECT: ['<select>', '</select>', 1]
}
};
(function() {
Object.extend(this.tags, {
THEAD: this.tags.TBODY,
TFOOT: this.tags.TBODY,
TH: this.tags.TD
});
}).call(Element._insertionTranslations);
Element.Methods.Simulated = {
hasAttribute: function(element, attribute) {
attribute = Element._attributeTranslations.has[attribute] || attribute;
var node = $(element).getAttributeNode(attribute);
return node && node.specified;
}
};
Element.Methods.ByTag = { };
Object.extend(Element, Element.Methods);
if (!Prototype.BrowserFeatures.ElementExtensions &&
document.createElement('div').__proto__) {
window.HTMLElement = { };
window.HTMLElement.prototype = document.createElement('div').__proto__;
Prototype.BrowserFeatures.ElementExtensions = true;
}
Element.extend = (function() {
if (Prototype.BrowserFeatures.SpecificElementExtensions)
return Prototype.K;
var Methods = { }, ByTag = Element.Methods.ByTag;
var extend = Object.extend(function(element) {
if (!element || element._extendedByPrototype ||
element.nodeType != 1 || element == window) return element;
var methods = Object.clone(Methods),
tagName = element.tagName, property, value;
// extend methods for specific tags
if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
for (property in methods) {
value = methods[property];
if (Object.isFunction(value) && !(property in element))
element[property] = value.methodize();
}
element._extendedByPrototype = Prototype.emptyFunction;
return element;
}, {
refresh: function() {
// extend methods for all tags (Safari doesn't need this)
if (!Prototype.BrowserFeatures.ElementExtensions) {
Object.extend(Methods, Element.Methods);
Object.extend(Methods, Element.Methods.Simulated);
}
}
});
extend.refresh();
return extend;
})();
Element.hasAttribute = function(element, attribute) {
if (element.hasAttribute) return element.hasAttribute(attribute);
return Element.Methods.Simulated.hasAttribute(element, attribute);
};
Element.addMethods = function(methods) {
var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
if (!methods) {
Object.extend(Form, Form.Methods);
Object.extend(Form.Element, Form.Element.Methods);
Object.extend(Element.Methods.ByTag, {
"FORM": Object.clone(Form.Methods),
"INPUT": Object.clone(Form.Element.Methods),
"SELECT": Object.clone(Form.Element.Methods),
"TEXTAREA": Object.clone(Form.Element.Methods)
});
}
if (arguments.length == 2) {
var tagName = methods;
methods = arguments[1];
}
if (!tagName) Object.extend(Element.Methods, methods || { });
else {
if (Object.isArray(tagName)) tagName.each(extend);
else extend(tagName);
}
function extend(tagName) {
tagName = tagName.toUpperCase();
if (!Element.Methods.ByTag[tagName])
Element.Methods.ByTag[tagName] = { };
Object.extend(Element.Methods.ByTag[tagName], methods);
}
function copy(methods, destination, onlyIfAbsent) {
onlyIfAbsent = onlyIfAbsent || false;
for (var property in methods) {
var value = methods[property];
if (!Object.isFunction(value)) continue;
if (!onlyIfAbsent || !(property in destination))
destination[property] = value.methodize();
}
}
function findDOMClass(tagName) {
var klass;
var trans = {
"OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
"FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
"DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
"H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
"INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
"TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
"TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
"TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
"FrameSet", "IFRAME": "IFrame"
};
if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
if (window[klass]) return window[klass];
klass = 'HTML' + tagName + 'Element';
if (window[klass]) return window[klass];
klass = 'HTML' + tagName.capitalize() + 'Element';
if (window[klass]) return window[klass];
window[klass] = { };
window[klass].prototype = document.createElement(tagName).__proto__;
return window[klass];
}
if (F.ElementExtensions) {
copy(Element.Methods, HTMLElement.prototype);
copy(Element.Methods.Simulated, HTMLElement.prototype, true);
}
if (F.SpecificElementExtensions) {
for (var tag in Element.Methods.ByTag) {
var klass = findDOMClass(tag);
if (Object.isUndefined(klass)) continue;
copy(T[tag], klass.prototype);
}
}
Object.extend(Element, Element.Methods);
delete Element.ByTag;
if (Element.extend.refresh) Element.extend.refresh();
Element.cache = { };
};
document.viewport = {
getDimensions: function() {
var dimensions = { };
var B = Prototype.Browser;
$w('width height').each(function(d) {
var D = d.capitalize();
dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
(B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
});
return dimensions;
},
getWidth: function() {
return this.getDimensions().width;
},
getHeight: function() {
return this.getDimensions().height;
},
getScrollOffsets: function() {
return Element._returnOffset(
window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
}
};
/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
* part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
* license. Please see http://www.yui-ext.com/ for more information. */
var Selector = Class.create({
initialize: function(expression) {
this.expression = expression.strip();
this.compileMatcher();
},
shouldUseXPath: function() {
if (!Prototype.BrowserFeatures.XPath) return false;
var e = this.expression;
// Safari 3 chokes on :*-of-type and :empty
if (Prototype.Browser.WebKit &&
(e.include("-of-type") || e.include(":empty")))
return false;
// XPath can't do namespaced attributes, nor can it read
// the "checked" property from DOM nodes
if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
return false;
return true;
},
compileMatcher: function() {
if (this.shouldUseXPath())
return this.compileXPathMatcher();
var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
c = Selector.criteria, le, p, m;
if (Selector._cache[e]) {
this.matcher = Selector._cache[e];
return;
}
this.matcher = ["this.matcher = function(root) {",
"var r = root, h = Selector.handlers, c = false, n;"];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
p = ps[i];
if (m = e.match(p)) {
this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
new Template(c[i]).evaluate(m));
e = e.replace(m[0], '');
break;
}
}
}
this.matcher.push("return h.unique(n);\n}");
eval(this.matcher.join('\n'));
Selector._cache[this.expression] = this.matcher;
},
compileXPathMatcher: function() {
var e = this.expression, ps = Selector.patterns,
x = Selector.xpath, le, m;
if (Selector._cache[e]) {
this.xpath = Selector._cache[e]; return;
}
this.matcher = ['.//*'];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
if (m = e.match(ps[i])) {
this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
new Template(x[i]).evaluate(m));
e = e.replace(m[0], '');
break;
}
}
}
this.xpath = this.matcher.join('');
Selector._cache[this.expression] = this.xpath;
},
findElements: function(root) {
root = root || document;
if (this.xpath) return document._getElementsByXPath(this.xpath, root);
return this.matcher(root);
},
match: function(element) {
this.tokens = [];
var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
var le, p, m;
while (e && le !== e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
p = ps[i];
if (m = e.match(p)) {
// use the Selector.assertions methods unless the selector
// is too complex.
if (as[i]) {
this.tokens.push([i, Object.clone(m)]);
e = e.replace(m[0], '');
} else {
// reluctantly do a document-wide search
// and look for a match in the array
return this.findElements(document).include(element);
}
}
}
}
var match = true, name, matches;
for (var i = 0, token; token = this.tokens[i]; i++) {
name = token[0], matches = token[1];
if (!Selector.assertions[name](element, matches)) {
match = false; break;
}
}
return match;
},
toString: function() {
return this.expression;
},
inspect: function() {
return "#<Selector:" + this.expression.inspect() + ">";
}
});
Object.extend(Selector, {
_cache: { },
xpath: {
descendant: "//*",
child: "/*",
adjacent: "/following-sibling::*[1]",
laterSibling: '/following-sibling::*',
tagName: function(m) {
if (m[1] == '*') return '';
return "[local-name()='" + m[1].toLowerCase() +
"' or local-name()='" + m[1].toUpperCase() + "']";
},
className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
id: "[@id='#{1}']",
attrPresence: function(m) {
m[1] = m[1].toLowerCase();
return new Template("[@#{1}]").evaluate(m);
},
attr: function(m) {
m[1] = m[1].toLowerCase();
m[3] = m[5] || m[6];
return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
},
pseudo: function(m) {
var h = Selector.xpath.pseudos[m[1]];
if (!h) return '';
if (Object.isFunction(h)) return h(m);
return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
},
operators: {
'=': "[@#{1}='#{3}']",
'!=': "[@#{1}!='#{3}']",
'^=': "[starts-with(@#{1}, '#{3}')]",
'$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
'*=': "[contains(@#{1}, '#{3}')]",
'~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
'|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
},
pseudos: {
'first-child': '[not(preceding-sibling::*)]',
'last-child': '[not(following-sibling::*)]',
'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
'checked': "[@checked]",
'disabled': "[@disabled]",
'enabled': "[not(@disabled)]",
'not': function(m) {
var e = m[6], p = Selector.patterns,
x = Selector.xpath, le, v;
var exclusion = [];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in p) {
if (m = e.match(p[i])) {
v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
exclusion.push("(" + v.substring(1, v.length - 1) + ")");
e = e.replace(m[0], '');
break;
}
}
}
return "[not(" + exclusion.join(" and ") + ")]";
},
'nth-child': function(m) {
return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
},
'nth-last-child': function(m) {
return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
},
'nth-of-type': function(m) {
return Selector.xpath.pseudos.nth("position() ", m);
},
'nth-last-of-type': function(m) {
return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
},
'first-of-type': function(m) {
m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
},
'last-of-type': function(m) {
m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
},
'only-of-type': function(m) {
var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
},
nth: function(fragment, m) {
var mm, formula = m[6], predicate;
if (formula == 'even') formula = '2n+0';
if (formula == 'odd') formula = '2n+1';
if (mm = formula.match(/^(\d+)$/)) // digit only
return '[' + fragment + "= " + mm[1] + ']';
if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
if (mm[1] == "-") mm[1] = -1;
var a = mm[1] ? Number(mm[1]) : 1;
var b = mm[2] ? Number(mm[2]) : 0;
predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
"((#{fragment} - #{b}) div #{a} >= 0)]";
return new Template(predicate).evaluate({
fragment: fragment, a: a, b: b });
}
}
}
},
criteria: {
tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
className: 'n = h.className(n, r, "#{1}", c); c = false;',
id: 'n = h.id(n, r, "#{1}", c); c = false;',
attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
attr: function(m) {
m[3] = (m[5] || m[6]);
return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
},
pseudo: function(m) {
if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
},
descendant: 'c = "descendant";',
child: 'c = "child";',
adjacent: 'c = "adjacent";',
laterSibling: 'c = "laterSibling";'
},
patterns: {
// combinators must be listed first
// (and descendant needs to be last combinator)
laterSibling: /^\s*~\s*/,
child: /^\s*>\s*/,
adjacent: /^\s*\+\s*/,
descendant: /^\s/,
// selectors follow
tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
id: /^#([\w\-\*]+)(\b|$)/,
className: /^\.([\w\-\*]+)(\b|$)/,
pseudo:
/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
attrPresence: /^\[([\w]+)\]/,
attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
},
// for Selector.match and Element#match
assertions: {
tagName: function(element, matches) {
return matches[1].toUpperCase() == element.tagName.toUpperCase();
},
className: function(element, matches) {
return Element.hasClassName(element, matches[1]);
},
id: function(element, matches) {
return element.id === matches[1];
},
attrPresence: function(element, matches) {
return Element.hasAttribute(element, matches[1]);
},
attr: function(element, matches) {
var nodeValue = Element.readAttribute(element, matches[1]);
return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
}
},
handlers: {
// UTILITY FUNCTIONS
// joins two collections
concat: function(a, b) {
for (var i = 0, node; node = b[i]; i++)
a.push(node);
return a;
},
// marks an array of nodes for counting
mark: function(nodes) {
var _true = Prototype.emptyFunction;
for (var i = 0, node; node = nodes[i]; i++)
node._countedByPrototype = _true;
return nodes;
},
unmark: function(nodes) {
for (var i = 0, node; node = nodes[i]; i++)
node._countedByPrototype = undefined;
return nodes;
},
// mark each child node with its position (for nth calls)
// "ofType" flag indicates whether we're indexing for nth-of-type
// rather than nth-child
index: function(parentNode, reverse, ofType) {
parentNode._countedByPrototype = Prototype.emptyFunction;
if (reverse) {
for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
var node = nodes[i];
if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
}
} else {
for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
}
},
// filters out duplicates and extends all nodes
unique: function(nodes) {
if (nodes.length == 0) return nodes;
var results = [], n;
for (var i = 0, l = nodes.length; i < l; i++)
if (!(n = nodes[i])._countedByPrototype) {
n._countedByPrototype = Prototype.emptyFunction;
results.push(Element.extend(n));
}
return Selector.handlers.unmark(results);
},
// COMBINATOR FUNCTIONS
descendant: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
h.concat(results, node.getElementsByTagName('*'));
return results;
},
child: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++) {
for (var j = 0, child; child = node.childNodes[j]; j++)
if (child.nodeType == 1 && child.tagName != '!') results.push(child);
}
return results;
},
adjacent: function(nodes) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
var next = this.nextElementSibling(node);
if (next) results.push(next);
}
return results;
},
laterSibling: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
h.concat(results, Element.nextSiblings(node));
return results;
},
nextElementSibling: function(node) {
while (node = node.nextSibling)
if (node.nodeType == 1) return node;
return null;
},
previousElementSibling: function(node) {
while (node = node.previousSibling)
if (node.nodeType == 1) return node;
return null;
},
// TOKEN FUNCTIONS
tagName: function(nodes, root, tagName, combinator) {
var uTagName = tagName.toUpperCase();
var results = [], h = Selector.handlers;
if (nodes) {
if (combinator) {
// fastlane for ordinary descendant combinators
if (combinator == "descendant") {
for (var i = 0, node; node = nodes[i]; i++)
h.concat(results, node.getElementsByTagName(tagName));
return results;
} else nodes = this[combinator](nodes);
if (tagName == "*") return nodes;
}
for (var i = 0, node; node = nodes[i]; i++)
if (node.tagName.toUpperCase() === uTagName) results.push(node);
return results;
} else return root.getElementsByTagName(tagName);
},
id: function(nodes, root, id, combinator) {
var targetNode = $(id), h = Selector.handlers;
if (!targetNode) return [];
if (!nodes && root == document) return [targetNode];
if (nodes) {
if (combinator) {
if (combinator == 'child') {
for (var i = 0, node; node = nodes[i]; i++)
if (targetNode.parentNode == node) return [targetNode];
} else if (combinator == 'descendant') {
for (var i = 0, node; node = nodes[i]; i++)
if (Element.descendantOf(targetNode, node)) return [targetNode];
} else if (combinator == 'adjacent') {
for (var i = 0, node; node = nodes[i]; i++)
if (Selector.handlers.previousElementSibling(targetNode) == node)
return [targetNode];
} else nodes = h[combinator](nodes);
}
for (var i = 0, node; node = nodes[i]; i++)
if (node == targetNode) return [targetNode];
return [];
}
return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
},
className: function(nodes, root, className, combinator) {
if (nodes && combinator) nodes = this[combinator](nodes);
return Selector.handlers.byClassName(nodes, root, className);
},
byClassName: function(nodes, root, className) {
if (!nodes) nodes = Selector.handlers.descendant([root]);
var needle = ' ' + className + ' ';
for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
nodeClassName = node.className;
if (nodeClassName.length == 0) continue;
if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
results.push(node);
}
return results;
},
attrPresence: function(nodes, root, attr, combinator) {
if (!nodes) nodes = root.getElementsByTagName("*");
if (nodes && combinator) nodes = this[combinator](nodes);
var results = [];
for (var i = 0, node; node = nodes[i]; i++)
if (Element.hasAttribute(node, attr)) results.push(node);
return results;
},
attr: function(nodes, root, attr, value, operator, combinator) {
if (!nodes) nodes = root.getElementsByTagName("*");
if (nodes && combinator) nodes = this[combinator](nodes);
var handler = Selector.operators[operator], results = [];
for (var i = 0, node; node = nodes[i]; i++) {
var nodeValue = Element.readAttribute(node, attr);
if (nodeValue === null) continue;
if (handler(nodeValue, value)) results.push(node);
}
return results;
},
pseudo: function(nodes, name, value, root, combinator) {
if (nodes && combinator) nodes = this[combinator](nodes);
if (!nodes) nodes = root.getElementsByTagName("*");
return Selector.pseudos[name](nodes, value, root);
}
},
pseudos: {
'first-child': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
if (Selector.handlers.previousElementSibling(node)) continue;
results.push(node);
}
return results;
},
'last-child': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
if (Selector.handlers.nextElementSibling(node)) continue;
results.push(node);
}
return results;
},
'only-child': function(nodes, value, root) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
results.push(node);
return results;
},
'nth-child': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root);
},
'nth-last-child': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, true);
},
'nth-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, false, true);
},
'nth-last-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, true, true);
},
'first-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, "1", root, false, true);
},
'last-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, "1", root, true, true);
},
'only-of-type': function(nodes, formula, root) {
var p = Selector.pseudos;
return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
},
// handles the an+b logic
getIndices: function(a, b, total) {
if (a == 0) return b > 0 ? [b] : [];
return $R(1, total).inject([], function(memo, i) {
if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
return memo;
});
},
// handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
nth: function(nodes, formula, root, reverse, ofType) {
if (nodes.length == 0) return [];
if (formula == 'even') formula = '2n+0';
if (formula == 'odd') formula = '2n+1';
var h = Selector.handlers, results = [], indexed = [], m;
h.mark(nodes);
for (var i = 0, node; node = nodes[i]; i++) {
if (!node.parentNode._countedByPrototype) {
h.index(node.parentNode, reverse, ofType);
indexed.push(node.parentNode);
}
}
if (formula.match(/^\d+$/)) { // just a number
formula = Number(formula);
for (var i = 0, node; node = nodes[i]; i++)
if (node.nodeIndex == formula) results.push(node);
} else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
if (m[1] == "-") m[1] = -1;
var a = m[1] ? Number(m[1]) : 1;
var b = m[2] ? Number(m[2]) : 0;
var indices = Selector.pseudos.getIndices(a, b, nodes.length);
for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
for (var j = 0; j < l; j++)
if (node.nodeIndex == indices[j]) results.push(node);
}
}
h.unmark(nodes);
h.unmark(indexed);
return results;
},
'empty': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
// IE treats comments as element nodes
if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
results.push(node);
}
return results;
},
'not': function(nodes, selector, root) {
var h = Selector.handlers, selectorType, m;
var exclusions = new Selector(selector).findElements(root);
h.mark(exclusions);
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!node._countedByPrototype) results.push(node);
h.unmark(exclusions);
return results;
},
'enabled': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!node.disabled) results.push(node);
return results;
},
'disabled': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (node.disabled) results.push(node);
return results;
},
'checked': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (node.checked) results.push(node);
return results;
}
},
operators: {
'=': function(nv, v) { return nv == v; },
'!=': function(nv, v) { return nv != v; },
'^=': function(nv, v) { return nv.startsWith(v); },
'$=': function(nv, v) { return nv.endsWith(v); },
'*=': function(nv, v) { return nv.include(v); },
'~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
'|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
},
split: function(expression) {
var expressions = [];
expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
expressions.push(m[1].strip());
});
return expressions;
},
matchElements: function(elements, expression) {
var matches = $$(expression), h = Selector.handlers;
h.mark(matches);
for (var i = 0, results = [], element; element = elements[i]; i++)
if (element._countedByPrototype) results.push(element);
h.unmark(matches);
return results;
},
findElement: function(elements, expression, index) {
if (Object.isNumber(expression)) {
index = expression; expression = false;
}
return Selector.matchElements(elements, expression || '*')[index || 0];
},
findChildElements: function(element, expressions) {
expressions = Selector.split(expressions.join(','));
var results = [], h = Selector.handlers;
for (var i = 0, l = expressions.length, selector; i < l; i++) {
selector = new Selector(expressions[i].strip());
h.concat(results, selector.findElements(element));
}
return (l > 1) ? h.unique(results) : results;
}
});
if (Prototype.Browser.IE) {
Object.extend(Selector.handlers, {
// IE returns comment nodes on getElementsByTagName("*").
// Filter them out.
concat: function(a, b) {
for (var i = 0, node; node = b[i]; i++)
if (node.tagName !== "!") a.push(node);
return a;
},
// IE improperly serializes _countedByPrototype in (inner|outer)HTML.
unmark: function(nodes) {
for (var i = 0, node; node = nodes[i]; i++)
node.removeAttribute('_countedByPrototype');
return nodes;
}
});
}
function $$() {
return Selector.findChildElements(document, $A(arguments));
}
var Form = {
reset: function(form) {
$(form).reset();
return form;
},
serializeElements: function(elements, options) {
if (typeof options != 'object') options = { hash: !!options };
else if (Object.isUndefined(options.hash)) options.hash = true;
var key, value, submitted = false, submit = options.submit;
var data = elements.inject({ }, function(result, element) {
if (!element.disabled && element.name) {
key = element.name; value = $(element).getValue();
if (value != null && (element.type != 'submit' || (!submitted &&
submit !== false && (!submit || key == submit) && (submitted = true)))) {
if (key in result) {
// a key is already present; construct an array of values
if (!Object.isArray(result[key])) result[key] = [result[key]];
result[key].push(value);
}
else result[key] = value;
}
}
return result;
});
return options.hash ? data : Object.toQueryString(data);
}
};
Form.Methods = {
serialize: function(form, options) {
return Form.serializeElements(Form.getElements(form), options);
},
getElements: function(form) {
return $A($(form).getElementsByTagName('*')).inject([],
function(elements, child) {
if (Form.Element.Serializers[child.tagName.toLowerCase()])
elements.push(Element.extend(child));
return elements;
}
);
},
getInputs: function(form, typeName, name) {
form = $(form);
var inputs = form.getElementsByTagName('input');
if (!typeName && !name) return $A(inputs).map(Element.extend);
for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
var input = inputs[i];
if ((typeName && input.type != typeName) || (name && input.name != name))
continue;
matchingInputs.push(Element.extend(input));
}
return matchingInputs;
},
disable: function(form) {
form = $(form);
Form.getElements(form).invoke('disable');
return form;
},
enable: function(form) {
form = $(form);
Form.getElements(form).invoke('enable');
return form;
},
findFirstElement: function(form) {
var elements = $(form).getElements().findAll(function(element) {
return 'hidden' != element.type && !element.disabled;
});
var firstByIndex = elements.findAll(function(element) {
return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
}).sortBy(function(element) { return element.tabIndex }).first();
return firstByIndex ? firstByIndex : elements.find(function(element) {
return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
},
focusFirstElement: function(form) {
form = $(form);
form.findFirstElement().activate();
return form;
},
request: function(form, options) {
form = $(form), options = Object.clone(options || { });
var params = options.parameters, action = form.readAttribute('action') || '';
if (action.blank()) action = window.location.href;
options.parameters = form.serialize(true);
if (params) {
if (Object.isString(params)) params = params.toQueryParams();
Object.extend(options.parameters, params);
}
if (form.hasAttribute('method') && !options.method)
options.method = form.method;
return new Ajax.Request(action, options);
}
};
/*--------------------------------------------------------------------------*/
Form.Element = {
focus: function(element) {
$(element).focus();
return element;
},
select: function(element) {
$(element).select();
return element;
}
};
Form.Element.Methods = {
serialize: function(element) {
element = $(element);
if (!element.disabled && element.name) {
var value = element.getValue();
if (value != undefined) {
var pair = { };
pair[element.name] = value;
return Object.toQueryString(pair);
}
}
return '';
},
getValue: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
return Form.Element.Serializers[method](element);
},
setValue: function(element, value) {
element = $(element);
var method = element.tagName.toLowerCase();
Form.Element.Serializers[method](element, value);
return element;
},
clear: function(element) {
$(element).value = '';
return element;
},
present: function(element) {
return $(element).value != '';
},
activate: function(element) {
element = $(element);
try {
element.focus();
if (element.select && (element.tagName.toLowerCase() != 'input' ||
!['button', 'reset', 'submit'].include(element.type)))
element.select();
} catch (e) { }
return element;
},
disable: function(element) {
element = $(element);
element.blur();
element.disabled = true;
return element;
},
enable: function(element) {
element = $(element);
element.disabled = false;
return element;
}
};
/*--------------------------------------------------------------------------*/
var Field = Form.Element;
var $F = Form.Element.Methods.getValue;
/*--------------------------------------------------------------------------*/
Form.Element.Serializers = {
input: function(element, value) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
return Form.Element.Serializers.inputSelector(element, value);
default:
return Form.Element.Serializers.textarea(element, value);
}
},
inputSelector: function(element, value) {
if (Object.isUndefined(value)) return element.checked ? element.value : null;
else element.checked = !!value;
},
textarea: function(element, value) {
if (Object.isUndefined(value)) return element.value;
else element.value = value;
},
select: function(element, index) {
if (Object.isUndefined(index))
return this[element.type == 'select-one' ?
'selectOne' : 'selectMany'](element);
else {
var opt, value, single = !Object.isArray(index);
for (var i = 0, length = element.length; i < length; i++) {
opt = element.options[i];
value = this.optionValue(opt);
if (single) {
if (value == index) {
opt.selected = true;
return;
}
}
else opt.selected = index.include(value);
}
}
},
selectOne: function(element) {
var index = element.selectedIndex;
return index >= 0 ? this.optionValue(element.options[index]) : null;
},
selectMany: function(element) {
var values, length = element.length;
if (!length) return null;
for (var i = 0, values = []; i < length; i++) {
var opt = element.options[i];
if (opt.selected) values.push(this.optionValue(opt));
}
return values;
},
optionValue: function(opt) {
// extend element because hasAttribute may not be native
return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
}
};
/*--------------------------------------------------------------------------*/
Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
initialize: function($super, element, frequency, callback) {
$super(callback, frequency);
this.element = $(element);
this.lastValue = this.getValue();
},
execute: function() {
var value = this.getValue();
if (Object.isString(this.lastValue) && Object.isString(value) ?
this.lastValue != value : String(this.lastValue) != String(value)) {
this.callback(this.element, value);
this.lastValue = value;
}
}
});
Form.Element.Observer = Class.create(Abstract.TimedObserver, {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.Observer = Class.create(Abstract.TimedObserver, {
getValue: function() {
return Form.serialize(this.element);
}
});
/*--------------------------------------------------------------------------*/
Abstract.EventObserver = Class.create({
initialize: function(element, callback) {
this.element = $(element);
this.callback = callback;
this.lastValue = this.getValue();
if (this.element.tagName.toLowerCase() == 'form')
this.registerFormCallbacks();
else
this.registerCallback(this.element);
},
onElementEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
},
registerFormCallbacks: function() {
Form.getElements(this.element).each(this.registerCallback, this);
},
registerCallback: function(element) {
if (element.type) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
Event.observe(element, 'click', this.onElementEvent.bind(this));
break;
default:
Event.observe(element, 'change', this.onElementEvent.bind(this));
break;
}
}
}
});
Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.EventObserver = Class.create(Abstract.EventObserver, {
getValue: function() {
return Form.serialize(this.element);
}
});
if (!window.Event) var Event = { };
Object.extend(Event, {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_RETURN: 13,
KEY_ESC: 27,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
KEY_HOME: 36,
KEY_END: 35,
KEY_PAGEUP: 33,
KEY_PAGEDOWN: 34,
KEY_INSERT: 45,
cache: { },
relatedTarget: function(event) {
var element;
switch(event.type) {
case 'mouseover': element = event.fromElement; break;
case 'mouseout': element = event.toElement; break;
default: return null;
}
return Element.extend(element);
}
});
Event.Methods = (function() {
var isButton;
if (Prototype.Browser.IE) {
var buttonMap = { 0: 1, 1: 4, 2: 2 };
isButton = function(event, code) {
return event.button == buttonMap[code];
};
} else if (Prototype.Browser.WebKit) {
isButton = function(event, code) {
switch (code) {
case 0: return event.which == 1 && !event.metaKey;
case 1: return event.which == 1 && event.metaKey;
default: return false;
}
};
} else {
isButton = function(event, code) {
return event.which ? (event.which === code + 1) : (event.button === code);
};
}
return {
isLeftClick: function(event) { return isButton(event, 0) },
isMiddleClick: function(event) { return isButton(event, 1) },
isRightClick: function(event) { return isButton(event, 2) },
element: function(event) {
var node = Event.extend(event).target;
return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
},
findElement: function(event, expression) {
var element = Event.element(event);
if (!expression) return element;
var elements = [element].concat(element.ancestors());
return Selector.findElement(elements, expression, 0);
},
pointer: function(event) {
return {
x: event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft)),
y: event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop))
};
},
pointerX: function(event) { return Event.pointer(event).x },
pointerY: function(event) { return Event.pointer(event).y },
stop: function(event) {
Event.extend(event);
event.preventDefault();
event.stopPropagation();
event.stopped = true;
}
};
})();
Event.extend = (function() {
var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
m[name] = Event.Methods[name].methodize();
return m;
});
if (Prototype.Browser.IE) {
Object.extend(methods, {
stopPropagation: function() { this.cancelBubble = true },
preventDefault: function() { this.returnValue = false },
inspect: function() { return "[object Event]" }
});
return function(event) {
if (!event) return false;
if (event._extendedByPrototype) return event;
event._extendedByPrototype = Prototype.emptyFunction;
var pointer = Event.pointer(event);
Object.extend(event, {
target: event.srcElement,
relatedTarget: Event.relatedTarget(event),
pageX: pointer.x,
pageY: pointer.y
});
return Object.extend(event, methods);
};
} else {
Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
Object.extend(Event.prototype, methods);
return Prototype.K;
}
})();
Object.extend(Event, (function() {
var cache = Event.cache;
function getEventID(element) {
if (element._prototypeEventID) return element._prototypeEventID[0];
arguments.callee.id = arguments.callee.id || 1;
return element._prototypeEventID = [++arguments.callee.id];
}
function getDOMEventName(eventName) {
if (eventName && eventName.include(':')) return "dataavailable";
return eventName;
}
function getCacheForID(id) {
return cache[id] = cache[id] || { };
}
function getWrappersForEventName(id, eventName) {
var c = getCacheForID(id);
return c[eventName] = c[eventName] || [];
}
function createWrapper(element, eventName, handler) {
var id = getEventID(element);
var c = getWrappersForEventName(id, eventName);
if (c.pluck("handler").include(handler)) return false;
var wrapper = function(event) {
if (!Event || !Event.extend ||
(event.eventName && event.eventName != eventName))
return false;
Event.extend(event);
handler.call(element, event);
};
wrapper.handler = handler;
c.push(wrapper);
return wrapper;
}
function findWrapper(id, eventName, handler) {
var c = getWrappersForEventName(id, eventName);
return c.find(function(wrapper) { return wrapper.handler == handler });
}
function destroyWrapper(id, eventName, handler) {
var c = getCacheForID(id);
if (!c[eventName]) return false;
c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
}
function destroyCache() {
for (var id in cache)
for (var eventName in cache[id])
cache[id][eventName] = null;
}
if (window.attachEvent) {
window.attachEvent("onunload", destroyCache);
}
return {
observe: function(element, eventName, handler) {
element = $(element);
var name = getDOMEventName(eventName);
var wrapper = createWrapper(element, eventName, handler);
if (!wrapper) return element;
if (element.addEventListener) {
element.addEventListener(name, wrapper, false);
} else {
element.attachEvent("on" + name, wrapper);
}
return element;
},
stopObserving: function(element, eventName, handler) {
element = $(element);
var id = getEventID(element), name = getDOMEventName(eventName);
if (!handler && eventName) {
getWrappersForEventName(id, eventName).each(function(wrapper) {
element.stopObserving(eventName, wrapper.handler);
});
return element;
} else if (!eventName) {
Object.keys(getCacheForID(id)).each(function(eventName) {
element.stopObserving(eventName);
});
return element;
}
var wrapper = findWrapper(id, eventName, handler);
if (!wrapper) return element;
if (element.removeEventListener) {
element.removeEventListener(name, wrapper, false);
} else {
element.detachEvent("on" + name, wrapper);
}
destroyWrapper(id, eventName, handler);
return element;
},
fire: function(element, eventName, memo) {
element = $(element);
if (element == document && document.createEvent && !element.dispatchEvent)
element = document.documentElement;
var event;
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent("dataavailable", true, true);
} else {
event = document.createEventObject();
event.eventType = "ondataavailable";
}
event.eventName = eventName;
event.memo = memo || { };
if (document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent(event.eventType, event);
}
return Event.extend(event);
}
};
})());
Object.extend(Event, Event.Methods);
Element.addMethods({
fire: Event.fire,
observe: Event.observe,
stopObserving: Event.stopObserving
});
Object.extend(document, {
fire: Element.Methods.fire.methodize(),
observe: Element.Methods.observe.methodize(),
stopObserving: Element.Methods.stopObserving.methodize(),
loaded: false
});
(function() {
/* Support for the DOMContentLoaded event is based on work by Dan Webb,
Matthias Miller, Dean Edwards and John Resig. */
var timer;
function fireContentLoadedEvent() {
if (document.loaded) return;
if (timer) window.clearInterval(timer);
document.fire("dom:loaded");
document.loaded = true;
}
if (document.addEventListener) {
if (Prototype.Browser.WebKit) {
timer = window.setInterval(function() {
if (/loaded|complete/.test(document.readyState))
fireContentLoadedEvent();
}, 0);
Event.observe(window, "load", fireContentLoadedEvent);
} else {
document.addEventListener("DOMContentLoaded",
fireContentLoadedEvent, false);
}
} else {
document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
$("__onDOMContentLoaded").onreadystatechange = function() {
if (this.readyState == "complete") {
this.onreadystatechange = null;
fireContentLoadedEvent();
}
};
}
})();
/*------------------------------- DEPRECATED -------------------------------*/
Hash.toQueryString = Object.toQueryString;
var Toggle = { display: Element.toggle };
Element.Methods.childOf = Element.Methods.descendantOf;
var Insertion = {
Before: function(element, content) {
return Element.insert(element, {before:content});
},
Top: function(element, content) {
return Element.insert(element, {top:content});
},
Bottom: function(element, content) {
return Element.insert(element, {bottom:content});
},
After: function(element, content) {
return Element.insert(element, {after:content});
}
};
var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
// This should be moved to script.aculo.us; notice the deprecated methods
// further below, that map to the newer Element methods.
var Position = {
// set to true if needed, warning: firefox performance problems
// NOT neeeded for page scrolling, only if draggable contained in
// scrollable elements
includeScrollOffsets: false,
// must be called before calling withinIncludingScrolloffset, every time the
// page is scrolled
prepare: function() {
this.deltaX = window.pageXOffset
|| document.documentElement.scrollLeft
|| document.body.scrollLeft
|| 0;
this.deltaY = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
},
// caches x/y coordinate pair to use with overlap
within: function(element, x, y) {
if (this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element, x, y);
this.xcomp = x;
this.ycomp = y;
this.offset = Element.cumulativeOffset(element);
return (y >= this.offset[1] &&
y < this.offset[1] + element.offsetHeight &&
x >= this.offset[0] &&
x < this.offset[0] + element.offsetWidth);
},
withinIncludingScrolloffsets: function(element, x, y) {
var offsetcache = Element.cumulativeScrollOffset(element);
this.xcomp = x + offsetcache[0] - this.deltaX;
this.ycomp = y + offsetcache[1] - this.deltaY;
this.offset = Element.cumulativeOffset(element);
return (this.ycomp >= this.offset[1] &&
this.ycomp < this.offset[1] + element.offsetHeight &&
this.xcomp >= this.offset[0] &&
this.xcomp < this.offset[0] + element.offsetWidth);
},
// within must be called directly before
overlap: function(mode, element) {
if (!mode) return 0;
if (mode == 'vertical')
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
element.offsetHeight;
if (mode == 'horizontal')
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
element.offsetWidth;
},
// Deprecation layer -- use newer Element methods now (1.5.2).
cumulativeOffset: Element.Methods.cumulativeOffset,
positionedOffset: Element.Methods.positionedOffset,
absolutize: function(element) {
Position.prepare();
return Element.absolutize(element);
},
relativize: function(element) {
Position.prepare();
return Element.relativize(element);
},
realOffset: Element.Methods.cumulativeScrollOffset,
offsetParent: Element.Methods.getOffsetParent,
page: Element.Methods.viewportOffset,
clone: function(source, target, options) {
options = options || { };
return Element.clonePosition(target, source, options);
}
};
/*--------------------------------------------------------------------------*/
if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
function iter(name) {
return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
}
instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
function(element, className) {
className = className.toString().strip();
var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
} : function(element, className) {
className = className.toString().strip();
var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
if (!classNames && !className) return elements;
var nodes = $(element).getElementsByTagName('*');
className = ' ' + className + ' ';
for (var i = 0, child, cn; child = nodes[i]; i++) {
if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
(classNames && classNames.all(function(name) {
return !name.toString().blank() && cn.include(' ' + name + ' ');
}))))
elements.push(Element.extend(child));
}
return elements;
};
return function(className, parentElement) {
return $(parentElement || document.body).getElementsByClassName(className);
};
}(Element.Methods);
/*--------------------------------------------------------------------------*/
Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
initialize: function(element) {
this.element = $(element);
},
_each: function(iterator) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
})._each(iterator);
},
set: function(className) {
this.element.className = className;
},
add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
this.set($A(this).concat(classNameToAdd).join(' '));
},
remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
this.set($A(this).without(classNameToRemove).join(' '));
},
toString: function() {
return $A(this).join(' ');
}
};
Object.extend(Element.ClassNames.prototype, Enumerable);
/*--------------------------------------------------------------------------*/
Element.addMethods();/* Prototype JavaScript framework, version 1.6.0.2
* (c) 2005-2008 Sam Stephenson
*
* Prototype is freely distributable under the terms of an MIT-style license.
* For details, see the Prototype web site: http://www.prototypejs.org/
*
*--------------------------------------------------------------------------*/
var Prototype = {
Version: '1.6.0.2',
Browser: {
IE: !!(window.attachEvent && !window.opera),
Opera: !!window.opera,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
},
BrowserFeatures: {
XPath: !!document.evaluate,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
document.createElement('div').__proto__ &&
document.createElement('div').__proto__ !==
document.createElement('form').__proto__
},
ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
emptyFunction: function() { },
K: function(x) { return x }
};
if (Prototype.Browser.MobileSafari)
Prototype.BrowserFeatures.SpecificElementExtensions = false;
/* Based on Alex Arnell's inheritance implementation. */
var Class = {
create: function() {
var parent = null, properties = $A(arguments);
if (Object.isFunction(properties[0]))
parent = properties.shift();
function klass() {
this.initialize.apply(this, arguments);
}
Object.extend(klass, Class.Methods);
klass.superclass = parent;
klass.subclasses = [];
if (parent) {
var subclass = function() { };
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
parent.subclasses.push(klass);
}
for (var i = 0; i < properties.length; i++)
klass.addMethods(properties[i]);
if (!klass.prototype.initialize)
klass.prototype.initialize = Prototype.emptyFunction;
klass.prototype.constructor = klass;
return klass;
}
};
Class.Methods = {
addMethods: function(source) {
var ancestor = this.superclass && this.superclass.prototype;
var properties = Object.keys(source);
if (!Object.keys({ toString: true }).length)
properties.push("toString", "valueOf");
for (var i = 0, length = properties.length; i < length; i++) {
var property = properties[i], value = source[property];
if (ancestor && Object.isFunction(value) &&
value.argumentNames().first() == "$super") {
var method = value, value = Object.extend((function(m) {
return function() { return ancestor[m].apply(this, arguments) };
})(property).wrap(method), {
valueOf: function() { return method },
toString: function() { return method.toString() }
});
}
this.prototype[property] = value;
}
return this;
}
};
var Abstract = { };
Object.extend = function(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
};
Object.extend(Object, {
inspect: function(object) {
try {
if (Object.isUndefined(object)) return 'undefined';
if (object === null) return 'null';
return object.inspect ? object.inspect() : String(object);
} catch (e) {
if (e instanceof RangeError) return '...';
throw e;
}
},
toJSON: function(object) {
var type = typeof object;
switch (type) {
case 'undefined':
case 'function':
case 'unknown': return;
case 'boolean': return object.toString();
}
if (object === null) return 'null';
if (object.toJSON) return object.toJSON();
if (Object.isElement(object)) return;
var results = [];
for (var property in object) {
var value = Object.toJSON(object[property]);
if (!Object.isUndefined(value))
results.push(property.toJSON() + ': ' + value);
}
return '{' + results.join(', ') + '}';
},
toQueryString: function(object) {
return $H(object).toQueryString();
},
toHTML: function(object) {
return object && object.toHTML ? object.toHTML() : String.interpret(object);
},
keys: function(object) {
var keys = [];
for (var property in object)
keys.push(property);
return keys;
},
values: function(object) {
var values = [];
for (var property in object)
values.push(object[property]);
return values;
},
clone: function(object) {
return Object.extend({ }, object);
},
isElement: function(object) {
return object && object.nodeType == 1;
},
isArray: function(object) {
return object != null && typeof object == "object" &&
'splice' in object && 'join' in object;
},
isHash: function(object) {
return object instanceof Hash;
},
isFunction: function(object) {
return typeof object == "function";
},
isString: function(object) {
return typeof object == "string";
},
isNumber: function(object) {
return typeof object == "number";
},
isUndefined: function(object) {
return typeof object == "undefined";
}
});
Object.extend(Function.prototype, {
argumentNames: function() {
var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
return names.length == 1 && !names[0] ? [] : names;
},
bind: function() {
if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
},
bindAsEventListener: function() {
var __method = this, args = $A(arguments), object = args.shift();
return function(event) {
return __method.apply(object, [event || window.event].concat(args));
}
},
curry: function() {
if (!arguments.length) return this;
var __method = this, args = $A(arguments);
return function() {
return __method.apply(this, args.concat($A(arguments)));
}
},
delay: function() {
var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
return window.setTimeout(function() {
return __method.apply(__method, args);
}, timeout);
},
wrap: function(wrapper) {
var __method = this;
return function() {
return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
}
},
methodize: function() {
if (this._methodized) return this._methodized;
var __method = this;
return this._methodized = function() {
return __method.apply(null, [this].concat($A(arguments)));
};
}
});
Function.prototype.defer = Function.prototype.delay.curry(0.01);
Date.prototype.toJSON = function() {
return '"' + this.getUTCFullYear() + '-' +
(this.getUTCMonth() + 1).toPaddedString(2) + '-' +
this.getUTCDate().toPaddedString(2) + 'T' +
this.getUTCHours().toPaddedString(2) + ':' +
this.getUTCMinutes().toPaddedString(2) + ':' +
this.getUTCSeconds().toPaddedString(2) + 'Z"';
};
var Try = {
these: function() {
var returnValue;
for (var i = 0, length = arguments.length; i < length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) { }
}
return returnValue;
}
};
RegExp.prototype.match = RegExp.prototype.test;
RegExp.escape = function(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
/*--------------------------------------------------------------------------*/
var PeriodicalExecuter = Class.create({
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback();
},
registerCallback: function() {
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
execute: function() {
this.callback(this);
},
stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.execute();
} finally {
this.currentlyExecuting = false;
}
}
}
});
Object.extend(String, {
interpret: function(value) {
return value == null ? '' : String(value);
},
specialChar: {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'\\': '\\\\'
}
});
Object.extend(String.prototype, {
gsub: function(pattern, replacement) {
var result = '', source = this, match;
replacement = arguments.callee.prepareReplacement(replacement);
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
result += String.interpret(replacement(match));
source = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
}
}
return result;
},
sub: function(pattern, replacement, count) {
replacement = this.gsub.prepareReplacement(replacement);
count = Object.isUndefined(count) ? 1 : count;
return this.gsub(pattern, function(match) {
if (--count < 0) return match[0];
return replacement(match);
});
},
scan: function(pattern, iterator) {
this.gsub(pattern, iterator);
return String(this);
},
truncate: function(length, truncation) {
length = length || 30;
truncation = Object.isUndefined(truncation) ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) + truncation : String(this);
},
strip: function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
},
stripTags: function() {
return this.replace(/<\/?[^>]+>/gi, '');
},
stripScripts: function() {
return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
},
extractScripts: function() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
return (this.match(matchAll) || []).map(function(scriptTag) {
return (scriptTag.match(matchOne) || ['', ''])[1];
});
},
evalScripts: function() {
return this.extractScripts().map(function(script) { return eval(script) });
},
escapeHTML: function() {
var self = arguments.callee;
self.text.data = this;
return self.div.innerHTML;
},
unescapeHTML: function() {
var div = new Element('div');
div.innerHTML = this.stripTags();
return div.childNodes[0] ? (div.childNodes.length > 1 ?
$A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
div.childNodes[0].nodeValue) : '';
},
toQueryParams: function(separator) {
var match = this.strip().match(/([^?#]*)(#.*)?$/);
if (!match) return { };
return match[1].split(separator || '&').inject({ }, function(hash, pair) {
if ((pair = pair.split('='))[0]) {
var key = decodeURIComponent(pair.shift());
var value = pair.length > 1 ? pair.join('=') : pair[0];
if (value != undefined) value = decodeURIComponent(value);
if (key in hash) {
if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
hash[key].push(value);
}
else hash[key] = value;
}
return hash;
});
},
toArray: function() {
return this.split('');
},
succ: function() {
return this.slice(0, this.length - 1) +
String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
},
times: function(count) {
return count < 1 ? '' : new Array(count + 1).join(this);
},
camelize: function() {
var parts = this.split('-'), len = parts.length;
if (len == 1) return parts[0];
var camelized = this.charAt(0) == '-'
? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
: parts[0];
for (var i = 1; i < len; i++)
camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
return camelized;
},
capitalize: function() {
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
},
underscore: function() {
return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
},
dasherize: function() {
return this.gsub(/_/,'-');
},
inspect: function(useDoubleQuotes) {
var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
var character = String.specialChar[match[0]];
return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
});
if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
},
toJSON: function() {
return this.inspect(true);
},
unfilterJSON: function(filter) {
return this.sub(filter || Prototype.JSONFilter, '#{1}');
},
isJSON: function() {
var str = this;
if (str.blank()) return false;
str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
},
evalJSON: function(sanitize) {
var json = this.unfilterJSON();
try {
if (!sanitize || json.isJSON()) return eval('(' + json + ')');
} catch (e) { }
throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
},
include: function(pattern) {
return this.indexOf(pattern) > -1;
},
startsWith: function(pattern) {
return this.indexOf(pattern) === 0;
},
endsWith: function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
},
empty: function() {
return this == '';
},
blank: function() {
return /^\s*$/.test(this);
},
interpolate: function(object, pattern) {
return new Template(this, pattern).evaluate(object);
}
});
if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
escapeHTML: function() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
},
unescapeHTML: function() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
});
String.prototype.gsub.prepareReplacement = function(replacement) {
if (Object.isFunction(replacement)) return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };
};
String.prototype.parseQuery = String.prototype.toQueryParams;
Object.extend(String.prototype.escapeHTML, {
div: document.createElement('div'),
text: document.createTextNode('')
});
with (String.prototype.escapeHTML) div.appendChild(text);
var Template = Class.create({
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},
evaluate: function(object) {
if (Object.isFunction(object.toTemplateReplacements))
object = object.toTemplateReplacements();
return this.template.gsub(this.pattern, function(match) {
if (object == null) return '';
var before = match[1] || '';
if (before == '\\') return match[2];
var ctx = object, expr = match[3];
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
match = pattern.exec(expr);
if (match == null) return before;
while (match != null) {
var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
ctx = ctx[comp];
if (null == ctx || '' == match[3]) break;
expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
match = pattern.exec(expr);
}
return before + String.interpret(ctx);
});
}
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
var $break = { };
var Enumerable = {
each: function(iterator, context) {
var index = 0;
iterator = iterator.bind(context);
try {
this._each(function(value) {
iterator(value, index++);
});
} catch (e) {
if (e != $break) throw e;
}
return this;
},
eachSlice: function(number, iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var index = -number, slices = [], array = this.toArray();
while ((index += number) < array.length)
slices.push(array.slice(index, index+number));
return slices.collect(iterator, context);
},
all: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result = true;
this.each(function(value, index) {
result = result && !!iterator(value, index);
if (!result) throw $break;
});
return result;
},
any: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result = false;
this.each(function(value, index) {
if (result = !!iterator(value, index))
throw $break;
});
return result;
},
collect: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var results = [];
this.each(function(value, index) {
results.push(iterator(value, index));
});
return results;
},
detect: function(iterator, context) {
iterator = iterator.bind(context);
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
result = value;
throw $break;
}
});
return result;
},
findAll: function(iterator, context) {
iterator = iterator.bind(context);
var results = [];
this.each(function(value, index) {
if (iterator(value, index))
results.push(value);
});
return results;
},
grep: function(filter, iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var results = [];
if (Object.isString(filter))
filter = new RegExp(filter);
this.each(function(value, index) {
if (filter.match(value))
results.push(iterator(value, index));
});
return results;
},
include: function(object) {
if (Object.isFunction(this.indexOf))
if (this.indexOf(object) != -1) return true;
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
},
inGroupsOf: function(number, fillWith) {
fillWith = Object.isUndefined(fillWith) ? null : fillWith;
return this.eachSlice(number, function(slice) {
while(slice.length < number) slice.push(fillWith);
return slice;
});
},
inject: function(memo, iterator, context) {
iterator = iterator.bind(context);
this.each(function(value, index) {
memo = iterator(memo, value, index);
});
return memo;
},
invoke: function(method) {
var args = $A(arguments).slice(1);
return this.map(function(value) {
return value[method].apply(value, args);
});
},
max: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result;
this.each(function(value, index) {
value = iterator(value, index);
if (result == null || value >= result)
result = value;
});
return result;
},
min: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result;
this.each(function(value, index) {
value = iterator(value, index);
if (result == null || value < result)
result = value;
});
return result;
},
partition: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var trues = [], falses = [];
this.each(function(value, index) {
(iterator(value, index) ?
trues : falses).push(value);
});
return [trues, falses];
},
pluck: function(property) {
var results = [];
this.each(function(value) {
results.push(value[property]);
});
return results;
},
reject: function(iterator, context) {
iterator = iterator.bind(context);
var results = [];
this.each(function(value, index) {
if (!iterator(value, index))
results.push(value);
});
return results;
},
sortBy: function(iterator, context) {
iterator = iterator.bind(context);
return this.map(function(value, index) {
return {value: value, criteria: iterator(value, index)};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}).pluck('value');
},
toArray: function() {
return this.map();
},
zip: function() {
var iterator = Prototype.K, args = $A(arguments);
if (Object.isFunction(args.last()))
iterator = args.pop();
var collections = [this].concat(args).map($A);
return this.map(function(value, index) {
return iterator(collections.pluck(index));
});
},
size: function() {
return this.toArray().length;
},
inspect: function() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
};
Object.extend(Enumerable, {
map: Enumerable.collect,
find: Enumerable.detect,
select: Enumerable.findAll,
filter: Enumerable.findAll,
member: Enumerable.include,
entries: Enumerable.toArray,
every: Enumerable.all,
some: Enumerable.any
});
function $A(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
if (Prototype.Browser.WebKit) {
$A = function(iterable) {
if (!iterable) return [];
if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
iterable.toArray) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
};
}
Array.from = $A;
Object.extend(Array.prototype, Enumerable);
if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
Object.extend(Array.prototype, {
_each: function(iterator) {
for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
},
clear: function() {
this.length = 0;
return this;
},
first: function() {
return this[0];
},
last: function() {
return this[this.length - 1];
},
compact: function() {
return this.select(function(value) {
return value != null;
});
},
flatten: function() {
return this.inject([], function(array, value) {
return array.concat(Object.isArray(value) ?
value.flatten() : [value]);
});
},
without: function() {
var values = $A(arguments);
return this.select(function(value) {
return !values.include(value);
});
},
reverse: function(inline) {
return (inline !== false ? this : this.toArray())._reverse();
},
reduce: function() {
return this.length > 1 ? this : this[0];
},
uniq: function(sorted) {
return this.inject([], function(array, value, index) {
if (0 == index || (sorted ? array.last() != value : !array.include(value)))
array.push(value);
return array;
});
},
intersect: function(array) {
return this.uniq().findAll(function(item) {
return array.detect(function(value) { return item === value });
});
},
clone: function() {
return [].concat(this);
},
size: function() {
return this.length;
},
inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
},
toJSON: function() {
var results = [];
this.each(function(object) {
var value = Object.toJSON(object);
if (!Object.isUndefined(value)) results.push(value);
});
return '[' + results.join(', ') + ']';
}
});
// use native browser JS 1.6 implementation if available
if (Object.isFunction(Array.prototype.forEach))
Array.prototype._each = Array.prototype.forEach;
if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
i || (i = 0);
var length = this.length;
if (i < 0) i = length + i;
for (; i < length; i++)
if (this[i] === item) return i;
return -1;
};
if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
var n = this.slice(0, i).reverse().indexOf(item);
return (n < 0) ? n : i - n - 1;
};
Array.prototype.toArray = Array.prototype.clone;
function $w(string) {
if (!Object.isString(string)) return [];
string = string.strip();
return string ? string.split(/\s+/) : [];
}
if (Prototype.Browser.Opera){
Array.prototype.concat = function() {
var array = [];
for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
for (var i = 0, length = arguments.length; i < length; i++) {
if (Object.isArray(arguments[i])) {
for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
array.push(arguments[i][j]);
} else {
array.push(arguments[i]);
}
}
return array;
};
}
Object.extend(Number.prototype, {
toColorPart: function() {
return this.toPaddedString(2, 16);
},
succ: function() {
return this + 1;
},
times: function(iterator) {
$R(0, this, true).each(iterator);
return this;
},
toPaddedString: function(length, radix) {
var string = this.toString(radix || 10);
return '0'.times(length - string.length) + string;
},
toJSON: function() {
return isFinite(this) ? this.toString() : 'null';
}
});
$w('abs round ceil floor').each(function(method){
Number.prototype[method] = Math[method].methodize();
});
function $H(object) {
return new Hash(object);
};
var Hash = Class.create(Enumerable, (function() {
function toQueryPair(key, value) {
if (Object.isUndefined(value)) return key;
return key + '=' + encodeURIComponent(String.interpret(value));
}
return {
initialize: function(object) {
this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
},
_each: function(iterator) {
for (var key in this._object) {
var value = this._object[key], pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},
set: function(key, value) {
return this._object[key] = value;
},
get: function(key) {
return this._object[key];
},
unset: function(key) {
var value = this._object[key];
delete this._object[key];
return value;
},
toObject: function() {
return Object.clone(this._object);
},
keys: function() {
return this.pluck('key');
},
values: function() {
return this.pluck('value');
},
index: function(value) {
var match = this.detect(function(pair) {
return pair.value === value;
});
return match && match.key;
},
merge: function(object) {
return this.clone().update(object);
},
update: function(object) {
return new Hash(object).inject(this, function(result, pair) {
result.set(pair.key, pair.value);
return result;
});
},
toQueryString: function() {
return this.map(function(pair) {
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
if (Object.isArray(values))
return values.map(toQueryPair.curry(key)).join('&');
}
return toQueryPair(key, values);
}).join('&');
},
inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
},
toJSON: function() {
return Object.toJSON(this.toObject());
},
clone: function() {
return new Hash(this);
}
}
})());
Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;
var ObjectRange = Class.create(Enumerable, {
initialize: function(start, end, exclusive) {
this.start = start;
this.end = end;
this.exclusive = exclusive;
},
_each: function(iterator) {
var value = this.start;
while (this.include(value)) {
iterator(value);
value = value.succ();
}
},
include: function(value) {
if (value < this.start)
return false;
if (this.exclusive)
return value < this.end;
return value <= this.end;
}
});
var $R = function(start, end, exclusive) {
return new ObjectRange(start, end, exclusive);
};
var Ajax = {
getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false;
},
activeRequestCount: 0
};
Ajax.Responders = {
responders: [],
_each: function(iterator) {
this.responders._each(iterator);
},
register: function(responder) {
if (!this.include(responder))
this.responders.push(responder);
},
unregister: function(responder) {
this.responders = this.responders.without(responder);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (Object.isFunction(responder[callback])) {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) { }
}
});
}
};
Object.extend(Ajax.Responders, Enumerable);
Ajax.Responders.register({
onCreate: function() { Ajax.activeRequestCount++ },
onComplete: function() { Ajax.activeRequestCount-- }
});
Ajax.Base = Class.create({
initialize: function(options) {
this.options = {
method: 'post',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
encoding: 'UTF-8',
parameters: '',
evalJSON: true,
evalJS: true
};
Object.extend(this.options, options || { });
this.options.method = this.options.method.toLowerCase();
if (Object.isString(this.options.parameters))
this.options.parameters = this.options.parameters.toQueryParams();
else if (Object.isHash(this.options.parameters))
this.options.parameters = this.options.parameters.toObject();
}
});
Ajax.Request = Class.create(Ajax.Base, {
_complete: false,
initialize: function($super, url, options) {
$super(options);
this.transport = Ajax.getTransport();
this.request(url);
},
request: function(url) {
this.url = url;
this.method = this.options.method;
var params = Object.clone(this.options.parameters);
if (!['get', 'post'].include(this.method)) {
// simulate other verbs over post
params['_method'] = this.method;
this.method = 'post';
}
this.parameters = params;
if (params = Object.toQueryString(params)) {
// when GET, append parameters to URL
if (this.method == 'get')
this.url += (this.url.include('?') ? '&' : '?') + params;
else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
params += '&_=';
}
try {
var response = new Ajax.Response(this);
if (this.options.onCreate) this.options.onCreate(response);
Ajax.Responders.dispatch('onCreate', this, response);
this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
this.body = this.method == 'post' ? (this.options.postBody || params) : null;
this.transport.send(this.body);
/* Force Firefox to handle ready state 4 for synchronous requests */
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();
}
catch (e) {
this.dispatchException(e);
}
},
onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState > 1 && !((readyState == 4) && this._complete))
this.respondToReadyState(this.transport.readyState);
},
setRequestHeaders: function() {
var headers = {
'X-Requested-With': 'XMLHttpRequest',
'X-Prototype-Version': Prototype.Version,
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
};
if (this.method == 'post') {
headers['Content-type'] = this.options.contentType +
(this.options.encoding ? '; charset=' + this.options.encoding : '');
/* Force "Connection: close" for older Mozilla browsers to work
* around a bug where XMLHttpRequest sends an incorrect
* Content-length header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType &&
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
headers['Connection'] = 'close';
}
// user-defined headers
if (typeof this.options.requestHeaders == 'object') {
var extras = this.options.requestHeaders;
if (Object.isFunction(extras.push))
for (var i = 0, length = extras.length; i < length; i += 2)
headers[extras[i]] = extras[i+1];
else
$H(extras).each(function(pair) { headers[pair.key] = pair.value });
}
for (var name in headers)
this.transport.setRequestHeader(name, headers[name]);
},
success: function() {
var status = this.getStatus();
return !status || (status >= 200 && status < 300);
},
getStatus: function() {
try {
return this.transport.status || 0;
} catch (e) { return 0 }
},
respondToReadyState: function(readyState) {
var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
if (state == 'Complete') {
try {
this._complete = true;
(this.options['on' + response.status]
|| this.options['on' + (this.success() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
var contentType = response.getHeader('Content-type');
if (this.options.evalJS == 'force'
|| (this.options.evalJS && this.isSameOrigin() && contentType
&& contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
this.evalResponse();
}
try {
(this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
if (state == 'Complete') {
// avoid memory leak in MSIE: clean up
this.transport.onreadystatechange = Prototype.emptyFunction;
}
},
isSameOrigin: function() {
var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
protocol: location.protocol,
domain: document.domain,
port: location.port ? ':' + location.port : ''
}));
},
getHeader: function(name) {
try {
return this.transport.getResponseHeader(name) || null;
} catch (e) { return null }
},
evalResponse: function() {
try {
return eval((this.transport.responseText || '').unfilterJSON());
} catch (e) {
this.dispatchException(e);
}
},
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
}
});
Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Response = Class.create({
initialize: function(request){
this.request = request;
var transport = this.transport = request.transport,
readyState = this.readyState = transport.readyState;
if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
this.status = this.getStatus();
this.statusText = this.getStatusText();
this.responseText = String.interpret(transport.responseText);
this.headerJSON = this._getHeaderJSON();
}
if(readyState == 4) {
var xml = transport.responseXML;
this.responseXML = Object.isUndefined(xml) ? null : xml;
this.responseJSON = this._getResponseJSON();
}
},
status: 0,
statusText: '',
getStatus: Ajax.Request.prototype.getStatus,
getStatusText: function() {
try {
return this.transport.statusText || '';
} catch (e) { return '' }
},
getHeader: Ajax.Request.prototype.getHeader,
getAllHeaders: function() {
try {
return this.getAllResponseHeaders();
} catch (e) { return null }
},
getResponseHeader: function(name) {
return this.transport.getResponseHeader(name);
},
getAllResponseHeaders: function() {
return this.transport.getAllResponseHeaders();
},
_getHeaderJSON: function() {
var json = this.getHeader('X-JSON');
if (!json) return null;
json = decodeURIComponent(escape(json));
try {
return json.evalJSON(this.request.options.sanitizeJSON ||
!this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
},
_getResponseJSON: function() {
var options = this.request.options;
if (!options.evalJSON || (options.evalJSON != 'force' &&
!(this.getHeader('Content-type') || '').include('application/json')) ||
this.responseText.blank())
return null;
try {
return this.responseText.evalJSON(options.sanitizeJSON ||
!this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
}
});
Ajax.Updater = Class.create(Ajax.Request, {
initialize: function($super, container, url, options) {
this.container = {
success: (container.success || container),
failure: (container.failure || (container.success ? null : container))
};
options = Object.clone(options);
var onComplete = options.onComplete;
options.onComplete = (function(response, json) {
this.updateContent(response.responseText);
if (Object.isFunction(onComplete)) onComplete(response, json);
}).bind(this);
$super(url, options);
},
updateContent: function(responseText) {
var receiver = this.container[this.success() ? 'success' : 'failure'],
options = this.options;
if (!options.evalScripts) responseText = responseText.stripScripts();
if (receiver = $(receiver)) {
if (options.insertion) {
if (Object.isString(options.insertion)) {
var insertion = { }; insertion[options.insertion] = responseText;
receiver.insert(insertion);
}
else options.insertion(receiver, responseText);
}
else receiver.update(responseText);
}
}
});
Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
initialize: function($super, container, url, options) {
$super(options);
this.onComplete = this.options.onComplete;
this.frequency = (this.options.frequency || 2);
this.decay = (this.options.decay || 1);
this.updater = { };
this.container = container;
this.url = url;
this.start();
},
start: function() {
this.options.onComplete = this.updateComplete.bind(this);
this.onTimerEvent();
},
stop: function() {
this.updater.options.onComplete = undefined;
clearTimeout(this.timer);
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
},
updateComplete: function(response) {
if (this.options.decay) {
this.decay = (response.responseText == this.lastText ?
this.decay * this.options.decay : 1);
this.lastText = response.responseText;
}
this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
},
onTimerEvent: function() {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
if (Prototype.BrowserFeatures.XPath) {
document._getElementsByXPath = function(expression, parentElement) {
var results = [];
var query = document.evaluate(expression, $(parentElement) || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0, length = query.snapshotLength; i < length; i++)
results.push(Element.extend(query.snapshotItem(i)));
return results;
};
}
/*--------------------------------------------------------------------------*/
if (!window.Node) var Node = { };
if (!Node.ELEMENT_NODE) {
// DOM level 2 ECMAScript Language Binding
Object.extend(Node, {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12
});
}
(function() {
var element = this.Element;
this.Element = function(tagName, attributes) {
attributes = attributes || { };
tagName = tagName.toLowerCase();
var cache = Element.cache;
if (Prototype.Browser.IE && attributes.name) {
tagName = '<' + tagName + ' name="' + attributes.name + '">';
delete attributes.name;
return Element.writeAttribute(document.createElement(tagName), attributes);
}
if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
};
Object.extend(this.Element, element || { });
}).call(window);
Element.cache = { };
Element.Methods = {
visible: function(element) {
return $(element).style.display != 'none';
},
toggle: function(element) {
element = $(element);
Element[Element.visible(element) ? 'hide' : 'show'](element);
return element;
},
hide: function(element) {
$(element).style.display = 'none';
return element;
},
show: function(element) {
$(element).style.display = '';
return element;
},
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
return element;
},
update: function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) return element.update().insert(content);
content = Object.toHTML(content);
element.innerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
},
replace: function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
else if (!Object.isElement(content)) {
content = Object.toHTML(content);
var range = element.ownerDocument.createRange();
range.selectNode(element);
content.evalScripts.bind(content).defer();
content = range.createContextualFragment(content.stripScripts());
}
element.parentNode.replaceChild(content, element);
return element;
},
insert: function(element, insertions) {
element = $(element);
if (Object.isString(insertions) || Object.isNumber(insertions) ||
Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
insertions = {bottom:insertions};
var content, insert, tagName, childNodes;
for (var position in insertions) {
content = insertions[position];
position = position.toLowerCase();
insert = Element._insertionTranslations[position];
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
insert(element, content);
continue;
}
content = Object.toHTML(content);
tagName = ((position == 'before' || position == 'after')
? element.parentNode : element).tagName.toUpperCase();
childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
if (position == 'top' || position == 'after') childNodes.reverse();
childNodes.each(insert.curry(element));
content.evalScripts.bind(content).defer();
}
return element;
},
wrap: function(element, wrapper, attributes) {
element = $(element);
if (Object.isElement(wrapper))
$(wrapper).writeAttribute(attributes || { });
else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
else wrapper = new Element('div', wrapper);
if (element.parentNode)
element.parentNode.replaceChild(wrapper, element);
wrapper.appendChild(element);
return wrapper;
},
inspect: function(element) {
element = $(element);
var result = '<' + element.tagName.toLowerCase();
$H({'id': 'id', 'className': 'class'}).each(function(pair) {
var property = pair.first(), attribute = pair.last();
var value = (element[property] || '').toString();
if (value) result += ' ' + attribute + '=' + value.inspect(true);
});
return result + '>';
},
recursivelyCollect: function(element, property) {
element = $(element);
var elements = [];
while (element = element[property])
if (element.nodeType == 1)
elements.push(Element.extend(element));
return elements;
},
ancestors: function(element) {
return $(element).recursivelyCollect('parentNode');
},
descendants: function(element) {
return $(element).select("*");
},
firstDescendant: function(element) {
element = $(element).firstChild;
while (element && element.nodeType != 1) element = element.nextSibling;
return $(element);
},
immediateDescendants: function(element) {
if (!(element = $(element).firstChild)) return [];
while (element && element.nodeType != 1) element = element.nextSibling;
if (element) return [element].concat($(element).nextSiblings());
return [];
},
previousSiblings: function(element) {
return $(element).recursivelyCollect('previousSibling');
},
nextSiblings: function(element) {
return $(element).recursivelyCollect('nextSibling');
},
siblings: function(element) {
element = $(element);
return element.previousSiblings().reverse().concat(element.nextSiblings());
},
match: function(element, selector) {
if (Object.isString(selector))
selector = new Selector(selector);
return selector.match($(element));
},
up: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(element.parentNode);
var ancestors = element.ancestors();
return Object.isNumber(expression) ? ancestors[expression] :
Selector.findElement(ancestors, expression, index);
},
down: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return element.firstDescendant();
return Object.isNumber(expression) ? element.descendants()[expression] :
element.select(expression)[index || 0];
},
previous: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
var previousSiblings = element.previousSiblings();
return Object.isNumber(expression) ? previousSiblings[expression] :
Selector.findElement(previousSiblings, expression, index);
},
next: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
var nextSiblings = element.nextSiblings();
return Object.isNumber(expression) ? nextSiblings[expression] :
Selector.findElement(nextSiblings, expression, index);
},
select: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element, args);
},
adjacent: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element.parentNode, args).without(element);
},
identify: function(element) {
element = $(element);
var id = element.readAttribute('id'), self = arguments.callee;
if (id) return id;
do { id = 'anonymous_element_' + self.counter++ } while ($(id));
element.writeAttribute('id', id);
return id;
},
readAttribute: function(element, name) {
element = $(element);
if (Prototype.Browser.IE) {
var t = Element._attributeTranslations.read;
if (t.values[name]) return t.values[name](element, name);
if (t.names[name]) name = t.names[name];
if (name.include(':')) {
return (!element.attributes || !element.attributes[name]) ? null :
element.attributes[name].value;
}
}
return element.getAttribute(name);
},
writeAttribute: function(element, name, value) {
element = $(element);
var attributes = { }, t = Element._attributeTranslations.write;
if (typeof name == 'object') attributes = name;
else attributes[name] = Object.isUndefined(value) ? true : value;
for (var attr in attributes) {
name = t.names[attr] || attr;
value = attributes[attr];
if (t.values[attr]) name = t.values[attr](element, value);
if (value === false || value === null)
element.removeAttribute(name);
else if (value === true)
element.setAttribute(name, name);
else element.setAttribute(name, value);
}
return element;
},
getHeight: function(element) {
return $(element).getDimensions().height;
},
getWidth: function(element) {
return $(element).getDimensions().width;
},
classNames: function(element) {
return new Element.ClassNames(element);
},
hasClassName: function(element, className) {
if (!(element = $(element))) return;
var elementClassName = element.className;
return (elementClassName.length > 0 && (elementClassName == className ||
new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
},
addClassName: function(element, className) {
if (!(element = $(element))) return;
if (!element.hasClassName(className))
element.className += (element.className ? ' ' : '') + className;
return element;
},
removeClassName: function(element, className) {
if (!(element = $(element))) return;
element.className = element.className.replace(
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
return element;
},
toggleClassName: function(element, className) {
if (!(element = $(element))) return;
return element[element.hasClassName(className) ?
'removeClassName' : 'addClassName'](className);
},
// removes whitespace-only text node children
cleanWhitespace: function(element) {
element = $(element);
var node = element.firstChild;
while (node) {
var nextNode = node.nextSibling;
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
node = nextNode;
}
return element;
},
empty: function(element) {
return $(element).innerHTML.blank();
},
descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
var originalAncestor = ancestor;
if (element.compareDocumentPosition)
return (element.compareDocumentPosition(ancestor) & 8) === 8;
if (element.sourceIndex && !Prototype.Browser.Opera) {
var e = element.sourceIndex, a = ancestor.sourceIndex,
nextAncestor = ancestor.nextSibling;
if (!nextAncestor) {
do { ancestor = ancestor.parentNode; }
while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
}
if (nextAncestor && nextAncestor.sourceIndex)
return (e > a && e < nextAncestor.sourceIndex);
}
while (element = element.parentNode)
if (element == originalAncestor) return true;
return false;
},
scrollTo: function(element) {
element = $(element);
var pos = element.cumulativeOffset();
window.scrollTo(pos[0], pos[1]);
return element;
},
getStyle: function(element, style) {
element = $(element);
style = style == 'float' ? 'cssFloat' : style.camelize();
var value = element.style[style];
if (!value) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
}
if (style == 'opacity') return value ? parseFloat(value) : 1.0;
return value == 'auto' ? null : value;
},
getOpacity: function(element) {
return $(element).getStyle('opacity');
},
setStyle: function(element, styles) {
element = $(element);
var elementStyle = element.style, match;
if (Object.isString(styles)) {
element.style.cssText += ';' + styles;
return styles.include('opacity') ?
element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
}
for (var property in styles)
if (property == 'opacity') element.setOpacity(styles[property]);
else
elementStyle[(property == 'float' || property == 'cssFloat') ?
(Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
property] = styles[property];
return element;
},
setOpacity: function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
return element;
},
getDimensions: function(element) {
element = $(element);
var display = $(element).getStyle('display');
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
// so enable the element temporarily
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
var originalDisplay = els.display;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
makePositioned: function(element) {
element = $(element);
var pos = Element.getStyle(element, 'position');
if (pos == 'static' || !pos) {
element._madePositioned = true;
element.style.position = 'relative';
// Opera returns the offset relative to the positioning context, when an
// element is position relative but top and left have not been defined
if (window.opera) {
element.style.top = 0;
element.style.left = 0;
}
}
return element;
},
undoPositioned: function(element) {
element = $(element);
if (element._madePositioned) {
element._madePositioned = undefined;
element.style.position =
element.style.top =
element.style.left =
element.style.bottom =
element.style.right = '';
}
return element;
},
makeClipping: function(element) {
element = $(element);
if (element._overflow) return element;
element._overflow = Element.getStyle(element, 'overflow') || 'auto';
if (element._overflow !== 'hidden')
element.style.overflow = 'hidden';
return element;
},
undoClipping: function(element) {
element = $(element);
if (!element._overflow) return element;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
},
cumulativeOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return Element._returnOffset(valueL, valueT);
},
positionedOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
if (element.tagName == 'BODY') break;
var p = Element.getStyle(element, 'position');
if (p !== 'static') break;
}
} while (element);
return Element._returnOffset(valueL, valueT);
},
absolutize: function(element) {
element = $(element);
if (element.getStyle('position') == 'absolute') return;
// Position.prepare(); // To be done manually by Scripty when it needs it.
var offsets = element.positionedOffset();
var top = offsets[1];
var left = offsets[0];
var width = element.clientWidth;
var height = element.clientHeight;
element._originalLeft = left - parseFloat(element.style.left || 0);
element._originalTop = top - parseFloat(element.style.top || 0);
element._originalWidth = element.style.width;
element._originalHeight = element.style.height;
element.style.position = 'absolute';
element.style.top = top + 'px';
element.style.left = left + 'px';
element.style.width = width + 'px';
element.style.height = height + 'px';
return element;
},
relativize: function(element) {
element = $(element);
if (element.getStyle('position') == 'relative') return;
// Position.prepare(); // To be done manually by Scripty when it needs it.
element.style.position = 'relative';
var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
element.style.top = top + 'px';
element.style.left = left + 'px';
element.style.height = element._originalHeight;
element.style.width = element._originalWidth;
return element;
},
cumulativeScrollOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.scrollTop || 0;
valueL += element.scrollLeft || 0;
element = element.parentNode;
} while (element);
return Element._returnOffset(valueL, valueT);
},
getOffsetParent: function(element) {
if (element.offsetParent) return $(element.offsetParent);
if (element == document.body) return $(element);
while ((element = element.parentNode) && element != document.body)
if (Element.getStyle(element, 'position') != 'static')
return $(element);
return $(document.body);
},
viewportOffset: function(forElement) {
var valueT = 0, valueL = 0;
var element = forElement;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
// Safari fix
if (element.offsetParent == document.body &&
Element.getStyle(element, 'position') == 'absolute') break;
} while (element = element.offsetParent);
element = forElement;
do {
if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
valueT -= element.scrollTop || 0;
valueL -= element.scrollLeft || 0;
}
} while (element = element.parentNode);
return Element._returnOffset(valueL, valueT);
},
clonePosition: function(element, source) {
var options = Object.extend({
setLeft: true,
setTop: true,
setWidth: true,
setHeight: true,
offsetTop: 0,
offsetLeft: 0
}, arguments[2] || { });
// find page position of source
source = $(source);
var p = source.viewportOffset();
// find coordinate system to use
element = $(element);
var delta = [0, 0];
var parent = null;
// delta [0,0] will do fine with position: fixed elements,
// position:absolute needs offsetParent deltas
if (Element.getStyle(element, 'position') == 'absolute') {
parent = element.getOffsetParent();
delta = parent.viewportOffset();
}
// correct by body offsets (fixes Safari)
if (parent == document.body) {
delta[0] -= document.body.offsetLeft;
delta[1] -= document.body.offsetTop;
}
// set position
if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
if (options.setWidth) element.style.width = source.offsetWidth + 'px';
if (options.setHeight) element.style.height = source.offsetHeight + 'px';
return element;
}
};
Element.Methods.identify.counter = 1;
Object.extend(Element.Methods, {
getElementsBySelector: Element.Methods.select,
childElements: Element.Methods.immediateDescendants
});
Element._attributeTranslations = {
write: {
names: {
className: 'class',
htmlFor: 'for'
},
values: { }
}
};
if (Prototype.Browser.Opera) {
Element.Methods.getStyle = Element.Methods.getStyle.wrap(
function(proceed, element, style) {
switch (style) {
case 'left': case 'top': case 'right': case 'bottom':
if (proceed(element, 'position') === 'static') return null;
case 'height': case 'width':
// returns '0px' for hidden elements; we want it to return null
if (!Element.visible(element)) return null;
// returns the border-box dimensions rather than the content-box
// dimensions, so we subtract padding and borders from the value
var dim = parseInt(proceed(element, style), 10);
if (dim !== element['offset' + style.capitalize()])
return dim + 'px';
var properties;
if (style === 'height') {
properties = ['border-top-width', 'padding-top',
'padding-bottom', 'border-bottom-width'];
}
else {
properties = ['border-left-width', 'padding-left',
'padding-right', 'border-right-width'];
}
return properties.inject(dim, function(memo, property) {
var val = proceed(element, property);
return val === null ? memo : memo - parseInt(val, 10);
}) + 'px';
default: return proceed(element, style);
}
}
);
Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
function(proceed, element, attribute) {
if (attribute === 'title') return element.title;
return proceed(element, attribute);
}
);
}
else if (Prototype.Browser.IE) {
// IE doesn't report offsets correctly for static elements, so we change them
// to "relative" to get the values, then change them back.
Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
function(proceed, element) {
element = $(element);
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
element.setStyle({ position: 'relative' });
var value = proceed(element);
element.setStyle({ position: position });
return value;
}
);
$w('positionedOffset viewportOffset').each(function(method) {
Element.Methods[method] = Element.Methods[method].wrap(
function(proceed, element) {
element = $(element);
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
// Trigger hasLayout on the offset parent so that IE6 reports
// accurate offsetTop and offsetLeft values for position: fixed.
var offsetParent = element.getOffsetParent();
if (offsetParent && offsetParent.getStyle('position') === 'fixed')
offsetParent.setStyle({ zoom: 1 });
element.setStyle({ position: 'relative' });
var value = proceed(element);
element.setStyle({ position: position });
return value;
}
);
});
Element.Methods.getStyle = function(element, style) {
element = $(element);
style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
var value = element.style[style];
if (!value && element.currentStyle) value = element.currentStyle[style];
if (style == 'opacity') {
if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
if (value[1]) return parseFloat(value[1]) / 100;
return 1.0;
}
if (value == 'auto') {
if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
return element['offset' + style.capitalize()] + 'px';
return null;
}
return value;
};
Element.Methods.setOpacity = function(element, value) {
function stripAlpha(filter){
return filter.replace(/alpha\([^\)]*\)/gi,'');
}
element = $(element);
var currentStyle = element.currentStyle;
if ((currentStyle && !currentStyle.hasLayout) ||
(!currentStyle && element.style.zoom == 'normal'))
element.style.zoom = 1;
var filter = element.getStyle('filter'), style = element.style;
if (value == 1 || value === '') {
(filter = stripAlpha(filter)) ?
style.filter = filter : style.removeAttribute('filter');
return element;
} else if (value < 0.00001) value = 0;
style.filter = stripAlpha(filter) +
'alpha(opacity=' + (value * 100) + ')';
return element;
};
Element._attributeTranslations = {
read: {
names: {
'class': 'className',
'for': 'htmlFor'
},
values: {
_getAttr: function(element, attribute) {
return element.getAttribute(attribute, 2);
},
_getAttrNode: function(element, attribute) {
var node = element.getAttributeNode(attribute);
return node ? node.value : "";
},
_getEv: function(element, attribute) {
attribute = element.getAttribute(attribute);
return attribute ? attribute.toString().slice(23, -2) : null;
},
_flag: function(element, attribute) {
return $(element).hasAttribute(attribute) ? attribute : null;
},
style: function(element) {
return element.style.cssText.toLowerCase();
},
title: function(element) {
return element.title;
}
}
}
};
Element._attributeTranslations.write = {
names: Object.extend({
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing'
}, Element._attributeTranslations.read.names),
values: {
checked: function(element, value) {
element.checked = !!value;
},
style: function(element, value) {
element.style.cssText = value ? value : '';
}
}
};
Element._attributeTranslations.has = {};
$w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
'encType maxLength readOnly longDesc').each(function(attr) {
Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
Element._attributeTranslations.has[attr.toLowerCase()] = attr;
});
(function(v) {
Object.extend(v, {
href: v._getAttr,
src: v._getAttr,
type: v._getAttr,
action: v._getAttrNode,
disabled: v._flag,
checked: v._flag,
readonly: v._flag,
multiple: v._flag,
onload: v._getEv,
onunload: v._getEv,
onclick: v._getEv,
ondblclick: v._getEv,
onmousedown: v._getEv,
onmouseup: v._getEv,
onmouseover: v._getEv,
onmousemove: v._getEv,
onmouseout: v._getEv,
onfocus: v._getEv,
onblur: v._getEv,
onkeypress: v._getEv,
onkeydown: v._getEv,
onkeyup: v._getEv,
onsubmit: v._getEv,
onreset: v._getEv,
onselect: v._getEv,
onchange: v._getEv
});
})(Element._attributeTranslations.read.values);
}
else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
Element.Methods.setOpacity = function(element, value) {
element = $(element);
element.style.opacity = (value == 1) ? 0.999999 :
(value === '') ? '' : (value < 0.00001) ? 0 : value;
return element;
};
}
else if (Prototype.Browser.WebKit) {
Element.Methods.setOpacity = function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
if (value == 1)
if(element.tagName == 'IMG' && element.width) {
element.width++; element.width--;
} else try {
var n = document.createTextNode(' ');
element.appendChild(n);
element.removeChild(n);
} catch (e) { }
return element;
};
// Safari returns margins on body which is incorrect if the child is absolutely
// positioned. For performance reasons, redefine Element#cumulativeOffset for
// KHTML/WebKit only.
Element.Methods.cumulativeOffset = function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body)
if (Element.getStyle(element, 'position') == 'absolute') break;
element = element.offsetParent;
} while (element);
return Element._returnOffset(valueL, valueT);
};
}
if (Prototype.Browser.IE || Prototype.Browser.Opera) {
// IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
Element.Methods.update = function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) return element.update().insert(content);
content = Object.toHTML(content);
var tagName = element.tagName.toUpperCase();
if (tagName in Element._insertionTranslations.tags) {
$A(element.childNodes).each(function(node) { element.removeChild(node) });
Element._getContentFromAnonymousElement(tagName, content.stripScripts())
.each(function(node) { element.appendChild(node) });
}
else element.innerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
};
}
if ('outerHTML' in document.createElement('div')) {
Element.Methods.replace = function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
element.parentNode.replaceChild(content, element);
return element;
}
content = Object.toHTML(content);
var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
if (Element._insertionTranslations.tags[tagName]) {
var nextSibling = element.next();
var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
parent.removeChild(element);
if (nextSibling)
fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
else
fragments.each(function(node) { parent.appendChild(node) });
}
else element.outerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
};
}
Element._returnOffset = function(l, t) {
var result = [l, t];
result.left = l;
result.top = t;
return result;
};
Element._getContentFromAnonymousElement = function(tagName, html) {
var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
if (t) {
div.innerHTML = t[0] + html + t[1];
t[2].times(function() { div = div.firstChild });
} else div.innerHTML = html;
return $A(div.childNodes);
};
Element._insertionTranslations = {
before: function(element, node) {
element.parentNode.insertBefore(node, element);
},
top: function(element, node) {
element.insertBefore(node, element.firstChild);
},
bottom: function(element, node) {
element.appendChild(node);
},
after: function(element, node) {
element.parentNode.insertBefore(node, element.nextSibling);
},
tags: {
TABLE: ['<table>', '</table>', 1],
TBODY: ['<table><tbody>', '</tbody></table>', 2],
TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
SELECT: ['<select>', '</select>', 1]
}
};
(function() {
Object.extend(this.tags, {
THEAD: this.tags.TBODY,
TFOOT: this.tags.TBODY,
TH: this.tags.TD
});
}).call(Element._insertionTranslations);
Element.Methods.Simulated = {
hasAttribute: function(element, attribute) {
attribute = Element._attributeTranslations.has[attribute] || attribute;
var node = $(element).getAttributeNode(attribute);
return node && node.specified;
}
};
Element.Methods.ByTag = { };
Object.extend(Element, Element.Methods);
if (!Prototype.BrowserFeatures.ElementExtensions &&
document.createElement('div').__proto__) {
window.HTMLElement = { };
window.HTMLElement.prototype = document.createElement('div').__proto__;
Prototype.BrowserFeatures.ElementExtensions = true;
}
Element.extend = (function() {
if (Prototype.BrowserFeatures.SpecificElementExtensions)
return Prototype.K;
var Methods = { }, ByTag = Element.Methods.ByTag;
var extend = Object.extend(function(element) {
if (!element || element._extendedByPrototype ||
element.nodeType != 1 || element == window) return element;
var methods = Object.clone(Methods),
tagName = element.tagName, property, value;
// extend methods for specific tags
if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
for (property in methods) {
value = methods[property];
if (Object.isFunction(value) && !(property in element))
element[property] = value.methodize();
}
element._extendedByPrototype = Prototype.emptyFunction;
return element;
}, {
refresh: function() {
// extend methods for all tags (Safari doesn't need this)
if (!Prototype.BrowserFeatures.ElementExtensions) {
Object.extend(Methods, Element.Methods);
Object.extend(Methods, Element.Methods.Simulated);
}
}
});
extend.refresh();
return extend;
})();
Element.hasAttribute = function(element, attribute) {
if (element.hasAttribute) return element.hasAttribute(attribute);
return Element.Methods.Simulated.hasAttribute(element, attribute);
};
Element.addMethods = function(methods) {
var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
if (!methods) {
Object.extend(Form, Form.Methods);
Object.extend(Form.Element, Form.Element.Methods);
Object.extend(Element.Methods.ByTag, {
"FORM": Object.clone(Form.Methods),
"INPUT": Object.clone(Form.Element.Methods),
"SELECT": Object.clone(Form.Element.Methods),
"TEXTAREA": Object.clone(Form.Element.Methods)
});
}
if (arguments.length == 2) {
var tagName = methods;
methods = arguments[1];
}
if (!tagName) Object.extend(Element.Methods, methods || { });
else {
if (Object.isArray(tagName)) tagName.each(extend);
else extend(tagName);
}
function extend(tagName) {
tagName = tagName.toUpperCase();
if (!Element.Methods.ByTag[tagName])
Element.Methods.ByTag[tagName] = { };
Object.extend(Element.Methods.ByTag[tagName], methods);
}
function copy(methods, destination, onlyIfAbsent) {
onlyIfAbsent = onlyIfAbsent || false;
for (var property in methods) {
var value = methods[property];
if (!Object.isFunction(value)) continue;
if (!onlyIfAbsent || !(property in destination))
destination[property] = value.methodize();
}
}
function findDOMClass(tagName) {
var klass;
var trans = {
"OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
"FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
"DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
"H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
"INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
"TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
"TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
"TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
"FrameSet", "IFRAME": "IFrame"
};
if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
if (window[klass]) return window[klass];
klass = 'HTML' + tagName + 'Element';
if (window[klass]) return window[klass];
klass = 'HTML' + tagName.capitalize() + 'Element';
if (window[klass]) return window[klass];
window[klass] = { };
window[klass].prototype = document.createElement(tagName).__proto__;
return window[klass];
}
if (F.ElementExtensions) {
copy(Element.Methods, HTMLElement.prototype);
copy(Element.Methods.Simulated, HTMLElement.prototype, true);
}
if (F.SpecificElementExtensions) {
for (var tag in Element.Methods.ByTag) {
var klass = findDOMClass(tag);
if (Object.isUndefined(klass)) continue;
copy(T[tag], klass.prototype);
}
}
Object.extend(Element, Element.Methods);
delete Element.ByTag;
if (Element.extend.refresh) Element.extend.refresh();
Element.cache = { };
};
document.viewport = {
getDimensions: function() {
var dimensions = { };
var B = Prototype.Browser;
$w('width height').each(function(d) {
var D = d.capitalize();
dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
(B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
});
return dimensions;
},
getWidth: function() {
return this.getDimensions().width;
},
getHeight: function() {
return this.getDimensions().height;
},
getScrollOffsets: function() {
return Element._returnOffset(
window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
}
};
/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
* part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
* license. Please see http://www.yui-ext.com/ for more information. */
var Selector = Class.create({
initialize: function(expression) {
this.expression = expression.strip();
this.compileMatcher();
},
shouldUseXPath: function() {
if (!Prototype.BrowserFeatures.XPath) return false;
var e = this.expression;
// Safari 3 chokes on :*-of-type and :empty
if (Prototype.Browser.WebKit &&
(e.include("-of-type") || e.include(":empty")))
return false;
// XPath can't do namespaced attributes, nor can it read
// the "checked" property from DOM nodes
if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
return false;
return true;
},
compileMatcher: function() {
if (this.shouldUseXPath())
return this.compileXPathMatcher();
var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
c = Selector.criteria, le, p, m;
if (Selector._cache[e]) {
this.matcher = Selector._cache[e];
return;
}
this.matcher = ["this.matcher = function(root) {",
"var r = root, h = Selector.handlers, c = false, n;"];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
p = ps[i];
if (m = e.match(p)) {
this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
new Template(c[i]).evaluate(m));
e = e.replace(m[0], '');
break;
}
}
}
this.matcher.push("return h.unique(n);\n}");
eval(this.matcher.join('\n'));
Selector._cache[this.expression] = this.matcher;
},
compileXPathMatcher: function() {
var e = this.expression, ps = Selector.patterns,
x = Selector.xpath, le, m;
if (Selector._cache[e]) {
this.xpath = Selector._cache[e]; return;
}
this.matcher = ['.//*'];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
if (m = e.match(ps[i])) {
this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
new Template(x[i]).evaluate(m));
e = e.replace(m[0], '');
break;
}
}
}
this.xpath = this.matcher.join('');
Selector._cache[this.expression] = this.xpath;
},
findElements: function(root) {
root = root || document;
if (this.xpath) return document._getElementsByXPath(this.xpath, root);
return this.matcher(root);
},
match: function(element) {
this.tokens = [];
var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
var le, p, m;
while (e && le !== e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
p = ps[i];
if (m = e.match(p)) {
// use the Selector.assertions methods unless the selector
// is too complex.
if (as[i]) {
this.tokens.push([i, Object.clone(m)]);
e = e.replace(m[0], '');
} else {
// reluctantly do a document-wide search
// and look for a match in the array
return this.findElements(document).include(element);
}
}
}
}
var match = true, name, matches;
for (var i = 0, token; token = this.tokens[i]; i++) {
name = token[0], matches = token[1];
if (!Selector.assertions[name](element, matches)) {
match = false; break;
}
}
return match;
},
toString: function() {
return this.expression;
},
inspect: function() {
return "#<Selector:" + this.expression.inspect() + ">";
}
});
Object.extend(Selector, {
_cache: { },
xpath: {
descendant: "//*",
child: "/*",
adjacent: "/following-sibling::*[1]",
laterSibling: '/following-sibling::*',
tagName: function(m) {
if (m[1] == '*') return '';
return "[local-name()='" + m[1].toLowerCase() +
"' or local-name()='" + m[1].toUpperCase() + "']";
},
className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
id: "[@id='#{1}']",
attrPresence: function(m) {
m[1] = m[1].toLowerCase();
return new Template("[@#{1}]").evaluate(m);
},
attr: function(m) {
m[1] = m[1].toLowerCase();
m[3] = m[5] || m[6];
return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
},
pseudo: function(m) {
var h = Selector.xpath.pseudos[m[1]];
if (!h) return '';
if (Object.isFunction(h)) return h(m);
return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
},
operators: {
'=': "[@#{1}='#{3}']",
'!=': "[@#{1}!='#{3}']",
'^=': "[starts-with(@#{1}, '#{3}')]",
'$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
'*=': "[contains(@#{1}, '#{3}')]",
'~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
'|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
},
pseudos: {
'first-child': '[not(preceding-sibling::*)]',
'last-child': '[not(following-sibling::*)]',
'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
'checked': "[@checked]",
'disabled': "[@disabled]",
'enabled': "[not(@disabled)]",
'not': function(m) {
var e = m[6], p = Selector.patterns,
x = Selector.xpath, le, v;
var exclusion = [];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in p) {
if (m = e.match(p[i])) {
v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
exclusion.push("(" + v.substring(1, v.length - 1) + ")");
e = e.replace(m[0], '');
break;
}
}
}
return "[not(" + exclusion.join(" and ") + ")]";
},
'nth-child': function(m) {
return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
},
'nth-last-child': function(m) {
return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
},
'nth-of-type': function(m) {
return Selector.xpath.pseudos.nth("position() ", m);
},
'nth-last-of-type': function(m) {
return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
},
'first-of-type': function(m) {
m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
},
'last-of-type': function(m) {
m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
},
'only-of-type': function(m) {
var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
},
nth: function(fragment, m) {
var mm, formula = m[6], predicate;
if (formula == 'even') formula = '2n+0';
if (formula == 'odd') formula = '2n+1';
if (mm = formula.match(/^(\d+)$/)) // digit only
return '[' + fragment + "= " + mm[1] + ']';
if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
if (mm[1] == "-") mm[1] = -1;
var a = mm[1] ? Number(mm[1]) : 1;
var b = mm[2] ? Number(mm[2]) : 0;
predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
"((#{fragment} - #{b}) div #{a} >= 0)]";
return new Template(predicate).evaluate({
fragment: fragment, a: a, b: b });
}
}
}
},
criteria: {
tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
className: 'n = h.className(n, r, "#{1}", c); c = false;',
id: 'n = h.id(n, r, "#{1}", c); c = false;',
attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
attr: function(m) {
m[3] = (m[5] || m[6]);
return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
},
pseudo: function(m) {
if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
},
descendant: 'c = "descendant";',
child: 'c = "child";',
adjacent: 'c = "adjacent";',
laterSibling: 'c = "laterSibling";'
},
patterns: {
// combinators must be listed first
// (and descendant needs to be last combinator)
laterSibling: /^\s*~\s*/,
child: /^\s*>\s*/,
adjacent: /^\s*\+\s*/,
descendant: /^\s/,
// selectors follow
tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
id: /^#([\w\-\*]+)(\b|$)/,
className: /^\.([\w\-\*]+)(\b|$)/,
pseudo:
/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
attrPresence: /^\[([\w]+)\]/,
attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
},
// for Selector.match and Element#match
assertions: {
tagName: function(element, matches) {
return matches[1].toUpperCase() == element.tagName.toUpperCase();
},
className: function(element, matches) {
return Element.hasClassName(element, matches[1]);
},
id: function(element, matches) {
return element.id === matches[1];
},
attrPresence: function(element, matches) {
return Element.hasAttribute(element, matches[1]);
},
attr: function(element, matches) {
var nodeValue = Element.readAttribute(element, matches[1]);
return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
}
},
handlers: {
// UTILITY FUNCTIONS
// joins two collections
concat: function(a, b) {
for (var i = 0, node; node = b[i]; i++)
a.push(node);
return a;
},
// marks an array of nodes for counting
mark: function(nodes) {
var _true = Prototype.emptyFunction;
for (var i = 0, node; node = nodes[i]; i++)
node._countedByPrototype = _true;
return nodes;
},
unmark: function(nodes) {
for (var i = 0, node; node = nodes[i]; i++)
node._countedByPrototype = undefined;
return nodes;
},
// mark each child node with its position (for nth calls)
// "ofType" flag indicates whether we're indexing for nth-of-type
// rather than nth-child
index: function(parentNode, reverse, ofType) {
parentNode._countedByPrototype = Prototype.emptyFunction;
if (reverse) {
for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
var node = nodes[i];
if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
}
} else {
for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
}
},
// filters out duplicates and extends all nodes
unique: function(nodes) {
if (nodes.length == 0) return nodes;
var results = [], n;
for (var i = 0, l = nodes.length; i < l; i++)
if (!(n = nodes[i])._countedByPrototype) {
n._countedByPrototype = Prototype.emptyFunction;
results.push(Element.extend(n));
}
return Selector.handlers.unmark(results);
},
// COMBINATOR FUNCTIONS
descendant: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
h.concat(results, node.getElementsByTagName('*'));
return results;
},
child: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++) {
for (var j = 0, child; child = node.childNodes[j]; j++)
if (child.nodeType == 1 && child.tagName != '!') results.push(child);
}
return results;
},
adjacent: function(nodes) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
var next = this.nextElementSibling(node);
if (next) results.push(next);
}
return results;
},
laterSibling: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
h.concat(results, Element.nextSiblings(node));
return results;
},
nextElementSibling: function(node) {
while (node = node.nextSibling)
if (node.nodeType == 1) return node;
return null;
},
previousElementSibling: function(node) {
while (node = node.previousSibling)
if (node.nodeType == 1) return node;
return null;
},
// TOKEN FUNCTIONS
tagName: function(nodes, root, tagName, combinator) {
var uTagName = tagName.toUpperCase();
var results = [], h = Selector.handlers;
if (nodes) {
if (combinator) {
// fastlane for ordinary descendant combinators
if (combinator == "descendant") {
for (var i = 0, node; node = nodes[i]; i++)
h.concat(results, node.getElementsByTagName(tagName));
return results;
} else nodes = this[combinator](nodes);
if (tagName == "*") return nodes;
}
for (var i = 0, node; node = nodes[i]; i++)
if (node.tagName.toUpperCase() === uTagName) results.push(node);
return results;
} else return root.getElementsByTagName(tagName);
},
id: function(nodes, root, id, combinator) {
var targetNode = $(id), h = Selector.handlers;
if (!targetNode) return [];
if (!nodes && root == document) return [targetNode];
if (nodes) {
if (combinator) {
if (combinator == 'child') {
for (var i = 0, node; node = nodes[i]; i++)
if (targetNode.parentNode == node) return [targetNode];
} else if (combinator == 'descendant') {
for (var i = 0, node; node = nodes[i]; i++)
if (Element.descendantOf(targetNode, node)) return [targetNode];
} else if (combinator == 'adjacent') {
for (var i = 0, node; node = nodes[i]; i++)
if (Selector.handlers.previousElementSibling(targetNode) == node)
return [targetNode];
} else nodes = h[combinator](nodes);
}
for (var i = 0, node; node = nodes[i]; i++)
if (node == targetNode) return [targetNode];
return [];
}
return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
},
className: function(nodes, root, className, combinator) {
if (nodes && combinator) nodes = this[combinator](nodes);
return Selector.handlers.byClassName(nodes, root, className);
},
byClassName: function(nodes, root, className) {
if (!nodes) nodes = Selector.handlers.descendant([root]);
var needle = ' ' + className + ' ';
for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
nodeClassName = node.className;
if (nodeClassName.length == 0) continue;
if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
results.push(node);
}
return results;
},
attrPresence: function(nodes, root, attr, combinator) {
if (!nodes) nodes = root.getElementsByTagName("*");
if (nodes && combinator) nodes = this[combinator](nodes);
var results = [];
for (var i = 0, node; node = nodes[i]; i++)
if (Element.hasAttribute(node, attr)) results.push(node);
return results;
},
attr: function(nodes, root, attr, value, operator, combinator) {
if (!nodes) nodes = root.getElementsByTagName("*");
if (nodes && combinator) nodes = this[combinator](nodes);
var handler = Selector.operators[operator], results = [];
for (var i = 0, node; node = nodes[i]; i++) {
var nodeValue = Element.readAttribute(node, attr);
if (nodeValue === null) continue;
if (handler(nodeValue, value)) results.push(node);
}
return results;
},
pseudo: function(nodes, name, value, root, combinator) {
if (nodes && combinator) nodes = this[combinator](nodes);
if (!nodes) nodes = root.getElementsByTagName("*");
return Selector.pseudos[name](nodes, value, root);
}
},
pseudos: {
'first-child': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
if (Selector.handlers.previousElementSibling(node)) continue;
results.push(node);
}
return results;
},
'last-child': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
if (Selector.handlers.nextElementSibling(node)) continue;
results.push(node);
}
return results;
},
'only-child': function(nodes, value, root) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
results.push(node);
return results;
},
'nth-child': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root);
},
'nth-last-child': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, true);
},
'nth-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, false, true);
},
'nth-last-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, true, true);
},
'first-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, "1", root, false, true);
},
'last-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, "1", root, true, true);
},
'only-of-type': function(nodes, formula, root) {
var p = Selector.pseudos;
return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
},
// handles the an+b logic
getIndices: function(a, b, total) {
if (a == 0) return b > 0 ? [b] : [];
return $R(1, total).inject([], function(memo, i) {
if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
return memo;
});
},
// handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
nth: function(nodes, formula, root, reverse, ofType) {
if (nodes.length == 0) return [];
if (formula == 'even') formula = '2n+0';
if (formula == 'odd') formula = '2n+1';
var h = Selector.handlers, results = [], indexed = [], m;
h.mark(nodes);
for (var i = 0, node; node = nodes[i]; i++) {
if (!node.parentNode._countedByPrototype) {
h.index(node.parentNode, reverse, ofType);
indexed.push(node.parentNode);
}
}
if (formula.match(/^\d+$/)) { // just a number
formula = Number(formula);
for (var i = 0, node; node = nodes[i]; i++)
if (node.nodeIndex == formula) results.push(node);
} else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
if (m[1] == "-") m[1] = -1;
var a = m[1] ? Number(m[1]) : 1;
var b = m[2] ? Number(m[2]) : 0;
var indices = Selector.pseudos.getIndices(a, b, nodes.length);
for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
for (var j = 0; j < l; j++)
if (node.nodeIndex == indices[j]) results.push(node);
}
}
h.unmark(nodes);
h.unmark(indexed);
return results;
},
'empty': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
// IE treats comments as element nodes
if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
results.push(node);
}
return results;
},
'not': function(nodes, selector, root) {
var h = Selector.handlers, selectorType, m;
var exclusions = new Selector(selector).findElements(root);
h.mark(exclusions);
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!node._countedByPrototype) results.push(node);
h.unmark(exclusions);
return results;
},
'enabled': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!node.disabled) results.push(node);
return results;
},
'disabled': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (node.disabled) results.push(node);
return results;
},
'checked': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (node.checked) results.push(node);
return results;
}
},
operators: {
'=': function(nv, v) { return nv == v; },
'!=': function(nv, v) { return nv != v; },
'^=': function(nv, v) { return nv.startsWith(v); },
'$=': function(nv, v) { return nv.endsWith(v); },
'*=': function(nv, v) { return nv.include(v); },
'~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
'|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
},
split: function(expression) {
var expressions = [];
expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
expressions.push(m[1].strip());
});
return expressions;
},
matchElements: function(elements, expression) {
var matches = $$(expression), h = Selector.handlers;
h.mark(matches);
for (var i = 0, results = [], element; element = elements[i]; i++)
if (element._countedByPrototype) results.push(element);
h.unmark(matches);
return results;
},
findElement: function(elements, expression, index) {
if (Object.isNumber(expression)) {
index = expression; expression = false;
}
return Selector.matchElements(elements, expression || '*')[index || 0];
},
findChildElements: function(element, expressions) {
expressions = Selector.split(expressions.join(','));
var results = [], h = Selector.handlers;
for (var i = 0, l = expressions.length, selector; i < l; i++) {
selector = new Selector(expressions[i].strip());
h.concat(results, selector.findElements(element));
}
return (l > 1) ? h.unique(results) : results;
}
});
if (Prototype.Browser.IE) {
Object.extend(Selector.handlers, {
// IE returns comment nodes on getElementsByTagName("*").
// Filter them out.
concat: function(a, b) {
for (var i = 0, node; node = b[i]; i++)
if (node.tagName !== "!") a.push(node);
return a;
},
// IE improperly serializes _countedByPrototype in (inner|outer)HTML.
unmark: function(nodes) {
for (var i = 0, node; node = nodes[i]; i++)
node.removeAttribute('_countedByPrototype');
return nodes;
}
});
}
function $$() {
return Selector.findChildElements(document, $A(arguments));
}
var Form = {
reset: function(form) {
$(form).reset();
return form;
},
serializeElements: function(elements, options) {
if (typeof options != 'object') options = { hash: !!options };
else if (Object.isUndefined(options.hash)) options.hash = true;
var key, value, submitted = false, submit = options.submit;
var data = elements.inject({ }, function(result, element) {
if (!element.disabled && element.name) {
key = element.name; value = $(element).getValue();
if (value != null && (element.type != 'submit' || (!submitted &&
submit !== false && (!submit || key == submit) && (submitted = true)))) {
if (key in result) {
// a key is already present; construct an array of values
if (!Object.isArray(result[key])) result[key] = [result[key]];
result[key].push(value);
}
else result[key] = value;
}
}
return result;
});
return options.hash ? data : Object.toQueryString(data);
}
};
Form.Methods = {
serialize: function(form, options) {
return Form.serializeElements(Form.getElements(form), options);
},
getElements: function(form) {
return $A($(form).getElementsByTagName('*')).inject([],
function(elements, child) {
if (Form.Element.Serializers[child.tagName.toLowerCase()])
elements.push(Element.extend(child));
return elements;
}
);
},
getInputs: function(form, typeName, name) {
form = $(form);
var inputs = form.getElementsByTagName('input');
if (!typeName && !name) return $A(inputs).map(Element.extend);
for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
var input = inputs[i];
if ((typeName && input.type != typeName) || (name && input.name != name))
continue;
matchingInputs.push(Element.extend(input));
}
return matchingInputs;
},
disable: function(form) {
form = $(form);
Form.getElements(form).invoke('disable');
return form;
},
enable: function(form) {
form = $(form);
Form.getElements(form).invoke('enable');
return form;
},
findFirstElement: function(form) {
var elements = $(form).getElements().findAll(function(element) {
return 'hidden' != element.type && !element.disabled;
});
var firstByIndex = elements.findAll(function(element) {
return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
}).sortBy(function(element) { return element.tabIndex }).first();
return firstByIndex ? firstByIndex : elements.find(function(element) {
return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
},
focusFirstElement: function(form) {
form = $(form);
form.findFirstElement().activate();
return form;
},
request: function(form, options) {
form = $(form), options = Object.clone(options || { });
var params = options.parameters, action = form.readAttribute('action') || '';
if (action.blank()) action = window.location.href;
options.parameters = form.serialize(true);
if (params) {
if (Object.isString(params)) params = params.toQueryParams();
Object.extend(options.parameters, params);
}
if (form.hasAttribute('method') && !options.method)
options.method = form.method;
return new Ajax.Request(action, options);
}
};
/*--------------------------------------------------------------------------*/
Form.Element = {
focus: function(element) {
$(element).focus();
return element;
},
select: function(element) {
$(element).select();
return element;
}
};
Form.Element.Methods = {
serialize: function(element) {
element = $(element);
if (!element.disabled && element.name) {
var value = element.getValue();
if (value != undefined) {
var pair = { };
pair[element.name] = value;
return Object.toQueryString(pair);
}
}
return '';
},
getValue: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
return Form.Element.Serializers[method](element);
},
setValue: function(element, value) {
element = $(element);
var method = element.tagName.toLowerCase();
Form.Element.Serializers[method](element, value);
return element;
},
clear: function(element) {
$(element).value = '';
return element;
},
present: function(element) {
return $(element).value != '';
},
activate: function(element) {
element = $(element);
try {
element.focus();
if (element.select && (element.tagName.toLowerCase() != 'input' ||
!['button', 'reset', 'submit'].include(element.type)))
element.select();
} catch (e) { }
return element;
},
disable: function(element) {
element = $(element);
element.blur();
element.disabled = true;
return element;
},
enable: function(element) {
element = $(element);
element.disabled = false;
return element;
}
};
/*--------------------------------------------------------------------------*/
var Field = Form.Element;
var $F = Form.Element.Methods.getValue;
/*--------------------------------------------------------------------------*/
Form.Element.Serializers = {
input: function(element, value) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
return Form.Element.Serializers.inputSelector(element, value);
default:
return Form.Element.Serializers.textarea(element, value);
}
},
inputSelector: function(element, value) {
if (Object.isUndefined(value)) return element.checked ? element.value : null;
else element.checked = !!value;
},
textarea: function(element, value) {
if (Object.isUndefined(value)) return element.value;
else element.value = value;
},
select: function(element, index) {
if (Object.isUndefined(index))
return this[element.type == 'select-one' ?
'selectOne' : 'selectMany'](element);
else {
var opt, value, single = !Object.isArray(index);
for (var i = 0, length = element.length; i < length; i++) {
opt = element.options[i];
value = this.optionValue(opt);
if (single) {
if (value == index) {
opt.selected = true;
return;
}
}
else opt.selected = index.include(value);
}
}
},
selectOne: function(element) {
var index = element.selectedIndex;
return index >= 0 ? this.optionValue(element.options[index]) : null;
},
selectMany: function(element) {
var values, length = element.length;
if (!length) return null;
for (var i = 0, values = []; i < length; i++) {
var opt = element.options[i];
if (opt.selected) values.push(this.optionValue(opt));
}
return values;
},
optionValue: function(opt) {
// extend element because hasAttribute may not be native
return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
}
};
/*--------------------------------------------------------------------------*/
Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
initialize: function($super, element, frequency, callback) {
$super(callback, frequency);
this.element = $(element);
this.lastValue = this.getValue();
},
execute: function() {
var value = this.getValue();
if (Object.isString(this.lastValue) && Object.isString(value) ?
this.lastValue != value : String(this.lastValue) != String(value)) {
this.callback(this.element, value);
this.lastValue = value;
}
}
});
Form.Element.Observer = Class.create(Abstract.TimedObserver, {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.Observer = Class.create(Abstract.TimedObserver, {
getValue: function() {
return Form.serialize(this.element);
}
});
/*--------------------------------------------------------------------------*/
Abstract.EventObserver = Class.create({
initialize: function(element, callback) {
this.element = $(element);
this.callback = callback;
this.lastValue = this.getValue();
if (this.element.tagName.toLowerCase() == 'form')
this.registerFormCallbacks();
else
this.registerCallback(this.element);
},
onElementEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
},
registerFormCallbacks: function() {
Form.getElements(this.element).each(this.registerCallback, this);
},
registerCallback: function(element) {
if (element.type) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
Event.observe(element, 'click', this.onElementEvent.bind(this));
break;
default:
Event.observe(element, 'change', this.onElementEvent.bind(this));
break;
}
}
}
});
Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.EventObserver = Class.create(Abstract.EventObserver, {
getValue: function() {
return Form.serialize(this.element);
}
});
if (!window.Event) var Event = { };
Object.extend(Event, {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_RETURN: 13,
KEY_ESC: 27,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
KEY_HOME: 36,
KEY_END: 35,
KEY_PAGEUP: 33,
KEY_PAGEDOWN: 34,
KEY_INSERT: 45,
cache: { },
relatedTarget: function(event) {
var element;
switch(event.type) {
case 'mouseover': element = event.fromElement; break;
case 'mouseout': element = event.toElement; break;
default: return null;
}
return Element.extend(element);
}
});
Event.Methods = (function() {
var isButton;
if (Prototype.Browser.IE) {
var buttonMap = { 0: 1, 1: 4, 2: 2 };
isButton = function(event, code) {
return event.button == buttonMap[code];
};
} else if (Prototype.Browser.WebKit) {
isButton = function(event, code) {
switch (code) {
case 0: return event.which == 1 && !event.metaKey;
case 1: return event.which == 1 && event.metaKey;
default: return false;
}
};
} else {
isButton = function(event, code) {
return event.which ? (event.which === code + 1) : (event.button === code);
};
}
return {
isLeftClick: function(event) { return isButton(event, 0) },
isMiddleClick: function(event) { return isButton(event, 1) },
isRightClick: function(event) { return isButton(event, 2) },
element: function(event) {
var node = Event.extend(event).target;
return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
},
findElement: function(event, expression) {
var element = Event.element(event);
if (!expression) return element;
var elements = [element].concat(element.ancestors());
return Selector.findElement(elements, expression, 0);
},
pointer: function(event) {
return {
x: event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft)),
y: event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop))
};
},
pointerX: function(event) { return Event.pointer(event).x },
pointerY: function(event) { return Event.pointer(event).y },
stop: function(event) {
Event.extend(event);
event.preventDefault();
event.stopPropagation();
event.stopped = true;
}
};
})();
Event.extend = (function() {
var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
m[name] = Event.Methods[name].methodize();
return m;
});
if (Prototype.Browser.IE) {
Object.extend(methods, {
stopPropagation: function() { this.cancelBubble = true },
preventDefault: function() { this.returnValue = false },
inspect: function() { return "[object Event]" }
});
return function(event) {
if (!event) return false;
if (event._extendedByPrototype) return event;
event._extendedByPrototype = Prototype.emptyFunction;
var pointer = Event.pointer(event);
Object.extend(event, {
target: event.srcElement,
relatedTarget: Event.relatedTarget(event),
pageX: pointer.x,
pageY: pointer.y
});
return Object.extend(event, methods);
};
} else {
Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
Object.extend(Event.prototype, methods);
return Prototype.K;
}
})();
Object.extend(Event, (function() {
var cache = Event.cache;
function getEventID(element) {
if (element._prototypeEventID) return element._prototypeEventID[0];
arguments.callee.id = arguments.callee.id || 1;
return element._prototypeEventID = [++arguments.callee.id];
}
function getDOMEventName(eventName) {
if (eventName && eventName.include(':')) return "dataavailable";
return eventName;
}
function getCacheForID(id) {
return cache[id] = cache[id] || { };
}
function getWrappersForEventName(id, eventName) {
var c = getCacheForID(id);
return c[eventName] = c[eventName] || [];
}
function createWrapper(element, eventName, handler) {
var id = getEventID(element);
var c = getWrappersForEventName(id, eventName);
if (c.pluck("handler").include(handler)) return false;
var wrapper = function(event) {
if (!Event || !Event.extend ||
(event.eventName && event.eventName != eventName))
return false;
Event.extend(event);
handler.call(element, event);
};
wrapper.handler = handler;
c.push(wrapper);
return wrapper;
}
function findWrapper(id, eventName, handler) {
var c = getWrappersForEventName(id, eventName);
return c.find(function(wrapper) { return wrapper.handler == handler });
}
function destroyWrapper(id, eventName, handler) {
var c = getCacheForID(id);
if (!c[eventName]) return false;
c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
}
function destroyCache() {
for (var id in cache)
for (var eventName in cache[id])
cache[id][eventName] = null;
}
if (window.attachEvent) {
window.attachEvent("onunload", destroyCache);
}
return {
observe: function(element, eventName, handler) {
element = $(element);
var name = getDOMEventName(eventName);
var wrapper = createWrapper(element, eventName, handler);
if (!wrapper) return element;
if (element.addEventListener) {
element.addEventListener(name, wrapper, false);
} else {
element.attachEvent("on" + name, wrapper);
}
return element;
},
stopObserving: function(element, eventName, handler) {
element = $(element);
var id = getEventID(element), name = getDOMEventName(eventName);
if (!handler && eventName) {
getWrappersForEventName(id, eventName).each(function(wrapper) {
element.stopObserving(eventName, wrapper.handler);
});
return element;
} else if (!eventName) {
Object.keys(getCacheForID(id)).each(function(eventName) {
element.stopObserving(eventName);
});
return element;
}
var wrapper = findWrapper(id, eventName, handler);
if (!wrapper) return element;
if (element.removeEventListener) {
element.removeEventListener(name, wrapper, false);
} else {
element.detachEvent("on" + name, wrapper);
}
destroyWrapper(id, eventName, handler);
return element;
},
fire: function(element, eventName, memo) {
element = $(element);
if (element == document && document.createEvent && !element.dispatchEvent)
element = document.documentElement;
var event;
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent("dataavailable", true, true);
} else {
event = document.createEventObject();
event.eventType = "ondataavailable";
}
event.eventName = eventName;
event.memo = memo || { };
if (document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent(event.eventType, event);
}
return Event.extend(event);
}
};
})());
Object.extend(Event, Event.Methods);
Element.addMethods({
fire: Event.fire,
observe: Event.observe,
stopObserving: Event.stopObserving
});
Object.extend(document, {
fire: Element.Methods.fire.methodize(),
observe: Element.Methods.observe.methodize(),
stopObserving: Element.Methods.stopObserving.methodize(),
loaded: false
});
(function() {
/* Support for the DOMContentLoaded event is based on work by Dan Webb,
Matthias Miller, Dean Edwards and John Resig. */
var timer;
function fireContentLoadedEvent() {
if (document.loaded) return;
if (timer) window.clearInterval(timer);
document.fire("dom:loaded");
document.loaded = true;
}
if (document.addEventListener) {
if (Prototype.Browser.WebKit) {
timer = window.setInterval(function() {
if (/loaded|complete/.test(document.readyState))
fireContentLoadedEvent();
}, 0);
Event.observe(window, "load", fireContentLoadedEvent);
} else {
document.addEventListener("DOMContentLoaded",
fireContentLoadedEvent, false);
}
} else {
document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
$("__onDOMContentLoaded").onreadystatechange = function() {
if (this.readyState == "complete") {
this.onreadystatechange = null;
fireContentLoadedEvent();
}
};
}
})();
/*------------------------------- DEPRECATED -------------------------------*/
Hash.toQueryString = Object.toQueryString;
var Toggle = { display: Element.toggle };
Element.Methods.childOf = Element.Methods.descendantOf;
var Insertion = {
Before: function(element, content) {
return Element.insert(element, {before:content});
},
Top: function(element, content) {
return Element.insert(element, {top:content});
},
Bottom: function(element, content) {
return Element.insert(element, {bottom:content});
},
After: function(element, content) {
return Element.insert(element, {after:content});
}
};
var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
// This should be moved to script.aculo.us; notice the deprecated methods
// further below, that map to the newer Element methods.
var Position = {
// set to true if needed, warning: firefox performance problems
// NOT neeeded for page scrolling, only if draggable contained in
// scrollable elements
includeScrollOffsets: false,
// must be called before calling withinIncludingScrolloffset, every time the
// page is scrolled
prepare: function() {
this.deltaX = window.pageXOffset
|| document.documentElement.scrollLeft
|| document.body.scrollLeft
|| 0;
this.deltaY = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
},
// caches x/y coordinate pair to use with overlap
within: function(element, x, y) {
if (this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element, x, y);
this.xcomp = x;
this.ycomp = y;
this.offset = Element.cumulativeOffset(element);
return (y >= this.offset[1] &&
y < this.offset[1] + element.offsetHeight &&
x >= this.offset[0] &&
x < this.offset[0] + element.offsetWidth);
},
withinIncludingScrolloffsets: function(element, x, y) {
var offsetcache = Element.cumulativeScrollOffset(element);
this.xcomp = x + offsetcache[0] - this.deltaX;
this.ycomp = y + offsetcache[1] - this.deltaY;
this.offset = Element.cumulativeOffset(element);
return (this.ycomp >= this.offset[1] &&
this.ycomp < this.offset[1] + element.offsetHeight &&
this.xcomp >= this.offset[0] &&
this.xcomp < this.offset[0] + element.offsetWidth);
},
// within must be called directly before
overlap: function(mode, element) {
if (!mode) return 0;
if (mode == 'vertical')
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
element.offsetHeight;
if (mode == 'horizontal')
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
element.offsetWidth;
},
// Deprecation layer -- use newer Element methods now (1.5.2).
cumulativeOffset: Element.Methods.cumulativeOffset,
positionedOffset: Element.Methods.positionedOffset,
absolutize: function(element) {
Position.prepare();
return Element.absolutize(element);
},
relativize: function(element) {
Position.prepare();
return Element.relativize(element);
},
realOffset: Element.Methods.cumulativeScrollOffset,
offsetParent: Element.Methods.getOffsetParent,
page: Element.Methods.viewportOffset,
clone: function(source, target, options) {
options = options || { };
return Element.clonePosition(target, source, options);
}
};
/*--------------------------------------------------------------------------*/
if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
function iter(name) {
return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
}
instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
function(element, className) {
className = className.toString().strip();
var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
} : function(element, className) {
className = className.toString().strip();
var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
if (!classNames && !className) return elements;
var nodes = $(element).getElementsByTagName('*');
className = ' ' + className + ' ';
for (var i = 0, child, cn; child = nodes[i]; i++) {
if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
(classNames && classNames.all(function(name) {
return !name.toString().blank() && cn.include(' ' + name + ' ');
}))))
elements.push(Element.extend(child));
}
return elements;
};
return function(className, parentElement) {
return $(parentElement || document.body).getElementsByClassName(className);
};
}(Element.Methods);
/*--------------------------------------------------------------------------*/
Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
initialize: function(element) {
this.element = $(element);
},
_each: function(iterator) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
})._each(iterator);
},
set: function(className) {
this.element.className = className;
},
add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
this.set($A(this).concat(classNameToAdd).join(' '));
},
remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
this.set($A(this).without(classNameToRemove).join(' '));
},
toString: function() {
return $A(this).join(' ');
}
};
Object.extend(Element.ClassNames.prototype, Enumerable);
/*--------------------------------------------------------------------------*/
Element.addMethods();
| JavaScript |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
function test(){
alert("hello");
}
| JavaScript |
/**********************************************************************************
Project Name: SimpleAdmin CMS Theme
Project Description: A clean admin theme
File Name: script.js
Author: Adi Purdila
Author URI: http://www.adipurdila.com
Version: 1.0.0
**********************************************************************************/
$(document).ready(function() {
//Content boxes expand/collapse
$(".initial-expand").hide();
$("div.content-module-heading").click(function(){
$(this).next("div.content-module-main").slideToggle();
$(this).children(".expand-collapse-text").toggle();
});
});
| JavaScript |
// 1 - START DROPDOWN SLIDER SCRIPTS ------------------------------------------------------------------------
$(document).ready(function () {
$(".showhide-account").click(function () {
$(".account-content").slideToggle("fast");
$(this).toggleClass("active");
return false;
});
});
$(document).ready(function () {
$(".action-slider").click(function () {
$("#actions-box-slider").slideToggle("fast");
$(this).toggleClass("activated");
return false;
});
});
// END ----------------------------- 1
// 2 - START LOGIN PAGE SHOW HIDE BETWEEN LOGIN AND FORGOT PASSWORD BOXES--------------------------------------
$(document).ready(function () {
$(".forgot-pwd").click(function () {
$("#loginbox").hide();
$("#forgotbox").show();
return false;
});
});
$(document).ready(function () {
$(".back-login").click(function () {
$("#loginbox").show();
$("#forgotbox").hide();
return false;
});
});
// END ----------------------------- 2
// 3 - MESSAGE BOX FADING SCRIPTS ---------------------------------------------------------------------
$(document).ready(function() {
$(".close-yellow").click(function () {
$("#message-yellow").fadeOut("slow");
});
$(".close-red").click(function () {
$("#message-red").fadeOut("slow");
});
$(".close-blue").click(function () {
$("#message-blue").fadeOut("slow");
});
$(".close-green").click(function () {
$("#message-green").fadeOut("slow");
});
});
// END ----------------------------- 3
// 4 - CLOSE OPEN SLIDERS BY CLICKING ELSEWHERE ON PAGE -------------------------------------------------------------------------
$(document).bind("click", function (e) {
if (e.target.id != $(".showhide-account").attr("class")) $(".account-content").slideUp();
});
$(document).bind("click", function (e) {
if (e.target.id != $(".action-slider").attr("class")) $("#actions-box-slider").slideUp();
});
// END ----------------------------- 4
// 5 - TABLE ROW BACKGROUND COLOR CHANGES ON ROLLOVER -----------------------------------------------------------------------
/*
$(document).ready(function () {
$('#product-table tr').hover(function () {
$(this).addClass('activity-blue');
},
function () {
$(this).removeClass('activity-blue');
});
});
*/
// END ----------------------------- 5
// 6 - DYNAMIC YEAR STAMP FOR FOOTER -----------------------------------------------------------------------
$('#spanYear').html(new Date().getFullYear());
// END ----------------------------- 6
| JavaScript |
jQuery(document).ready(function(){
//global vars
var enquiryfrm = jQuery("#agt_mail_agent");
var yourname = jQuery("#agt_mail_name");
var yournameInfo = jQuery("#span_agt_mail_name");
var youremail = jQuery("#agt_mail_email");
var youremailInfo = jQuery("#span_agt_mail_email");
var frnd_comments = jQuery("#agt_mail_msg");
var frnd_commentsInfo = jQuery("#span_agt_mail_msg");
//On blur
yourname.blur(validate_yourname);
youremail.blur(validate_youremail);
frnd_comments.blur(validate_frnd_comments_author);
//On key press
yourname.keyup(validate_yourname);
youremail.keyup(validate_youremail);
frnd_comments.keyup(validate_frnd_comments_author);
//On Submitting
enquiryfrm.submit(function(){
if(validate_yourname() & validate_youremail() & validate_frnd_comments_author())
{
//hideform();
setTimeout("document.getElementById('pinquiry_send_success').style.display='block';document.getElementById('pinquiry_send_success').innerHTML = 'Message Send Successfully!'",500);
/*document.getElementById('agt_mail_name').value = '';
document.getElementById('agt_mail_email').value = '';
document.getElementById('agt_mail_phone').value = '';
document.getElementById('agt_mail_msg').value = ''; */
return true
}
else
{
return false;
}
});
//validation functions
function validate_yourname()
{
if(jQuery("#agt_mail_name").val() == '')
{
yourname.addClass("error");
yournameInfo.text("Please Enter Your Name");
yournameInfo.addClass("message_error2");
return false;
}
else{
yourname.removeClass("error");
yournameInfo.text("");
yournameInfo.removeClass("message_error2");
return true;
}
}
function validate_youremail()
{
var isvalidemailflag = 0;
if(jQuery("#agt_mail_email").val() == '')
{
isvalidemailflag = 1;
}else
if(jQuery("#agt_mail_email").val() != '')
{
var a = jQuery("#agt_mail_email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
isvalidemailflag = 0;
}else{
isvalidemailflag = 1;
}
}
if(isvalidemailflag)
{
youremail.addClass("error");
youremailInfo.text("Please Enter valid Email Address");
youremailInfo.addClass("message_error2");
return false;
}else
{
youremail.removeClass("error");
youremailInfo.text("");
youremailInfo.removeClass("message_error");
return true;
}
}
function validate_frnd_comments_author()
{
if(jQuery("#agt_mail_msg").val() == '')
{
frnd_comments.addClass("error");
frnd_commentsInfo.text("Please Enter Comments");
frnd_commentsInfo.addClass("message_error2");
return false;
}else{
frnd_comments.removeClass("error");
frnd_commentsInfo.text("");
frnd_commentsInfo.removeClass("message_error2");
return true;
}
}
}); | JavaScript |
/*
Copyright (C) 2011 Google Inc.
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
http://www.apache.org/licenses/LICENSE-2.0
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.
*/
var a=null;
PR.registerLangHandler(PR.createSimpleLexer([["opn",/^[([{]+/,a,"([{"],["clo",/^[)\]}]+/,a,")]}"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \xa0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:def|if|do|let|quote|var|fn|loop|recur|throw|try|monitor-enter|monitor-exit|defmacro|defn|defn-|macroexpand|macroexpand-1|for|doseq|dosync|dotimes|and|or|when|not|assert|doto|proxy|defstruct|first|rest|cons|defprotocol|deftype|defrecord|reify|defmulti|defmethod|meta|with-meta|ns|in-ns|create-ns|import|intern|refer|alias|namespace|resolve|ref|deref|refset|new|set!|memfn|to-array|into-array|aset|gen-class|reduce|map|filter|find|nil?|empty?|hash-map|hash-set|vec|vector|seq|flatten|reverse|assoc|dissoc|list|list?|disj|get|union|difference|intersection|extend|extend-type|extend-protocol|prn)\b/,a],
["typ",/^:[\dA-Za-z-]+/]]),["clj"]);
| JavaScript |
(function(window) {
var ORIGIN_ = location.protocol + '//' + location.host;
function SlideController() {
this.popup = null;
this.isPopup = window.opener;
if (this.setupDone()) {
window.addEventListener('message', this.onMessage_.bind(this), false);
// Close popups if we reload the main window.
window.addEventListener('beforeunload', function(e) {
if (this.popup) {
this.popup.close();
}
}.bind(this), false);
}
}
SlideController.PRESENTER_MODE_PARAM = 'presentme';
SlideController.prototype.setupDone = function() {
var params = location.search.substring(1).split('&').map(function(el) {
return el.split('=');
});
var presentMe = null;
for (var i = 0, param; param = params[i]; ++i) {
if (param[0].toLowerCase() == SlideController.PRESENTER_MODE_PARAM) {
presentMe = param[1] == 'true';
break;
}
}
if (presentMe !== null) {
localStorage.ENABLE_PRESENTOR_MODE = presentMe;
// TODO: use window.history.pushState to update URL instead of the redirect.
if (window.history.replaceState) {
window.history.replaceState({}, '', location.pathname);
} else {
location.replace(location.pathname);
return false;
}
}
var enablePresenterMode = localStorage.getItem('ENABLE_PRESENTOR_MODE');
if (enablePresenterMode && JSON.parse(enablePresenterMode)) {
// Only open popup from main deck. Don't want recursive popup opening!
if (!this.isPopup) {
var opts = 'menubar=no,location=yes,resizable=yes,scrollbars=no,status=no';
this.popup = window.open(location.href, 'mywindow', opts);
// Loading in the popup? Trigger the hotkey for turning presenter mode on.
this.popup.addEventListener('load', function(e) {
var evt = this.popup.document.createEvent('Event');
evt.initEvent('keydown', true, true);
evt.keyCode = 'P'.charCodeAt(0);
this.popup.document.dispatchEvent(evt);
// this.popup.document.body.classList.add('with-notes');
// document.body.classList.add('popup');
}.bind(this), false);
}
}
return true;
}
SlideController.prototype.onMessage_ = function(e) {
var data = e.data;
// Restrict messages to being from this origin. Allow local developmet
// from file:// though.
// TODO: It would be dope if FF implemented location.origin!
if (e.origin != ORIGIN_ && ORIGIN_.indexOf('file://') != 0) {
alert('Someone tried to postMessage from an unknown origin');
return;
}
// if (e.source.location.hostname != 'localhost') {
// alert('Someone tried to postMessage from an unknown origin');
// return;
// }
if ('keyCode' in data) {
var evt = document.createEvent('Event');
evt.initEvent('keydown', true, true);
evt.keyCode = data.keyCode;
document.dispatchEvent(evt);
}
};
SlideController.prototype.sendMsg = function(msg) {
// // Send message to popup window.
// if (this.popup) {
// this.popup.postMessage(msg, ORIGIN_);
// }
// Send message to main window.
if (this.isPopup) {
// TODO: It would be dope if FF implemented location.origin.
window.opener.postMessage(msg, '*');
}
};
window.SlideController = SlideController;
})(window);
| JavaScript |
/*
* Hammer.JS
* version 0.4
* author: Eight Media
* https://github.com/EightMedia/hammer.js
*/
function Hammer(element, options, undefined)
{
var self = this;
var defaults = {
// prevent the default event or not... might be buggy when false
prevent_default : false,
css_hacks : true,
drag : true,
drag_vertical : true,
drag_horizontal : true,
// minimum distance before the drag event starts
drag_min_distance : 20, // pixels
// pinch zoom and rotation
transform : true,
scale_treshold : 0.1,
rotation_treshold : 15, // degrees
tap : true,
tap_double : true,
tap_max_interval : 300,
tap_double_distance: 20,
hold : true,
hold_timeout : 500
};
options = mergeObject(defaults, options);
// some css hacks
(function() {
if(!options.css_hacks) {
return false;
}
var vendors = ['webkit','moz','ms','o',''];
var css_props = {
"userSelect": "none",
"touchCallout": "none",
"userDrag": "none",
"tapHighlightColor": "rgba(0,0,0,0)"
};
var prop = '';
for(var i = 0; i < vendors.length; i++) {
for(var p in css_props) {
prop = p;
if(vendors[i]) {
prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
}
element.style[ prop ] = css_props[p];
}
}
})();
// holds the distance that has been moved
var _distance = 0;
// holds the exact angle that has been moved
var _angle = 0;
// holds the diraction that has been moved
var _direction = 0;
// holds position movement for sliding
var _pos = { };
// how many fingers are on the screen
var _fingers = 0;
var _first = false;
var _gesture = null;
var _prev_gesture = null;
var _touch_start_time = null;
var _prev_tap_pos = {x: 0, y: 0};
var _prev_tap_end_time = null;
var _hold_timer = null;
var _offset = {};
// keep track of the mouse status
var _mousedown = false;
var _event_start;
var _event_move;
var _event_end;
/**
* angle to direction define
* @param float angle
* @return string direction
*/
this.getDirectionFromAngle = function( angle )
{
var directions = {
down: angle >= 45 && angle < 135, //90
left: angle >= 135 || angle <= -135, //180
up: angle < -45 && angle > -135, //270
right: angle >= -45 && angle <= 45 //0
};
var direction, key;
for(key in directions){
if(directions[key]){
direction = key;
break;
}
}
return direction;
};
/**
* count the number of fingers in the event
* when no fingers are detected, one finger is returned (mouse pointer)
* @param event
* @return int fingers
*/
function countFingers( event )
{
// there is a bug on android (until v4?) that touches is always 1,
// so no multitouch is supported, e.g. no, zoom and rotation...
return event.touches ? event.touches.length : 1;
}
/**
* get the x and y positions from the event object
* @param event
* @return array [{ x: int, y: int }]
*/
function getXYfromEvent( event )
{
event = event || window.event;
// no touches, use the event pageX and pageY
if(!event.touches) {
var doc = document,
body = doc.body;
return [{
x: event.pageX || event.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && doc.clientLeft || 0 ),
y: event.pageY || event.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && doc.clientTop || 0 )
}];
}
// multitouch, return array with positions
else {
var pos = [], src;
for(var t=0, len=event.touches.length; t<len; t++) {
src = event.touches[t];
pos.push({ x: src.pageX, y: src.pageY });
}
return pos;
}
}
/**
* calculate the angle between two points
* @param object pos1 { x: int, y: int }
* @param object pos2 { x: int, y: int }
*/
function getAngle( pos1, pos2 )
{
return Math.atan2(pos2.y - pos1.y, pos2.x - pos1.x) * 180 / Math.PI;
}
/**
* trigger an event/callback by name with params
* @param string name
* @param array params
*/
function triggerEvent( eventName, params )
{
// return touches object
params.touches = getXYfromEvent(params.originalEvent);
params.type = eventName;
// trigger callback
if(isFunction(self["on"+ eventName])) {
self["on"+ eventName].call(self, params);
}
}
/**
* cancel event
* @param object event
* @return void
*/
function cancelEvent(event){
event = event || window.event;
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
event.cancelBubble = true;
}
}
/**
* reset the internal vars to the start values
*/
function reset()
{
_pos = {};
_first = false;
_fingers = 0;
_distance = 0;
_angle = 0;
_gesture = null;
}
var gestures = {
// hold gesture
// fired on touchstart
hold : function(event)
{
// only when one finger is on the screen
if(options.hold) {
_gesture = 'hold';
clearTimeout(_hold_timer);
_hold_timer = setTimeout(function() {
if(_gesture == 'hold') {
triggerEvent("hold", {
originalEvent : event,
position : _pos.start
});
}
}, options.hold_timeout);
}
},
// drag gesture
// fired on mousemove
drag : function(event)
{
// get the distance we moved
var _distance_x = _pos.move[0].x - _pos.start[0].x;
var _distance_y = _pos.move[0].y - _pos.start[0].y;
_distance = Math.sqrt(_distance_x * _distance_x + _distance_y * _distance_y);
// drag
// minimal movement required
if(options.drag && (_distance > options.drag_min_distance) || _gesture == 'drag') {
// calculate the angle
_angle = getAngle(_pos.start[0], _pos.move[0]);
_direction = self.getDirectionFromAngle(_angle);
// check the movement and stop if we go in the wrong direction
var is_vertical = (_direction == 'up' || _direction == 'down');
if(((is_vertical && !options.drag_vertical) || (!is_vertical && !options.drag_horizontal))
&& (_distance > options.drag_min_distance)) {
return;
}
_gesture = 'drag';
var position = { x: _pos.move[0].x - _offset.left,
y: _pos.move[0].y - _offset.top };
var event_obj = {
originalEvent : event,
position : position,
direction : _direction,
distance : _distance,
distanceX : _distance_x,
distanceY : _distance_y,
angle : _angle
};
// on the first time trigger the start event
if(_first) {
triggerEvent("dragstart", event_obj);
_first = false;
}
// normal slide event
triggerEvent("drag", event_obj);
cancelEvent(event);
}
},
// transform gesture
// fired on touchmove
transform : function(event)
{
if(options.transform) {
var scale = event.scale || 1;
var rotation = event.rotation || 0;
if(countFingers(event) != 2) {
return false;
}
if(_gesture != 'drag' &&
(_gesture == 'transform' || Math.abs(1-scale) > options.scale_treshold
|| Math.abs(rotation) > options.rotation_treshold)) {
_gesture = 'transform';
_pos.center = { x: ((_pos.move[0].x + _pos.move[1].x) / 2) - _offset.left,
y: ((_pos.move[0].y + _pos.move[1].y) / 2) - _offset.top };
var event_obj = {
originalEvent : event,
position : _pos.center,
scale : scale,
rotation : rotation
};
// on the first time trigger the start event
if(_first) {
triggerEvent("transformstart", event_obj);
_first = false;
}
triggerEvent("transform", event_obj);
cancelEvent(event);
return true;
}
}
return false;
},
// tap and double tap gesture
// fired on touchend
tap : function(event)
{
// compare the kind of gesture by time
var now = new Date().getTime();
var touch_time = now - _touch_start_time;
// dont fire when hold is fired
if(options.hold && !(options.hold && options.hold_timeout > touch_time)) {
return;
}
// when previous event was tap and the tap was max_interval ms ago
var is_double_tap = (function(){
if (_prev_tap_pos && options.tap_double && _prev_gesture == 'tap' && (_touch_start_time - _prev_tap_end_time) < options.tap_max_interval) {
var x_distance = Math.abs(_prev_tap_pos[0].x - _pos.start[0].x);
var y_distance = Math.abs(_prev_tap_pos[0].y - _pos.start[0].y);
return (_prev_tap_pos && _pos.start && Math.max(x_distance, y_distance) < options.tap_double_distance);
}
return false;
})();
if(is_double_tap) {
_gesture = 'double_tap';
_prev_tap_end_time = null;
triggerEvent("doubletap", {
originalEvent : event,
position : _pos.start
});
cancelEvent(event);
}
// single tap is single touch
else {
_gesture = 'tap';
_prev_tap_end_time = now;
_prev_tap_pos = _pos.start;
if(options.tap) {
triggerEvent("tap", {
originalEvent : event,
position : _pos.start
});
cancelEvent(event);
}
}
}
};
function handleEvents(event)
{
switch(event.type)
{
case 'mousedown':
case 'touchstart':
_pos.start = getXYfromEvent(event);
_touch_start_time = new Date().getTime();
_fingers = countFingers(event);
_first = true;
_event_start = event;
// borrowed from jquery offset https://github.com/jquery/jquery/blob/master/src/offset.js
var box = element.getBoundingClientRect();
var clientTop = element.clientTop || document.body.clientTop || 0;
var clientLeft = element.clientLeft || document.body.clientLeft || 0;
var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop;
var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft;
_offset = {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
_mousedown = true;
// hold gesture
gestures.hold(event);
if(options.prevent_default) {
cancelEvent(event);
}
break;
case 'mousemove':
case 'touchmove':
if(!_mousedown) {
return false;
}
_event_move = event;
_pos.move = getXYfromEvent(event);
if(!gestures.transform(event)) {
gestures.drag(event);
}
break;
case 'mouseup':
case 'mouseout':
case 'touchcancel':
case 'touchend':
if(!_mousedown || (_gesture != 'transform' && event.touches && event.touches.length > 0)) {
return false;
}
_mousedown = false;
_event_end = event;
// drag gesture
// dragstart is triggered, so dragend is possible
if(_gesture == 'drag') {
triggerEvent("dragend", {
originalEvent : event,
direction : _direction,
distance : _distance,
angle : _angle
});
}
// transform
// transformstart is triggered, so transformed is possible
else if(_gesture == 'transform') {
triggerEvent("transformend", {
originalEvent : event,
position : _pos.center,
scale : event.scale,
rotation : event.rotation
});
}
else {
gestures.tap(_event_start);
}
_prev_gesture = _gesture;
// reset vars
reset();
break;
}
}
// bind events for touch devices
// except for windows phone 7.5, it doesnt support touch events..!
if('ontouchstart' in window) {
element.addEventListener("touchstart", handleEvents, false);
element.addEventListener("touchmove", handleEvents, false);
element.addEventListener("touchend", handleEvents, false);
element.addEventListener("touchcancel", handleEvents, false);
}
// for non-touch
else {
if(element.addEventListener){ // prevent old IE errors
element.addEventListener("mouseout", function(event) {
if(!isInsideHammer(element, event.relatedTarget)) {
handleEvents(event);
}
}, false);
element.addEventListener("mouseup", handleEvents, false);
element.addEventListener("mousedown", handleEvents, false);
element.addEventListener("mousemove", handleEvents, false);
// events for older IE
}else if(document.attachEvent){
element.attachEvent("onmouseout", function(event) {
if(!isInsideHammer(element, event.relatedTarget)) {
handleEvents(event);
}
}, false);
element.attachEvent("onmouseup", handleEvents);
element.attachEvent("onmousedown", handleEvents);
element.attachEvent("onmousemove", handleEvents);
}
}
/**
* find if element is (inside) given parent element
* @param object element
* @param object parent
* @return bool inside
*/
function isInsideHammer(parent, child) {
// get related target for IE
if(!child && window.event && window.event.toElement){
child = window.event.toElement;
}
if(parent === child){
return true;
}
// loop over parentNodes of child until we find hammer element
if(child){
var node = child.parentNode;
while(node !== null){
if(node === parent){
return true;
};
node = node.parentNode;
}
}
return false;
}
/**
* merge 2 objects into a new object
* @param object obj1
* @param object obj2
* @return object merged object
*/
function mergeObject(obj1, obj2) {
var output = {};
if(!obj2) {
return obj1;
}
for (var prop in obj1) {
if (prop in obj2) {
output[prop] = obj2[prop];
} else {
output[prop] = obj1[prop];
}
}
return output;
}
function isFunction( obj ){
return Object.prototype.toString.call( obj ) == "[object Function]";
}
} | JavaScript |
/**
* @authors TODO
* @fileoverview TODO
*/
document.cancelFullScreen = document.webkitCancelFullScreen ||
document.mozCancelFullScreen;
/**
* @constructor
*/
function SlideDeck(el) {
this.curSlide_ = 0;
this.prevSlide_ = 0;
this.config_ = null;
this.container = el || document.querySelector('slides');
this.slides = [];
this.controller = null;
this.getCurrentSlideFromHash_();
// Call this explicitly. Modernizr.load won't be done until after DOM load.
this.onDomLoaded_.bind(this)();
}
/**
* @const
* @private
*/
SlideDeck.prototype.SLIDE_CLASSES_ = [
'far-past', 'past', 'current', 'next', 'far-next'];
/**
* @const
* @private
*/
SlideDeck.prototype.CSS_DIR_ = 'theme/css/';
/**
* @private
*/
SlideDeck.prototype.getCurrentSlideFromHash_ = function() {
var slideNo = parseInt(document.location.hash.substr(1));
if (slideNo) {
this.curSlide_ = slideNo - 1;
} else {
this.curSlide_ = 0;
}
};
/**
* @param {number} slideNo
*/
SlideDeck.prototype.loadSlide = function(slideNo) {
if (slideNo) {
this.curSlide_ = slideNo - 1;
this.updateSlides_();
}
};
/**
* @private
*/
SlideDeck.prototype.onDomLoaded_ = function(e) {
document.body.classList.add('loaded'); // Add loaded class for templates to use.
this.slides = this.container.querySelectorAll('slide:not([hidden]):not(.backdrop)');
// If we're on a smartphone, apply special sauce.
if (Modernizr.mq('only screen and (max-device-width: 480px)')) {
// var style = document.createElement('link');
// style.rel = 'stylesheet';
// style.type = 'text/css';
// style.href = this.CSS_DIR_ + 'phone.css';
// document.querySelector('head').appendChild(style);
// No need for widescreen layout on a phone.
this.container.classList.remove('layout-widescreen');
}
this.loadConfig_(SLIDE_CONFIG);
this.addEventListeners_();
this.updateSlides_();
// Add slide numbers and total slide count metadata to each slide.
var that = this;
for (var i = 0, slide; slide = this.slides[i]; ++i) {
slide.dataset.slideNum = i + 1;
slide.dataset.totalSlides = this.slides.length;
slide.addEventListener('click', function(e) {
if (document.body.classList.contains('overview')) {
that.loadSlide(this.dataset.slideNum);
e.preventDefault();
window.setTimeout(function() {
that.toggleOverview();
}, 500);
}
}, false);
}
// Note: this needs to come after addEventListeners_(), which adds a
// 'keydown' listener that this controller relies on.
// Also, no need to set this up if we're on mobile.
if (!Modernizr.touch) {
this.controller = new SlideController(this);
if (this.controller.isPopup) {
document.body.classList.add('popup');
}
}
};
/**
* @private
*/
SlideDeck.prototype.addEventListeners_ = function() {
document.addEventListener('keydown', this.onBodyKeyDown_.bind(this), false);
window.addEventListener('popstate', this.onPopState_.bind(this), false);
// var transEndEventNames = {
// 'WebkitTransition': 'webkitTransitionEnd',
// 'MozTransition': 'transitionend',
// 'OTransition': 'oTransitionEnd',
// 'msTransition': 'MSTransitionEnd',
// 'transition': 'transitionend'
// };
//
// // Find the correct transitionEnd vendor prefix.
// window.transEndEventName = transEndEventNames[
// Modernizr.prefixed('transition')];
//
// // When slides are done transitioning, kickoff loading iframes.
// // Note: we're only looking at a single transition (on the slide). This
// // doesn't include autobuilds the slides may have. Also, if the slide
// // transitions on multiple properties (e.g. not just 'all'), this doesn't
// // handle that case.
// this.container.addEventListener(transEndEventName, function(e) {
// this.enableSlideFrames_(this.curSlide_);
// }.bind(this), false);
// document.addEventListener('slideenter', function(e) {
// var slide = e.target;
// window.setTimeout(function() {
// this.enableSlideFrames_(e.slideNumber);
// this.enableSlideFrames_(e.slideNumber + 1);
// }.bind(this), 300);
// }.bind(this), false);
};
/**
* @private
* @param {Event} e The pop event.
*/
SlideDeck.prototype.onPopState_ = function(e) {
if (e.state != null) {
this.curSlide_ = e.state;
this.updateSlides_(true);
}
};
/**
* @param {Event} e
*/
SlideDeck.prototype.onBodyKeyDown_ = function(e) {
if (/^(input|textarea)$/i.test(e.target.nodeName) ||
e.target.isContentEditable) {
return;
}
// Forward keydowns to the main slides if we're the popup.
if (this.controller && this.controller.isPopup) {
this.controller.sendMsg({keyCode: e.keyCode});
}
switch (e.keyCode) {
case 13: // Enter
if (document.body.classList.contains('overview')) {
this.toggleOverview();
}
break;
case 39: // right arrow
case 32: // space
case 34: // PgDn
this.nextSlide();
e.preventDefault();
break;
case 37: // left arrow
case 8: // Backspace
case 33: // PgUp
this.prevSlide();
e.preventDefault();
break;
case 40: // down arrow
this.nextSlide();
e.preventDefault();
break;
case 38: // up arrow
this.prevSlide();
e.preventDefault();
break;
case 72: // H: Toggle code highlighting
document.body.classList.toggle('highlight-code');
break;
case 79: // O: Toggle overview
this.toggleOverview();
break;
case 80: // P
if (this.controller && this.controller.isPopup) {
document.body.classList.toggle('with-notes');
} else if (this.controller && !this.controller.popup) {
document.body.classList.toggle('with-notes');
}
break;
case 82: // R
// TODO: implement refresh on main slides when popup is refreshed.
break;
case 27: // ESC: Hide notes and highlighting
document.body.classList.remove('with-notes');
document.body.classList.remove('highlight-code');
if (document.body.classList.contains('overview')) {
this.toggleOverview();
}
break;
case 70: // F: Toggle fullscreen
// Only respect 'f' on body. Don't want to capture keys from an <input>.
// Also, ignore browser's fullscreen shortcut (cmd+shift+f) so we don't
// get trapped in fullscreen!
if (e.target == document.body && !(e.shiftKey && e.metaKey)) {
if (document.mozFullScreen !== undefined && !document.mozFullScreen) {
document.body.mozRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
} else if (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen) {
document.body.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
} else {
document.cancelFullScreen();
}
}
break;
case 87: // W: Toggle widescreen
// Only respect 'w' on body. Don't want to capture keys from an <input>.
if (e.target == document.body && !(e.shiftKey && e.metaKey)) {
this.container.classList.toggle('layout-widescreen');
}
break;
}
};
/**
*
*/
SlideDeck.prototype.focusOverview_ = function() {
var overview = document.body.classList.contains('overview');
for (var i = 0, slide; slide = this.slides[i]; i++) {
slide.style[Modernizr.prefixed('transform')] = overview ?
'translateZ(-2500px) translate(' + (( i - this.curSlide_ ) * 105) +
'%, 0%)' : '';
}
};
/**
*/
SlideDeck.prototype.toggleOverview = function() {
document.body.classList.toggle('overview');
this.focusOverview_();
};
/**
* @private
*/
SlideDeck.prototype.loadConfig_ = function(config) {
if (!config) {
return;
}
this.config_ = config;
var settings = this.config_.settings;
this.loadTheme_(settings.theme || []);
if (settings.favIcon) {
this.addFavIcon_(settings.favIcon);
}
// Prettyprint. Default to on.
if (!!!('usePrettify' in settings) || settings.usePrettify) {
prettyPrint();
}
if (settings.analytics) {
this.loadAnalytics_();
}
if (settings.fonts) {
this.addFonts_(settings.fonts);
}
// Builds. Default to on.
if (!!!('useBuilds' in settings) || settings.useBuilds) {
this.makeBuildLists_();
}
if (settings.title) {
document.title = settings.title.replace(/<br\/?>/, ' ') + ' - Google IO 2012';
document.querySelector('[data-config-title]').innerHTML = settings.title;
}
if (settings.subtitle) {
document.querySelector('[data-config-subtitle]').innerHTML = settings.subtitle;
}
if (this.config_.presenters) {
var presenters = this.config_.presenters;
var html = [];
if (presenters.length == 1) {
var p = presenters[0]
html = [p.name, p.company].join('<br>');
var gplus = p.gplus ? '<span>g+</span><a href="' + p.gplus +
'">' + p.gplus.replace('http://', '') + '</a>' : '';
var twitter = p.twitter ? '<span>twitter</span>' +
'<a href="http://twitter.com/' + p.twitter + '">' +
p.twitter + '</a>' : '';
var www = p.www ? '<span>www</span><a href="' + p.www +
'">' + p.www.replace('http://', '') + '</a>' : '';
var html2 = [gplus, twitter, www].join('<br>');
document.querySelector('[data-config-contact]').innerHTML = html2;
} else {
for (var i = 0, p; p = presenters[i]; ++i) {
html.push(p.name + ' - ' + p.company);
}
html = html.join('<br>');
}
document.querySelector('[data-config-presenter]').innerHTML = html;
}
/* Left/Right tap areas. Default to including. */
if (!!!('enableSlideAreas' in settings) || settings.enableSlideAreas) {
var el = document.createElement('div');
el.classList.add('slide-area');
el.id = 'prev-slide-area';
el.addEventListener('click', this.prevSlide.bind(this), false);
this.container.appendChild(el);
var el = document.createElement('div');
el.classList.add('slide-area');
el.id = 'next-slide-area';
el.addEventListener('click', this.nextSlide.bind(this), false);
this.container.appendChild(el);
}
if (Modernizr.touch && (!!!('enableTouch' in settings) ||
settings.enableTouch)) {
var self = this;
// Note: this prevents mobile zoom in/out but prevents iOS from doing
// it's crazy scroll over effect and disaligning the slides.
window.addEventListener('touchstart', function(e) {
e.preventDefault();
}, false);
var hammer = new Hammer(this.container);
hammer.ondragend = function(e) {
if (e.direction == 'right' || e.direction == 'down') {
self.prevSlide();
} else if (e.direction == 'left' || e.direction == 'up') {
self.nextSlide();
}
};
}
};
/**
* @private
* @param {Array.<string>} fonts
*/
SlideDeck.prototype.addFonts_ = function(fonts) {
var el = document.createElement('link');
el.rel = 'stylesheet';
el.href = 'http://fonts.googleapis.com/css?family=' + fonts.join('|') + '&v2';
document.querySelector('head').appendChild(el);
};
/**
* @private
*/
SlideDeck.prototype.buildNextItem_ = function() {
var slide = this.slides[this.curSlide_];
var toBuild = slide.querySelector('.to-build');
var built = slide.querySelector('.build-current');
if (built) {
built.classList.remove('build-current');
if (built.classList.contains('fade')) {
built.classList.add('build-fade');
}
}
if (!toBuild) {
var items = slide.querySelectorAll('.build-fade');
for (var j = 0, item; item = items[j]; j++) {
item.classList.remove('build-fade');
}
return false;
}
toBuild.classList.remove('to-build');
toBuild.classList.add('build-current');
return true;
};
/**
* @param {boolean=} opt_dontPush
*/
SlideDeck.prototype.prevSlide = function(opt_dontPush) {
if (this.curSlide_ > 0) {
var bodyClassList = document.body.classList;
bodyClassList.remove('highlight-code');
// Toggle off speaker notes if they're showing when we move backwards on the
// main slides. If we're the speaker notes popup, leave them up.
if (this.controller && !this.controller.isPopup) {
bodyClassList.remove('with-notes');
} else if (!this.controller) {
bodyClassList.remove('with-notes');
}
this.prevSlide_ = this.curSlide_--;
this.updateSlides_(opt_dontPush);
}
};
/**
* @param {boolean=} opt_dontPush
*/
SlideDeck.prototype.nextSlide = function(opt_dontPush) {
if (!document.body.classList.contains('overview') && this.buildNextItem_()) {
return;
}
if (this.curSlide_ < this.slides.length - 1) {
var bodyClassList = document.body.classList;
bodyClassList.remove('highlight-code');
// Toggle off speaker notes if they're showing when we advanced on the main
// slides. If we're the speaker notes popup, leave them up.
if (this.controller && !this.controller.isPopup) {
bodyClassList.remove('with-notes');
} else if (!this.controller) {
bodyClassList.remove('with-notes');
}
this.prevSlide_ = this.curSlide_++;
this.updateSlides_(opt_dontPush);
}
};
/* Slide events */
/**
* Triggered when a slide enter/leave event should be dispatched.
*
* @param {string} type The type of event to trigger
* (e.g. 'slideenter', 'slideleave').
* @param {number} slideNo The index of the slide that is being left.
*/
SlideDeck.prototype.triggerSlideEvent = function(type, slideNo) {
var el = this.getSlideEl_(slideNo);
if (!el) {
return;
}
// Call onslideenter/onslideleave if the attribute is defined on this slide.
var func = el.getAttribute(type);
if (func) {
new Function(func).call(el); // TODO: Don't use new Function() :(
}
// Dispatch event to listeners setup using addEventListener.
var evt = document.createEvent('Event');
evt.initEvent(type, true, true);
evt.slideNumber = slideNo + 1; // Make it readable
evt.slide = el;
el.dispatchEvent(evt);
};
/**
* @private
*/
SlideDeck.prototype.updateSlides_ = function(opt_dontPush) {
var dontPush = opt_dontPush || false;
var curSlide = this.curSlide_;
for (var i = 0; i < this.slides.length; ++i) {
switch (i) {
case curSlide - 2:
this.updateSlideClass_(i, 'far-past');
break;
case curSlide - 1:
this.updateSlideClass_(i, 'past');
break;
case curSlide:
this.updateSlideClass_(i, 'current');
break;
case curSlide + 1:
this.updateSlideClass_(i, 'next');
break;
case curSlide + 2:
this.updateSlideClass_(i, 'far-next');
break;
default:
this.updateSlideClass_(i);
break;
}
};
this.triggerSlideEvent('slideleave', this.prevSlide_);
this.triggerSlideEvent('slideenter', curSlide);
// window.setTimeout(this.disableSlideFrames_.bind(this, curSlide - 2), 301);
//
// this.enableSlideFrames_(curSlide - 1); // Previous slide.
// this.enableSlideFrames_(curSlide + 1); // Current slide.
// this.enableSlideFrames_(curSlide + 2); // Next slide.
// Enable current slide's iframes (needed for page loat at current slide).
this.enableSlideFrames_(curSlide + 1);
// No way to tell when all slide transitions + auto builds are done.
// Give ourselves a good buffer to preload the next slide's iframes.
window.setTimeout(this.enableSlideFrames_.bind(this, curSlide + 2), 1000);
this.updateHash_(dontPush);
if (document.body.classList.contains('overview')) {
this.focusOverview_();
return;
}
};
/**
* @private
* @param {number} slideNo
*/
SlideDeck.prototype.enableSlideFrames_ = function(slideNo) {
var el = this.slides[slideNo - 1];
if (!el) {
return;
}
var frames = el.querySelectorAll('iframe');
for (var i = 0, frame; frame = frames[i]; i++) {
this.enableFrame_(frame);
}
};
/**
* @private
* @param {number} slideNo
*/
SlideDeck.prototype.enableFrame_ = function(frame) {
var src = frame.dataset.src;
if (src && frame.src != src) {
frame.src = src;
}
};
/**
* @private
* @param {number} slideNo
*/
SlideDeck.prototype.disableSlideFrames_ = function(slideNo) {
var el = this.slides[slideNo - 1];
if (!el) {
return;
}
var frames = el.querySelectorAll('iframe');
for (var i = 0, frame; frame = frames[i]; i++) {
this.disableFrame_(frame);
}
};
/**
* @private
* @param {Node} frame
*/
SlideDeck.prototype.disableFrame_ = function(frame) {
frame.src = 'about:blank';
};
/**
* @private
* @param {number} slideNo
*/
SlideDeck.prototype.getSlideEl_ = function(no) {
if ((no < 0) || (no >= this.slides.length)) {
return null;
} else {
return this.slides[no];
}
};
/**
* @private
* @param {number} slideNo
* @param {string} className
*/
SlideDeck.prototype.updateSlideClass_ = function(slideNo, className) {
var el = this.getSlideEl_(slideNo);
if (!el) {
return;
}
if (className) {
el.classList.add(className);
}
for (var i = 0, slideClass; slideClass = this.SLIDE_CLASSES_[i]; ++i) {
if (className != slideClass) {
el.classList.remove(slideClass);
}
}
};
/**
* @private
*/
SlideDeck.prototype.makeBuildLists_ = function () {
for (var i = this.curSlide_, slide; slide = this.slides[i]; ++i) {
var items = slide.querySelectorAll('.build > *');
for (var j = 0, item; item = items[j]; ++j) {
if (item.classList) {
item.classList.add('to-build');
if (item.parentNode.classList.contains('fade')) {
item.classList.add('fade');
}
}
}
}
};
/**
* @private
* @param {boolean} dontPush
*/
SlideDeck.prototype.updateHash_ = function(dontPush) {
if (!dontPush) {
var slideNo = this.curSlide_ + 1;
var hash = '#' + slideNo;
if (window.history.pushState) {
window.history.pushState(this.curSlide_, 'Slide ' + slideNo, hash);
} else {
window.location.replace(hash);
}
// Record GA hit on this slide.
window['_gaq'] && window['_gaq'].push(['_trackPageview',
document.location.href]);
}
};
/**
* @private
* @param {string} favIcon
*/
SlideDeck.prototype.addFavIcon_ = function(favIcon) {
var el = document.createElement('link');
el.rel = 'icon';
el.type = 'image/png';
el.href = favIcon;
document.querySelector('head').appendChild(el);
};
/**
* @private
* @param {string} theme
*/
SlideDeck.prototype.loadTheme_ = function(theme) {
var styles = [];
if (theme.constructor.name === 'String') {
styles.push(theme);
} else {
styles = theme;
}
for (var i = 0, style; themeUrl = styles[i]; i++) {
var style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
if (themeUrl.indexOf('http') == -1) {
style.href = this.CSS_DIR_ + themeUrl + '.css';
} else {
style.href = themeUrl;
}
document.querySelector('head').appendChild(style);
}
};
/**
* @private
*/
SlideDeck.prototype.loadAnalytics_ = function() {
var _gaq = window['_gaq'] || [];
_gaq.push(['_setAccount', this.config_.settings.analytics]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
};
// Polyfill missing APIs (if we need to), then create the slide deck.
// iOS < 5 needs classList, dataset, and window.matchMedia. Modernizr contains
// the last one.
(function() {
Modernizr.load({
test: !!document.body.classList && !!document.body.dataset,
nope: ['js/polyfills/classList.min.js', 'js/polyfills/dataset.min.js'],
complete: function() {
window.slidedeck = new SlideDeck();
}
});
})();
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.