code stringlengths 2 1.05M |
|---|
import React from 'react';
import PropTypes from 'prop-types';
import Item from './Item';
import Wrapper from './Wrapper';
import SearchPage from 'containers/SearchPage';
function PageItemSearchPage(props) {
const label = props.label ? <strong>{props.labelValue}:</strong> : '';
const collection = props.data.def.collection;
const item = props.data.doc[props.data.def.arg];
const selectedFacets = [[collection, item]];
return (
<div style={{margin: "50px 0"}}>
{label}
<SearchPage passedFacets={selectedFacets} />
</div>
);
}
PageItemSearchPage.propTypes = {
item: PropTypes.any,
};
export default PageItemSearchPage;
|
'use strict'
const { isMainThread, parentPort, workerData } = require('worker_threads')
const multipart = require('./multipart')
const run = require('./run')
const createHist = (name) => ({
__custom: true,
recordValue: v => updateHist(name, v),
destroy: () => {},
reset: () => resetHist(name)
})
const updateHist = (name, value) => {
parentPort.postMessage({
cmd: 'UPDATE_HIST',
data: { name, value }
})
}
const resetHist = (name) => {
parentPort.postMessage({
cmd: 'RESET_HIST',
data: { name }
})
}
function runTracker (opts, cb) {
const tracker = run({
...opts,
...(opts.form ? { form: multipart(opts.form) } : undefined),
...(opts.setupClient ? { setupClient: require(opts.setupClient) } : undefined),
requests: opts.requests
? opts.requests.map(r => ({
...r,
...(r.setupRequest ? { setupRequest: require(r.setupRequest) } : undefined),
...(r.onResponse ? { onResponse: require(r.onResponse) } : undefined)
}))
: undefined,
histograms: {
requests: createHist('requests'),
throughput: createHist('throughput')
}
}, null, cb)
tracker.on('tick', (data) => {
parentPort.postMessage({ cmd: 'TICK', data })
})
return {
stop: tracker.stop
}
}
if (!isMainThread) {
const { opts } = workerData
let tracker
parentPort.on('message', (msg) => {
const { cmd } = msg
if (cmd === 'START') {
tracker = runTracker(opts, (error, data) => {
parentPort.postMessage({ cmd: error ? 'ERROR' : 'RESULT', error, data })
parentPort.close()
})
} else if (cmd === 'STOP') {
tracker.stop()
parentPort.close()
}
})
}
|
/* Contentview for details is used to show description, sources, relations of an entity */
function Details(entity){
this.$container;
this.$description;
this.$action;
this.$relatedness;
this.$sources;
this.entity = entity;
this.loaded = false;
this.partialLoaded = false;
this.init();
}
/* INIT */
/* init Details objects */
Details.prototype.init = function(){
this.build();
}
/* build html */
Details.prototype.build = function(){
this.$container = $(document.createElement('div')).addClass('content').addClass('content-details').data('content',this);
}
Details.prototype.addBody = function(){
this.$relatedness = $(document.createElement('div')).addClass('relations');
this.$container.append(this.$relatedness);
this.$sources = $(document.createElement('div')).addClass('sources');
this.$container.append(this.$sources);
this.$action = $(document.createElement('div')).addClass('action');
this.$container.append(this.$action);
this.$description = $(document.createElement('div')).addClass('description');
this.$container.append(this.$description);
}
/* HELPERS */
Details.prototype.getContainer = function(){
return this.$container;
}
Details.prototype.show = function(){
if (!this.loaded){
this.load();
}
}
/* DATA */
/* Load details from API */
Details.prototype.load = function(){
if (this.loaded){
return;
}
this.loaded = true;
this.addBody();
this.$container.addClass('loading_white');
if (this.entity.row.entity){
this.entity.data.relatedness = [];
if (this.entity.data.uid == this.entity.data.event){
this.entity.data.relatedness.push('Direct relation');
} else{
this.entity.data.relatedness.push('Related by event ' + this.entity.data.event);
}
this.partialLoaded = true;
} else{
this.entity.data.relatedness = [];
this.entity.data.relatedness.push('Related by ' + this.entity.row.relatedness);
this.partialLoaded = true;
}
if (this.entity.isCollection()){
this.addContents();
} else{
Global.data.getEntity(this.entity.getUID(), this.detailsSuccess.bind(this));
}
}
Details.prototype.detailsSuccess = function(data){
if (!data || !data.data){ return; }
if (data.data.length > 0){
this.entity.data.description = '';
if (this.entity.data.type == 'Event'){
this.entity.data.description += this.entity.data.date.start ? this.entity.data.date.start + ' : ' : "Unknown timestamp : ";
}
this.entity.data.description += data.data[0].description
this.entity.data.sources = [];
var checkSources = [];
var link;
for(var i=0, len = data.data.length; i<len; i++){
link = data.data[i].sources;
if(link){
if (typeof checkSources[link] == 'undefined'){
this.entity.data.sources.push(link);
checkSources[link] = true;
}
}
}
if (this.partialLoaded){
this.addContents();
} else{
this.partialLoaded = true;
}
} else{
this.entity.data.description = 'No details found. ' + data.data.error ? data.data.error : '';
}
this.loaded = true;
this.$container.removeClass('loading_white');
this.showContainer();
}
Details.prototype.showContainer = function (){
this.$container.velocity('stop').velocity("slideDown", {
queue: false,
easing: Global.easing,
duration: Global.animationDuration
});
}
Details.prototype.relatednessSuccess = function(data){
if (!data || !data.data){ return; }
var results = data.data.results.bindings;
if (results && results.length){
this.entity.data.relatedness = [];
var e;
for(var i=0, len = results.length; i<len; i++){
e = Global.parser.getEvent(results[i]);
if(e){
this.entity.data.relatedness.push('Related by common event ' + e);
}
}
if (this.partialLoaded){
this.addContents();
} else{
this.partialLoaded = true;
}
}
this.loaded = true;
this.$container.removeClass('loading_white');
}
Details.prototype.relatednessTypesSuccess = function(data){
if (!data || !data.data){ return; }
var results = data.data.results.bindings;
if (results && results.length){
this.entity.data.relatedness = [];
var r;
for(var i=0, len = results.length; i<len; i++){
r = Global.parser.getRelatedness(results[i]);
if(r){
this.entity.data.relatedness.push(r);
}
}
if (this.partialLoaded){
this.addContents();
} else{
this.partialLoaded = true;
}
}
this.loaded = true;
this.$container.removeClass('loading_white');
}
/* add detail information to the object */
Details.prototype.addContents = function(){
this.$container.removeClass('loading_white');
// description
this.$description.text(this.entity.data.description);
this.$description.html(this.$description.text().replace(/(?:\r\n|\r|\n)/g, '<br />'));
// WTODO:
// add entity-sharing information (twitter/facebook)
//
// collection edit details
if (this.entity.isCollection()){
this.$action.append(
$(document.createElement('button')).addClass('ok').text('Edit collection details').click(
function(){
this.editCollectionDetails('Edit collection details',this.entity.isCollection(),this.entity.data.title,this.entity.data.description,this.entity.data['public']);
}.bind(this)
)
).append(
$(document.createElement('button')).addClass('delete').text('Delete collection').click(
function(){
this.confirmDelete('Delete collection',this.entity.isCollection());
}.bind(this)
)
);
} else{
// normal entity
this.$action.append(
$(document.createElement('button')).addClass('ok').text('Improve entity').click(
function(){
this.editEntityDetails('Improve entity',this.entity);
}.bind(this)
)
)
}
// normal entity
this.$action.append(
$(document.createElement('button')).addClass('ok twitter').text('Share on Twitter').click(
function(){
var videoSrc = this.entity.data.depicted_by.source;
incrementVideoStat(videoSrc,'twitter');
window.open('https://twitter.com/intent/tweet?text=Check out this DIVE entity: ' + encodeURIComponent(Global.hashPath.getUrlForEntity(this.entity)));
}.bind(this)
)
);
// normal entity
this.$action.append(
$(document.createElement('button')).addClass('delete pinterest').text('Pin on Pinterest').click(
function(){
url = Global.basePath + "#browser\\entity\\" + this.entity.getUID();
source = this.entity.data.depicted_by.source;
title = this.entity.getTitle();
incrementVideoStat(source,'pinterest');
window.open("http://pinterest.com/pin/create/button/?url="+url+"&media="+source+"&description="+title+"");
}.bind(this)
)
);
// relations
this.$relatedness.html('');
for (var i=0, len = this.entity.data.relatedness.length; i<len;i++){
var $related = $(document.createElement('span')).text(this.entity.data.relatedness[i]).addClass('entity-color');
this.$relatedness.append($related);
}
// sources
this.$sources.html('');
for (var i=0, len = this.entity.data.sources.length; i < len; i++){
var $source = $(document.createElement('span')).text(this.entity.data.sources[i]);
this.$sources.append($source);
}
this.showContainer();
}
/* Suggest new entity information */
Details.prototype.editEntityDetails = function(title,entity){
var checked = true;
var options = '';
var selected = '';
for(var i = 0, len = Global.config.entityTypes.length; i<len; i++){
// exclude collection from type list
if (Global.config.entityTypes[i] == 'Collection'){ continue; }
// populate options
if (Global.config.entityTypes[i] == entity.getType()){
selected = 'selected="true"';
} else{
selected = '';
}
options += '<option '+ selected+'value="'+ Global.config.entityTypes[i]+'">'+Global.config.entityTypes[i]+'</option>'
}
var $form = $('<div><label>Title</label><input type="text" maxlength="255" class="entity-title" placeholder="Entity title" value=""><br><label>Description</label><textarea class="entity-description"></textarea><br><label>Type</label><select class="entity-type">'+options+'</select></div>');
$form.find('.entity-title').attr('value',entity.data.title);
$form.find('.entity-description').text(entity.data.description);
var popup= new Popup(title,
$form.html(),
{
'cancel': {
label: 'Cancel',
click : function(){
$(window).trigger('popup-hide');
}
},
'ok': {
label: 'Save',
click : function(){
var newTitle = $('#popup .entity-title').val();
var newType = $('#popup .entity-type').val();
var newDescription = $('#popup .entity-description').val();
var checkId = this.entity.getUID();
Global.browser.updateEntity(checkId,newTitle,newDescription,newType);
AjaxLog.info('Improve Entity',JSON.stringify({'uid': entity.getUID(), 'type':newType, 'title':newTitle, 'description':newDescription }));
Global.user.refresh();
$(window).trigger('popup-hide');
}.bind(this)
}
}
);
$('#popup input.entity-title').focus();
}
/* Edit collection details */
Details.prototype.editCollectionDetails = function(title,collection,collectionTitle,collectionDescription,collectionPublic){
var checked = ((collectionPublic == 'true' || collectionPublic==true) ? "checked" : "");
var $form = $('<div><label>Collection title</label><input type="text" maxlength="255" class="collection-title" placeholder="My collection title" value=""><br><label>Description</label><textarea class="collection-description"></textarea><br><label>Public</label><input type="checkbox" '+ checked +' class="collection-public" /></div>');
$form.find('.collection-title').val(collectionTitle);
$form.find('.collection-description').val(collectionDescription);
var popup= new Popup(title,
$form.html(),
{
'cancel': {
label: 'Cancel',
click : function(){
$(window).trigger('popup-hide');
}
},
'ok': {
label: 'Save',
click : function(){
var newTitle = $('#popup input.collection-title').val();
var newPublic = $('#popup input.collection-public').is(':checked');
var newDescription = $('#popup textarea.collection-description').val();
var checkId = this.entity.getUID();
Global.browser.updateEntity(checkId,newTitle,newDescription,newPublic);
$.post(Global.basePath + 'collection/'+collection+'/edit', {
title: newTitle,
'public': newPublic,
description: newDescription
}, function(data){
Global.user.refresh();
$(window).trigger('popup-hide');
}.bind(this)
); }.bind(this)
}
}
);
$('#popup input.collection-title').focus();
}
/* Delete a collection */
Details.prototype.confirmDelete = function(title,collection){
var popup= new Popup(title,
'<label>Are you sure you want to delete this collection?</label>',
{
'cancel': {
label: 'Cancel',
click : function(){
$(window).trigger('popup-hide');
}
},
'delete': {
label: 'Delete',
click : function(){
var checkId = this.entity.getUID();
Global.browser.deleteEntity(checkId);
$.post(Global.basePath + 'collection/'+collection+'/delete', {
}, function(data){
Global.user.refresh();
$(window).trigger('popup-hide');
}.bind(this)
); }.bind(this)
}
}
);
$('#popup').css('height','250px');
}
|
define([
'Utils/CheckType',
'Utils/Debug',
'underscore',
'Pool/DomainPool',
'Api/SpotifyResourceService',
'Domain/Album',
'Domain/Collection'
], function (
CheckType,
Debug,
_,
DomainPool,
MusicResourceService,
Album,
Collection
) {
var AlbumPoolServiceClass = AlbumPoolService;
AlbumPoolServiceClass.prototype = new DomainPool;
AlbumPoolServiceClass.prototype.domainCode = 'album';
AlbumPoolServiceClass.prototype.createNewDomain = _createNewDomain;
AlbumPoolServiceClass.prototype.artistGetAlbums = _artistGetAlbums;
AlbumPoolServiceClass.prototype.trackGetAlbum = _trackGetAlbum;
function AlbumPoolService() {}
function _artistGetAlbums(artist) {
var _this = this,
request = this.createRequestByDomain(artist, 'artist')
;
return MusicResourceService
.artistGetAlbums(request)
.then(function(response) {
return _this.populateCollection(response, function(album) {
album._relation_album = artist;
album.set('album', artist.get('name'));
});
},
function(response) {
console.log('REJECT artistGetAlbums()', response);
}
)
;
}
function _trackGetAlbum(track) {
var _this = this,
request = this.createRequestByDomain(track, 'track')
;
return MusicResourceService
.trackGetInfo(request)
.then(function(response) {
var album = _this.findOrCreate(response.album);
return album;
},
function(response) {
console.log('REJECT artistGetInfo()', response);
}
)
;
}
function _search(albumName) {
var _this = this,
request = {'album': albumName}
;
return MusicResourceService
.albumSearch(request)
.then(function(response) {
return _this.populateCollection(response);
},
function(response) {
console.log('REJECT albumSearch()', response);
}
)
;
}
function _createNewDomain() {
return new Album;
}
return new AlbumPoolServiceClass();
});
|
define(function(require) {
var Marionette = require('marionette');
/**
* @class FlashComponent
* @extends {Marionette.View}
*/
var FlashComponent = Marionette.View.extend({
template: false,
ui: {
dismissBtn: '.dismiss-flash'
},
events: {
'click @ui.dismissBtn': 'dismiss'
},
dismiss: function(event) {
event.preventDefault();
this.$el.addClass('flash-message--dismissing').slideUp();
}
});
return FlashComponent;
});
|
/*!
* FullCalendar v1.6.4
* Docs & License: http://arshaw.com/fullcalendar/
* (c) 2013 Adam Shaw
*/
/*
* Use fullcalendar.css for basic styling.
* For event drag & drop, requires jQuery UI draggable.
* For event resizing, requires jQuery UI resizable.
*/
(function($, undefined) {
;;
var defaults = {
// display
defaultView: 'month',
aspectRatio: 1.35,
header: {
left: 'title',
center: '',
right: 'today prev,next'
},
weekends: true,
weekNumbers: false,
weekNumberCalculation: 'iso',
weekNumberTitle: 'W',
// editing
//editable: false,
//disableDragging: false,
//disableResizing: false,
allDayDefault: true,
ignoreTimezone: true,
// event ajax
lazyFetching: true,
startParam: 'start',
endParam: 'end',
// time formats
titleFormat: {
month: 'MMMM yyyy',
week: "MMM d[ yyyy]{ '—'[ MMM] d yyyy}",
day: 'dddd, MMM d, yyyy'
},
columnFormat: {
month: 'ddd',
week: 'ddd M/d',
day: 'dddd M/d'
},
timeFormat: { // for event elements
'': 'h(:mm)t' // default
},
// locale
isRTL: false,
firstDay: 0,
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
buttonText: {
prev: "<span class='fc-text-arrow'>‹</span>",
next: "<span class='fc-text-arrow'>›</span>",
prevYear: "<span class='fc-text-arrow'>«</span>",
nextYear: "<span class='fc-text-arrow'>»</span>",
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
// jquery-ui theming
theme: false,
buttonIcons: {
prev: 'circle-triangle-w',
next: 'circle-triangle-e'
},
//selectable: false,
unselectAuto: true,
dropAccept: '*',
handleWindowResize: true,
indentationMultiplier : 1,
splitBySources: false,
isBackground: false
};
// right-to-left defaults
var rtlDefaults = {
header: {
left: 'next,prev today',
center: '',
right: 'title'
},
buttonText: {
prev: "<span class='fc-text-arrow'>›</span>",
next: "<span class='fc-text-arrow'>‹</span>",
prevYear: "<span class='fc-text-arrow'>»</span>",
nextYear: "<span class='fc-text-arrow'>«</span>"
},
buttonIcons: {
prev: 'circle-triangle-e',
next: 'circle-triangle-w'
}
};
;;
var fc = $.fullCalendar = { version: "1.6.4" };
var fcViews = fc.views = {};
$.fn.fullCalendar = function(options) {
// method calling
if (typeof options == 'string') {
var args = Array.prototype.slice.call(arguments, 1);
var res;
this.each(function() {
var calendar = $.data(this, 'fullCalendar');
if (calendar && $.isFunction(calendar[options])) {
var r = calendar[options].apply(calendar, args);
if (res === undefined) {
res = r;
}
if (options == 'destroy') {
$.removeData(this, 'fullCalendar');
}
}
});
if (res !== undefined) {
return res;
}
return this;
}
options = options || {};
// would like to have this logic in EventManager, but needs to happen before options are recursively extended
var eventSources = options.eventSources || [];
delete options.eventSources;
if (options.events) {
eventSources.push(options.events);
delete options.events;
}
options = $.extend(true, {},
defaults,
(options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {},
options
);
this.each(function(i, _element) {
var element = $(_element);
var calendar = new Calendar(element, options, eventSources);
element.data('fullCalendar', calendar); // TODO: look into memory leak implications
calendar.render();
});
return this;
};
// function for adding/overriding defaults
function setDefaults(d) {
$.extend(true, defaults, d);
}
;;
function Calendar(element, options, eventSources) {
var t = this;
// exports
t.options = options;
t.render = render;
t.destroy = destroy;
t.refetchEvents = refetchEvents;
t.reportEvents = reportEvents;
t.reportEventChange = reportEventChange;
t.rerenderEvents = rerenderEvents;
t.changeView = changeView;
t.select = select;
t.unselect = unselect;
t.prev = prev;
t.next = next;
t.prevYear = prevYear;
t.nextYear = nextYear;
t.today = today;
t.gotoDate = gotoDate;
t.incrementDate = incrementDate;
t.formatDate = function(format, date) { return formatDate(format, date, options) };
t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
t.getDate = getDate;
t.getView = getView;
t.option = option;
t.trigger = trigger;
// imports
EventManager.call(t, options, eventSources);
var isFetchNeeded = t.isFetchNeeded;
var fetchEvents = t.fetchEvents;
// locals
var _element = element[0];
var header;
var headerElement;
var content;
var tm; // for making theme classes
var currentView;
var elementOuterWidth;
var suggestedViewHeight;
var resizeUID = 0;
var ignoreWindowResize = 0;
var date = new Date();
var events = [];
var _dragElement;
/* Main Rendering
-----------------------------------------------------------------------------*/
setYMD(date, options.year, options.month, options.date);
function render(inc) {
if (!content) {
initialRender();
}
else if (elementVisible()) {
// mainly for the public API
calcSize();
_renderView(inc);
}
}
function initialRender() {
tm = options.theme ? 'ui' : 'fc';
element.addClass('fc');
if (options.isRTL) {
element.addClass('fc-rtl');
}
else {
element.addClass('fc-ltr');
}
if (options.theme) {
element.addClass('ui-widget');
}
content = $("<div class='fc-content' style='position:relative'/>")
.prependTo(element);
header = new Header(t, options);
headerElement = header.render();
if (headerElement) {
element.prepend(headerElement);
}
changeView(options.defaultView);
if (options.handleWindowResize) {
$(window).resize(windowResize);
}
// needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
if (!bodyVisible()) {
lateRender();
}
}
// called when we know the calendar couldn't be rendered when it was initialized,
// but we think it's ready now
function lateRender() {
setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
renderView();
}
},0);
}
function destroy() {
if (currentView) {
trigger('viewDestroy', currentView, currentView, currentView.element);
currentView.triggerEventDestroy();
}
$(window).unbind('resize', windowResize);
header.destroy();
content.remove();
element.removeClass('fc fc-rtl ui-widget');
}
function elementVisible() {
return element.is(':visible');
}
function bodyVisible() {
return $('body').is(':visible');
}
/* View Rendering
-----------------------------------------------------------------------------*/
function changeView(newViewName) {
if (!currentView || newViewName != currentView.name) {
_changeView(newViewName);
}
}
function _changeView(newViewName) {
ignoreWindowResize++;
if (currentView) {
trigger('viewDestroy', currentView, currentView, currentView.element);
unselect();
currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
freezeContentHeight();
currentView.element.remove();
header.deactivateButton(currentView.name);
}
header.activateButton(newViewName);
currentView = new fcViews[newViewName](
$("<div class='fc-view fc-view-" + newViewName + "' style='position:relative'/>")
.appendTo(content),
t // the calendar object
);
renderView();
unfreezeContentHeight();
ignoreWindowResize--;
}
function renderView(inc) {
if (
!currentView.start || // never rendered before
inc || date < currentView.start || date >= currentView.end // or new date range
) {
if (elementVisible()) {
_renderView(inc);
}
}
}
function _renderView(inc) { // assumes elementVisible
ignoreWindowResize++;
if (currentView.start) { // already been rendered?
trigger('viewDestroy', currentView, currentView, currentView.element);
unselect();
clearEvents();
}
freezeContentHeight();
currentView.render(date, inc || 0); // the view's render method ONLY renders the skeleton, nothing else
setSize();
unfreezeContentHeight();
(currentView.afterRender || noop)();
updateTitle();
updateTodayButton();
trigger('viewRender', currentView, currentView, currentView.element);
currentView.trigger('viewDisplay', _element); // deprecated
ignoreWindowResize--;
getAndRenderEvents();
}
/* Resizing
-----------------------------------------------------------------------------*/
function updateSize() {
if (elementVisible()) {
unselect();
clearEvents();
calcSize();
setSize();
renderEvents();
}
}
function calcSize() { // assumes elementVisible
if (options.contentHeight) {
suggestedViewHeight = options.contentHeight;
}
else if (options.height) {
suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
}
else {
suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
}
}
function setSize() { // assumes elementVisible
if (suggestedViewHeight === undefined) {
calcSize(); // for first time
// NOTE: we don't want to recalculate on every renderView because
// it could result in oscillating heights due to scrollbars.
}
ignoreWindowResize++;
currentView.setHeight(suggestedViewHeight);
currentView.setWidth(content.width());
ignoreWindowResize--;
elementOuterWidth = element.outerWidth();
}
function windowResize() {
if (!ignoreWindowResize) {
if (currentView.start) { // view has already been rendered
var uid = ++resizeUID;
setTimeout(function() { // add a delay
if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
ignoreWindowResize++; // in case the windowResize callback changes the height
updateSize();
currentView.trigger('windowResize', _element);
ignoreWindowResize--;
}
}
}, 200);
}else{
// calendar must have been initialized in a 0x0 iframe that has just been resized
lateRender();
}
}
}
/* Event Fetching/Rendering
-----------------------------------------------------------------------------*/
// TODO: going forward, most of this stuff should be directly handled by the view
function refetchEvents() { // can be called as an API method
clearEvents();
fetchAndRenderEvents();
}
function rerenderEvents(modifiedEventID) { // can be called as an API method
clearEvents();
renderEvents(modifiedEventID);
}
function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack
if (elementVisible()) {
currentView.setEventData(events); // for View.js, TODO: unify with renderEvents
currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements
currentView.trigger('eventAfterAllRender');
}
}
function clearEvents() {
currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
currentView.clearEvents(); // actually remove the DOM elements
currentView.clearEventData(); // for View.js, TODO: unify with clearEvents
}
function getAndRenderEvents() {
if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
fetchAndRenderEvents();
}
else {
renderEvents();
}
}
function fetchAndRenderEvents() {
fetchEvents(currentView.visStart, currentView.visEnd);
// ... will call reportEvents
// ... which will call renderEvents
}
// called when event data arrives
function reportEvents(_events) {
events = _events;
renderEvents();
}
// called when a single event's data has been changed
function reportEventChange(eventID) {
rerenderEvents(eventID);
}
/* Header Updating
-----------------------------------------------------------------------------*/
function updateTitle() {
header.updateTitle(currentView.title);
}
function updateTodayButton() {
var today = new Date();
if (today >= currentView.start && today < currentView.end) {
header.disableButton('today');
}
else {
header.enableButton('today');
}
}
/* Selection
-----------------------------------------------------------------------------*/
function select(start, end, allDay) {
currentView.select(start, end, allDay===undefined ? true : allDay);
}
function unselect() { // safe to be called before renderView
if (currentView) {
currentView.unselect();
}
}
/* Date
-----------------------------------------------------------------------------*/
function prev() {
renderView(-1);
}
function next() {
renderView(1);
}
function prevYear() {
addYears(date, -1);
renderView();
}
function nextYear() {
addYears(date, 1);
renderView();
}
function today() {
date = new Date();
renderView();
}
function gotoDate(year, month, dateOfMonth) {
if (year instanceof Date) {
date = cloneDate(year); // provided 1 argument, a Date
}else{
setYMD(date, year, month, dateOfMonth);
}
renderView();
}
function incrementDate(years, months, days) {
if (years !== undefined) {
addYears(date, years);
}
if (months !== undefined) {
addMonths(date, months);
}
if (days !== undefined) {
addDays(date, days);
}
renderView();
}
function getDate() {
return cloneDate(date);
}
/* Height "Freezing"
-----------------------------------------------------------------------------*/
function freezeContentHeight() {
content.css({
width: '100%',
height: content.height(),
overflow: 'hidden'
});
}
function unfreezeContentHeight() {
content.css({
width: '',
height: '',
overflow: ''
});
}
/* Misc
-----------------------------------------------------------------------------*/
function getView() {
return currentView;
}
function option(name, value) {
if (value === undefined) {
return options[name];
}
if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
options[name] = value;
updateSize();
}
}
function trigger(name, thisObj) {
if (options[name]) {
return options[name].apply(
thisObj || _element,
Array.prototype.slice.call(arguments, 2)
);
}
}
/* External Dragging
------------------------------------------------------------------------*/
if (options.droppable) {
$(document)
.bind('dragstart', function(ev, ui) {
var _e = ev.target;
var e = $(_e);
if (!e.parents('.fc').length) { // not already inside a calendar
var accept = options.dropAccept;
if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
_dragElement = _e;
currentView.dragStart(_dragElement, ev, ui);
}
}
})
.bind('dragstop', function(ev, ui) {
if (_dragElement) {
currentView.dragStop(_dragElement, ev, ui);
_dragElement = null;
}
});
}
}
;;
function Header(calendar, options) {
var t = this;
// exports
t.render = render;
t.destroy = destroy;
t.updateTitle = updateTitle;
t.activateButton = activateButton;
t.deactivateButton = deactivateButton;
t.disableButton = disableButton;
t.enableButton = enableButton;
// locals
var element = $([]);
var tm;
function render() {
tm = options.theme ? 'ui' : 'fc';
var sections = options.header;
if (sections) {
element = $("<table class='fc-header' style='width:100%'/>")
.append(
$("<tr/>")
.append(renderSection('left'))
.append(renderSection('center'))
.append(renderSection('right'))
);
return element;
}
}
function destroy() {
element.remove();
}
function renderSection(position) {
var e = $("<td class='fc-header-" + position + "'/>");
var buttonStr = options.header[position];
if (buttonStr) {
$.each(buttonStr.split(' '), function(i) {
if (i > 0) {
e.append("<span class='fc-header-space'/>");
}
var prevButton;
$.each(this.split(','), function(j, buttonName) {
if (buttonName == 'title') {
e.append("<span class='fc-header-title'><h2> </h2></span>");
if (prevButton) {
prevButton.addClass(tm + '-corner-right');
}
prevButton = null;
}else{
var buttonClick;
if (calendar[buttonName]) {
buttonClick = calendar[buttonName]; // calendar method
}
else if (fcViews[buttonName]) {
buttonClick = function() {
button.removeClass(tm + '-state-hover'); // forget why
calendar.changeView(buttonName);
};
}
if (buttonClick) {
var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here?
var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here?
var button = $(
"<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
(icon ?
"<span class='fc-icon-wrap'>" +
"<span class='ui-icon ui-icon-" + icon + "'/>" +
"</span>" :
text
) +
"</span>"
)
.click(function() {
if (!button.hasClass(tm + '-state-disabled')) {
buttonClick();
}
})
.mousedown(function() {
button
.not('.' + tm + '-state-active')
.not('.' + tm + '-state-disabled')
.addClass(tm + '-state-down');
})
.mouseup(function() {
button.removeClass(tm + '-state-down');
})
.hover(
function() {
button
.not('.' + tm + '-state-active')
.not('.' + tm + '-state-disabled')
.addClass(tm + '-state-hover');
},
function() {
button
.removeClass(tm + '-state-hover')
.removeClass(tm + '-state-down');
}
)
.appendTo(e);
disableTextSelection(button);
if (!prevButton) {
button.addClass(tm + '-corner-left');
}
prevButton = button;
}
}
});
if (prevButton) {
prevButton.addClass(tm + '-corner-right');
}
});
}
return e;
}
function updateTitle(html) {
element.find('h2')
.html(html);
}
function activateButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.addClass(tm + '-state-active');
}
function deactivateButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.removeClass(tm + '-state-active');
}
function disableButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.addClass(tm + '-state-disabled');
}
function enableButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.removeClass(tm + '-state-disabled');
}
}
;;
fc.sourceNormalizers = [];
fc.sourceFetchers = [];
var ajaxDefaults = {
dataType: 'json',
cache: false
};
var eventGUID = 1;
function EventManager(options, _sources) {
var t = this;
// exports
t.isFetchNeeded = isFetchNeeded;
t.fetchEvents = fetchEvents;
t.addEventSource = addEventSource;
t.removeEventSource = removeEventSource;
t.updateEvent = updateEvent;
t.renderEvent = renderEvent;
t.removeEvents = removeEvents;
t.clientEvents = clientEvents;
t.normalizeEvent = normalizeEvent;
t.getSourcesCount = getSourcesCount;
t.getSourceLabel = getSourceLabel;
t.getSources = getSources;
t.getSourceKey = getSourceKey;
// imports
var trigger = t.trigger;
var getView = t.getView;
var reportEvents = t.reportEvents;
// locals
var stickySource = { events: [] };
var sources = [ stickySource ];
var rangeStart, rangeEnd;
var currentFetchID = 0;
var pendingSourceCnt = 0;
var loadingLevel = 0;
var cache = [];
for (var i=0; i<_sources.length; i++) {
_addEventSource(_sources[i]);
}
/* Fetching
-----------------------------------------------------------------------------*/
function isFetchNeeded(start, end) {
return !rangeStart || start < rangeStart || end > rangeEnd;
}
function fetchEvents(start, end) {
rangeStart = start;
rangeEnd = end;
cache = [];
var fetchID = ++currentFetchID;
var len = sources.length;
pendingSourceCnt = len;
for (var i=0; i<len; i++) {
fetchEventSource(sources[i], fetchID);
}
}
function fetchEventSource(source, fetchID) {
_fetchEventSource(source, function(events) {
if (fetchID == currentFetchID) {
if (events) {
if (options.eventDataTransform) {
events = $.map(events, options.eventDataTransform);
}
if (source.eventDataTransform) {
events = $.map(events, source.eventDataTransform);
}
// TODO: this technique is not ideal for static array event sources.
// For arrays, we'll want to process all events right in the beginning, then never again.
for (var i=0; i<events.length; i++) {
events[i].source = source;
normalizeEvent(events[i]);
}
cache = cache.concat(events);
}
pendingSourceCnt--;
if (!pendingSourceCnt) {
reportEvents(cache);
}
}
});
}
function _fetchEventSource(source, callback) {
var i;
var fetchers = fc.sourceFetchers;
var res;
for (i=0; i<fetchers.length; i++) {
res = fetchers[i](source, rangeStart, rangeEnd, callback);
if (res === true) {
// the fetcher is in charge. made its own async request
return;
}
else if (typeof res == 'object') {
// the fetcher returned a new source. process it
_fetchEventSource(res, callback);
return;
}
}
var events = source.events;
if (events) {
if ($.isFunction(events)) {
pushLoading();
events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) {
callback(events);
popLoading();
});
}
else if ($.isArray(events)) {
callback(events);
}
else {
callback();
}
}else{
var url = source.url;
if (url) {
var success = source.success;
var error = source.error;
var complete = source.complete;
// retrieve any outbound GET/POST $.ajax data from the options
var customData;
if ($.isFunction(source.data)) {
// supplied as a function that returns a key/value object
customData = source.data();
}
else {
// supplied as a straight key/value object
customData = source.data;
}
// use a copy of the custom data so we can modify the parameters
// and not affect the passed-in object.
var data = $.extend({}, customData || {});
var startParam = firstDefined(source.startParam, options.startParam);
var endParam = firstDefined(source.endParam, options.endParam);
if (startParam) {
data[startParam] = Math.round(+rangeStart / 1000);
}
if (endParam) {
data[endParam] = Math.round(+rangeEnd / 1000);
}
pushLoading();
$.ajax($.extend({}, ajaxDefaults, source, {
data: data,
success: function(events) {
events = events || [];
var res = applyAll(success, this, arguments);
if ($.isArray(res)) {
events = res;
}
callback(events);
},
error: function() {
applyAll(error, this, arguments);
callback();
},
complete: function() {
applyAll(complete, this, arguments);
popLoading();
}
}));
}else{
callback();
}
}
}
/* Sources
-----------------------------------------------------------------------------*/
function addEventSource(source) {
source = _addEventSource(source);
if (source) {
pendingSourceCnt++;
fetchEventSource(source, currentFetchID); // will eventually call reportEvents
}
}
function _addEventSource(source) {
if ($.isFunction(source) || $.isArray(source)) {
source = { events: source };
}
else if (typeof source == 'string') {
source = { url: source };
}
if (typeof source == 'object') {
normalizeSource(source);
sources.push(source);
return source;
}
}
function removeEventSource(source) {
sources = $.grep(sources, function(src) {
return !isSourcesEqual(src, source);
});
// remove all client events from that source
cache = $.grep(cache, function(e) {
return !isSourcesEqual(e.source, source);
});
reportEvents(cache);
}
/* Manipulation
-----------------------------------------------------------------------------*/
function updateEvent(event) { // update an existing event
var i, len = cache.length, e,
defaultEventEnd = getView().defaultEventEnd, // getView???
startDelta = event.start - event._start,
endDelta = event.end ?
(event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end
: 0; // was null and event was just resized
for (i=0; i<len; i++) {
e = cache[i];
if (e._id == event._id && e != event) {
e.start = new Date(+e.start + startDelta);
if (event.end) {
if (e.end) {
e.end = new Date(+e.end + endDelta);
}else{
e.end = new Date(+defaultEventEnd(e) + endDelta);
}
}else{
e.end = null;
}
e.title = event.title;
e.url = event.url;
e.allDay = event.allDay;
e.className = event.className;
e.editable = event.editable;
e.color = event.color;
e.backgroundColor = event.backgroundColor;
e.borderColor = event.borderColor;
e.textColor = event.textColor;
normalizeEvent(e);
}
}
normalizeEvent(event);
reportEvents(cache);
}
function renderEvent(event, stick) {
normalizeEvent(event);
if (!event.source) {
if (stick) {
stickySource.events.push(event);
event.source = stickySource;
}
cache.push(event);
}
reportEvents(cache);
}
function removeEvents(filter) {
if (!filter) { // remove all
cache = [];
// clear all array sources
for (var i=0; i<sources.length; i++) {
if ($.isArray(sources[i].events)) {
sources[i].events = [];
}
}
}else{
if (!$.isFunction(filter)) { // an event ID
var id = filter + '';
filter = function(e) {
return e._id == id;
};
}
cache = $.grep(cache, filter, true);
// remove events from array sources
for (var i=0; i<sources.length; i++) {
if ($.isArray(sources[i].events)) {
sources[i].events = $.grep(sources[i].events, filter, true);
}
}
}
reportEvents(cache);
}
function clientEvents(filter) {
if ($.isFunction(filter)) {
return $.grep(cache, filter);
}
else if (filter) { // an event ID
filter += '';
return $.grep(cache, function(e) {
return e._id == filter;
});
}
return cache; // else, return all
}
/* Loading State
-----------------------------------------------------------------------------*/
function pushLoading() {
if (!loadingLevel++) {
trigger('loading', null, true, getView());
}
}
function popLoading() {
if (!--loadingLevel) {
trigger('loading', null, false, getView());
}
}
/* Event Normalization
-----------------------------------------------------------------------------*/
function normalizeEvent(event) {
var source = event.source || {};
var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone);
event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + '');
if (event.date) {
if (!event.start) {
event.start = event.date;
}
delete event.date;
}
event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone));
event.end = parseDate(event.end, ignoreTimezone);
if (event.end && event.end <= event.start) {
event.end = null;
}
event._end = event.end ? cloneDate(event.end) : null;
if (event.allDay === undefined) {
event.allDay = firstDefined(source.allDayDefault, options.allDayDefault);
}
if (event.isBackground === undefined) {
event.isBackground = firstDefined(source.isBackground, options.isBackground);
}
if (event.className) {
if (typeof event.className == 'string') {
event.className = event.className.split(/\s+/);
}
}else{
event.className = [];
}
// TODO: if there is no start date, return false to indicate an invalid event
}
/* Utils
------------------------------------------------------------------------------*/
function normalizeSource(source) {
if (source.className) {
// TODO: repeat code, same code for event classNames
if (typeof source.className == 'string') {
source.className = source.className.split(/\s+/);
}
}else{
source.className = [];
}
var normalizers = fc.sourceNormalizers;
for (var i=0; i<normalizers.length; i++) {
normalizers[i](source);
}
}
function isSourcesEqual(source1, source2) {
return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
}
function getSourcePrimitive(source) {
return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
}
function getSourcesCount() {
return sources.length - 1; // -1 is because of initialization of sources var - first item in sources array is object with empty events array
}
function getSourceLabel(i) {
i++; //because of initialization of sources var - first item in sources array is object with empty events array
if (sources.length < i)
return null;
return sources[i].label;
}
function getSources() {
return $.grep(sources, function(n, i){return (i > 0);}); //do not return 0 indexed source - it's empty source
}
function getSourceKey(source) {
for (var key in sources) {
if (isSourcesEqual(sources[key], source)) return key - 1;
}
return -1;
}
}
;;
fc.addDays = addDays;
fc.cloneDate = cloneDate;
fc.parseDate = parseDate;
fc.parseISO8601 = parseISO8601;
fc.parseTime = parseTime;
fc.formatDate = formatDate;
fc.formatDates = formatDates;
/* Date Math
-----------------------------------------------------------------------------*/
var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
DAY_MS = 86400000,
HOUR_MS = 3600000,
MINUTE_MS = 60000;
function addYears(d, n, keepTime) {
d.setFullYear(d.getFullYear() + n);
if (!keepTime) {
clearTime(d);
}
return d;
}
function addMonths(d, n, keepTime) { // prevents day overflow/underflow
if (+d) { // prevent infinite looping on invalid dates
var m = d.getMonth() + n,
check = cloneDate(d);
check.setDate(1);
check.setMonth(m);
d.setMonth(m);
if (!keepTime) {
clearTime(d);
}
while (d.getMonth() != check.getMonth()) {
d.setDate(d.getDate() + (d < check ? 1 : -1));
}
}
return d;
}
function addDays(d, n, keepTime) { // deals with daylight savings
if (+d) {
var dd = d.getDate() + n,
check = cloneDate(d);
check.setHours(9); // set to middle of day
check.setDate(dd);
d.setDate(dd);
if (!keepTime) {
clearTime(d);
}
fixDate(d, check);
}
return d;
}
function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes
if (+d) { // prevent infinite looping on invalid dates
while (d.getDate() != check.getDate()) {
d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS);
}
}
}
function addMinutes(d, n) {
d.setMinutes(d.getMinutes() + n);
return d;
}
function clearTime(d) {
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d;
}
function cloneDate(d, dontKeepTime) {
if (dontKeepTime) {
return clearTime(new Date(+d));
}
return new Date(+d);
}
function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1
var i=0, d;
do {
d = new Date(1970, i++, 1);
} while (d.getHours()); // != 0
return d;
}
function dayDiff(d1, d2) { // d1 - d2
return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS);
}
function setYMD(date, y, m, d) {
if (y !== undefined && y != date.getFullYear()) {
date.setDate(1);
date.setMonth(0);
date.setFullYear(y);
}
if (m !== undefined && m != date.getMonth()) {
date.setDate(1);
date.setMonth(m);
}
if (d !== undefined) {
date.setDate(d);
}
}
/* Date Parsing
-----------------------------------------------------------------------------*/
function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true
if (typeof s == 'object') { // already a Date object
return s;
}
if (typeof s == 'number') { // a UNIX timestamp
return new Date(s * 1000);
}
if (typeof s == 'string') {
if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp
return new Date(parseFloat(s) * 1000);
}
if (ignoreTimezone === undefined) {
ignoreTimezone = true;
}
return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null);
}
// TODO: never return invalid dates (like from new Date(<string>)), return null instead
return null;
}
function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false
// derived from http://delete.me.uk/2005/03/iso8601.html
// TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html
var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);
if (!m) {
return null;
}
var date = new Date(m[1], 0, 1);
if (ignoreTimezone || !m[13]) {
var check = new Date(m[1], 0, 1, 9, 0);
if (m[3]) {
date.setMonth(m[3] - 1);
check.setMonth(m[3] - 1);
}
if (m[5]) {
date.setDate(m[5]);
check.setDate(m[5]);
}
fixDate(date, check);
if (m[7]) {
date.setHours(m[7]);
}
if (m[8]) {
date.setMinutes(m[8]);
}
if (m[10]) {
date.setSeconds(m[10]);
}
if (m[12]) {
date.setMilliseconds(Number("0." + m[12]) * 1000);
}
fixDate(date, check);
}else{
date.setUTCFullYear(
m[1],
m[3] ? m[3] - 1 : 0,
m[5] || 1
);
date.setUTCHours(
m[7] || 0,
m[8] || 0,
m[10] || 0,
m[12] ? Number("0." + m[12]) * 1000 : 0
);
if (m[14]) {
var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0);
offset *= m[15] == '-' ? 1 : -1;
date = new Date(+date + (offset * 60 * 1000));
}
}
return date;
}
function parseTime(s) { // returns minutes since start of day
if (typeof s == 'number') { // an hour
return s * 60;
}
if (typeof s == 'object') { // a Date object
return s.getHours() * 60 + s.getMinutes();
}
var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/);
if (m) {
var h = parseInt(m[1], 10);
if (m[3]) {
h %= 12;
if (m[3].toLowerCase().charAt(0) == 'p') {
h += 12;
}
}
return h * 60 + (m[2] ? parseInt(m[2], 10) : 0);
}
}
/* Date Formatting
-----------------------------------------------------------------------------*/
// TODO: use same function formatDate(date, [date2], format, [options])
function formatDate(date, format, options) {
return formatDates(date, null, format, options);
}
function formatDates(date1, date2, format, options) {
options = options || defaults;
var date = date1,
otherDate = date2,
i, len = format.length, c,
i2, formatter,
res = '';
for (i=0; i<len; i++) {
c = format.charAt(i);
if (c == "'") {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == "'") {
if (date) {
if (i2 == i+1) {
res += "'";
}else{
res += format.substring(i+1, i2);
}
i = i2;
}
break;
}
}
}
else if (c == '(') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ')') {
var subres = formatDate(date, format.substring(i+1, i2), options);
if (parseInt(subres.replace(/\D/, ''), 10)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '[') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ']') {
var subformat = format.substring(i+1, i2);
var subres = formatDate(date, subformat, options);
if (subres != formatDate(otherDate, subformat, options)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '{') {
date = date2;
otherDate = date1;
}
else if (c == '}') {
date = date1;
otherDate = date2;
}
else {
for (i2=len; i2>i; i2--) {
if (formatter = dateFormatters[format.substring(i, i2)]) {
if (date) {
res += formatter(date, options);
}
i = i2 - 1;
break;
}
}
if (i2 == i) {
if (date) {
res += c;
}
}
}
}
return res;
};
var dateFormatters = {
s : function(d) { return d.getSeconds() },
ss : function(d) { return zeroPad(d.getSeconds()) },
m : function(d) { return d.getMinutes() },
mm : function(d) { return zeroPad(d.getMinutes()) },
h : function(d) { return d.getHours() % 12 || 12 },
hh : function(d) { return zeroPad(d.getHours() % 12 || 12) },
H : function(d) { return d.getHours() },
HH : function(d) { return zeroPad(d.getHours()) },
d : function(d) { return d.getDate() },
dd : function(d) { return zeroPad(d.getDate()) },
ddd : function(d,o) { return o.dayNamesShort[d.getDay()] },
dddd: function(d,o) { return o.dayNames[d.getDay()] },
M : function(d) { return d.getMonth() + 1 },
MM : function(d) { return zeroPad(d.getMonth() + 1) },
MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] },
MMMM: function(d,o) { return o.monthNames[d.getMonth()] },
yy : function(d) { return (d.getFullYear()+'').substring(2) },
yyyy: function(d) { return d.getFullYear() },
t : function(d) { return d.getHours() < 12 ? 'a' : 'p' },
tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' },
T : function(d) { return d.getHours() < 12 ? 'A' : 'P' },
TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' },
u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") },
S : function(d) {
var date = d.getDate();
if (date > 10 && date < 20) {
return 'th';
}
return ['st', 'nd', 'rd'][date%10-1] || 'th';
},
w : function(d, o) { // local
return o.weekNumberCalculation(d);
},
W : function(d) { // ISO
return iso8601Week(d);
}
};
fc.dateFormatters = dateFormatters;
/* thanks jQuery UI (https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js)
*
* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* `date` - the date to get the week for
* `number` - the number of the week within the year that contains this date
*/
function iso8601Week(date) {
var time;
var checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
;;
fc.applyAll = applyAll;
/* Event Date Math
-----------------------------------------------------------------------------*/
function exclEndDay(event) {
if (event.end) {
return _exclEndDay(event.end, event.allDay);
}else{
return addDays(cloneDate(event.start), 1);
}
}
function _exclEndDay(end, allDay) {
end = cloneDate(end);
return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end);
// why don't we check for seconds/ms too?
}
/* Event Element Binding
-----------------------------------------------------------------------------*/
function lazySegBind(container, segs, bindHandlers) {
container.unbind('mouseover').mouseover(function(ev) {
var parent=ev.target, e,
i, seg;
while (parent != this) {
e = parent;
parent = parent.parentNode;
}
if ((i = e._fci) !== undefined) {
e._fci = undefined;
seg = segs[i];
bindHandlers(seg.event, seg.element, seg);
$(ev.target).trigger(ev);
}
ev.stopPropagation();
});
}
/* Element Dimensions
-----------------------------------------------------------------------------*/
function setOuterWidth(element, width, includeMargins) {
for (var i=0, e; i<element.length; i++) {
e = $(element[i]);
e.width(Math.max(0, width - hsides(e, includeMargins)));
}
}
function setOuterHeight(element, height, includeMargins) {
for (var i=0, e; i<element.length; i++) {
e = $(element[i]);
e.height(Math.max(0, height - vsides(e, includeMargins)));
}
}
function hsides(element, includeMargins) {
return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
}
function hpadding(element) {
return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) +
(parseFloat($.css(element[0], 'paddingRight', true)) || 0);
}
function hmargins(element) {
return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) +
(parseFloat($.css(element[0], 'marginRight', true)) || 0);
}
function hborders(element) {
return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) +
(parseFloat($.css(element[0], 'borderRightWidth', true)) || 0);
}
function vsides(element, includeMargins) {
return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
}
function vpadding(element) {
return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) +
(parseFloat($.css(element[0], 'paddingBottom', true)) || 0);
}
function vmargins(element) {
return (parseFloat($.css(element[0], 'marginTop', true)) || 0) +
(parseFloat($.css(element[0], 'marginBottom', true)) || 0);
}
function vborders(element) {
return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) +
(parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0);
}
/* Misc Utils
-----------------------------------------------------------------------------*/
//TODO: arraySlice
//TODO: isFunction, grep ?
function noop() { }
function dateCompare(a, b) {
return a - b;
}
function arrayMax(a) {
return Math.max.apply(Math, a);
}
function zeroPad(n) {
return (n < 10 ? '0' : '') + n;
}
function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
if (obj[name] !== undefined) {
return obj[name];
}
var parts = name.split(/(?=[A-Z])/),
i=parts.length-1, res;
for (; i>=0; i--) {
res = obj[parts[i].toLowerCase()];
if (res !== undefined) {
return res;
}
}
return obj[''];
}
function htmlEscape(s) {
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />');
}
function disableTextSelection(element) {
element
.attr('unselectable', 'on')
.css('MozUserSelect', 'none')
.bind('selectstart.ui', function() { return false; });
}
/*
function enableTextSelection(element) {
element
.attr('unselectable', 'off')
.css('MozUserSelect', '')
.unbind('selectstart.ui');
}
*/
function markFirstLast(e) {
e.children()
.removeClass('fc-first fc-last')
.filter(':first-child')
.addClass('fc-first')
.end()
.filter(':last-child')
.addClass('fc-last');
}
function setDayID(cell, date) {
cell.each(function(i, _cell) {
_cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]);
// TODO: make a way that doesn't rely on order of classes
});
}
function getSkinCss(event, opt) {
var source = event.source || {};
var eventColor = event.color;
var sourceColor = source.color;
var optionColor = opt('eventColor');
var backgroundColor =
event.backgroundColor ||
eventColor ||
source.backgroundColor ||
sourceColor ||
opt('eventBackgroundColor') ||
optionColor;
var borderColor =
event.borderColor ||
eventColor ||
source.borderColor ||
sourceColor ||
opt('eventBorderColor') ||
optionColor;
var textColor =
event.textColor ||
source.textColor ||
opt('eventTextColor');
var statements = [];
if (backgroundColor) {
statements.push('background-color:' + backgroundColor);
}
if (borderColor) {
statements.push('border-color:' + borderColor);
}
if (textColor) {
statements.push('color:' + textColor);
}
return statements.join(';');
}
function applyAll(functions, thisObj, args) {
if ($.isFunction(functions)) {
functions = [ functions ];
}
if (functions) {
var i;
var ret;
for (i=0; i<functions.length; i++) {
ret = functions[i].apply(thisObj, args) || ret;
}
return ret;
}
}
function firstDefined() {
for (var i=0; i<arguments.length; i++) {
if (arguments[i] !== undefined) {
return arguments[i];
}
}
}
;;
fcViews.month = MonthView;
function MonthView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'month');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addMonths(date, delta);
date.setDate(1);
}
var firstDay = opt('firstDay');
var start = cloneDate(date, true);
start.setDate(1);
var end = addMonths(cloneDate(start), 1);
var visStart = cloneDate(start);
addDays(visStart, -((visStart.getDay() - firstDay + 7) % 7));
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
addDays(visEnd, (7 - visEnd.getDay() + firstDay) % 7);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
var rowCnt = Math.round(dayDiff(visEnd, visStart) / 7); // should be no need for Math.round
if (opt('weekMode') == 'fixed') {
addDays(visEnd, (6 - rowCnt) * 7); // add weeks to make up for it
rowCnt = 6;
}
t.title = formatDate(start, opt('titleFormat'));
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderBasic(rowCnt, colCnt, true);
}
}
;;
fcViews.basicWeek = BasicWeekView;
function BasicWeekView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'basicWeek');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDates = calendar.formatDates;
function render(date, delta) {
if (delta) {
addDays(date, delta * 7);
}
var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
var end = addDays(cloneDate(start), 7);
var visStart = cloneDate(start);
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
t.title = formatDates(
visStart,
addDays(cloneDate(visEnd), -1),
opt('titleFormat')
);
renderBasic(1, colCnt, false);
}
}
;;
fcViews.basicDay = BasicDayView;
function BasicDayView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'basicDay');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addDays(date, delta);
}
skipHiddenDays(date, delta < 0 ? -1 : 1);
var start = cloneDate(date, true);
var end = addDays(cloneDate(start), 1);
t.title = formatDate(date, opt('titleFormat'));
t.start = t.visStart = start;
t.end = t.visEnd = end;
renderBasic(1, 1, false);
}
}
;;
setDefaults({
weekMode: 'fixed'
});
function BasicView(element, calendar, viewName) {
var t = this;
// exports
t.renderBasic = renderBasic;
t.setHeight = setHeight;
t.setWidth = setWidth;
t.renderDayOverlay = renderDayOverlay;
t.defaultSelectionEnd = defaultSelectionEnd;
t.renderSelection = renderSelection;
t.clearSelection = clearSelection;
t.reportDayClick = reportDayClick; // for selection (kinda hacky)
t.dragStart = dragStart;
t.dragStop = dragStop;
t.defaultEventEnd = defaultEventEnd;
t.getHoverListener = function() { return hoverListener };
t.colLeft = colLeft;
t.colRight = colRight;
t.colContentLeft = colContentLeft;
t.colContentRight = colContentRight;
t.getIsCellAllDay = function() { return true };
t.allDayRow = allDayRow;
t.getRowCnt = function() { return rowCnt };
t.getColCnt = function() { return colCnt };
t.getColWidth = function() { return colWidth };
t.getDaySegmentContainer = function() { return daySegmentContainer };
// imports
View.call(t, element, calendar, viewName);
OverlayManager.call(t);
SelectionManager.call(t);
BasicEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var renderOverlay = t.renderOverlay;
var clearOverlays = t.clearOverlays;
var daySelectionMousedown = t.daySelectionMousedown;
var cellToDate = t.cellToDate;
var dateToCell = t.dateToCell;
var rangeToSegments = t.rangeToSegments;
var formatDate = calendar.formatDate;
// locals
var table;
var head;
var headCells;
var body;
var bodyRows;
var bodyCells;
var bodyFirstCells;
var firstRowCellInners;
var firstRowCellContentInners;
var daySegmentContainer;
var viewWidth;
var viewHeight;
var colWidth;
var weekNumberWidth;
var rowCnt, colCnt;
var showNumbers;
var coordinateGrid;
var hoverListener;
var colPositions;
var colContentPositions;
var tm;
var colFormat;
var showWeekNumbers;
var weekNumberTitle;
var weekNumberFormat;
/* Rendering
------------------------------------------------------------*/
disableTextSelection(element.addClass('fc-grid'));
function renderBasic(_rowCnt, _colCnt, _showNumbers) {
rowCnt = _rowCnt;
colCnt = _colCnt;
showNumbers = _showNumbers;
updateOptions();
if (!body) {
buildEventContainer();
}
buildTable();
}
function updateOptions() {
tm = opt('theme') ? 'ui' : 'fc';
colFormat = opt('columnFormat');
// week # options. (TODO: bad, logic also in other views)
showWeekNumbers = opt('weekNumbers');
weekNumberTitle = opt('weekNumberTitle');
if (opt('weekNumberCalculation') != 'iso') {
weekNumberFormat = "w";
}
else {
weekNumberFormat = "W";
}
}
function buildEventContainer() {
daySegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(element);
}
function buildTable() {
var html = buildTableHTML();
if (table) {
table.remove();
}
table = $(html).appendTo(element);
head = table.find('thead');
headCells = head.find('.fc-day-header');
body = table.find('tbody');
bodyRows = body.find('tr');
bodyCells = body.find('.fc-day');
bodyFirstCells = bodyRows.find('td:first-child');
firstRowCellInners = bodyRows.eq(0).find('.fc-day > div');
firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div');
markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
markFirstLast(bodyRows); // marks first+last td's
bodyRows.eq(0).addClass('fc-first');
bodyRows.filter(':last').addClass('fc-last');
bodyCells.each(function(i, _cell) {
var date = cellToDate(
Math.floor(i / colCnt),
i % colCnt
);
trigger('dayRender', t, date, $(_cell));
});
dayBind(bodyCells);
}
/* HTML Building
-----------------------------------------------------------*/
function buildTableHTML() {
var html =
"<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
buildHeadHTML() +
buildBodyHTML() +
"</table>";
return html;
}
function buildHeadHTML() {
var headerClass = tm + "-widget-header";
var html = '';
var col;
var date;
html += "<thead><tr>";
if (showWeekNumbers) {
html +=
"<th class='fc-week-number " + headerClass + "'>" +
htmlEscape(weekNumberTitle) +
"</th>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(0, col);
html +=
"<th class='fc-day-header fc-" + dayIDs[date.getDay()] + " " + headerClass + "'>" +
htmlEscape(formatDate(date, colFormat)) +
"</th>";
}
html += "</tr></thead>";
return html;
}
function buildBodyHTML() {
var contentClass = tm + "-widget-content";
var html = '';
var row;
var col;
var date;
html += "<tbody>";
for (row=0; row<rowCnt; row++) {
html += "<tr class='fc-week'>";
if (showWeekNumbers) {
date = cellToDate(row, 0);
html +=
"<td class='fc-week-number " + contentClass + "'>" +
"<div>" +
htmlEscape(formatDate(date, weekNumberFormat)) +
"</div>" +
"</td>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(row, col);
html += buildCellHTML(date);
}
html += "</tr>";
}
html += "</tbody>";
return html;
}
function buildCellHTML(date) {
var contentClass = tm + "-widget-content";
var month = t.start.getMonth();
var today = clearTime(new Date());
var html = '';
var classNames = [
'fc-day',
'fc-' + dayIDs[date.getDay()],
contentClass
];
if (date.getMonth() != month) {
classNames.push('fc-other-month');
}
if (+date == +today) {
classNames.push(
'fc-today',
tm + '-state-highlight'
);
}
else if (date < today) {
classNames.push('fc-past');
}
else {
classNames.push('fc-future');
}
html +=
"<td" +
" class='" + classNames.join(' ') + "'" +
" data-date='" + formatDate(date, 'yyyy-MM-dd') + "'" +
">" +
"<div>";
if (showNumbers) {
html += "<div class='fc-day-number'>" + date.getDate() + "</div>";
}
html +=
"<div class='fc-day-content'>" +
"<div style='position:relative'> </div>" +
"</div>" +
"</div>" +
"</td>";
return html;
}
/* Dimensions
-----------------------------------------------------------*/
function setHeight(height) {
viewHeight = height;
var bodyHeight = viewHeight - head.height();
var rowHeight;
var rowHeightLast;
var cell;
if (opt('weekMode') == 'variable') {
rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
}else{
rowHeight = Math.floor(bodyHeight / rowCnt);
rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
}
bodyFirstCells.each(function(i, _cell) {
if (i < rowCnt) {
cell = $(_cell);
cell.find('> div').css(
'min-height',
(i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
);
}
});
}
function setWidth(width) {
viewWidth = width;
colPositions.clear();
colContentPositions.clear();
weekNumberWidth = 0;
if (showWeekNumbers) {
weekNumberWidth = head.find('th.fc-week-number').outerWidth();
}
colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt);
setOuterWidth(headCells.slice(0, -1), colWidth);
}
/* Day clicking and binding
-----------------------------------------------------------*/
function dayBind(days) {
days.click(dayClick)
.mousedown(daySelectionMousedown);
}
function dayClick(ev) {
if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
var date = parseISO8601($(this).data('date'));
trigger('dayClick', this, date, true, ev);
}
}
/* Semi-transparent Overlay Helpers
------------------------------------------------------*/
// TODO: should be consolidated with AgendaView's methods
function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
if (refreshCoordinateGrid) {
coordinateGrid.build();
}
var segments = rangeToSegments(overlayStart, overlayEnd);
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
dayBind(
renderCellOverlay(
segment.row,
segment.leftCol,
segment.row,
segment.rightCol
)
);
}
}
function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
return renderOverlay(rect, element);
}
/* Selection
-----------------------------------------------------------------------*/
function defaultSelectionEnd(startDate, allDay) {
return cloneDate(startDate);
}
function renderSelection(startDate, endDate, allDay) {
renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time???
}
function clearSelection() {
clearOverlays();
}
function reportDayClick(date, allDay, ev) {
var cell = dateToCell(date);
var _element = bodyCells[cell.row*colCnt + cell.col];
trigger('dayClick', _element, date, allDay, ev);
}
/* External Dragging
-----------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
}
}, ev);
}
function dragStop(_dragElement, ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
if (cell) {
var d = cellToDate(cell);
trigger('drop', _dragElement, d, true, ev, ui);
}
}
/* Utilities
--------------------------------------------------------*/
function defaultEventEnd(event) {
return cloneDate(event.start);
}
coordinateGrid = new CoordinateGrid(function(rows, cols) {
var e, n, p;
headCells.each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
cols[i] = p;
});
p[1] = n + e.outerWidth();
bodyRows.each(function(i, _e) {
if (i < rowCnt) {
e = $(_e);
n = e.offset().top;
if (i) {
p[1] = n;
}
p = [n];
rows[i] = p;
}
});
p[1] = n + e.outerHeight();
});
hoverListener = new HoverListener(coordinateGrid);
colPositions = new HorizontalPositionCache(function(col) {
return firstRowCellInners.eq(col);
});
colContentPositions = new HorizontalPositionCache(function(col) {
return firstRowCellContentInners.eq(col);
});
function colLeft(col) {
return colPositions.left(col);
}
function colRight(col) {
return colPositions.right(col);
}
function colContentLeft(col) {
return colContentPositions.left(col);
}
function colContentRight(col) {
return colContentPositions.right(col);
}
function allDayRow(i) {
return bodyRows.eq(i);
}
}
;;
function BasicEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.clearEvents = clearEvents;
// imports
DayEventRenderer.call(t);
function renderEvents(events, modifiedEventId) {
t.renderDayEvents(events, modifiedEventId);
}
function clearEvents() {
t.getDaySegmentContainer().empty();
}
// TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div
}
;;
fcViews.agendaWeek = AgendaWeekView;
function AgendaWeekView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
AgendaView.call(t, element, calendar, 'agendaWeek');
var opt = t.opt;
var renderAgenda = t.renderAgenda;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDates = calendar.formatDates;
function render(date, delta) {
if (delta) {
addDays(date, delta * 7);
}
var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
var end = addDays(cloneDate(start), 7);
var visStart = cloneDate(start);
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
t.title = formatDates(
visStart,
addDays(cloneDate(visEnd), -1),
opt('titleFormat')
);
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderAgenda(colCnt);
}
}
;;
fcViews.agendaDay = AgendaDayView;
function AgendaDayView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
AgendaView.call(t, element, calendar, 'agendaDay');
var opt = t.opt;
var renderAgenda = t.renderAgenda;
var skipHiddenDays = t.skipHiddenDays;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addDays(date, delta);
}
skipHiddenDays(date, delta < 0 ? -1 : 1);
var start = cloneDate(date, true);
var end = addDays(cloneDate(start), 1);
t.title = formatDate(date, opt('titleFormat'));
t.start = t.visStart = start;
t.end = t.visEnd = end;
renderAgenda(1);
}
}
;;
setDefaults({
allDaySlot: true,
allDayText: 'all-day',
firstHour: 6,
slotMinutes: 30,
defaultEventMinutes: 120,
axisFormat: 'h(:mm)tt',
timeFormat: {
agenda: 'h:mm{ - h:mm}'
},
dragOpacity: {
agenda: .5
},
minTime: 0,
maxTime: 24,
slotEventOverlap: true
});
// TODO: make it work in quirks mode (event corners, all-day height)
// TODO: test liquid width, especially in IE6
function AgendaView(element, calendar, viewName) {
var t = this;
// exports
t.renderAgenda = renderAgenda;
t.setWidth = setWidth;
t.setHeight = setHeight;
t.afterRender = afterRender;
t.defaultEventEnd = defaultEventEnd;
t.timePosition = timePosition;
t.getIsCellAllDay = getIsCellAllDay;
t.allDayRow = getAllDayRow;
t.getCoordinateGrid = function() { return coordinateGrid }; // specifically for AgendaEventRenderer
t.getHoverListener = function() { return hoverListener };
t.colLeft = colLeft;
t.colRight = colRight;
t.colContentLeft = colContentLeft;
t.colContentRight = colContentRight;
t.getDaySegmentContainer = function() { return daySegmentContainer };
t.getSlotSegmentContainer = function() { return slotSegmentContainer };
t.getMinMinute = function() { return minMinute };
t.getMaxMinute = function() { return maxMinute };
t.getSlotContainer = function() { return slotContainer };
t.getRowCnt = function() { return 1 };
t.getColCnt = function() { return colCnt };
t.getColWidth = function() { return colWidth };
t.getSrcColWidth = function() { return srcColWidth };
t.getSnapHeight = function() { return snapHeight };
t.getSnapMinutes = function() { return snapMinutes };
t.defaultSelectionEnd = defaultSelectionEnd;
t.renderDayOverlay = renderDayOverlay;
t.renderSelection = renderSelection;
t.clearSelection = clearSelection;
t.reportDayClick = reportDayClick; // selection mousedown hack
t.dragStart = dragStart;
t.dragStop = dragStop;
// imports
View.call(t, element, calendar, viewName);
OverlayManager.call(t);
SelectionManager.call(t);
AgendaEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var renderOverlay = t.renderOverlay;
var clearOverlays = t.clearOverlays;
var reportSelection = t.reportSelection;
var unselect = t.unselect;
var daySelectionMousedown = t.daySelectionMousedown;
var slotSegHtml = t.slotSegHtml;
var cellToDate = t.cellToDate;
var dateToCell = t.dateToCell;
var rangeToSegments = t.rangeToSegments;
var formatDate = calendar.formatDate;
// locals
var dayTable;
var dayHead;
var dayHeadCells;
var sourcesHeadCells;
var dayBody;
var dayBodyCells;
var dayBodyCellInners;
var dayBodyCellContentInners;
var dayBodyFirstCell;
var dayBodyFirstCellStretcher;
var slotLayer;
var daySegmentContainer;
var allDayTable;
var allDayRow;
var slotScroller;
var slotContainer;
var slotSegmentContainer;
var slotTable;
var selectionHelper;
var viewWidth;
var viewHeight;
var axisWidth;
var colWidth;
var srcColWidth;
var gutterWidth;
var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
var snapMinutes;
var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4)
var snapHeight; // holds the pixel hight of a "selection" slot
var colCnt;
var slotCnt;
var coordinateGrid;
var hoverListener;
var colPositions;
var colContentPositions;
var slotTopCache = {};
var tm;
var rtl;
var minMinute, maxMinute;
var colFormat;
var showWeekNumbers;
var weekNumberTitle;
var weekNumberFormat;
var splitBySources;
/* Rendering
-----------------------------------------------------------------------------*/
disableTextSelection(element.addClass('fc-agenda'));
function renderAgenda(c) {
colCnt = c;
updateOptions();
if (!dayTable) { // first time rendering?
buildSkeleton(); // builds day table, slot area, events containers
}
else {
buildDayTable(); // rebuilds day table
}
}
function updateOptions() {
tm = opt('theme') ? 'ui' : 'fc';
rtl = opt('isRTL')
minMinute = parseTime(opt('minTime'));
maxMinute = parseTime(opt('maxTime'));
colFormat = opt('columnFormat');
// week # options. (TODO: bad, logic also in other views)
showWeekNumbers = opt('weekNumbers');
weekNumberTitle = opt('weekNumberTitle');
splitBySources = opt('splitBySources');
if (opt('weekNumberCalculation') != 'iso') {
weekNumberFormat = "w";
}
else {
weekNumberFormat = "W";
}
snapMinutes = opt('snapMinutes') || opt('slotMinutes');
}
/* Build DOM
-----------------------------------------------------------------------*/
function buildSkeleton() {
var headerClass = tm + "-widget-header";
var contentClass = tm + "-widget-content";
var s;
var d;
var i;
var maxd;
var minutes;
var slotNormal = opt('slotMinutes') % 15 == 0;
buildDayTable();
slotLayer =
$("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
.appendTo(element);
if (opt('allDaySlot')) {
daySegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(slotLayer);
s =
"<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
"<tr>" +
"<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" +
"<td>" +
"<div class='fc-day-content'><div style='position:relative'/></div>" +
"</td>" +
"<th class='" + headerClass + " fc-agenda-gutter'> </th>" +
"</tr>" +
"</table>";
allDayTable = $(s).appendTo(slotLayer);
allDayRow = allDayTable.find('tr');
dayBind(allDayRow.find('td'));
slotLayer.append(
"<div class='fc-agenda-divider " + headerClass + "'>" +
"<div class='fc-agenda-divider-inner'/>" +
"</div>"
);
}else{
daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
}
slotScroller =
$("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
.appendTo(slotLayer);
slotContainer =
$("<div style='position:relative;width:100%;overflow:hidden'/>")
.appendTo(slotScroller);
slotSegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(slotContainer);
s =
"<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
"<tbody>";
d = zeroDate();
maxd = addMinutes(cloneDate(d), maxMinute);
addMinutes(d, minMinute);
slotCnt = 0;
for (i=0; d < maxd; i++) {
minutes = d.getMinutes();
s +=
"<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
"<th class='fc-agenda-axis " + headerClass + "'>" +
((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') +
"</th>" +
"<td class='" + contentClass + "'>" +
"<div style='position:relative'> </div>" +
"</td>" +
"</tr>";
addMinutes(d, opt('slotMinutes'));
slotCnt++;
}
s +=
"</tbody>" +
"</table>";
slotTable = $(s).appendTo(slotContainer);
slotBind(slotTable.find('td'));
}
/* Build Day Table
-----------------------------------------------------------------------*/
function buildDayTable() {
var html = buildDayTableHTML();
if (dayTable) {
dayTable.remove();
}
dayTable = $(html).appendTo(element);
dayHead = dayTable.find('thead');
dayHeadCells = dayHead.find('th').not('.fc-source, .fc-agenda-axis, .fc-agenda-gutter'); // exclude gutter
sourcesHeadCells = dayHead.find('th.fc-source');
dayBody = dayTable.find('tbody');
dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter
dayBodyCellInners = dayBodyCells.find('> div');
dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div');
dayBodyFirstCell = dayBodyCells.eq(0);
dayBodyFirstCellStretcher = dayBodyCellInners.eq(0);
markFirstLast(dayHead.add(dayHead.find('tr')));
markFirstLast(dayBody.add(dayBody.find('tr')));
// TODO: now that we rebuild the cells every time, we should call dayRender
}
function buildDayTableHTML() {
var html =
"<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
buildDayTableHeadHTML() +
buildDayTableBodyHTML() +
"</table>";
return html;
}
function buildDayTableHeadHTML() {
var headerClass = tm + "-widget-header";
var date;
var html = '';
var weekText;
var col;
var sourcesCount = calendar.getSourcesCount();
var colSpan = splitBySources ? ' colspan="'+sourcesCount+'"' : '';
var rowSpan = splitBySources ? ' rowspan="2"' : '';
html +=
"<thead>" +
"<tr>";
if (showWeekNumbers) {
date = cellToDate(0, 0);
weekText = formatDate(date, weekNumberFormat);
if (rtl) {
weekText += weekNumberTitle;
}
else {
weekText = weekNumberTitle + weekText;
}
html +=
"<th class='fc-agenda-axis fc-week-number " + headerClass + "' " + rowSpan + ">" +
htmlEscape(weekText) +
"</th>";
}
else {
html += "<th class='fc-agenda-axis " + headerClass + "' " + rowSpan + "> </th>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(0, col);
html +=
"<th class='fc-" + dayIDs[date.getDay()] + " fc-col" + col + ' ' + headerClass + "' " + colSpan + " >" +
htmlEscape(formatDate(date, colFormat)) +
"</th>";
}
if (splitBySources) {
html +=
"<th class='fc-agenda-gutter " + headerClass + "'> </th>" +
"</tr>";
for (var i = 0; i < colCnt * sourcesCount; i++) {
var sourceId = i % sourcesCount;
html += "<th class='fc- fc-source " + headerClass + "' ><div class='outer'><div class='inner'>"+
calendar.getSourceLabel(sourceId)+"</div></div></th>"; // fc- needed for setDayID
}
}
html +=
"<th class='fc-agenda-gutter " + headerClass + "'> </th>" +
"</tr>" +
"</thead>";
return html;
}
function buildDayTableBodyHTML() {
var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called
var contentClass = tm + "-widget-content";
var date;
var today = clearTime(new Date());
var col;
var cellsHTML;
var cellHTML;
var classNames;
var html = '';
var sourcesCount = calendar.getSourcesCount();
html +=
"<tbody>" +
"<tr>" +
"<th class='fc-agenda-axis " + headerClass + "'> </th>";
cellsHTML = '';
for (col=0; col<colCnt * (splitBySources ? sourcesCount : 1); col++) {
date = cellToDate(0, parseInt(col / (splitBySources ? sourcesCount : 1)));
classNames = [
'fc-col' + col,
'fc-' + dayIDs[date.getDay()],
contentClass
];
if (+date == +today) {
classNames.push(
tm + '-state-highlight',
'fc-today'
);
}
else if (date < today) {
classNames.push('fc-past');
}
else {
classNames.push('fc-future');
}
cellHTML =
"<td class='" + classNames.join(' ') + "'>" +
"<div>" +
"<div class='fc-day-content'>" +
"<div style='position:relative'> </div>" +
"</div>" +
"</div>" +
"</td>";
cellsHTML += cellHTML;
}
html += cellsHTML;
html +=
"<td class='fc-agenda-gutter " + contentClass + "'> </td>" +
"</tr>" +
"</tbody>";
return html;
}
// TODO: data-date on the cells
/* Dimensions
-----------------------------------------------------------------------*/
function setHeight(height) {
if (height === undefined) {
height = viewHeight;
}
viewHeight = height;
slotTopCache = {};
var headHeight = dayBody.position().top;
var allDayHeight = slotScroller.position().top; // including divider
var bodyHeight = Math.min( // total body height, including borders
height - headHeight, // when scrollbars
slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
);
dayBodyFirstCellStretcher
.height(bodyHeight - vsides(dayBodyFirstCell));
slotLayer.css('top', headHeight);
slotScroller.height(bodyHeight - allDayHeight - 1);
// the stylesheet guarantees that the first row has no border.
// this allows .height() to work well cross-browser.
slotHeight = slotTable.find('tr:first').height() + 1; // +1 for bottom border
snapRatio = opt('slotMinutes') / snapMinutes;
snapHeight = slotHeight / snapRatio;
}
function setWidth(width) {
viewWidth = width;
colPositions.clear();
colContentPositions.clear();
var axisFirstCells = dayHead.find('th:first');
if (allDayTable) {
axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
}
axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
axisWidth = 0;
setOuterWidth(
axisFirstCells
.width('')
.each(function(i, _cell) {
axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
}),
axisWidth
);
var gutterCells = dayTable.find('.fc-agenda-gutter');
if (allDayTable) {
gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
}
var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
gutterWidth = slotScroller.width() - slotTableWidth;
if (gutterWidth) {
setOuterWidth(gutterCells, gutterWidth);
gutterCells
.show()
.prev()
.removeClass('fc-last');
}else{
gutterCells
.hide()
.prev()
.addClass('fc-last');
}
colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
srcColWidth = Math.floor(colWidth / calendar.getSourcesCount());
setOuterWidth(dayHeadCells, colWidth);
}
/* Scrolling
-----------------------------------------------------------------------*/
function resetScroll() {
var d0 = zeroDate();
var scrollDate = cloneDate(d0);
scrollDate.setHours(opt('firstHour'));
var top = timePosition(d0, scrollDate) + 1; // +1 for the border
function scroll() {
slotScroller.scrollTop(top);
}
scroll();
setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
}
function afterRender() { // after the view has been freshly rendered and sized
resetScroll();
}
/* Slot/Day clicking and binding
-----------------------------------------------------------------------*/
function dayBind(cells) {
cells.click(slotClick)
.mousedown(daySelectionMousedown);
}
function slotBind(cells) {
cells.click(slotClick)
.mousedown(slotSelectionMousedown);
}
function slotClick(ev) {
if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
var date = cellToDate(0, col);
var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
if (rowMatch) {
var mins = parseInt(rowMatch[1]) * opt('slotMinutes');
var hours = Math.floor(mins/60);
date.setHours(hours);
date.setMinutes(mins%60 + minMinute);
trigger('dayClick', dayBodyCells[col], date, false, ev);
}else{
trigger('dayClick', dayBodyCells[col], date, true, ev);
}
}
}
/* Semi-transparent Overlay Helpers
-----------------------------------------------------*/
// TODO: should be consolidated with BasicView's methods
function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
if (refreshCoordinateGrid) {
coordinateGrid.build();
}
var segments = rangeToSegments(overlayStart, overlayEnd);
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
dayBind(
renderCellOverlay(
segment.row,
segment.leftCol,
segment.row,
segment.rightCol
)
);
}
}
function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
return renderOverlay(rect, slotLayer);
}
function renderSlotOverlay(overlayStart, overlayEnd, srcCol) {
for (var i=0; i<colCnt; i++) {
var dayStart = cellToDate(0, i);
var dayEnd = addDays(cloneDate(dayStart), 1);
var stretchStart = new Date(Math.max(dayStart, overlayStart));
var stretchEnd = new Date(Math.min(dayEnd, overlayEnd));
if (stretchStart < stretchEnd) {
var rect = coordinateGrid.rect(0, i, 0, i, slotContainer, srcCol); // only use it for horizontal coords
var top = timePosition(dayStart, stretchStart);
var bottom = timePosition(dayStart, stretchEnd);
rect.top = top;
rect.height = bottom - top;
slotBind(
renderOverlay(rect, slotContainer)
);
}
}
}
/* Coordinate Utilities
-----------------------------------------------------------------------------*/
coordinateGrid = new CoordinateGrid(function(rows, cols, sources) {
var e, n, p;
var sourcesCount = calendar.getSourcesCount();
dayHeadCells.each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
cols[i] = p;
});
p[1] = n + e.outerWidth();
sourcesHeadCells.each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
p[2] = i%sourcesCount;
sources[i] = p;
});
p[1] = n + e.outerWidth();
if (opt('allDaySlot')) {
e = allDayRow;
n = e.offset().top;
rows[0] = [n, n+e.outerHeight()];
}
var slotTableTop = slotContainer.offset().top;
var slotScrollerTop = slotScroller.offset().top;
var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
function constrain(n) {
return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
}
for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count
rows.push([
constrain(slotTableTop + snapHeight*i),
constrain(slotTableTop + snapHeight*(i+1))
]);
}
});
hoverListener = new HoverListener(coordinateGrid);
colPositions = new HorizontalPositionCache(function(col) {
return dayBodyCellInners.eq(col);
});
colContentPositions = new HorizontalPositionCache(function(col) {
return dayBodyCellContentInners.eq(col);
});
function colLeft(col, isAllDay) {
var colIndex = isAllDay && splitBySources ? col * calendar.getSourcesCount() : col;
return colPositions.left(colIndex);
}
function colContentLeft(col, isAllDay) {
var colIndex = isAllDay && splitBySources ? col * calendar.getSourcesCount() : col;
return colContentPositions.left(colIndex);
}
function colRight(col, isAllDay) {
var colIndex = isAllDay && splitBySources ? (col + 1) * calendar.getSourcesCount() - 1 : col;
return colPositions.right(colIndex);
}
function colContentRight(col, isAllDay) {
var colIndex = isAllDay && splitBySources ? (col + 1) * calendar.getSourcesCount() - 1: col;
return colContentPositions.right(colIndex);
}
function getIsCellAllDay(cell) {
return opt('allDaySlot') && !cell.row;
}
function realCellToDate(cell) { // ugh "real" ... but blame it on our abuse of the "cell" system
var d = cellToDate(0, cell.col);
var slotIndex = cell.row;
if (opt('allDaySlot')) {
slotIndex--;
}
if (slotIndex >= 0) {
addMinutes(d, minMinute + slotIndex * snapMinutes);
}
return d;
}
// get the Y coordinate of the given time on the given day (both Date objects)
function timePosition(day, time) { // both date objects. day holds 00:00 of current day
day = cloneDate(day, true);
if (time < addMinutes(cloneDate(day), minMinute)) {
return 0;
}
if (time >= addMinutes(cloneDate(day), maxMinute)) {
return slotTable.height();
}
var slotMinutes = opt('slotMinutes'),
minutes = time.getHours()*60 + time.getMinutes() - minMinute,
slotI = Math.floor(minutes / slotMinutes),
slotTop = slotTopCache[slotI];
if (slotTop === undefined) {
slotTop = slotTopCache[slotI] =
slotTable.find('tr').eq(slotI).find('td div')[0].offsetTop;
// .eq() is faster than ":eq()" selector
// [0].offsetTop is faster than .position().top (do we really need this optimization?)
// a better optimization would be to cache all these divs
}
return Math.max(0, Math.round(
slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes)
));
}
function getAllDayRow(index) {
return allDayRow;
}
function defaultEventEnd(event) {
var start = cloneDate(event.start);
if (event.allDay) {
return start;
}
return addMinutes(start, opt('defaultEventMinutes'));
}
/* Selection
---------------------------------------------------------------------------------*/
function defaultSelectionEnd(startDate, allDay) {
if (allDay) {
return cloneDate(startDate);
}
return addMinutes(cloneDate(startDate), opt('slotMinutes'));
}
function renderSelection(startDate, endDate, allDay) { // only for all-day
if (allDay) {
if (opt('allDaySlot')) {
renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true);
}
}else{
renderSlotSelection(startDate, endDate);
}
}
function renderSlotSelection(startDate, endDate, srcCol) {
var helperOption = opt('selectHelper');
coordinateGrid.build();
if (helperOption) {
var col = dateToCell(startDate).col;
if (col >= 0 && col < colCnt) { // only works when times are on same day
var rect;
if (splitBySources)
rect = coordinateGrid.rect(0, col, 0, col, slotContainer, srcCol); // only for horizontal coords
else
rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords
var top = timePosition(startDate, startDate);
var bottom = timePosition(startDate, endDate);
if (bottom > top) { // protect against selections that are entirely before or after visible range
rect.top = top;
rect.height = bottom - top;
rect.left += 2;
rect.width -= 5;
if ($.isFunction(helperOption)) {
var helperRes = helperOption(startDate, endDate);
if (helperRes) {
rect.position = 'absolute';
selectionHelper = $(helperRes)
.css(rect)
.appendTo(slotContainer);
}
}else{
rect.isStart = true; // conside rect a "seg" now
rect.isEnd = true; //
selectionHelper = $(slotSegHtml(
{
title: '',
start: startDate,
end: endDate,
className: ['fc-select-helper'],
editable: false
},
rect
));
selectionHelper.css('opacity', opt('dragOpacity'));
}
if (selectionHelper) {
slotBind(selectionHelper);
slotContainer.append(selectionHelper);
setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
setOuterHeight(selectionHelper, rect.height, true);
}
}
}
}else{
var undef;
renderSlotOverlay(startDate, endDate, splitBySources ? srcCol : undef);
}
}
function clearSelection() {
clearOverlays();
if (selectionHelper) {
selectionHelper.remove();
selectionHelper = null;
}
}
function slotSelectionMousedown(ev) {
if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
unselect(ev);
var dates;
var undef;
var sourceNo;
hoverListener.start(function(cell, origCell) {
clearSelection();
if (cell && cell.col == origCell.col && !getIsCellAllDay(cell) && (splitBySources || cell.srcCol == origCell.srcCol)) {
var d1 = realCellToDate(origCell);
var d2 = realCellToDate(cell);
dates = [
d1,
addMinutes(cloneDate(d1), snapMinutes), // calculate minutes depending on selection slot minutes
d2,
addMinutes(cloneDate(d2), snapMinutes)
].sort(dateCompare);
renderSlotSelection(dates[0], dates[3], cell.srcCol);
sourceNo = splitBySources ? cell.srcNo : undef;
}else{
dates = null;
sourceNo = splitBySources ? null : undef;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], false, ev, sourceNo);
}
reportSelection(dates[0], dates[3], false, ev, sourceNo);
}
});
}
}
function reportDayClick(date, allDay, ev) {
trigger('dayClick', dayBodyCells[dateToCell(date).col], date, allDay, ev);
}
/* External Dragging
--------------------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
if (getIsCellAllDay(cell)) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
}else{
var d1 = realCellToDate(cell);
var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes'));
renderSlotOverlay(d1, d2);
}
}
}, ev);
}
function dragStop(_dragElement, ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
if (cell) {
trigger('drop', _dragElement, realCellToDate(cell), getIsCellAllDay(cell), ev, ui);
}
}
}
;;
function AgendaEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.clearEvents = clearEvents;
t.slotSegHtml = slotSegHtml;
t.incrementDays = true;
t.draggableSlotEvent = draggableSlotEvent;
// imports
DayEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var eventEnd = t.eventEnd;
var eventElementHandlers = t.eventElementHandlers;
var setHeight = t.setHeight;
var getDaySegmentContainer = t.getDaySegmentContainer;
var getSlotSegmentContainer = t.getSlotSegmentContainer;
var getHoverListener = t.getHoverListener;
var getMaxMinute = t.getMaxMinute;
var getMinMinute = t.getMinMinute;
var timePosition = t.timePosition;
var getIsCellAllDay = t.getIsCellAllDay;
var colContentLeft = t.colContentLeft;
var colContentRight = t.colContentRight;
var cellToDate = t.cellToDate;
var getColCnt = t.getColCnt;
var getColWidth = t.getColWidth;
var getSrcColWidth = t.getSrcColWidth;
var getSnapHeight = t.getSnapHeight;
var getSnapMinutes = t.getSnapMinutes;
var getSlotContainer = t.getSlotContainer;
var reportEventElement = t.reportEventElement;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventDrop = t.eventDrop;
var eventResize = t.eventResize;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var renderDayEvents = t.renderDayEvents;
var calendar = t.calendar;
var formatDate = calendar.formatDate;
var formatDates = calendar.formatDates;
// overrides
t.draggableDayEvent = draggableDayEvent;
var splitBySources = opt('splitBySources');
/* Rendering
----------------------------------------------------------------------------*/
function renderEvents(events, modifiedEventId) {
var i, len=events.length,
dayEvents=[],
slotEvents=[];
for (i=0; i<len; i++) {
if (events[i].allDay) {
dayEvents.push(events[i]);
}else{
slotEvents.push(events[i]);
}
}
if (opt('allDaySlot')) {
renderDayEvents(dayEvents, modifiedEventId);
setHeight(); // no params means set to viewHeight
}
renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
}
function clearEvents() {
getDaySegmentContainer().empty();
getSlotSegmentContainer().empty();
}
function compileSlotSegs(events) {
var colCnt = getColCnt(),
minMinute = getMinMinute(),
maxMinute = getMaxMinute(),
d,
visEventEnds = $.map(events, slotEventEnd),
i,
j, seg,
colSegs, src,
segs = [];
var sourcesCount = opt('splitBySources') ? calendar.getSourcesCount() : 1;
for (i=0; i<colCnt; i++) {
for (src=0; src<sourcesCount; src++) {
d = cellToDate(0, i);
addMinutes(d, minMinute);
if (opt('splitBySources')) {
colSegs = sliceSegs(
events,
visEventEnds,
d,
addMinutes(cloneDate(d), maxMinute-minMinute),
src
);
} else {
colSegs = sliceSegs(
events,
visEventEnds,
d,
addMinutes(cloneDate(d), maxMinute-minMinute)
);
}
colSegs = placeSlotSegs(colSegs); // returns a new order
for (j=0; j<colSegs.length; j++) {
seg = colSegs[j];
seg.col = i * sourcesCount + src;
segs.push(seg);
}
}
}
return segs;
}
function sliceSegs(events, visEventEnds, start, end, source) {
var segs = [],
i, len=events.length, event,
eventStart, eventEnd,
segStart, segEnd,
isStart, isEnd;
for (i=0; i<len; i++) {
event = events[i];
eventStart = event.start;
eventEnd = visEventEnds[i];
var sourceKey = calendar.getSourceKey(event.source);
if (eventEnd > start && eventStart < end && (typeof source === 'undefined' || sourceKey === -1 || (splitBySources && sourceKey === source))) {
if (eventStart < start) {
segStart = cloneDate(start);
isStart = false;
}else{
segStart = eventStart;
isStart = true;
}
if (eventEnd > end) {
segEnd = cloneDate(end);
isEnd = false;
}else{
segEnd = eventEnd;
isEnd = true;
}
segs.push({
event: event,
start: segStart,
end: segEnd,
isStart: isStart,
isEnd: isEnd
});
}
}
return segs.sort(compareSlotSegs);
}
function slotEventEnd(event) {
if (event.end) {
return cloneDate(event.end);
}else{
return addMinutes(cloneDate(event.start), opt('defaultEventMinutes'));
}
}
// renders events in the 'time slots' at the bottom
// TODO: when we refactor this, when user returns `false` eventRender, don't have empty space
// TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp)
function renderSlotSegs(segs, modifiedEventId) {
var i, segCnt=segs.length, seg,
event,
top,
bottom,
columnLeft,
columnRight,
columnWidth,
width,
left,
right,
html = '',
eventElements,
eventElement,
triggerRes,
titleElement,
height,
slotSegmentContainer = getSlotSegmentContainer(),
isRTL = opt('isRTL');
// calculate position/dimensions, create html
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
top = timePosition(seg.start, seg.start);
bottom = timePosition(seg.start, seg.end);
columnLeft = colContentLeft(seg.col);
columnRight = colContentRight(seg.col);
columnWidth = columnRight - columnLeft;
// shave off space on right near scrollbars (2.5%)
// TODO: move this to CSS somehow
columnRight -= columnWidth * .025;
columnWidth = columnRight - columnLeft;
width = columnWidth * (seg.forwardCoord - seg.backwardCoord);
if (opt('slotEventOverlap')) {
// double the width while making sure resize handle is visible
// (assumed to be 20px wide)
width = Math.max(
(width - (20/2)) * 2,
width // narrow columns will want to make the segment smaller than
// the natural width. don't allow it
);
}
if (isRTL) {
right = columnRight - seg.backwardCoord * columnWidth;
left = right - width;
}
else {
left = columnLeft + seg.backwardCoord * columnWidth;
right = left + width;
}
// make sure horizontal coordinates are in bounds
left = Math.max(left, columnLeft);
right = Math.min(right, columnRight);
width = right - left;
seg.top = top;
seg.left = left;
seg.outerWidth = width;
seg.outerHeight = bottom - top;
html += slotSegHtml(event, seg);
}
slotSegmentContainer[0].innerHTML = html; // faster than html()
eventElements = slotSegmentContainer.children();
// retrieve elements, run through eventRender callback, bind event handlers
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
eventElement = $(eventElements[i]); // faster than eq()
triggerRes = trigger('eventRender', event, event, eventElement);
if (triggerRes === false) {
eventElement.remove();
}else{
if (triggerRes && triggerRes !== true) {
eventElement.remove();
eventElement = $(triggerRes)
.css({
position: 'absolute',
top: seg.top,
left: seg.left
})
.appendTo(slotSegmentContainer);
}
seg.element = eventElement;
if (event._id === modifiedEventId) {
bindSlotSeg(event, eventElement, seg);
}else{
eventElement[0]._fci = i; // for lazySegBind
}
reportEventElement(event, eventElement);
}
}
lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
// record event sides and title positions
for (i=0; i<segCnt; i++) {
seg = segs[i];
if (eventElement = seg.element) {
seg.vsides = vsides(eventElement, true);
seg.hsides = hsides(eventElement, true);
titleElement = eventElement.find('.fc-event-title');
if (titleElement.length) {
seg.contentTop = titleElement[0].offsetTop;
}
}
}
// set all positions/dimensions at once
for (i=0; i<segCnt; i++) {
seg = segs[i];
if (eventElement = seg.element) {
eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
height = Math.max(0, seg.outerHeight - seg.vsides);
eventElement[0].style.height = height + 'px';
event = seg.event;
if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
// not enough room for title, put it in the time (TODO: maybe make both display:inline instead)
eventElement.find('div.fc-event-time')
.text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title);
eventElement.find('div.fc-event-title')
.remove();
}
trigger('eventAfterRender', event, event, eventElement);
}
}
}
function slotSegHtml(event, seg) {
var html = "<";
var url = event.url;
var skinCss = getSkinCss(event, opt);
var classes = ['fc-event', 'fc-event-vert'];
if (isEventDraggable(event)) {
classes.push('fc-event-draggable');
}
if (seg.isStart) {
classes.push('fc-event-start');
}
if (seg.isEnd) {
classes.push('fc-event-end');
}
if (event.isBackground) {
classes.push('fc-event-background');
}
classes = classes.concat(event.className);
if (event.source) {
classes = classes.concat(event.source.className || []);
}
if (url) {
html += "a href='" + htmlEscape(event.url) + "'";
}else{
html += "div";
}
html +=
" class='" + classes.join(' ') + "'" +
" style=" +
"'" +
"position:absolute;" +
"top:" + seg.top + "px;" +
"left:" + seg.left + "px;" +
skinCss +
"'" +
">" +
"<div class='fc-event-inner'>" +
"<div class='fc-event-time'>" +
htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
"</div>" +
"<div class='fc-event-title'>" +
htmlEscape(event.title || '') +
"</div>" +
"</div>" +
"<div class='fc-event-bg'></div>";
if (seg.isEnd && isEventResizable(event)) {
html +=
"<div class='ui-resizable-handle ui-resizable-s'>=</div>";
}
html +=
"</" + (url ? "a" : "div") + ">";
return html;
}
function bindSlotSeg(event, eventElement, seg) {
var timeElement = eventElement.find('div.fc-event-time');
if (isEventDraggable(event)) {
draggableSlotEvent(event, eventElement, timeElement);
}
if (seg.isEnd && isEventResizable(event)) {
resizableSlotEvent(event, eventElement, timeElement);
}
eventElementHandlers(event, eventElement);
}
/* Dragging
-----------------------------------------------------------------------------------*/
// when event starts out FULL-DAY
// overrides DayEventRenderer's version because it needs to account for dragging elements
// to and from the slot area.
function draggableDayEvent(event, eventElement, seg) {
var isStart = seg.isStart;
var origWidth;
var revert;
var allDay = true;
var dayDelta;
var hoverListener = getHoverListener();
var colWidth = splitBySources ? getSrcColWidth() : getColWidth();
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
var minMinute = getMinMinute();
eventElement.draggable({
opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
origWidth = eventElement.width();
hoverListener.start(function(cell, origCell) {
clearOverlays();
if (cell) {
revert = false;
var origDate = cellToDate(0, origCell.col);
var date = cellToDate(0, cell.col);
dayDelta = dayDiff(date, origDate);
if (!cell.row) {
// on full-days
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
resetElement();
}else{
// mouse is over bottom slots
if (isStart) {
if (allDay) {
// convert event to temporary slot-event
eventElement.width(colWidth - 10); // don't use entire width
setOuterHeight(
eventElement,
snapHeight * Math.round(
(event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) /
snapMinutes
)
);
eventElement.draggable('option', 'grid', [colWidth, 1]);
allDay = false;
}
}else{
revert = true;
}
}
revert = revert || (allDay && !dayDelta);
}else{
resetElement();
revert = true;
}
eventElement.draggable('option', 'revert', revert);
}, ev, 'drag');
},
stop: function(ev, ui) {
hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (revert) {
// hasn't moved or is out of bounds (draggable has already reverted)
resetElement();
eventElement.css('filter', ''); // clear IE opacity side-effects
showEvents(event, eventElement);
}else{
// changed!
var minuteDelta = 0;
if (!allDay) {
minuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight)
* snapMinutes
+ minMinute
- (event.start.getHours() * 60 + event.start.getMinutes());
}
eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);
}
}
});
function resetElement() {
if (!allDay) {
eventElement
.width(origWidth)
.height('')
.draggable('option', 'grid', null);
allDay = true;
}
}
}
// when event starts out IN TIMESLOTS
function draggableSlotEvent(event, eventElement, timeElement) {
var coordinateGrid = t.getCoordinateGrid();
var colCnt = getColCnt();
var colWidth = getColWidth();
var snapWidth = splitBySources ? getSrcColWidth() : getColWidth();
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
// states
var origPosition; // original position of the element, not the mouse
var origCell;
var isInBounds, prevIsInBounds;
var isAllDay, prevIsAllDay;
var colDelta, prevColDelta;
var dayDelta; // derived from colDelta
var minuteDelta, prevMinuteDelta;
var srcNo;
eventElement.draggable({
scroll: false,
grid: [ snapWidth, snapHeight ],
axis: colCnt==1 && (!splitBySources || calendar.getSourcesCount() == 1)? 'y' : false,
opacity: opt('dragOpacity'),
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
coordinateGrid.build();
// initialize states
origPosition = eventElement.position();
origCell = coordinateGrid.cell(ev.pageX, ev.pageY);
isInBounds = prevIsInBounds = true;
isAllDay = prevIsAllDay = getIsCellAllDay(origCell);
colDelta = prevColDelta = 0;
dayDelta = 0;
minuteDelta = prevMinuteDelta = 0;
},
drag: function(ev, ui) {
// NOTE: this `cell` value is only useful for determining in-bounds and all-day.
// Bad for anything else due to the discrepancy between the mouse position and the
// element position while snapping. (problem revealed in PR #55)
//
// PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event.
// We should overhaul the dragging system and stop relying on jQuery UI.
var cell = coordinateGrid.cell(ev.pageX, ev.pageY);
srcNo = cell ? cell.srcNo : -1;
// update states
isInBounds = !!cell;
if (isInBounds) {
isAllDay = getIsCellAllDay(cell);
// calculate column delta
colDelta = Math.round((ui.position.left - origPosition.left) / colWidth);
if (colDelta != prevColDelta) {
// calculate the day delta based off of the original clicked column and the column delta
var origDate = cellToDate(0, origCell.col);
var col = origCell.col + colDelta;
col = Math.max(0, col);
col = Math.min(colCnt-1, col);
var date = cellToDate(0, col);
dayDelta = dayDiff(date, origDate);
}
// calculate minute delta (only if over slots)
if (!isAllDay) {
minuteDelta = Math.round((ui.position.top - origPosition.top) / snapHeight) * snapMinutes;
}
}
// any state changes?
if (
isInBounds != prevIsInBounds ||
isAllDay != prevIsAllDay ||
colDelta != prevColDelta ||
minuteDelta != prevMinuteDelta
) {
updateUI();
// update previous states for next time
prevIsInBounds = isInBounds;
prevIsAllDay = isAllDay;
prevColDelta = colDelta;
prevMinuteDelta = minuteDelta;
}
// if out-of-bounds, revert when done, and vice versa.
eventElement.draggable('option', 'revert', !isInBounds);
},
stop: function(ev, ui) {
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (isInBounds && (isAllDay || dayDelta || minuteDelta)) { // changed!
eventDrop(this, event, dayDelta, isAllDay ? 0 : minuteDelta, isAllDay, ev, ui, srcNo);
}
else { // either no change or out-of-bounds (draggable has already reverted)
// reset states for next time, and for updateUI()
isInBounds = true;
isAllDay = false;
colDelta = 0;
dayDelta = 0;
minuteDelta = 0;
updateUI();
eventElement.css('filter', ''); // clear IE opacity side-effects
// sometimes fast drags make event revert to wrong position, so reset.
// also, if we dragged the element out of the area because of snapping,
// but the *mouse* is still in bounds, we need to reset the position.
eventElement.css(origPosition);
showEvents(event, eventElement);
}
}
});
function updateUI() {
clearOverlays();
if (isInBounds) {
if (isAllDay) {
timeElement.hide();
eventElement.draggable('option', 'grid', null); // disable grid snapping
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
}
else {
updateTimeText(minuteDelta);
timeElement.css('display', ''); // show() was causing display=inline
eventElement.draggable('option', 'grid', [snapWidth, snapHeight]); // re-enable grid snapping
}
}
}
function updateTimeText(minuteDelta) {
var newStart = addMinutes(cloneDate(event.start), minuteDelta);
var newEnd;
if (event.end) {
newEnd = addMinutes(cloneDate(event.end), minuteDelta);
}
timeElement.text(formatDates(newStart, newEnd, opt('timeFormat')));
}
}
/* Resizing
--------------------------------------------------------------------------------------*/
function resizableSlotEvent(event, eventElement, timeElement) {
var snapDelta, prevSnapDelta;
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
eventElement.resizable({
handles: {
s: '.ui-resizable-handle'
},
grid: snapHeight,
start: function(ev, ui) {
snapDelta = prevSnapDelta = 0;
hideEvents(event, eventElement);
trigger('eventResizeStart', this, event, ev, ui);
},
resize: function(ev, ui) {
// don't rely on ui.size.height, doesn't take grid into account
snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight);
if (snapDelta != prevSnapDelta) {
timeElement.text(
formatDates(
event.start,
(!snapDelta && !event.end) ? null : // no change, so don't display time range
addMinutes(eventEnd(event), snapMinutes*snapDelta),
opt('timeFormat')
)
);
prevSnapDelta = snapDelta;
}
},
stop: function(ev, ui) {
trigger('eventResizeStop', this, event, ev, ui);
if (snapDelta) {
eventResize(this, event, 0, snapMinutes*snapDelta, ev, ui);
}else{
showEvents(event, eventElement);
// BUG: if event was really short, need to put title back in span
}
}
});
}
}
/* Agenda Event Segment Utilities
-----------------------------------------------------------------------------*/
// Sets the seg.backwardCoord and seg.forwardCoord on each segment and returns a new
// list in the order they should be placed into the DOM (an implicit z-index).
function placeSlotSegs(segs) {
var levels = buildSlotSegLevels(segs);
var level0 = levels[0];
var i;
computeForwardSlotSegs(levels);
if (level0) {
for (i=0; i<level0.length; i++) {
computeSlotSegPressures(level0[i]);
}
for (i=0; i<level0.length; i++) {
computeSlotSegCoords(level0[i], 0, 0);
}
}
return flattenSlotSegLevels(levels);
}
// Builds an array of segments "levels". The first level will be the leftmost tier of segments
// if the calendar is left-to-right, or the rightmost if the calendar is right-to-left.
function buildSlotSegLevels(segs) {
var levels = [];
var i, seg;
var j;
for (i=0; i<segs.length; i++) {
seg = segs[i];
// go through all the levels and stop on the first level where there are no collisions
for (j=0; j<levels.length; j++) {
if (!computeSlotSegCollisions(seg, levels[j]).length) {
break;
}
}
(levels[j] || (levels[j] = [])).push(seg);
}
return levels;
}
// For every segment, figure out the other segments that are in subsequent
// levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
function computeForwardSlotSegs(levels) {
var i, level;
var j, seg;
var k;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
seg = level[j];
seg.forwardSegs = [];
for (k=i+1; k<levels.length; k++) {
computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
}
}
}
}
// Figure out which path forward (via seg.forwardSegs) results in the longest path until
// the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
function computeSlotSegPressures(seg) {
var forwardSegs = seg.forwardSegs;
var forwardPressure = 0;
var i, forwardSeg;
if (seg.forwardPressure === undefined) { // not already computed
for (i=0; i<forwardSegs.length; i++) {
forwardSeg = forwardSegs[i];
// figure out the child's maximum forward path
computeSlotSegPressures(forwardSeg);
// either use the existing maximum, or use the child's forward pressure
// plus one (for the forwardSeg itself)
forwardPressure = Math.max(
forwardPressure,
1 + forwardSeg.forwardPressure
);
}
seg.forwardPressure = forwardPressure;
}
}
// Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
// from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
// seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
//
// The segment might be part of a "series", which means consecutive segments with the same pressure
// who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
// segments behind this one in the current series, and `seriesBackwardCoord` is the starting
// coordinate of the first segment in the series.
function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) {
var forwardSegs = seg.forwardSegs;
var i;
if (seg.forwardCoord === undefined) { // not already computed
if (!forwardSegs.length) {
// if there are no forward segments, this segment should butt up against the edge
seg.forwardCoord = 1;
}
else {
// sort highest pressure first
forwardSegs.sort(compareForwardSlotSegs);
// this segment's forwardCoord will be calculated from the backwardCoord of the
// highest-pressure forward segment.
computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
seg.forwardCoord = forwardSegs[0].backwardCoord;
}
// calculate the backwardCoord from the forwardCoord. consider the series
seg.backwardCoord = seg.forwardCoord -
(seg.forwardCoord - seriesBackwardCoord) / // available width for series
(seriesBackwardPressure + 1); // # of segments in the series
// use this segment's coordinates to computed the coordinates of the less-pressurized
// forward segments
for (i=0; i<forwardSegs.length; i++) {
computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord);
}
}
}
// Outputs a flat array of segments, from lowest to highest level
function flattenSlotSegLevels(levels) {
var segs = [];
var i, level;
var j;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
segs.push(level[j]);
}
}
return segs;
}
// Find all the segments in `otherSegs` that vertically collide with `seg`.
// Append into an optionally-supplied `results` array and return.
function computeSlotSegCollisions(seg, otherSegs, results) {
results = results || [];
for (var i=0; i<otherSegs.length; i++) {
if (isSlotSegCollision(seg, otherSegs[i])) {
results.push(otherSegs[i]);
}
}
return results;
}
// Do these segments occupy the same vertical space?
function isSlotSegCollision(seg1, seg2) {
return !seg1.event.isBackground && !seg2.event.isBackground && seg1.end > seg2.start && seg1.start < seg2.end;
}
// A cmp function for determining which forward segment to rely on more when computing coordinates.
function compareForwardSlotSegs(seg1, seg2) {
// put higher-pressure first
return seg2.forwardPressure - seg1.forwardPressure ||
// put segments that are closer to initial edge first (and favor ones with no coords yet)
(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
// do normal sorting...
compareSlotSegs(seg1, seg2);
}
// A cmp function for determining which segment should be closer to the initial edge
// (the left edge on a left-to-right calendar).
function compareSlotSegs(seg1, seg2) {
return seg1.start - seg2.start || // earlier start time goes first
(seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first
(seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title
}
;;
function View(element, calendar, viewName) {
var t = this;
// exports
t.element = element;
t.calendar = calendar;
t.name = viewName;
t.opt = opt;
t.trigger = trigger;
t.isEventDraggable = isEventDraggable;
t.isEventResizable = isEventResizable;
t.setEventData = setEventData;
t.clearEventData = clearEventData;
t.eventEnd = eventEnd;
t.reportEventElement = reportEventElement;
t.triggerEventDestroy = triggerEventDestroy;
t.eventElementHandlers = eventElementHandlers;
t.showEvents = showEvents;
t.hideEvents = hideEvents;
t.eventDrop = eventDrop;
t.eventResize = eventResize;
// t.title
// t.start, t.end
// t.visStart, t.visEnd
// imports
var defaultEventEnd = t.defaultEventEnd;
var normalizeEvent = calendar.normalizeEvent; // in EventManager
var reportEventChange = calendar.reportEventChange;
// locals
var eventsByID = {}; // eventID mapped to array of events (there can be multiple b/c of repeating events)
var eventElementsByID = {}; // eventID mapped to array of jQuery elements
var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system
var options = calendar.options;
function opt(name, viewNameOverride) {
var v = options[name];
if ($.isPlainObject(v)) {
return smartProperty(v, viewNameOverride || viewName);
}
return v;
}
function trigger(name, thisObj) {
return calendar.trigger.apply(
calendar,
[name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
);
}
/* Event Editable Boolean Calculations
------------------------------------------------------------------------------*/
function isEventDraggable(event) {
var source = event.source || {};
return firstDefined(
event.startEditable,
source.startEditable,
opt('eventStartEditable'),
event.editable,
source.editable,
opt('editable')
)
&& !opt('disableDragging'); // deprecated
}
function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
var source = event.source || {};
return firstDefined(
event.durationEditable,
source.durationEditable,
opt('eventDurationEditable'),
event.editable,
source.editable,
opt('editable')
)
&& !opt('disableResizing'); // deprecated
}
/* Event Data
------------------------------------------------------------------------------*/
function setEventData(events) { // events are already normalized at this point
eventsByID = {};
var i, len=events.length, event;
for (i=0; i<len; i++) {
event = events[i];
if (eventsByID[event._id]) {
eventsByID[event._id].push(event);
}else{
eventsByID[event._id] = [event];
}
}
}
function clearEventData() {
eventsByID = {};
eventElementsByID = {};
eventElementCouples = [];
}
// returns a Date object for an event's end
function eventEnd(event) {
return event.end ? cloneDate(event.end) : defaultEventEnd(event);
}
/* Event Elements
------------------------------------------------------------------------------*/
// report when view creates an element for an event
function reportEventElement(event, element) {
eventElementCouples.push({ event: event, element: element });
if (eventElementsByID[event._id]) {
eventElementsByID[event._id].push(element);
}else{
eventElementsByID[event._id] = [element];
}
}
function triggerEventDestroy() {
$.each(eventElementCouples, function(i, couple) {
t.trigger('eventDestroy', couple.event, couple.event, couple.element);
});
}
// attaches eventClick, eventMouseover, eventMouseout
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
}
function showEvents(event, exceptElement) {
eachEventElement(event, exceptElement, 'show');
}
function hideEvents(event, exceptElement) {
eachEventElement(event, exceptElement, 'hide');
}
function eachEventElement(event, exceptElement, funcName) {
// NOTE: there may be multiple events per ID (repeating events)
// and multiple segments per event
var elements = eventElementsByID[event._id],
i, len = elements.length;
for (i=0; i<len; i++) {
if (!exceptElement || elements[i][0] != exceptElement[0]) {
elements[i][funcName]();
}
}
}
/* Event Modification Reporting
---------------------------------------------------------------------------------*/
function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui, srcNo) {
var oldAllDay = event.allDay;
var eventId = event._id;
moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay);
trigger(
'eventDrop',
e,
event,
dayDelta,
minuteDelta,
allDay,
function() {
// TODO: investigate cases where this inverse technique might not work
moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay);
reportEventChange(eventId);
},
ev,
ui,
srcNo
);
reportEventChange(eventId);
}
function eventResize(e, event, dayDelta, minuteDelta, ev, ui) {
var eventId = event._id;
elongateEvents(eventsByID[eventId], dayDelta, minuteDelta);
trigger(
'eventResize',
e,
event,
dayDelta,
minuteDelta,
function() {
// TODO: investigate cases where this inverse technique might not work
elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta);
reportEventChange(eventId);
},
ev,
ui
);
reportEventChange(eventId);
}
/* Event Modification Math
---------------------------------------------------------------------------------*/
function moveEvents(events, dayDelta, minuteDelta, allDay) {
minuteDelta = minuteDelta || 0;
for (var e, len=events.length, i=0; i<len; i++) {
e = events[i];
if (allDay !== undefined) {
e.allDay = allDay;
}
addMinutes(addDays(e.start, dayDelta, true), minuteDelta);
if (e.end) {
e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta);
}
normalizeEvent(e, options);
}
}
function elongateEvents(events, dayDelta, minuteDelta) {
minuteDelta = minuteDelta || 0;
for (var e, len=events.length, i=0; i<len; i++) {
e = events[i];
e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta);
normalizeEvent(e, options);
}
}
// ====================================================================================================
// Utilities for day "cells"
// ====================================================================================================
// The "basic" views are completely made up of day cells.
// The "agenda" views have day cells at the top "all day" slot.
// This was the obvious common place to put these utilities, but they should be abstracted out into
// a more meaningful class (like DayEventRenderer).
// ====================================================================================================
// For determining how a given "cell" translates into a "date":
//
// 1. Convert the "cell" (row and column) into a "cell offset" (the # of the cell, cronologically from the first).
// Keep in mind that column indices are inverted with isRTL. This is taken into account.
//
// 2. Convert the "cell offset" to a "day offset" (the # of days since the first visible day in the view).
//
// 3. Convert the "day offset" into a "date" (a JavaScript Date object).
//
// The reverse transformation happens when transforming a date into a cell.
// exports
t.isHiddenDay = isHiddenDay;
t.skipHiddenDays = skipHiddenDays;
t.getCellsPerWeek = getCellsPerWeek;
t.dateToCell = dateToCell;
t.dateToDayOffset = dateToDayOffset;
t.dayOffsetToCellOffset = dayOffsetToCellOffset;
t.cellOffsetToCell = cellOffsetToCell;
t.cellToDate = cellToDate;
t.cellToCellOffset = cellToCellOffset;
t.cellOffsetToDayOffset = cellOffsetToDayOffset;
t.dayOffsetToDate = dayOffsetToDate;
t.rangeToSegments = rangeToSegments;
// internals
var hiddenDays = opt('hiddenDays') || []; // array of day-of-week indices that are hidden
var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
var cellsPerWeek;
var dayToCellMap = []; // hash from dayIndex -> cellIndex, for one week
var cellToDayMap = []; // hash from cellIndex -> dayIndex, for one week
var isRTL = opt('isRTL');
// initialize important internal variables
(function() {
if (opt('weekends') === false) {
hiddenDays.push(0, 6); // 0=sunday, 6=saturday
}
// Loop through a hypothetical week and determine which
// days-of-week are hidden. Record in both hashes (one is the reverse of the other).
for (var dayIndex=0, cellIndex=0; dayIndex<7; dayIndex++) {
dayToCellMap[dayIndex] = cellIndex;
isHiddenDayHash[dayIndex] = $.inArray(dayIndex, hiddenDays) != -1;
if (!isHiddenDayHash[dayIndex]) {
cellToDayMap[cellIndex] = dayIndex;
cellIndex++;
}
}
cellsPerWeek = cellIndex;
if (!cellsPerWeek) {
throw 'invalid hiddenDays'; // all days were hidden? bad.
}
})();
// Is the current day hidden?
// `day` is a day-of-week index (0-6), or a Date object
function isHiddenDay(day) {
if (typeof day == 'object') {
day = day.getDay();
}
return isHiddenDayHash[day];
}
function getCellsPerWeek() {
return cellsPerWeek;
}
// Keep incrementing the current day until it is no longer a hidden day.
// If the initial value of `date` is not a hidden day, don't do anything.
// Pass `isExclusive` as `true` if you are dealing with an end date.
// `inc` defaults to `1` (increment one day forward each time)
function skipHiddenDays(date, inc, isExclusive) {
inc = inc || 1;
while (
isHiddenDayHash[ ( date.getDay() + (isExclusive ? inc : 0) + 7 ) % 7 ]
) {
addDays(date, inc);
}
}
//
// TRANSFORMATIONS: cell -> cell offset -> day offset -> date
//
// cell -> date (combines all transformations)
// Possible arguments:
// - row, col
// - { row:#, col: # }
function cellToDate() {
var cellOffset = cellToCellOffset.apply(null, arguments);
var dayOffset = cellOffsetToDayOffset(cellOffset);
var date = dayOffsetToDate(dayOffset);
return date;
}
// cell -> cell offset
// Possible arguments:
// - row, col
// - { row:#, col:# }
function cellToCellOffset(row, col) {
var colCnt = t.getColCnt();
// rtl variables. wish we could pre-populate these. but where?
var dis = isRTL ? -1 : 1;
var dit = isRTL ? colCnt - 1 : 0;
if (typeof row == 'object') {
col = row.col;
row = row.row;
}
var cellOffset = row * colCnt + (col * dis + dit); // column, adjusted for RTL (dis & dit)
return cellOffset;
}
// cell offset -> day offset
function cellOffsetToDayOffset(cellOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-weekz
return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
+ cellToDayMap[ // # of days from partial last week
(cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
]
- day0; // adjustment for beginning-of-week normalization
}
// day offset -> date (JavaScript Date object)
function dayOffsetToDate(dayOffset) {
var date = cloneDate(t.visStart);
addDays(date, dayOffset);
return date;
}
//
// TRANSFORMATIONS: date -> day offset -> cell offset -> cell
//
// date -> cell (combines all transformations)
function dateToCell(date) {
var dayOffset = dateToDayOffset(date);
var cellOffset = dayOffsetToCellOffset(dayOffset);
var cell = cellOffsetToCell(cellOffset);
return cell;
}
// date -> day offset
function dateToDayOffset(date) {
return dayDiff(date, t.visStart);
}
// day offset -> cell offset
function dayOffsetToCellOffset(dayOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
dayOffset += day0; // normalize dayOffset to beginning-of-week
return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
+ dayToCellMap[ // # of cells from partial last week
(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
]
- dayToCellMap[day0]; // adjustment for beginning-of-week normalization
}
// cell offset -> cell (object with row & col keys)
function cellOffsetToCell(cellOffset) {
var colCnt = t.getColCnt();
// rtl variables. wish we could pre-populate these. but where?
var dis = isRTL ? -1 : 1;
var dit = isRTL ? colCnt - 1 : 0;
var row = Math.floor(cellOffset / colCnt);
var col = ((cellOffset % colCnt + colCnt) % colCnt) * dis + dit; // column, adjusted for RTL (dis & dit)
return {
row: row,
col: col
};
}
//
// Converts a date range into an array of segment objects.
// "Segments" are horizontal stretches of time, sliced up by row.
// A segment object has the following properties:
// - row
// - cols
// - isStart
// - isEnd
//
function rangeToSegments(startDate, endDate) {
var rowCnt = t.getRowCnt();
var colCnt = t.getColCnt();
var segments = []; // array of segments to return
// day offset for given date range
var rangeDayOffsetStart = dateToDayOffset(startDate);
var rangeDayOffsetEnd = dateToDayOffset(endDate); // exclusive
// first and last cell offset for the given date range
// "last" implies inclusivity
var rangeCellOffsetFirst = dayOffsetToCellOffset(rangeDayOffsetStart);
var rangeCellOffsetLast = dayOffsetToCellOffset(rangeDayOffsetEnd) - 1;
// loop through all the rows in the view
for (var row=0; row<rowCnt; row++) {
// first and last cell offset for the row
var rowCellOffsetFirst = row * colCnt;
var rowCellOffsetLast = rowCellOffsetFirst + colCnt - 1;
// get the segment's cell offsets by constraining the range's cell offsets to the bounds of the row
var segmentCellOffsetFirst = Math.max(rangeCellOffsetFirst, rowCellOffsetFirst);
var segmentCellOffsetLast = Math.min(rangeCellOffsetLast, rowCellOffsetLast);
// make sure segment's offsets are valid and in view
if (segmentCellOffsetFirst <= segmentCellOffsetLast) {
// translate to cells
var segmentCellFirst = cellOffsetToCell(segmentCellOffsetFirst);
var segmentCellLast = cellOffsetToCell(segmentCellOffsetLast);
// view might be RTL, so order by leftmost column
var cols = [ segmentCellFirst.col, segmentCellLast.col ].sort();
// Determine if segment's first/last cell is the beginning/end of the date range.
// We need to compare "day offset" because "cell offsets" are often ambiguous and
// can translate to multiple days, and an edge case reveals itself when we the
// range's first cell is hidden (we don't want isStart to be true).
var isStart = cellOffsetToDayOffset(segmentCellOffsetFirst) == rangeDayOffsetStart;
var isEnd = cellOffsetToDayOffset(segmentCellOffsetLast) + 1 == rangeDayOffsetEnd; // +1 for comparing exclusively
segments.push({
row: row,
leftCol: cols[0],
rightCol: cols[1],
isStart: isStart,
isEnd: isEnd
});
}
}
return segments;
}
}
;;
function DayEventRenderer() {
var t = this;
// exports
t.renderDayEvents = renderDayEvents;
t.draggableDayEvent = draggableDayEvent; // made public so that subclasses can override
t.resizableDayEvent = resizableDayEvent; // "
// imports
var opt = t.opt;
var trigger = t.trigger;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var eventEnd = t.eventEnd;
var reportEventElement = t.reportEventElement;
var eventElementHandlers = t.eventElementHandlers;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventDrop = t.eventDrop;
var eventResize = t.eventResize;
var getRowCnt = t.getRowCnt;
var getColCnt = t.getColCnt;
var getColWidth = t.getColWidth;
var allDayRow = t.allDayRow; // TODO: rename
var colLeft = t.colLeft;
var colRight = t.colRight;
var colContentLeft = t.colContentLeft;
var colContentRight = t.colContentRight;
var dateToCell = t.dateToCell;
var getDaySegmentContainer = t.getDaySegmentContainer;
var formatDates = t.calendar.formatDates;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var clearSelection = t.clearSelection;
var getHoverListener = t.getHoverListener;
var rangeToSegments = t.rangeToSegments;
var cellToDate = t.cellToDate;
var cellToCellOffset = t.cellToCellOffset;
var cellOffsetToDayOffset = t.cellOffsetToDayOffset;
var dateToDayOffset = t.dateToDayOffset;
var dayOffsetToCellOffset = t.dayOffsetToCellOffset;
// Render `events` onto the calendar, attach mouse event handlers, and call the `eventAfterRender` callback for each.
// Mouse event will be lazily applied, except if the event has an ID of `modifiedEventId`.
// Can only be called when the event container is empty (because it wipes out all innerHTML).
function renderDayEvents(events, modifiedEventId) {
// do the actual rendering. Receive the intermediate "segment" data structures.
var segments = _renderDayEvents(
events,
false, // don't append event elements
true // set the heights of the rows
);
// report the elements to the View, for general drag/resize utilities
segmentElementEach(segments, function(segment, element) {
reportEventElement(segment.event, element);
});
// attach mouse handlers
attachHandlers(segments, modifiedEventId);
// call `eventAfterRender` callback for each event
segmentElementEach(segments, function(segment, element) {
trigger('eventAfterRender', segment.event, segment.event, element);
});
}
// Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers.
// Append this event element to the event container, which might already be populated with events.
// If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`.
// This hack is used to maintain continuity when user is manually resizing an event.
// Returns an array of DOM elements for the event.
function renderTempDayEvent(event, adjustRow, adjustTop) {
// actually render the event. `true` for appending element to container.
// Recieve the intermediate "segment" data structures.
var segments = _renderDayEvents(
[ event ],
true, // append event elements
false // don't set the heights of the rows
);
var elements = [];
// Adjust certain elements' top coordinates
segmentElementEach(segments, function(segment, element) {
if (segment.row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]); // accumulate DOM nodes
});
return elements;
}
// Render events onto the calendar. Only responsible for the VISUAL aspect.
// Not responsible for attaching handlers or calling callbacks.
// Set `doAppend` to `true` for rendering elements without clearing the existing container.
// Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow.
function _renderDayEvents(events, doAppend, doRowHeights) {
// where the DOM nodes will eventually end up
var finalContainer = getDaySegmentContainer();
// the container where the initial HTML will be rendered.
// If `doAppend`==true, uses a temporary container.
var renderContainer = doAppend ? $("<div/>") : finalContainer;
var segments = buildSegments(events);
var html;
var elements;
// calculate the desired `left` and `width` properties on each segment object
calculateHorizontals(segments);
// build the HTML string. relies on `left` property
html = buildHTML(segments);
// render the HTML. innerHTML is considerably faster than jQuery's .html()
renderContainer[0].innerHTML = html;
// retrieve the individual elements
elements = renderContainer.children();
// if we were appending, and thus using a temporary container,
// re-attach elements to the real container.
if (doAppend) {
finalContainer.append(elements);
}
// assigns each element to `segment.event`, after filtering them through user callbacks
resolveElements(segments, elements);
// Calculate the left and right padding+margin for each element.
// We need this for setting each element's desired outer width, because of the W3C box model.
// It's important we do this in a separate pass from acually setting the width on the DOM elements
// because alternating reading/writing dimensions causes reflow for every iteration.
segmentElementEach(segments, function(segment, element) {
segment.hsides = hsides(element, true); // include margins = `true`
});
// Set the width of each element
segmentElementEach(segments, function(segment, element) {
element.width(
Math.max(0, segment.outerWidth - segment.hsides)
);
});
// Grab each element's outerHeight (setVerticals uses this).
// To get an accurate reading, it's important to have each element's width explicitly set already.
segmentElementEach(segments, function(segment, element) {
segment.outerHeight = element.outerHeight(true); // include margins = `true`
});
// Set the top coordinate on each element (requires segment.outerHeight)
setVerticals(segments, doRowHeights);
return segments;
}
// Generate an array of "segments" for all events.
function buildSegments(events) {
var segments = [];
for (var i=0; i<events.length; i++) {
var eventSegments = buildSegmentsForEvent(events[i]);
segments.push.apply(segments, eventSegments); // append an array to an array
}
return segments;
}
// Generate an array of segments for a single event.
// A "segment" is the same data structure that View.rangeToSegments produces,
// with the addition of the `event` property being set to reference the original event.
function buildSegmentsForEvent(event) {
var startDate = event.start;
var endDate = exclEndDay(event);
var segments = rangeToSegments(startDate, endDate);
for (var i=0; i<segments.length; i++) {
segments[i].event = event;
}
return segments;
}
// Sets the `left` and `outerWidth` property of each segment.
// These values are the desired dimensions for the eventual DOM elements.
function calculateHorizontals(segments) {
var isRTL = opt('isRTL');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// Determine functions used for calulating the elements left/right coordinates,
// depending on whether the view is RTL or not.
// NOTE:
// colLeft/colRight returns the coordinate butting up the edge of the cell.
// colContentLeft/colContentRight is indented a little bit from the edge.
var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
var left = leftFunc(segment.leftCol, true);
var right = rightFunc(segment.rightCol, true);
segment.left = left;
segment.outerWidth = right - left;
}
}
// Build a concatenated HTML string for an array of segments
function buildHTML(segments) {
var html = '';
for (var i=0; i<segments.length; i++) {
html += buildHTMLForSegment(segments[i]);
}
return html;
}
// Build an HTML string for a single segment.
// Relies on the following properties:
// - `segment.event` (from `buildSegmentsForEvent`)
// - `segment.left` (from `calculateHorizontals`)
function buildHTMLForSegment(segment) {
var html = '';
var isRTL = opt('isRTL');
var event = segment.event;
var url = event.url;
// generate the list of CSS classNames
var classNames = [ 'fc-event', 'fc-event-hori' ];
if (isEventDraggable(event)) {
classNames.push('fc-event-draggable');
}
if (segment.isStart) {
classNames.push('fc-event-start');
}
if (segment.isEnd) {
classNames.push('fc-event-end');
}
// use the event's configured classNames
// guaranteed to be an array via `normalizeEvent`
classNames = classNames.concat(event.className);
if (event.source) {
// use the event's source's classNames, if specified
classNames = classNames.concat(event.source.className || []);
}
// generate a semicolon delimited CSS string for any of the "skin" properties
// of the event object (`backgroundColor`, `borderColor` and such)
var skinCss = getSkinCss(event, opt);
if (url) {
html += "<a href='" + htmlEscape(url) + "'";
}else{
html += "<div";
}
html +=
" class='" + classNames.join(' ') + "'" +
" style=" +
"'" +
"position:absolute;" +
"left:" + segment.left + "px;" +
skinCss +
"'" +
">" +
"<div class='fc-event-inner'>";
if (!event.allDay && segment.isStart) {
html +=
"<span class='fc-event-time'>" +
htmlEscape(
formatDates(event.start, event.end, opt('timeFormat'))
) +
"</span>";
}
html +=
"<span class='fc-event-title'>" +
htmlEscape(event.title || '') +
"</span>" +
"</div>";
if (segment.isEnd && isEventResizable(event)) {
html +=
"<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" +
" " + // makes hit area a lot better for IE6/7
"</div>";
}
html += "</" + (url ? "a" : "div") + ">";
// TODO:
// When these elements are initially rendered, they will be briefly visibile on the screen,
// even though their widths/heights are not set.
// SOLUTION: initially set them as visibility:hidden ?
return html;
}
// Associate each segment (an object) with an element (a jQuery object),
// by setting each `segment.element`.
// Run each element through the `eventRender` filter, which allows developers to
// modify an existing element, supply a new one, or cancel rendering.
function resolveElements(segments, elements) {
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
var event = segment.event;
var element = elements.eq(i);
// call the trigger with the original element
var triggerRes = trigger('eventRender', event, event, element);
if (triggerRes === false) {
// if `false`, remove the event from the DOM and don't assign it to `segment.event`
element.remove();
}
else {
if (triggerRes && triggerRes !== true) {
// the trigger returned a new element, but not `true` (which means keep the existing element)
// re-assign the important CSS dimension properties that were already assigned in `buildHTMLForSegment`
triggerRes = $(triggerRes)
.css({
position: 'absolute',
left: segment.left
});
element.replaceWith(triggerRes);
element = triggerRes;
}
segment.element = element;
}
}
}
/* Top-coordinate Methods
-------------------------------------------------------------------------------------------------*/
// Sets the "top" CSS property for each element.
// If `doRowHeights` is `true`, also sets each row's first cell to an explicit height,
// so that if elements vertically overflow, the cell expands vertically to compensate.
function setVerticals(segments, doRowHeights) {
var rowContentHeights = calculateVerticals(segments); // also sets segment.top
var rowContentElements = getRowContentElements(); // returns 1 inner div per row
var rowContentTops = [];
// Set each row's height by setting height of first inner div
if (doRowHeights) {
for (var i=0; i<rowContentElements.length; i++) {
rowContentElements[i].height(rowContentHeights[i]);
}
}
// Get each row's top, relative to the views's origin.
// Important to do this after setting each row's height.
for (var i=0; i<rowContentElements.length; i++) {
rowContentTops.push(
rowContentElements[i].position().top
);
}
// Set each segment element's CSS "top" property.
// Each segment object has a "top" property, which is relative to the row's top, but...
segmentElementEach(segments, function(segment, element) {
element.css(
'top',
rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
);
});
}
// Calculate the "top" coordinate for each segment, relative to the "top" of the row.
// Also, return an array that contains the "content" height for each row
// (the height displaced by the vertically stacked events in the row).
// Requires segments to have their `outerHeight` property already set.
function calculateVerticals(segments) {
var rowCnt = getRowCnt();
var colCnt = getColCnt();
var rowContentHeights = []; // content height for each row
var segmentRows = buildSegmentRows(segments); // an array of segment arrays, one for each row
for (var rowI=0; rowI<rowCnt; rowI++) {
var segmentRow = segmentRows[rowI];
// an array of running total heights for each column.
// initialize with all zeros.
var colHeights = [];
for (var colI=0; colI<colCnt; colI++) {
colHeights.push(0);
}
// loop through every segment
for (var segmentI=0; segmentI<segmentRow.length; segmentI++) {
var segment = segmentRow[segmentI];
// find the segment's top coordinate by looking at the max height
// of all the columns the segment will be in.
segment.top = arrayMax(
colHeights.slice(
segment.leftCol,
segment.rightCol + 1 // make exclusive for slice
)
);
// adjust the columns to account for the segment's height
for (var colI=segment.leftCol; colI<=segment.rightCol; colI++) {
colHeights[colI] = segment.top + segment.outerHeight;
}
}
// the tallest column in the row should be the "content height"
rowContentHeights.push(arrayMax(colHeights));
}
return rowContentHeights;
}
// Build an array of segment arrays, each representing the segments that will
// be in a row of the grid, sorted by which event should be closest to the top.
function buildSegmentRows(segments) {
var rowCnt = getRowCnt();
var segmentRows = [];
var segmentI;
var segment;
var rowI;
// group segments by row
for (segmentI=0; segmentI<segments.length; segmentI++) {
segment = segments[segmentI];
rowI = segment.row;
if (segment.element) { // was rendered?
if (segmentRows[rowI]) {
// already other segments. append to array
segmentRows[rowI].push(segment);
}
else {
// first segment in row. create new array
segmentRows[rowI] = [ segment ];
}
}
}
// sort each row
for (rowI=0; rowI<rowCnt; rowI++) {
segmentRows[rowI] = sortSegmentRow(
segmentRows[rowI] || [] // guarantee an array, even if no segments
);
}
return segmentRows;
}
// Sort an array of segments according to which segment should appear closest to the top
function sortSegmentRow(segments) {
var sortedSegments = [];
// build the subrow array
var subrows = buildSegmentSubrows(segments);
// flatten it
for (var i=0; i<subrows.length; i++) {
sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
}
return sortedSegments;
}
// Take an array of segments, which are all assumed to be in the same row,
// and sort into subrows.
function buildSegmentSubrows(segments) {
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segments.sort(compareDaySegments);
var subrows = [];
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// loop through subrows, starting with the topmost, until the segment
// doesn't collide with other segments.
for (var j=0; j<subrows.length; j++) {
if (!isDaySegmentCollision(segment, subrows[j])) {
break;
}
}
// `j` now holds the desired subrow index
if (subrows[j]) {
subrows[j].push(segment);
}
else {
subrows[j] = [ segment ];
}
}
return subrows;
}
// Return an array of jQuery objects for the placeholder content containers of each row.
// The content containers don't actually contain anything, but their dimensions should match
// the events that are overlaid on top.
function getRowContentElements() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div');
}
return rowDivs;
}
/* Mouse Handlers
---------------------------------------------------------------------------------------------------*/
// TODO: better documentation!
function attachHandlers(segments, modifiedEventId) {
var segmentContainer = getDaySegmentContainer();
segmentElementEach(segments, function(segment, element, i) {
var event = segment.event;
if (event._id === modifiedEventId) {
bindDaySeg(event, element, segment);
}else{
element[0]._fci = i; // for lazySegBind
}
});
lazySegBind(segmentContainer, segments, bindDaySeg);
}
function bindDaySeg(event, eventElement, segment) {
if (isEventDraggable(event)) {
t.draggableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
}
if (
segment.isEnd && // only allow resizing on the final segment for an event
isEventResizable(event)
) {
t.resizableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
}
// attach all other handlers.
// needs to be after, because resizableDayEvent might stopImmediatePropagation on click
eventElementHandlers(event, eventElement);
}
function draggableDayEvent(event, eventElement) {
var hoverListener = getHoverListener();
var dayDelta;
eventElement.draggable({
delay: 50,
opacity: opt('dragOpacity'),
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
clearOverlays();
if (cell) {
var origDate = cellToDate(origCell);
var date = cellToDate(cell);
dayDelta = dayDiff(date, origDate);
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
}else{
dayDelta = 0;
}
}, ev, 'drag');
},
stop: function(ev, ui) {
hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (dayDelta) {
eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui);
}else{
eventElement.css('filter', ''); // clear IE opacity side-effects
showEvents(event, eventElement);
}
}
});
}
function resizableDayEvent(event, element, segment) {
var isRTL = opt('isRTL');
var direction = isRTL ? 'w' : 'e';
var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this
var isResizing = false;
// TODO: look into using jquery-ui mouse widget for this stuff
disableTextSelection(element); // prevent native <a> selection for IE
element
.mousedown(function(ev) { // prevent native <a> selection for others
ev.preventDefault();
})
.click(function(ev) {
if (isResizing) {
ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
// (eventElementHandlers needs to be bound after resizableDayEvent)
}
});
handle.mousedown(function(ev) {
if (ev.which != 1) {
return; // needs to be left mouse button
}
isResizing = true;
var hoverListener = getHoverListener();
var rowCnt = getRowCnt();
var colCnt = getColCnt();
var elementTop = element.css('top');
var dayDelta;
var helpers;
var eventCopy = $.extend({}, event);
var minCellOffset = dayOffsetToCellOffset( dateToDayOffset(event.start) );
clearSelection();
$('body')
.css('cursor', direction + '-resize')
.one('mouseup', mouseup);
trigger('eventResizeStart', this, event, ev);
hoverListener.start(function(cell, origCell) {
if (cell) {
var origCellOffset = cellToCellOffset(origCell);
var cellOffset = cellToCellOffset(cell);
// don't let resizing move earlier than start date cell
cellOffset = Math.max(cellOffset, minCellOffset);
dayDelta =
cellOffsetToDayOffset(cellOffset) -
cellOffsetToDayOffset(origCellOffset);
if (dayDelta) {
eventCopy.end = addDays(eventEnd(event), dayDelta, true);
var oldHelpers = helpers;
helpers = renderTempDayEvent(eventCopy, segment.row, elementTop);
helpers = $(helpers); // turn array into a jQuery object
helpers.find('*').css('cursor', direction + '-resize');
if (oldHelpers) {
oldHelpers.remove();
}
hideEvents(event);
}
else {
if (helpers) {
showEvents(event);
helpers.remove();
helpers = null;
}
}
clearOverlays();
renderDayOverlay( // coordinate grid already rebuilt with hoverListener.start()
event.start,
addDays( exclEndDay(event), dayDelta )
// TODO: instead of calling renderDayOverlay() with dates,
// call _renderDayOverlay (or whatever) with cell offsets.
);
}
}, ev);
function mouseup(ev) {
trigger('eventResizeStop', this, event, ev);
$('body').css('cursor', '');
hoverListener.stop();
clearOverlays();
if (dayDelta) {
eventResize(this, event, dayDelta, 0, ev);
// event redraw will clear helpers
}
// otherwise, the drag handler already restored the old events
setTimeout(function() { // make this happen after the element's click event
isResizing = false;
},0);
}
});
}
}
/* Generalized Segment Utilities
-------------------------------------------------------------------------------------------------*/
function isDaySegmentCollision(segment, otherSegments) {
for (var i=0; i<otherSegments.length; i++) {
var otherSegment = otherSegments[i];
if (
otherSegment.leftCol <= segment.rightCol &&
otherSegment.rightCol >= segment.leftCol
) {
return true;
}
}
return false;
}
function segmentElementEach(segments, callback) { // TODO: use in AgendaView?
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
var element = segment.element;
if (element) {
callback(segment, element, i);
}
}
}
// A cmp function for determining which segments should appear higher up
function compareDaySegments(a, b) {
return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
a.event.start - b.event.start || // if a tie, sort by event start date
(a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
}
;;
//BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trigger;
var defaultSelectionEnd = t.defaultSelectionEnd;
var renderSelection = t.renderSelection;
var clearSelection = t.clearSelection;
// locals
var selected = false;
// unselectAuto
if (opt('selectable') && opt('unselectAuto')) {
$(document).mousedown(function(ev) {
var ignore = opt('unselectCancel');
if (ignore) {
if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
return;
}
}
unselect(ev);
});
}
function select(startDate, endDate, allDay) {
unselect();
if (!endDate) {
endDate = defaultSelectionEnd(startDate, allDay);
}
renderSelection(startDate, endDate, allDay);
reportSelection(startDate, endDate, allDay);
}
function unselect(ev) {
if (selected) {
selected = false;
clearSelection();
trigger('unselect', null, ev);
}
}
function reportSelection(startDate, endDate, allDay, ev, sourceNo) {
selected = true;
trigger('select', null, startDate, endDate, allDay, ev, sourceNo);
}
function daySelectionMousedown(ev) { // not really a generic manager method, oh well
var cellToDate = t.cellToDate;
var getIsCellAllDay = t.getIsCellAllDay;
var hoverListener = t.getHoverListener();
var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
unselect(ev);
var _mousedownElement = this;
var dates;
hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell
clearSelection();
if (cell && getIsCellAllDay(cell)) {
dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare);
renderSelection(dates[0], dates[1], true);
}else{
dates = null;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], true, ev);
}
reportSelection(dates[0], dates[1], true, ev);
}
});
}
}
}
;;
function OverlayManager() {
var t = this;
// exports
t.renderOverlay = renderOverlay;
t.clearOverlays = clearOverlays;
// locals
var usedOverlays = [];
var unusedOverlays = [];
function renderOverlay(rect, parent) {
var e = unusedOverlays.shift();
if (!e) {
e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
}
if (e[0].parentNode != parent[0]) {
e.appendTo(parent);
}
usedOverlays.push(e.css(rect).show());
return e;
}
function clearOverlays() {
var e;
while (e = usedOverlays.shift()) {
unusedOverlays.push(e.hide().unbind());
}
}
}
;;
function CoordinateGrid(buildFunc) {
var t = this;
var rows;
var cols;
var sources;
t.build = function() {
rows = [];
cols = [];
sources = [];
buildFunc(rows, cols, sources);
};
t.cell = function(x, y) {
var rowCnt = rows.length;
var colCnt = cols.length;
var srcCnt = sources.length;
var cols_ = cols;
var rows_ = rows;
var i, j, r=-1, c=-1, srcCol=-1, srcNo=-1;
for (i=0; i<rowCnt; i++) {
if (y >= rows[i][0] && y < rows[i][1]) {
r = i;
break;
}
}
for (i=0; i<colCnt; i++) {
if (x >= cols[i][0] && x < cols[i][1]) {
c = i;
break;
}
}
for (i=0; i<srcCnt; i++) {
if (x >= sources[i][0] && x < sources[i][1]) {
srcCol = i;
srcNo = sources[i][2];
break;
}
}
return (r>=0 && c>=0) ? { row:r, col:c, srcCol: srcCol, srcNo: srcNo } : null;
};
t.rect = function(row0, col0, row1, col1, originElement, srcCol) { // row1,col1 is inclusive
var origin = originElement.offset();
return {
top: rows[row0][0] - origin.top,
left: (typeof srcCol === 'undefined') ? cols[col0][0] - origin.left : sources[srcCol][0] - origin.left,
width: (typeof srcCol === 'undefined') ? cols[col1][1] - cols[col0][0] : sources[srcCol][1] - sources[srcCol][0],
height: rows[row1][1] - rows[row0][0]
};
};
}
;;
function HoverListener(coordinateGrid) {
var t = this;
var bindType;
var change;
var firstCell;
var cell;
t.start = function(_change, ev, _bindType) {
change = _change;
firstCell = cell = null;
coordinateGrid.build();
mouse(ev);
bindType = _bindType || 'mousemove';
$(document).bind(bindType, mouse);
};
function mouse(ev) {
_fixUIEvent(ev); // see below
var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col || newCell.srcCol != cell.srcCol)) {
if (newCell) {
if (!firstCell) {
firstCell = newCell;
}
change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col, newCell.srcNo);
}else{
change(newCell, firstCell);
}
cell = newCell;
}
}
t.stop = function() {
$(document).unbind(bindType, mouse);
return cell;
};
}
// this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
// upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
// but keep this in here for 1.8.16 users
// and maybe remove it down the line
function _fixUIEvent(event) { // for issue 1168
if (event.pageX === undefined) {
event.pageX = event.originalEvent.pageX;
event.pageY = event.originalEvent.pageY;
}
}
;;
function HorizontalPositionCache(getElement) {
var t = this,
elements = {},
lefts = {},
rights = {};
function e(i) {
return elements[i] = elements[i] || getElement(i);
}
t.left = function(i) {
return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i];
};
t.right = function(i) {
return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i];
};
t.clear = function() {
elements = {};
lefts = {};
rights = {};
};
}
;;
})(jQuery); |
(function() {
'use strict';
describe('controllers', function(){
var vm;
var $timeout;
var toastr;
beforeEach(module('boardee'));
beforeEach(inject(function(_$controller_, _$timeout_, _webDevTec_, _toastr_) {
spyOn(_webDevTec_, 'getTec').and.returnValue([{}, {}, {}, {}, {}]);
spyOn(_toastr_, 'info').and.callThrough();
vm = _$controller_('MainController');
$timeout = _$timeout_;
toastr = _toastr_;
}));
it('should have a timestamp creation date', function() {
expect(vm.creationDate).toEqual(jasmine.any(Number));
});
it('should define animate class after delaying timeout ', function() {
$timeout.flush();
expect(vm.classAnimation).toEqual('rubberBand');
});
it('should show a Toastr info and stop animation when invoke showToastr()', function() {
vm.showToastr();
expect(toastr.info).toHaveBeenCalled();
expect(vm.classAnimation).toEqual('');
});
it('should define more than 5 awesome things', function() {
expect(angular.isArray(vm.awesomeThings)).toBeTruthy();
expect(vm.awesomeThings.length === 5).toBeTruthy();
});
});
})();
|
/*
* Copyright (c) 2015 Jeffrey Hunter
*
* Distributed under the MIT license. See the LICENSE file distributed
* with this work for details and restrictions.
*/
var Memcached = require("../../index");
/** Evaluate calling context for callback */
function testContext(test, that, name, args) {
test.ok(that.hasOwnProperty('start'));
test.ok(that.start <= Date.now());
test.ok(that.hasOwnProperty('execution'))
test.ok(that.execution >= 0);
var expected = {
start: that.start,
execution: that.execution,
callback: args.callback,
type: name,
command: null,
validate: []
};
Object.keys(args).forEach(function(arg) {
expected[arg] = args[arg];
expected.validate.push([arg,null]);
});
test.deepEqual(that, expected);
}
/** Test basic get and set operations */
module.exports.testGetSet = function(test) {
var key = '19en8bgbr';
var value = '19en8c6bs';
var memcached = new Memcached("127.0.0.1:11211");
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
memcached.set(key, value, 1, function setCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'set', {"key": key, "value": value, "lifetime": 1, callback: setCallback});
test.strictEqual(reply, true);
memcached.get(key, function getCallback(err, data) {
test.ifError(err);
test.strictEqual(data, value);
testContext(test, this, 'get', {"key": key, callback: getCallback});
test.done();
});
});
});
}
/** Test expiration */
module.exports.testSetExpiration = function(test) {
var key = '19epfu6vj';
var value = '19epfueu8';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value, 1, function(err, data) {
test.ifError(err);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value);
setTimeout(function() {
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
test.done();
});
}, 1500);
});
});
}
/** Test touch */
module.exports.testTouch = function(test) {
var key = '19eph2mg1';
var value = '19eph35c8';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value, 1, function(err, data) {
test.ifError(err);
memcached.touch(key, 2, function(err, reply) {
test.ifError(err);
test.strictEqual(reply, true);
setTimeout(function() {
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value);
test.done();
});
}, 1500);
});
});
}
/** Test touch non-existent key */
module.exports.testTouchNonExistent = function(test) {
var key = '19epr4uj1';
var memcached = new Memcached("127.0.0.1:11211");
memcached.touch(key, 1, function(err, reply) {
test.ifError(err);
test.strictEqual(reply, false);
test.done();
});
}
/** Test gets */
module.exports.testGets = function(test) {
var key = '19epmksqm';
var value = '19epml3p7';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value, 1, function(err, data) {
test.ifError(err);
test.strictEqual(data, true);
memcached.gets(key, function getsCallback(err, data) {
test.ifError(err);
testContext(test, this, 'gets', {"key": key, callback: getsCallback});
test.ok(data.hasOwnProperty('cas'));
test.ok(typeof data.cas, "string");
test.ok(data.cas.length > 0);
var expected = {cas: data.cas};
expected[key] = value;
test.deepEqual(data, expected);
test.done();
});
});
}
/** Test getMutli */
module.exports.testGetMulti = function(test) {
var keys = ['19epo6uuj', '19epo77eh', '19epo7jp8'];
var values = ['19epo7tqc', '19epo882f', '19epo8ek8'];
var toSet = [0, 1, 2];
var memcached = new Memcached("127.0.0.1:11211");
function setNext(err) {
test.ifError(err);
if (toSet.length > 0)
memcached.set(keys[toSet[0]], values[toSet.shift()], 1, setNext);
else
getAll();
}
function getAll() {
memcached.getMulti(keys, function getMultiCallback(err, data) {
test.ifError(err);
// global context is used by memcached for this call
var expected = {};
keys.forEach(function(key, idx) { expected[key] = values[idx]; });
test.deepEqual(expected, data);
test.done();
});
}
setNext();
}
/** Test get with array */
module.exports.testGetWithArray = function(test) {
var keys = ['19epp4imt', '19epp4rt5', '19epp555h'];
var values = ['19epp5fe3', '19epp5s4c', '19epp688v'];
var toSet = [0, 1, 2];
var memcached = new Memcached("127.0.0.1:11211");
function setNext(err) {
test.ifError(err);
if (toSet.length > 0)
memcached.set(keys[toSet[0]], values[toSet.shift()], 1, setNext);
else
getAll();
}
function getAll() {
memcached.get(keys, function getMultiCallback(err, data) {
test.ifError(err);
// global context is used by memcached for this call
var expected = {};
keys.forEach(function(key, idx) { expected[key] = values[idx]; });
test.deepEqual(expected, data);
test.done();
});
}
setNext();
}
/** Test successful replace */
module.exports.testReplaceSuccess = function(test) {
var key = '19ept1qon';
var value1 = '19ept7un3';
var value2 = '19ept96oc';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value1, 1, function(err) {
test.ifError(err);
memcached.replace(key, value2, 1, function replaceCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'replace', {"key": key, "value": value2, "lifetime": 1, callback: replaceCallback});
test.strictEqual(reply, true);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value2);
test.done();
});
});
});
}
/** Test unsuccessful replace */
module.exports.testReplaceFailure = function(test) {
var key = '19eptdnq3';
var value = '19epteo37';
var memcached = new Memcached("127.0.0.1:11211");
memcached.replace(key, value, 1, function replaceCallback(err, reply) {
test.ok(err);
test.strictEqual(err.notStored, true);
test.strictEqual(err.message, "Item is not stored");
testContext(test, this, 'replace', {"key": key, "value": value, "lifetime": 1, callback: replaceCallback});
test.strictEqual(reply, false);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
test.done();
});
});
}
/** Test flush */
module.exports.testFlush = function(test) {
var key = '19epuc5dp';
var value = '';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value, 1, function(err) {
test.ifError(err);
memcached.flush(function flushCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [true]);
memcached.get(key, function getCallback(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
test.done();
});
});
});
}
/** Test successful add */
module.exports.testAddSuccess = function(test) {
var key = '19esns0kt';
var value = '19esnsd6m';
var memcached = new Memcached("127.0.0.1:11211");
memcached.add(key, value, 1, function addCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'add', {"key": key, "value": value, "lifetime": 1, callback: addCallback});
test.strictEqual(reply, true);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value);
test.done();
});
});
}
/** Test failed add */
module.exports.testAddFailure = function(test) {
var key = '19esnstjk';
var value1 = '19eso8qge';
var value2 = '19eso924r';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value1, 1, function(err) {
test.ifError(err);
memcached.add(key, value2, 1, function addCallback(err, reply) {
test.ok(err);
test.strictEqual(err.notStored, true);
test.strictEqual(err.message, "Item is not stored");
testContext(test, this, 'add', {"key": key, "value": value2, "lifetime": 1, callback: addCallback});
test.strictEqual(reply, false);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value1);
test.done();
});
});
});
}
/** Test successful cas call */
module.exports.testCasSuccess = function(test) {
var key = '19espjh7k';
var value1 = '19espjpl5';
var value2 = '19espjtqq';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value1, 1, function(err) {
test.ifError(err);
memcached.gets(key, function(err, data) {
test.ifError(err);
memcached.cas(key, value2, data.cas, 1, function casCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'cas', {"key": key, "value": value2, "cas": data.cas, "lifetime": 1, callback: casCallback});
test.strictEqual(reply, true);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value2);
test.done();
});
});
});
});
}
/** Test failed cas call */
module.exports.testCasFailure = function(test) {
var key = '19espmmg4';
var value1 = '19espq82q';
var value2 = '19espqia5';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value1, 1, function(err) {
test.ifError(err);
memcached.gets(key, function(err, data) {
test.ifError(err);
memcached.cas(key, value2, "invalid", 1, function casCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'cas', {"key": key, "value": value2, "cas": "invalid", "lifetime": 1, callback: casCallback});
test.strictEqual(reply, false);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value1);
test.done();
});
});
});
});
}
/** Test successful append */
module.exports.testAppendSuccess = function(test) {
var key = '19esr70ik';
var value1 = '19esr75a6';
var value2 = '19esr7939';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value1, 1, function(err) {
test.ifError(err);
memcached.append(key, value2, function appendCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'append', {"key": key, "value": value2, callback: appendCallback});
test.strictEqual(reply, true);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value1 + value2);
test.done();
});
});
});
}
/** Test unsuccessful append */
module.exports.testAppendFailure = function(test) {
var key = '19esr7gcj';
var value = '19esr7lsr';
var memcached = new Memcached("127.0.0.1:11211");
memcached.append(key, value, function appendCallback(err, reply) {
test.ok(err);
test.strictEqual(err.notStored, true);
test.strictEqual(err.message, "Item is not stored");
testContext(test, this, 'append', {"key": key, "value": value, callback: appendCallback});
test.strictEqual(reply, false);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
test.done();
});
});
}
/** Test successful prepend */
module.exports.testPrependSuccess = function(test) {
var key = '19evau93p';
var value1 = '19evaujvt';
var value2 = '19evaunli';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value1, 1, function(err) {
test.ifError(err);
memcached.prepend(key, value2, function prependCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'prepend', {"key": key, "value": value2, callback: prependCallback});
test.strictEqual(reply, true);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value2 + value1);
test.done();
});
});
});
}
/** Test unsuccessful prepend */
module.exports.testPrependFailure = function(test) {
var key = '19evausm8';
var value = '19evavruq';
var memcached = new Memcached("127.0.0.1:11211");
memcached.prepend(key, value, function prependCallback(err, reply) {
test.ok(err);
test.strictEqual(err.notStored, true);
test.strictEqual(err.message, "Item is not stored");
testContext(test, this, 'prepend', {"key": key, "value": value, callback: prependCallback});
test.strictEqual(reply, false);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
test.done();
});
});
}
/** Test successful increment */
module.exports.testIncrSuccess = function(test) {
var key = '19evbdh8t';
var value1 = 258;
var value2 = 12;
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value1, 1, function(err) {
test.ifError(err);
memcached.incr(key, value2, function incrCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'incr', {"key": key, "value": value2, callback: incrCallback});
test.strictEqual(reply, value1 + value2);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value1 + value2);
test.done();
});
});
});
}
/** Test unsuccessful increment */
module.exports.testIncrFailure = function(test) {
var key = '19evbj7rf';
var value = 438;
var memcached = new Memcached("127.0.0.1:11211");
memcached.incr(key, value, function incrCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'incr', {"key": key, "value": value, callback: incrCallback});
test.strictEqual(reply, false);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
test.done();
});
});
}
/** Test successful decrement */
module.exports.testDecrSuccess = function(test) {
var key = '19evc21pi';
var value1 = 833;
var value2 = 333;
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value1, 1, function(err) {
test.ifError(err);
memcached.decr(key, value2, function decrCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'decr', {"key": key, "value": value2, callback: decrCallback});
test.strictEqual(reply, value1 - value2);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value1 - value2);
test.done();
});
});
});
}
/** Test unsuccessful decrement */
module.exports.testDecrFailure = function(test) {
var key = '19evc4uqo';
var value = 128;
var memcached = new Memcached("127.0.0.1:11211");
memcached.decr(key, value, function decrCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'decr', {"key": key, "value": value, callback: decrCallback});
test.strictEqual(reply, false);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
test.done();
});
});
}
/** Test delete */
module.exports.testDelete = function(test) {
var key = '19evevlni';
var value = '19evf0356';
var memcached = new Memcached("127.0.0.1:11211");
memcached.set(key, value, 1, function(err) {
test.ifError(err);
memcached.del(key, function delCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'delete', {"key": key, callback: delCallback});
test.strictEqual(reply, true);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, undefined);
test.done();
});
});
});
}
/** Test delete nonexistent key */
module.exports.testDeleteNonExisting = function(test) {
var key = '19evf3p03';
var memcached = new Memcached("127.0.0.1:11211");
memcached.del(key, function delCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'delete', {"key": key, callback: delCallback});
test.strictEqual(reply, false);
test.done();
});
}
/** Test version */
module.exports.testVersion = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
memcached.version(function versionCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "127.0.0.1:11211",
"version": "1.4.20",
"major": "1",
"minor": "4",
"bugfix": "20"
}]);
test.done();
});
}
/** Test version with multiple servers */
module.exports.testVersionMultiple = function(test) {
var memcached = new Memcached(["192.168.0.1:11211","192.168.0.2:11211"]);
memcached.version(function versionCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "192.168.0.1:11211",
"version": "1.4.20",
"major": "1",
"minor": "4",
"bugfix": "20"
},{
"server": "192.168.0.2:11211",
"version": "1.4.20",
"major": "1",
"minor": "4",
"bugfix": "20"
}]);
test.done();
});
}
/** Test stats */
module.exports.testStats = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
memcached.stats(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "127.0.0.1:11211",
"pid":1,"uptime":1,"time":reply[0].time,"version":"1.4.20","libevent":"2.0.22-stable","pointer_size":64,"rusage_user":"0.0","rusage_system":"0.0","curr_connections":1,"total_connections":1,"connection_structures":1,"reserved_fds":0,"cmd_get":0,"cmd_set":0,"cmd_flush":0,"cmd_touch":0,"get_hits":0,"get_misses":0,"delete_misses":0,"delete_hits":0,"incr_misses":0,"incr_hits":0,"decr_misses":0,"decr_hits":0,"cas_misses":0,"cas_hits":0,"cas_badval":0,"touch_hits":0,"touch_misses":0,"auth_cmds":0,"auth_errors":0,"bytes_read":1,"bytes_written":1,"limit_maxbytes":67108864,"accepting_conns":1,"listen_disabled_num":0,"threads":4,"conn_yields":0,"hash_power_level":16,"hash_bytes":524288,"hash_is_expanding":0,"malloc_fails":0,"bytes":0,"curr_items":0,"total_items":0,"expired_unfetched":0,"evicted_unfetched":0,"evictions":0,"reclaimed":0,"crawler_reclaimed":0
}]);
test.done();
});
}
/** Test stats with multiple servers */
module.exports.testStatsMultiple = function(test) {
var memcached = new Memcached(["192.168.0.1:11211","192.168.0.2:11211"]);
memcached.stats(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "192.168.0.1:11211",
"pid":1,"uptime":1,"time":reply[0].time,"version":"1.4.20","libevent":"2.0.22-stable","pointer_size":64,"rusage_user":"0.0","rusage_system":"0.0","curr_connections":1,"total_connections":1,"connection_structures":1,"reserved_fds":0,"cmd_get":0,"cmd_set":0,"cmd_flush":0,"cmd_touch":0,"get_hits":0,"get_misses":0,"delete_misses":0,"delete_hits":0,"incr_misses":0,"incr_hits":0,"decr_misses":0,"decr_hits":0,"cas_misses":0,"cas_hits":0,"cas_badval":0,"touch_hits":0,"touch_misses":0,"auth_cmds":0,"auth_errors":0,"bytes_read":1,"bytes_written":1,"limit_maxbytes":67108864,"accepting_conns":1,"listen_disabled_num":0,"threads":4,"conn_yields":0,"hash_power_level":16,"hash_bytes":524288,"hash_is_expanding":0,"malloc_fails":0,"bytes":0,"curr_items":0,"total_items":0,"expired_unfetched":0,"evicted_unfetched":0,"evictions":0,"reclaimed":0,"crawler_reclaimed":0
},{
"server": "192.168.0.2:11211",
"pid":1,"uptime":1,"time":reply[1].time,"version":"1.4.20","libevent":"2.0.22-stable","pointer_size":64,"rusage_user":"0.0","rusage_system":"0.0","curr_connections":1,"total_connections":1,"connection_structures":1,"reserved_fds":0,"cmd_get":0,"cmd_set":0,"cmd_flush":0,"cmd_touch":0,"get_hits":0,"get_misses":0,"delete_misses":0,"delete_hits":0,"incr_misses":0,"incr_hits":0,"decr_misses":0,"decr_hits":0,"cas_misses":0,"cas_hits":0,"cas_badval":0,"touch_hits":0,"touch_misses":0,"auth_cmds":0,"auth_errors":0,"bytes_read":1,"bytes_written":1,"limit_maxbytes":67108864,"accepting_conns":1,"listen_disabled_num":0,"threads":4,"conn_yields":0,"hash_power_level":16,"hash_bytes":524288,"hash_is_expanding":0,"malloc_fails":0,"bytes":0,"curr_items":0,"total_items":0,"expired_unfetched":0,"evicted_unfetched":0,"evictions":0,"reclaimed":0,"crawler_reclaimed":0
}]);
test.done();
});
}
/** Test settings */
module.exports.testSettings = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
memcached.settings(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "127.0.0.1:11211",
"maxbytes":67108864,"maxconns":1024,"tcpport":11211,"udpport":11211,"inter":"NULL","verbosity":0,"oldest":13516,"evictions":"on","domain_socket":"NULL","umask":700,"growth_factor":"1.25","chunk_size":48,"num_threads":4,"num_threads_per_udp":4,"stat_key_prefix":":","detail_enabled":"no","reqs_per_event":20,"cas_enabled":"yes","tcp_backlog":1024,"binding_protocol":"auto-negotiate","auth_enabled_sasl":"no","item_size_max":1048576,"maxconns_fast":"no","hashpower_init":0,"slab_reassign":"no","slab_automove":0,"lru_crawler":"no","lru_crawler_sleep":100,"lru_crawler_tocrawl":0,"tail_repair_time":0,"flush_enabled":"yes","hash_algorithm":"jenkins"
}]);
test.done();
});
}
/** Test settings with multiple servers */
module.exports.testSettingsMultiple = function(test) {
var memcached = new Memcached(["192.168.0.1:11211","192.168.0.2:11211"]);
memcached.settings(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "192.168.0.1:11211",
"maxbytes":67108864,"maxconns":1024,"tcpport":11211,"udpport":11211,"inter":"NULL","verbosity":0,"oldest":13516,"evictions":"on","domain_socket":"NULL","umask":700,"growth_factor":"1.25","chunk_size":48,"num_threads":4,"num_threads_per_udp":4,"stat_key_prefix":":","detail_enabled":"no","reqs_per_event":20,"cas_enabled":"yes","tcp_backlog":1024,"binding_protocol":"auto-negotiate","auth_enabled_sasl":"no","item_size_max":1048576,"maxconns_fast":"no","hashpower_init":0,"slab_reassign":"no","slab_automove":0,"lru_crawler":"no","lru_crawler_sleep":100,"lru_crawler_tocrawl":0,"tail_repair_time":0,"flush_enabled":"yes","hash_algorithm":"jenkins"
},{
"server": "192.168.0.2:11211",
"maxbytes":67108864,"maxconns":1024,"tcpport":11211,"udpport":11211,"inter":"NULL","verbosity":0,"oldest":13516,"evictions":"on","domain_socket":"NULL","umask":700,"growth_factor":"1.25","chunk_size":48,"num_threads":4,"num_threads_per_udp":4,"stat_key_prefix":":","detail_enabled":"no","reqs_per_event":20,"cas_enabled":"yes","tcp_backlog":1024,"binding_protocol":"auto-negotiate","auth_enabled_sasl":"no","item_size_max":1048576,"maxconns_fast":"no","hashpower_init":0,"slab_reassign":"no","slab_automove":0,"lru_crawler":"no","lru_crawler_sleep":100,"lru_crawler_tocrawl":0,"tail_repair_time":0,"flush_enabled":"yes","hash_algorithm":"jenkins"
}]);
test.done();
});
}
/** Test slabs */
module.exports.testSlabs = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
memcached.slabs(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "127.0.0.1:11211",
"1":{"chunk_size":96,"chunks_per_page":10922,"total_pages":1,"total_chunks":10922,"used_chunks":0,"free_chunks":10922,"free_chunks_end":0,"mem_requested":0,"get_hits":0,"cmd_set":0,"delete_hits":0,"incr_hits":0,"decr_hits":0,"cas_hits":0,"cas_badval":0,"touch_hits":0},"active_slabs":{"undefined":1},"total_malloced":{"undefined":1048512}
}]);
test.done();
});
}
/** Test slabs with multiple servers */
module.exports.testSlabsMultiple = function(test) {
var memcached = new Memcached(["192.168.0.1:11211","192.168.0.2:11211"]);
memcached.slabs(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "192.168.0.1:11211",
"1":{"chunk_size":96,"chunks_per_page":10922,"total_pages":1,"total_chunks":10922,"used_chunks":0,"free_chunks":10922,"free_chunks_end":0,"mem_requested":0,"get_hits":0,"cmd_set":0,"delete_hits":0,"incr_hits":0,"decr_hits":0,"cas_hits":0,"cas_badval":0,"touch_hits":0},"active_slabs":{"undefined":1},"total_malloced":{"undefined":1048512}
},{
"server": "192.168.0.2:11211",
"1":{"chunk_size":96,"chunks_per_page":10922,"total_pages":1,"total_chunks":10922,"used_chunks":0,"free_chunks":10922,"free_chunks_end":0,"mem_requested":0,"get_hits":0,"cmd_set":0,"delete_hits":0,"incr_hits":0,"decr_hits":0,"cas_hits":0,"cas_badval":0,"touch_hits":0},"active_slabs":{"undefined":1},"total_malloced":{"undefined":1048512}
}]);
test.done();
});
}
/** Test items with no entries */
module.exports.testItemsEmpty = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
memcached.flush(function(err) {
test.ifError(err);
memcached.items(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{}]);
test.done();
});
});
}
/** Test items with one entry */
module.exports.testItemsOne = function(test) {
var key = '19f3asnit';
var value = '19f3asukk';
var memcached = new Memcached("127.0.0.1:11211");
memcached.flush(function(err) {
test.ifError(err);
memcached.set(key, value, 1, function(err) {
test.ifError(err);
memcached.items(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "127.0.0.1:11211",
"1":{"number":1,"age":1,"evicted":0,"evicted_nonzero":0,"evicted_time":0,"outofmemory":0,"tailrepairs":0,"reclaimed":0,"expired_unfetched":0,"evicted_unfetched":0,"crawler_reclaimed":0}
}]);
test.done();
});
});
});
}
/** Test items with multiple servers */
module.exports.testItemsMultiple = function(test) {
var key = '19f3at90a';
var value = '19f3atbg0';
var memcached = new Memcached(["192.168.0.1:11211","192.168.0.2:11211"]);
memcached.flush(function(err) {
test.ifError(err);
memcached.set(key, value, 1, function(err) {
test.ifError(err);
memcached.items(function statsCallback(err, reply) {
test.ifError(err);
// global context is used by memcached for this call
test.deepEqual(reply, [{
"server": "192.168.0.1:11211",
"1":{"number":1,"age":1,"evicted":0,"evicted_nonzero":0,"evicted_time":0,"outofmemory":0,"tailrepairs":0,"reclaimed":0,"expired_unfetched":0,"evicted_unfetched":0,"crawler_reclaimed":0}
},{
"server": "192.168.0.2:11211",
"1":{"number":1,"age":1,"evicted":0,"evicted_nonzero":0,"evicted_time":0,"outofmemory":0,"tailrepairs":0,"reclaimed":0,"expired_unfetched":0,"evicted_unfetched":0,"crawler_reclaimed":0}
}]);
test.done();
});
});
});
}
/** Test cachedump with no entries */
module.exports.testCachedumpEmpty = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
memcached.flush(function(err) {
test.ifError(err);
memcached.cachedump("127.0.0.1:11211", 1, 100, function cachedumpCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'cachedump', {server: "127.0.0.1:11211", slabid: 1, number: 100, callback: cachedumpCallback});
test.strictEqual(reply, undefined);
test.done();
});
});
}
/** Test cachedump with one entry */
module.exports.testCachedumpOne = function(test) {
var key = '19fb4f76b';
var value = '19fb4hu8b';
var memcached = new Memcached("127.0.0.1:11211");
memcached.flush(function(err) {
test.ifError(err);
var ts = Math.round(Date.now()/1000);
memcached.set(key, value, 1, function(err, reply) {
test.ifError(err);
memcached.cachedump("127.0.0.1:11211", 1, 100, function cachedumpCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'cachedump', {server: "127.0.0.1:11211", slabid: 1, number: 100, callback: cachedumpCallback});
test.deepEqual(reply, {key: key, b: value.length, s: ts+1});
test.done();
});
});
});
}
/** Test cachedump with multiple entries */
module.exports.testCachedumpMultiple = function(test) {
var keys = ['19fb52dci','19fb52mb9'];
var values = ['19fb544h8','19fb549gt'];
var ts = [];
var memcached = new Memcached("127.0.0.1:11211");
memcached.flush(function(err) {
test.ifError(err);
ts.push(Math.round(Date.now()/1000));
memcached.set(keys[0], values[0], 1, function(err, reply) {
test.ifError(err);
ts.push(Math.round(Date.now()/1000));
memcached.set(keys[1], values[1], 1, function(err, reply) {
test.ifError(err);
memcached.cachedump("127.0.0.1:11211", 1, 100, function cachedumpCallback(err, reply) {
test.ifError(err);
testContext(test, this, 'cachedump', {server: "127.0.0.1:11211", slabid: 1, number: 100, callback: cachedumpCallback});
test.deepEqual(reply, [{key: keys[0], b: values[0].length, s: ts[0]+1},{key: keys[1], b: values[1].length, s: ts[1]+1}]);
test.done();
});
});
});
});
}
/** Test end */
module.exports.testEnd = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
memcached.end();
test.done();
}
/** Test config */
module.exports.testConfig = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
Object.keys(Memcached.config).forEach(function(c) {
test.strictEqual(memcached[c], Memcached.config[c]);
});
memcached = new Memcached("127.0.0.1:11211", {maxKeySize: 500, remove: true});
Object.keys(Memcached.config).forEach(function(c) {
if (c === 'maxKeySize')
test.strictEqual(memcached[c], 500);
else if (c === 'remove')
test.strictEqual(memcached[c], true);
else
test.strictEqual(memcached[c], Memcached.config[c]);
});
test.done();
}
/** Test access to the cache */
module.exports.testCacheGet = function(test) {
var key = '19flcg6tg';
var value = '19flcgclp';
var memcached = new Memcached("127.0.0.1:11211");
var cache = memcached.cache();
memcached.set(key, value, 1, function(err) {
test.ifError(err);
test.strictEqual(cache[key].value, value);
test.done();
});
}
/** Test setting the cache */
module.exports.testCacheSet = function(test) {
var keys = ['19gla8ho0','19gla8m1o'];
var values = ['19gla8qn0','19gla8sk1'];
var memcachedA = new Memcached("127.0.0.1:11211");
var cacheA = memcachedA.cache();
var cacheB = {};
var memcachedB = new Memcached("127.0.0.1:11211");
memcachedB.cache(cacheB);
memcachedA.set(keys[0], values[0], 1, function(err) {
test.ifError(err);
memcachedB.set(keys[1], values[1], 1, function(err) {
test.ifError(err);
test.strictEqual(cacheA[keys[0]].value, values[0]);
test.strictEqual(cacheB[keys[1]].value, values[1]);
test.ok(!cacheA.hasOwnProperty(keys[1]));
test.ok(!cacheB.hasOwnProperty(keys[0]));
memcachedA.flush(function(err) {
test.ifError(err);
test.strictEqual(Object.keys(cacheA).length, 0);
memcachedB.flush(function(err) {
test.ifError(err);
test.strictEqual(Object.keys(cacheB).length, 0);
test.done();
});
});
});
});
}
/** Test 0 TTL (doesn't expire) */
module.exports.testZeroTTL = function(test) {
var key = '19g4nsf8u';
var value = '19g4nv1vr';
var memcached = new Memcached("127.0.0.1:11211");
var cache = memcached.cache();
memcached.set(key, value, 0, function(err) {
test.ifError(err);
test.strictEqual(cache[key].expires, 0);
memcached.get(key, function(err, data) {
test.ifError(err);
test.strictEqual(data, value);
test.done();
});
});
}
/** Test maxExpiration setting */
module.exports.testMaxExpiration = function(test) {
var days = 60 * 60 * 24;
var keys = ['19g5rtq8c','19g5ru0fs'];
var values = ['19g5ru64u','19g5ru9e7'];
var memcached = new Memcached("127.0.0.1:11211");
var memcached2 = new Memcached("127.0.0.1:11211", {maxExpiration: 90 * days});
var cache = memcached.cache();
memcached.set(keys[0], values[0], 45 * days, function(err) {
test.ifError(err);
var now = Date.now();
memcached2.set(keys[1], values[1], 45 * days, function(err) {
test.ifError(err);
test.ok(Math.round(cache[keys[0]].expires/1000) - 45 * days <= 1);
test.ok(Math.round(cache[keys[1]].expires/1000) - (Math.round(now / 1000) + 45 * days) <= 1);
test.done();
});
});
}
/** Test aliases */
module.exports.testAliases = function(test) {
var memcached = new Memcached("127.0.0.1:11211");
test.strictEqual(memcached.delete, memcached.del);
test.strictEqual(memcached.flushAll, memcached.flush);
test.strictEqual(memcached.statsSettings, memcached.settings);
test.strictEqual(memcached.statsSlabs, memcached.slabs);
test.strictEqual(memcached.statsItems, memcached.items);
test.done();
}
|
/**
* @file Karma config
* @author ielgnaw(wuji0223@gmail.com)
*/
import path from 'path';
import webpack from 'webpack';
import {assetsPath} from '../tool/util';
const SRC_ROOT = path.resolve(__dirname, '../src');
export default function (config) {
config.set({
basePath: '../',
frameworks: ['mocha', 'chai'],
files: [
'node_modules/babel-polyfill/dist/polyfill.js',
{
pattern: 'test/karma.adapter.js',
watched: false,
served: true,
included: true
}
],
plugins: [
'karma-coverage',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-mocha',
'karma-sourcemap-loader',
'karma-webpack',
'karma-mocha-reporter',
'karma-chai',
'karma-babel-preprocessor'
],
exclude: [],
preprocessors: {
'test/karma.adapter.js': ['webpack', 'sourcemap']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [process.env.TRAVIS ? 'PhantomJS' : 'Chrome'],
singleRun: process.env.NODE_ENV !== 'test',
concurrency: Infinity,
webpack: {
devtool: 'inline-source-map',
resolve: {
extensions: ['', '.js', '.san'],
fallback: [path.join(__dirname, '../node_modules')],
alias: {
src: SRC_ROOT
}
},
module: {
loaders: [
{
test: /\.san$/,
loader: 'san-loader',
exclude: /node_modules/
},
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'stage-1'],
plugins: [
['transform-runtime', {
polyfill: false,
regenerator: false
}]
]
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 100000,
name: assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 100000,
name: assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('test')
})
]
},
webpackServer: {
noInfo: true
}
});
}
|
const React = require("react/addons");
const _ = require("lodash");
var FlashNotice = require('./flash_notices');
class MainFlash extends React.Component {
constructor(props){
super(props);
}
render(){
return (
<FlashNotice type={this.props.type}>
{this.props.message}
</FlashNotice>
);
}
}
module.exports = MainFlash;
|
version https://git-lfs.github.com/spec/v1
oid sha256:275d0f4cc752b6a57f247c903a14fdcbd6256dbf55ce027c085c040349730db7
size 49009
|
version https://git-lfs.github.com/spec/v1
oid sha256:dff8bca9b7290a519ccc582e9b7365f9185450ec3e96c5a4c70d5c860b575244
size 13617
|
/**
* Created by wangdi on 4/11/16.
*/
'use strict';
import React, {Component} from 'react';
import {Platform} from 'react-native';
import {Navigator} from 'react-native-deprecated-custom-components';
import MainPage from '../page/MainPage';
import SignInPage from '../page/SignInAndSignup/SignInPage';
import WebViewPage from '../page/WebViewPage';
import SplashScreen from '../native_modules/SplashScreen';
export default class Navigation extends Component{
render(){
return(
<Navigator
initialRoute={{component: MainPage}}
renderScene={(route, navigator) => {
return <route.component navigator={navigator} {...route.args}/>
}
}/>
);
}
componentDidMount(){
if(Platform.OS === 'android')
SplashScreen.hide();
}
} |
// Copyright 2013-2022, University of Colorado Boulder
/**
* An immutable permutation that can permute an array
*
* @author Jonathan Olson <jonathan.olson@colorado.edu>
*/
import isArray from '../../phet-core/js/isArray.js';
import './Utils.js';
import dot from './dot.js';
class Permutation {
/**
* Creates a permutation that will rearrange a list so that newList[i] = oldList[permutation[i]]
*
* @param {Array.<number>} indices
*/
constructor( indices ) {
// @public {Array.<number>}
this.indices = indices;
}
/**
* @public
*
* @returns {number}
*/
size() {
return this.indices.length;
}
/**
* Applies the permutation, returning either a new array or number (whatever was provided).
* @public
*
* @param {Array.<number>|number} arrayOrInt
* @returns {Array.<number>|number}
*/
apply( arrayOrInt ) {
if ( isArray( arrayOrInt ) ) {
if ( arrayOrInt.length !== this.size() ) {
throw new Error( `Permutation length ${this.size()} not equal to list length ${arrayOrInt.length}` );
}
// permute it as an array
const result = new Array( arrayOrInt.length );
for ( let i = 0; i < arrayOrInt.length; i++ ) {
result[ i ] = arrayOrInt[ this.indices[ i ] ];
}
return result;
}
else {
// permute a single index
return this.indices[ arrayOrInt ];
}
}
/**
* Creates a new permutation that is the inverse of this.
* @public
*
* @returns {Permutation}
*/
inverted() {
const newPermutation = new Array( this.size() );
for ( let i = 0; i < this.size(); i++ ) {
newPermutation[ this.indices[ i ] ] = i;
}
return new Permutation( newPermutation );
}
/**
* @public
*
* @param {Array.<number>} indices
* @returns {Array.<Permutation>}
*/
withIndicesPermuted( indices ) {
const result = [];
Permutation.forEachPermutation( indices, integers => {
const oldIndices = this.indices;
const newPermutation = oldIndices.slice( 0 );
for ( let i = 0; i < indices.length; i++ ) {
newPermutation[ indices[ i ] ] = oldIndices[ integers[ i ] ];
}
result.push( new Permutation( newPermutation ) );
} );
return result;
}
/**
* @public
*
* @returns {string}
*/
toString() {
return `P[${this.indices.join( ', ' )}]`;
}
/**
* @public
*
* @param {Permutation} permutation
* @returns {boolean}
*/
equals( permutation ) {
return this.indices.length === permutation.indices.length && _.isEqual( this.indices, permutation.indices );
}
/**
* Creates an identity permutation of a given size.
* @public
*
* @param {number} size
* @returns {Permutation}
*/
static identity( size ) {
assert && assert( size >= 0 );
const indices = new Array( size );
for ( let i = 0; i < size; i++ ) {
indices[ i ] = i;
}
return new Permutation( indices );
}
/**
* Lists all permutations that have a given size
* @public
*
* @param {number} size
* @returns {Array.<Permutation>}
*/
static permutations( size ) {
const result = [];
Permutation.forEachPermutation( dot.rangeInclusive( 0, size - 1 ), integers => {
result.push( new Permutation( integers ) );
} );
return result;
}
/**
* Calls a callback on every single possible permutation of the given Array
* @public
*
* @param {Array.<*>} array
* @param {function(Array.<*>)} callback - Called on each permuted version of the array possible
*/
static forEachPermutation( array, callback ) {
recursiveForEachPermutation( array, [], callback );
}
}
dot.register( 'Permutation', Permutation );
/**
* Call our function with each permutation of the provided list PREFIXED by prefix, in lexicographic order
*
* @param array List to generate permutations of
* @param prefix Elements that should be inserted at the front of each list before each call
* @param callback Function to call
*/
function recursiveForEachPermutation( array, prefix, callback ) {
if ( array.length === 0 ) {
callback( prefix );
}
else {
for ( let i = 0; i < array.length; i++ ) {
const element = array[ i ];
// remove the element from the array
const nextArray = array.slice( 0 );
nextArray.splice( i, 1 );
// add it into the prefix
const nextPrefix = prefix.slice( 0 );
nextPrefix.push( element );
recursiveForEachPermutation( nextArray, nextPrefix, callback );
}
}
}
export default Permutation; |
/*
* Copyright (c) 2017. MIT-license for Jari Van Melckebeke
* Note that there was a lot of educational work in this project,
* this project was (or is) used for an assignment from Realdolmen in Belgium.
* Please just don't abuse my work
*/
define(function (require) {
var simpleLayoutHelper = require('./simpleLayoutHelper');
return function (ecModel, api) {
ecModel.eachSeriesByType('graph', function (seriesModel) {
var layout = seriesModel.get('layout');
if (!layout || layout === 'none') {
simpleLayoutHelper(seriesModel);
}
});
};
}); |
Livefyre.require([
'streamhub-wall#3','streamhub-sdk#2','stream#0.2.2'],
function (LiveMediaWall,SDK,Stream) {
var collection = new SDK.Collection({
"articleId": "13",
"siteId": 333682,
"network": "client-solutions.fyre.co"
});
var wall = window.wall = new LiveMediaWall({
el: document.getElementById("wall"),
postButton: true
});
function itemsWithImages(){
var customTransform = new Stream.Transform({});
customTransform._transform = function(content, done){
if (content.attachments.length == 0){
done();
}else{
//TODO: attachment might be in array item > 0
if (content.attachments[0].type === "photo" || content.attachments[0].type === "video"){
return done(null, content);
}
done();
}
};
return customTransform;
};
collection.createUpdater().pipe(itemsWithImages()).pipe(wall);
collection.createArchive().pipe(itemsWithImages()).pipe(wall.more);
}); |
// ch05-functions--destructuring-arguments.js
// object as argument
function getSentenceObj({ subject, verb, object }) {
return `${subject} ${verb} ${object}`;
}
const o = {
subject: "I",
verb: "love",
object: "JavaScript",
};
let sentence = getSentenceObj(o);
console.log(sentence); // I love JavaScript
// array as argument
function getSentenceArr([ subject, verb, object ]) {
return `${subject} ${verb} ${object}`;
}
const arr = [ "I", "love", "JavaScript" ];
let sent = getSentenceArr(arr); // "I love JavaScript"
console.log(sent); // I love JavaScript
// spread operator (...)
// Note that if you use the spread operator in a function declaration, it must be the last argument.
function addPrefix(prefix, ...words) {
const prefixedWords = [];
for( let i = 0; i < words.length; i++ ) {
prefixedWords[i] = prefix + words[i];
}
return prefixedWords;
}
addPrefix("con", "verse", "vex");
console.log(addPrefix("con", "verse", "vex")); // ["converse", "convex"]
// Default Arguments
function f(a, b = "default", c = 3) {
console.log("\n" + arguments.length + " arguments");
return `${a} - ${b} - ${c}`;
}
console.log(f(5, 6, 7)); // "5 - 6 - 7"
console.log(f(5, 6)); // "5 - 6 - 3"
console.log(f(5)); // "5 - default - 3"
console.log(f()); // "undefined - default - 3"
|
'use strict';
const chai = require('chai'),
sinon = require('sinon'),
expect = chai.expect,
Sequelize = require('../../../index'),
Promise = Sequelize.Promise,
Op = Sequelize.Op,
Support = require('../support'),
current = Support.sequelize,
config = require('../../config/config');
describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
describe('validations', () => {
const checks = {
is: {
spec: { args: ['[a-z]', 'i'] },
fail: '0',
pass: 'a'
},
not: {
spec: { args: ['[a-z]', 'i'] },
fail: 'a',
pass: '0'
},
isEmail: {
fail: 'a',
pass: 'abc@abc.com'
},
isUrl: {
fail: 'abc',
pass: 'http://abc.com'
},
isIP: {
fail: 'abc',
pass: '129.89.23.1'
},
isIPv4: {
fail: 'abc',
pass: '129.89.23.1'
},
isIPv6: {
fail: '1111:2222:3333::5555:',
pass: 'fe80:0000:0000:0000:0204:61ff:fe9d:f156'
},
isAlpha: {
stringOrBoolean: true,
spec: { args: 'en-GB' },
fail: '012',
pass: 'abc'
},
isAlphanumeric: {
stringOrBoolean: true,
spec: { args: 'en-GB' },
fail: '_abc019',
pass: 'abc019'
},
isNumeric: {
fail: 'abc',
pass: '019'
},
isInt: {
fail: '9.2',
pass: '-9'
},
isLowercase: {
fail: 'AB',
pass: 'ab'
},
isUppercase: {
fail: 'ab',
pass: 'AB'
},
isDecimal: {
fail: 'a',
pass: '0.2'
},
isFloat: {
fail: 'a',
pass: '9.2'
},
isNull: {
fail: 0,
pass: null
},
notEmpty: {
fail: ' ',
pass: 'a'
},
equals: {
spec: { args: 'bla bla bla' },
fail: 'bla',
pass: 'bla bla bla'
},
contains: {
spec: { args: 'bla' },
fail: 'la',
pass: '0bla23'
},
notContains: {
spec: { args: 'bla' },
fail: '0bla23',
pass: 'la'
},
regex: {
spec: { args: ['[a-z]', 'i'] },
fail: '0',
pass: 'a'
},
notRegex: {
spec: { args: ['[a-z]', 'i'] },
fail: 'a',
pass: '0'
},
len: {
spec: { args: [2, 4] },
fail: ['1', '12345'],
pass: ['12', '123', '1234'],
raw: true
},
len$: {
spec: [2, 4],
fail: ['1', '12345'],
pass: ['12', '123', '1234'],
raw: true
},
isUUID: {
spec: { args: 4 },
fail: 'f47ac10b-58cc-3372-a567-0e02b2c3d479',
pass: 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
},
isDate: {
fail: 'not a date',
pass: '2011-02-04'
},
isAfter: {
spec: { args: '2011-11-05' },
fail: '2011-11-04',
pass: '2011-11-06'
},
isBefore: {
spec: { args: '2011-11-05' },
fail: '2011-11-06',
pass: '2011-11-04'
},
isIn: {
spec: { args: 'abcdefghijk' },
fail: 'ghik',
pass: 'ghij'
},
notIn: {
spec: { args: 'abcdefghijk' },
fail: 'ghij',
pass: 'ghik'
},
max: {
spec: { args: 23 },
fail: '24',
pass: '23'
},
max$: {
spec: 23,
fail: '24',
pass: '23'
},
min: {
spec: { args: 23 },
fail: '22',
pass: '23'
},
min$: {
spec: 23,
fail: '22',
pass: '23'
},
isCreditCard: {
fail: '401288888888188f',
pass: '4012888888881881'
}
};
const applyFailTest = function applyFailTest(validatorDetails, i, validator) {
const failingValue = validatorDetails.fail[i];
it(`correctly specifies an instance as invalid using a value of "${failingValue}" for the validation "${validator}"`, function() {
const validations = {},
message = `${validator}(${failingValue})`;
validations[validator] = validatorDetails.spec || {};
validations[validator].msg = message;
const UserFail = this.sequelize.define(`User${config.rand()}`, {
name: {
type: Sequelize.STRING,
validate: validations
}
});
const failingUser = UserFail.build({ name: failingValue });
return expect(failingUser.validate()).to.be.rejected.then(_errors => {
expect(_errors.get('name')[0].message).to.equal(message);
expect(_errors.get('name')[0].value).to.equal(failingValue);
});
});
},
applyPassTest = function applyPassTest(validatorDetails, j, validator, type) {
const succeedingValue = validatorDetails.pass[j];
it(`correctly specifies an instance as valid using a value of "${succeedingValue}" for the validation "${validator}"`, function() {
const validations = {},
message = `${validator}(${succeedingValue})`;
validations[validator] = validatorDetails.spec || {};
if (type === 'msg') {
validations[validator].msg = message;
} else if (type === 'args') {
validations[validator].args = validations[validator].args || true;
validations[validator].msg = message;
} else if (type === 'true') {
validations[validator] = true;
}
const UserSuccess = this.sequelize.define(`User${config.rand()}`, {
name: {
type: Sequelize.STRING,
validate: validations
}
});
const successfulUser = UserSuccess.build({ name: succeedingValue });
return expect(successfulUser.validate()).not.to.be.rejected;
});
};
for (let validator in checks) {
if (checks.hasOwnProperty(validator)) {
validator = validator.replace(/\$$/, '');
const validatorDetails = checks[validator];
if (!validatorDetails.raw) {
validatorDetails.fail = Array.isArray(validatorDetails.fail) ? validatorDetails.fail : [validatorDetails.fail];
validatorDetails.pass = Array.isArray(validatorDetails.pass) ? validatorDetails.pass : [validatorDetails.pass];
}
for (let i = 0; i < validatorDetails.fail.length; i++) {
applyFailTest(validatorDetails, i, validator);
}
for (let i = 0; i < validatorDetails.pass.length; i++) {
applyPassTest(validatorDetails, i, validator);
applyPassTest(validatorDetails, i, validator, 'msg');
applyPassTest(validatorDetails, i, validator, 'args');
if (validatorDetails.stringOrBoolean || validatorDetails.spec === undefined) {
applyPassTest(validatorDetails, i, validator, 'true');
}
}
}
}
});
describe('datatype validations', () => {
const current = Support.createSequelizeInstance({
typeValidation: true
});
const User = current.define('user', {
age: Sequelize.INTEGER,
name: Sequelize.STRING,
awesome: Sequelize.BOOLEAN,
number: Sequelize.DECIMAL,
uid: Sequelize.UUID,
date: Sequelize.DATE
});
before(function() {
this.stub = sinon.stub(current, 'query').callsFake(() => {
return new Promise(resolve => {
resolve([User.build({}), 1]);
});
});
});
after(function() {
this.stub.restore();
});
describe('should not throw', () => {
describe('create', () => {
it('should allow number as a string', () => {
return expect(User.create({
age: '12'
})).not.to.be.rejected;
});
it('should allow decimal as a string', () => {
return expect(User.create({
number: '12.6'
})).not.to.be.rejected;
});
it('should allow dates as a string', () => {
return expect(User.findOne({
where: {
date: '2000-12-16'
}
})).not.to.be.rejected;
});
it('should allow decimal big numbers as a string', () => {
return expect(User.create({
number: '2321312301230128391820831289123012'
})).not.to.be.rejected;
});
it('should allow decimal as scientific notation', () => {
return Promise.join(
expect(User.create({
number: '2321312301230128391820e219'
})).not.to.be.rejected,
expect(User.create({
number: '2321312301230128391820e+219'
})).not.to.be.rejected,
expect(User.create({
number: '2321312301230128391820f219'
})).to.be.rejected
);
});
it('should allow string as a number', () => {
return expect(User.create({
name: 12
})).not.to.be.rejected;
});
it('should allow 0/1 as a boolean', () => {
return expect(User.create({
awesome: 1
})).not.to.be.rejected;
});
it('should allow 0/1 string as a boolean', () => {
return expect(User.create({
awesome: '1'
})).not.to.be.rejected;
});
it('should allow true/false string as a boolean', () => {
return expect(User.create({
awesome: 'true'
})).not.to.be.rejected;
});
});
describe('findAll', () => {
it('should allow $in', () => {
return expect(User.findAll({
where: {
name: {
[Op.like]: {
[Op.any]: ['foo%', 'bar%']
}
}
}
})).not.to.be.rejected;
});
it('should allow $like for uuid', () => {
return expect(User.findAll({
where: {
uid: {
[Op.like]: '12345678%'
}
}
})).not.to.be.rejected;
});
});
});
describe('should throw validationerror', () => {
describe('create', () => {
it('should throw when passing string', () => {
return expect(User.create({
age: 'jan'
})).to.be.rejectedWith(Sequelize.ValidationError)
.which.eventually.have.property('errors')
.that.is.an('array')
.with.lengthOf(1)
.and.with.property(0)
.that.is.an.instanceOf(Sequelize.ValidationErrorItem)
.and.include({
type: 'Validation error',
path: 'age',
value: 'jan',
instance: null,
validatorKey: 'INTEGER validator'
});
});
it('should throw when passing decimal', () => {
return expect(User.create({
age: 4.5
})).to.be.rejectedWith(Sequelize.ValidationError)
.which.eventually.have.property('errors')
.that.is.an('array')
.with.lengthOf(1)
.and.with.property(0)
.that.is.an.instanceOf(Sequelize.ValidationErrorItem)
.and.include({
type: 'Validation error',
path: 'age',
value: 4.5,
instance: null,
validatorKey: 'INTEGER validator'
});
});
});
describe('update', () => {
it('should throw when passing string', () => {
return expect(User.update({
age: 'jan'
}, { where: {}})).to.be.rejectedWith(Sequelize.ValidationError)
.which.eventually.have.property('errors')
.that.is.an('array')
.with.lengthOf(1)
.and.with.property(0)
.that.is.an.instanceOf(Sequelize.ValidationErrorItem)
.and.include({
type: 'Validation error',
path: 'age',
value: 'jan',
instance: null,
validatorKey: 'INTEGER validator'
});
});
it('should throw when passing decimal', () => {
return expect(User.update({
age: 4.5
}, { where: {}})).to.be.rejectedWith(Sequelize.ValidationError)
.which.eventually.have.property('errors')
.that.is.an('array')
.with.lengthOf(1)
.and.with.property(0)
.that.is.an.instanceOf(Sequelize.ValidationErrorItem)
.and.include({
type: 'Validation error',
path: 'age',
value: 4.5,
instance: null,
validatorKey: 'INTEGER validator'
});
});
});
});
});
describe('custom validation functions', () => {
const User = current.define('user', {
age: {
type: Sequelize.INTEGER,
validate: {
customFn(val, next) {
if (val < 0) {
next('age must be greater or equal zero');
} else {
next();
}
}
}
},
name: Sequelize.STRING
}, {
validate: {
customFn() {
if (this.get('name') === 'error') {
return Promise.reject(new Error('Error from model validation promise'));
}
return Promise.resolve();
}
}
});
before(function() {
this.stub = sinon.stub(current, 'query').returns(Promise.resolve([User.build(), 1]));
});
after(function() {
this.stub.restore();
});
describe('should not throw', () => {
describe('create', () => {
it('custom validation functions are successful', () => {
return expect(User.create({
age: 1,
name: 'noerror'
})).not.to.be.rejected;
});
});
describe('update', () => {
it('custom validation functions are successful', () => {
return expect(User.update({
age: 1,
name: 'noerror'
}, { where: {}})).not.to.be.rejected;
});
});
});
describe('should throw validationerror', () => {
describe('create', () => {
it('custom attribute validation function fails', () => {
return expect(User.create({
age: -1
})).to.be.rejectedWith(Sequelize.ValidationError);
});
it('custom model validation function fails', () => {
return expect(User.create({
name: 'error'
})).to.be.rejectedWith(Sequelize.ValidationError);
});
});
describe('update', () => {
it('custom attribute validation function fails', () => {
return expect(User.update({
age: -1
}, { where: {}})).to.be.rejectedWith(Sequelize.ValidationError);
});
it('when custom model validation function fails', () => {
return expect(User.update({
name: 'error'
}, { where: {}})).to.be.rejectedWith(Sequelize.ValidationError);
});
});
});
});
describe('custom validation functions returning promises', () => {
const User = current.define('user', {
name: Sequelize.STRING
}, {
validate: {
customFn() {
if (this.get('name') === 'error') {
return Promise.reject(new Error('Error from model validation promise'));
}
return Promise.resolve();
}
}
});
before(function() {
this.stub = sinon.stub(current, 'query').returns(Promise.resolve([User.build(), 1]));
});
after(function() {
this.stub.restore();
});
describe('should not throw', () => {
describe('create', () => {
it('custom model validation functions are successful', () => {
return expect(User.create({
name: 'noerror'
})).not.to.be.rejected;
});
});
describe('update', () => {
it('custom model validation functions are successful', () => {
return expect(User.update({
name: 'noerror'
}, { where: {}})).not.to.be.rejected;
});
});
});
describe('should throw validationerror', () => {
describe('create', () => {
it('custom model validation function fails', () => {
return expect(User.create({
name: 'error'
})).to.be.rejectedWith(Sequelize.ValidationError);
});
});
describe('update', () => {
it('when custom model validation function fails', () => {
return expect(User.update({
name: 'error'
}, { where: {}})).to.be.rejectedWith(Sequelize.ValidationError);
});
});
});
});
});
|
const gulp = require('gulp');
const logger = require('gulplog');
const autoprefixer = require('gulp-autoprefixer');
const csso = require('gulp-csso');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const config = require('../gulp.config.js')();
const compileScss = () => {
function swallowError(error) {
// If you want details of the error in the console
logger.warn('\x1b[36m', error.toString(), '\x1b[0m');
this.emit('end');
}
return gulp
.src(config.paths.scss.src)
.pipe(sourcemaps.init())
.pipe(sass(config.options.sass))
.on('error', swallowError)
.pipe(csso(config.options.csso))
.pipe(autoprefixer(config.options.autoprefixer))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(config.paths.scss.dist));
};
module.exports = compileScss;
|
app.controller('UsersPasswordCtrl', ['$state', '$scope', 'users', '$timeout', 'SweetAlert', 'toaster','flowFactory', '$http', function ($state, $scope, users, $timeout, SweetAlert, toaster,flowFactory) {
//Init input addForm variable
//create users
$scope.removeImage = function () {
$scope.noImage = true;
};
$scope.obj = new Flow();
$scope.userInfo = {
firstName: 'Peter',
lastName: 'Clark',
url: 'www.example.com',
email: 'peter@example.com',
phone: '(641)-734-4763',
gender: 'male',
zipCode: '12345',
city: 'London (UK)',
avatar: 'assets/images/avatar-1-xl.jpg',
twitter: '',
github: '',
facebook: '',
linkedin: '',
google: '',
skype: 'peterclark82'
};
if ($scope.userInfo.avatar == '') {
$scope.noImage = true;
}
$scope.process = false;
if ($scope.dataUser.level == 0 ) {
$state.go("app.dashboard")
}
$scope.master = $scope.myModel;
$scope.form = {
submit: function (form) {
var firstError = null;
if (form.$invalid) {
var field = null, firstError = null;
for (field in form) {
if (field[0] != '$') {
if (firstError === null && !form[field].$valid) {
firstError = form[field].$name;
}
if (form[field].$pristine) {
form[field].$dirty = true;
}
}
}
angular.element('.ng-invalid[name=' + firstError + ']').focus();
SweetAlert.swal("The form cannot be submitted because it contains validation errors!", "Errors are marked with a red, dashed border!", "error");
return;
} else {
SweetAlert.swal("Good job!", "Your form is ready to be submitted!", "success");
//your code for submit
}
},
reset: function (form) {
$scope.myModel = angular.copy($scope.master);
form.$setPristine(true);
}
};
$scope.closeAlert = function (index) {
$scope.alerts.splice(index, 1);
};
$scope.submitData = function (isBack) {
$scope.alerts = [];
//Set process status
$scope.process = true;
//Close Alert
//Check validation status
if ($scope.Form.$valid) {
//run Ajax
users.updatepassword($scope.myModel)
.success(function (data) {
if (data.updated == true) {
//If back to list after submitting
if (isBack == true) {
$state.go('app.users');
$scope.toaster = {
type: 'success',
title: 'Sukses',
text: 'Simpan Data Berhasil!'
};
toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
} else {
$scope.clearInput();
$scope.sup();
$scope.alerts.push({
type: 'success',
msg: 'Simpan Data Berhasil!'
});
$scope.process = false;
$scope.toaster = {
type: 'success',
title: 'Sukses',
text: 'Simpan Data Berhasil!'
};
toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
}
//Clear Input
}
else{
$scope.process = false;
$scope.toaster = {
type: 'error',
title: 'CekData',
text: data.result.message
};
toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
}
})
.error(function (data, status) {
// unauthorized
if (status === 401) {
//redirect to login
$scope.redirect();
}
$scope.sup();
// Stop Loading
$scope.process = false;
$scope.alerts.push({
type: 'danger',
msg: data.validation
});
$scope.toaster = {
type: 'error',
title: 'Gagal',
text: 'Simpan Data Gagal!'
};
toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
});
}
};
}]);
|
function ChainableSelector(selector, scope) {
this.selector = selector;
this.scope = scope;
}
ChainableSelector.prototype = {
getElement: function() {
return this.scope.template.querySelector(this.selector);
},
attr: function(attributePath, dataPath) {
this.scope.bindElement(this.selector, attributePath, dataPath);
return this;
},
template: function(templateName, params) {
this.scope.bindTemplate(this.selector, templateName, params);
return this;
},
array: function(templateName, params, dataPath) {
this.scope.bindArray(this.selector, templateName, params, dataPath);
return this;
},
on: function(eventName, callback) {
this.scope.on(this.selector, eventName, callback);
return this;
},
focus: function() {
this.getElement()
.focus();
},
text: function(dataPath) {
return this.attr('innerHTML', dataPath);
},
value: function(dataPath) {
return this.attr('value', dataPath);
},
hide: function(dataPath) {
return this.scope.onSet(dataPath, (x) => this.getElement()
.style.display = x ? 'none' : ''
);
},
show: function(dataPath) {
return this.scope.onSet(dataPath, (x)=> this.getElement()
.style.display = x ? '' : 'none'
);
},
class: function(className, dataPaths) {
return this.scope.onSet(dataPath, (x)=> {
let e = this.getElement();
if (x) e.classList.add(className);
else e.classList.remove(className);
});
}
};
|
let assert = require("assert");
let check = require("./../index.js");
describe("Bundle", function() {
describe("bundle(methodNames, inputs)", function() {
it("returns a two-dimensional array of input-method verifications", function() {
assert.deepEqual(
check.bundle(["isInteger", "isPositive"], [5, -2]),
[ [true, true], [true, false] ]
);
assert.deepEqual(
check.bundle(["isDefined", "isPrimitive"], [null, undefined, new Object()]),
[ [false, true], [false, true], [true, false] ]
);
assert.throws(() => check.bundle(["isNumber", "isInRange", "isNatural"], [5, [3, 4]]), SyntaxError);
});
});
describe("everyMethod(methodNames, input)", function() {
it("returns `true` if all of the verifications return `true`", function() {
assert(!check.everyMethod(["isNumber", "isFinite", "isPositive"], -5));
assert(check.everyMethod(["isNumber", "isFinite", "isNegative"], -5));
assert(check.everyMethod(["isString", "isPrimitive"], "my text"));
});
});
describe("someMethod(methodNames, input)", function() {
it("returns `true` if any of the verifications returns `true`", function() {
assert(check.someMethod(["isNumber", "isString"], 42));
assert(!check.someMethod(["isNotNatural", "isFloat"], 42));
assert(!check.someMethod(["isObject", "isNull"], NaN));
});
});
describe("everyInput(methodName, inputs)", function() {
it("returns `true` if all input values pass verification", function() {
assert(check.everyInput("isNumber", [5, 4, -2]));
assert(!check.everyInput("isNumber", [5, 4, -2, "my text"]));
assert(check.everyInput("isNatural", [1, 2, 3]));
});
});
describe("someInput(methodName, inputs)", function() {
it("returns `true` if any of the input values passes verification", function() {
assert(check.someInput("isNotDefined", [5, 4, null, -2]));
assert(!check.someInput("isObject", [5, 4, -2, "my text"]));
assert(!check.someInput("isNaN", [1, 2, 3]));
});
});
}); |
const ProcessResponder = require("../src/process-responder");
const {project} = require("./constants");
const failProject = Object.assign(project, {coverage: {success: false}});
test('If coverage fails, but not halt, resolve 0', () => {
const settings = Object.assign({haltOnFailure: false}, {project: failProject});
return ProcessResponder.respond(settings)
.then(result => expect(result)
.toBe(0));
});
test('If coverage fails, and halt is true, reject', () => {
const settings = Object.assign({haltOnFailure: true}, {project: failProject});
return ProcessResponder.respond(settings)
.catch(error => {
expect(error)
.toBeDefined()
})
});
test('If coverage succeeds, and not halt, resolve 0', () => {
const settings = Object.assign({haltOnFailure: false}, {project});
return ProcessResponder.respond(settings)
.then(result => expect(result)
.toBe(0));
});
test('If coverage succeeds, and halt is true, still resolve 0', () => {
const settings = Object.assign({haltOnFailure: true}, {project});
return ProcessResponder.respond(settings)
.catch(error => {
expect(error)
.toBeDefined()
})
});
|
// Register `userList` component, along with its associated controller and template
angular.
module('addUser').
component('addUser', {
templateUrl:'add-user/addUser.html',
controller: ['$scope','$http', '$routeParams', AddUserController]
});
function AddUserController($scope, $http, $routeParams){
$scope.newUser = {
firstName : '',
lastName : '',
email: '',
address :{
street: '',
city: '',
state: '',
country: ''
}
};
$scope.addUser = function(){
$http.post('http://mocker.egen.io/users/',$scope.newUser).then(function(response){
console.log(response.data);
});
}
}
|
import { resolve } from 'path'
import { expect } from 'chai'
import expandConfig from '../src/expandConfig'
import buildRequiredTaskList from '../src/buildRequiredTaskList'
import buildTaskDependencyGraph from '../src/buildTaskDependencyGraph'
import sortTasks from '../src/sort'
describe('buildTaskDependencyGraph.js', function () {
let testSetup
beforeEach(() => testSetup = (launchTasks = []) => {
const testConfigPath = resolve(__dirname, 'test.topolo.config.js')
delete require.cache[require.resolve(testConfigPath)]
const tasks = expandConfig(require(testConfigPath))
const taskNameSet = buildRequiredTaskList(tasks, launchTasks)
const taskDepGraph = buildTaskDependencyGraph(tasks, taskNameSet)
return sortTasks(taskDepGraph, taskNameSet)
})
it('throws if a self-cyclical dependency is found', function () {
expect(testSetup.bind(testSetup, ['cyclical1'])).to.throw('Cyclical')
})
it('throws if a general cyclical dependency is found', function () {
expect(testSetup.bind(testSetup, ['cyclical2', 'cyclical3'])).to.throw('Cyclical')
})
it('sorts tasks correctly', function () {
const sortedTasks = testSetup(['dependencies1', 'stringTask'])
expect(sortedTasks).to.have.property(0).that.has.property('taskName').that.equals('stringTask')
expect(sortedTasks).to.have.property(1).that.has.property('taskName').that.equals('dependencies1')
})
})
|
// flow-typed signature: bba9a073875551baae4c947ca66de207
// flow-typed version: <<STUB>>/imports-loader_v0.8.0/flow_v0.69.0
/**
* This is an autogenerated libdef stub for:
*
* 'imports-loader'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'imports-loader' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'imports-loader/index' {
declare module.exports: $Exports<'imports-loader'>;
}
declare module 'imports-loader/index.js' {
declare module.exports: $Exports<'imports-loader'>;
}
|
'use strict';
var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var _ = require('underscore');
var MAPS_API_URL = 'https://maps.googleapis.com/maps/api/js';
var PLACES_API_URL = '?libraries=places';
var API_KEY = 'AIzaSyC0l32fdHosB1b5YmlUtlWBfmnUIaI2BMU';
var _instance;
var MapModuleView = Backbone.View.extend({
el: '#map-module',
locType: 'pharmacy',
initialize: function (options) {
if (!options.location) {
throw new Error('Must supply user location');
}
this.location = options.location;
},
render: function () {
//show the map module elements
this.$('.require-gps').slideDown();
//load script if needed
if (typeof google === 'undefined') {
this.loadScript();
} else {
//initializd the map
this.initializeMap();
}
//Reference to this object because after jquery call, 'this' is different
var self = this;
//Function to get and hide places requests
$('#map-module dt').click(function () {
var locType = $(this).attr('data-locType');
if (!$.trim($('dd.' + locType).html())) {
if (locType == 'embassy') {
self.embassyLink();
} else {
$(this).toggleClass('expanded');
self.placesRequest(locType);
}
} else {
$('dd.' + locType).html('').slideToggle();
}
});
},
triggerResize: function() {
if(typeof this.map !== 'undefined') {
google.maps.event.trigger(this.map, 'resize');
this.map.setOptions({
center: this.center
});
}
},
loadScript: function() {
//add listener for custom load event
$(document).off('map-api-load').one('map-api-load', _.bind(this.initializeMap, this));
//add script for google maps
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = MAPS_API_URL + PLACES_API_URL + '&key=' + API_KEY + '&sensor=true&callback=mapApiLoaded';
document.body.appendChild(script);
},
initializeMap: function () {
//set map cetner
this.center = new google.maps.LatLng(this.location.coords.latitude, this.location.coords.longitude);
var mapOptions = {
zoom : 14,
center : this.center,
mapTypeId : google.maps.MapTypeId.ROADMAP,
disableDefaultUI : true,
draggable: false
};
//create map object
this.map = new google.maps.Map(this.$('.map-ph').get(0), mapOptions);
//add center marker
var marker = new google.maps.Marker({
position: this.center,
animation: google.maps.Animation.DROP,
map: this.map
});
//Initialize Places
this.initializePlaces();
},
initializePlaces: function () {
//Create the Places Service
this.placesService = new google.maps.places.PlacesService(this.map);
},
placesRequest: function (locType) {
var request = {
location: new google.maps.LatLng(this.location.coords.latitude, this.location.coords.longitude), //Current Coordinates
types: [locType],
rankBy: google.maps.places.RankBy.DISTANCE
};
if (locType == 'embassy') {
request.keyword = 'United States';
}
//Set the locType for future reference
this.locType = locType;
//Perform the nearby search
this.placesService.nearbySearch(request, this.callback);
},
callback: function (results, status) {
//Get the saved locType
var locType = _instance.locType;
//Make sure the service is working
if (status == google.maps.places.PlacesServiceStatus.OK) {
var newcontent = '';
var i = 0;
var place;
//Loop through the results
if (results.length < 5) {
for (i = 0; i < results.length; i++) {
place = results[i];
newcontent += '<div><strong>' + place.name + '</strong><br/>' + place.vicinity + '</div>';
}
} else {
for (i = 0; i < 5; i++) {
place = results[i];
newcontent += '<div><strong>' + place.name + '</strong><br/>' + place.vicinity + '</div>';
}
}
//Append the results to the correct section, and animate their display
$('dd.' + locType).html(newcontent).slideDown();
} else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
var noResults = '<div><strong>No Results Found</strong></div>';
//Append the No Result string to the correct section, and animate the display
$('dd.' + locType).html(noResults).slideDown();
}
},
embassyLink: function (){
window.open(
'http://www.usembassy.gov/index.html',
'_blank' // <- This is what makes it open in a new window.
);
}
});
var SingletonWrapper = {
createInstance: function (location) {
//setup map view
if (!_instance && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
//init map module
console.log('initing map');
_instance = new MapModuleView({ location: position });
_instance.render();
});
}
},
getInstance: function () {
return _instance;
}
};
module.exports = SingletonWrapper; |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 8.14.4-8-b_1
description: Non-writable property on a prototype written to.
flags: [noStrict]
includes: [runTestCase.js]
---*/
function testcase() {
function foo() {};
Object.defineProperty(foo.prototype, "bar", {value: "unwritable"});
var o = new foo();
o.bar = "overridden";
return o.hasOwnProperty("bar")===false && o.bar==="unwritable";
}
runTestCase(testcase);
|
angular.module('ScoutIOApp')
.factory('Folder', function ($http, Project) {
var folders = [];
var projects = [];
// GET FOLDER BY ID
var getFolderById = function (folder) {
return $http({
method: 'GET',
url: '/api/folders/' + folder.id
})
.then(function (response) {
console.log(response);
return response;
})
.catch(function (error) {
console.log(error, "in catch: folder-factory")
});
};
//GET FOLDER LINKS
var getFolderLinks = function (folderId) {
return $http({
method: 'GET',
url: '/api/folders/' + folderId + '/links'
})
.then(function (response) {
console.log(response);
return response;
})
.catch(function (error) {
console.log(error, "in catch: folder-factory")
});
};
//GET FOLDER ASSETS
var getFolderAssets = function (folder) {
return $http({
method: 'GET',
url: '/api/folders/' + folder.id + '/assets'
})
.then(function (response) {
console.log(response);
return response;
})
.catch(function (error) {
console.log(error, "in catch: folder-factory")
});
};
//CREATE A FOLDER
var createFolder = function (folder) {
return $http({
method: 'POST',
url: '/api/folders',
data: folder
})
.then(function (response) {
console.log('folder was created');
var message = 'Your Folder Has Been Successfully Saved';
return message;
})
.catch(function (error) {
console.log(error, "in catch: folder-factory")
});
};
//EDIT A FOLDER
var editFolder = function (folder) {
return $http({
method: 'PUT',
url: '/api/folders/' + folder.id,
data: folder
})
.then(function (response) {
console.log('folder was updated');
var message = 'Your Folder Has Been Successfully Updated';
return message;
})
.catch(function (error) {
console.log(error, "in catch: folder-factory")
});
};
//DELETE A FOLDER
var deleteFolder = function (folder) {
return $http({
method: 'DELETE',
url: '/api/folders/' + folder.id
})
.then(function (response) {
console.log('folder was deleted');
var message = 'Your Folder Has Been Successfully Deleted';
return message;
})
.catch(function (error) {
console.log(error, "in catch: folder-factory")
});
};
return {
getFolders: function () {
return folders;
},
getProjects: function () {
return projects;
},
getFolderById: getFolderById,
getFolderLinks: getFolderLinks,
getFolderAssets: getFolderAssets,
createFolder: createFolder,
editFolder: editFolder,
deleteFolder: deleteFolder
};
});
|
(function () {
'use strict';
angular
.module('aMetroEditor')
.controller('MenuController', function MenuController($scope, $rootScope, $mdDialog, $timeout,EditorService, FileService, ModelService) {
var self = this;
this.settings = {
edit:{
undo: false,
redo: false,
cut: false,
copy: false,
paste: false,
},
view: {
layers: 'all'
},
help: {
items: [
{ name: 'Help', url: 'help', icon:'icons:help' },
{ name: 'Contacts', url: 'contacts', icon:'social:people' },
{ name: 'About', url: 'about', icon:'icons:dashboard' }
]
},
schemes: EditorService.getSchemes(),
currentSchemeId: EditorService.getCurrentSchemeId(),
lines: EditorService.getLines(),
currentLineId: EditorService.getCurrentLineId(),
transports: {
items: [{
id: 'Metro.trp',
name: 'Metro.trp',
type: 'Метро'
}],
current: 'Metro.trp'
},
translation: {
items: [
{ id: 'ru', name: 'Russian' },
{ id: 'en', name: 'English' }
],
current: 'ru'
}
};
this.hasEmptyLines = function(){
return !(self.settings.lines && self.settings.lines.length > 0);
};
this.createMap = function(ev){
ModelService.newMap();
};
this.uploadMap = function(ev){
FileService.openFile(function(file){
$timeout(function(){
ModelService.loadMap(file);
$scope.$emit('navigate', { navigate:'map/editor', event: ev });
}, 0);
}, function(error){
var alert = $mdDialog.alert()
.title('Cannot load file')
.textContent(error.message)
.ariaLabel('File loading error')
.targetEvent(ev)
.clickOutsideToClose(true)
.ok('Ok');
$mdDialog.show(alert);
});
};
this.downloadMap = function(ev){
var file = ModelService.saveMap();
FileService.saveFile(file);
};
this.addLine = function(ev){
};
this.editLine = function(ev){
};
this.deleteLine = function(ev){
var line = self.settings.lines.filter(function(l){ return l.id === self.settings.currentLineId })[0];
var confirm = $mdDialog.confirm()
.title('Would you like to delete a line \'' + line.name + '\' ?')
.textContent('All of the stations on this line will be deleted also.')
.ariaLabel('Delete line confirmation')
.targetEvent(ev)
.ok('Yes')
.cancel('Cancel');
$mdDialog.show(confirm).then(function() {
EditorService.deleteLine(line);
});
};
this.editLineDefaults = function(ev){
};
this.addScheme = function(ev){
};
this.editScheme = function(ev){
};
this.deleteScheme = function(ev){
var scheme = self.settings.schemes.filter(function(l){ return l.id === self.settings.currentSchemeId })[0];
var confirm = $mdDialog.confirm()
.title('Would you like to delete a scheme \'' + scheme.name + '\' ?')
.textContent('All of the stations on this scheme will be deleted also.')
.ariaLabel('Delete scheme confirmation')
.targetEvent(ev)
.ok('Yes')
.cancel('Cancel');
$mdDialog.show(confirm).then(function() {
EditorService.deleteScheme(scheme);
});
};
this.editSchemeDefaults = function(ev){
};
this.emit = function (name, ev) {
$scope.$emit('menu', { name: name, event: ev });
};
$scope.$on('$destroy', $rootScope.$on('editor', function(event, data){
if(data.name === 'selection'){
var size = data.selection.length;
self.settings.edit.undo = false;
self.settings.edit.redo = false;
self.settings.edit.cut = size >= 1;
self.settings.edit.copy = size >= 1;
self.settings.edit.paste = false;
self.settings.edit.connect = size > 1;
self.settings.edit.delete = size >= 1;
}
if(data.name === 'schemes'){
self.settings.schemes = EditorService.getSchemes();
self.settings.currentSchemeId = EditorService.getCurrentSchemeId();
}
if(data.name === 'lines'){
self.settings.lines = EditorService.getLines();
self.settings.currentLineId = EditorService.getCurrentLineId();
}
}));
$scope.$watch(function(){ return self.settings.view.layers; }, function(newValue, oldValue){
});
$scope.$watch(function(){ return self.settings.currentLineId; }, function(newValue, oldValue){
EditorService.setCurrentLineId(newValue);
});
$scope.$watch(function(){ return self.settings.currentSchemeId; }, function(newValue, oldValue){
EditorService.setCurrentSchemeId(newValue);
});
return this;
});
})();
|
(function () {
var moduleName = 'test';
var dependencies = [['lodash', '_'], 'Q'];
(function (context, factory) {
if (typeof define === 'function' && define.amd) {
for (var i = 0; i < dependencies.length; i++) {
if (Array.isArray(dependencies[i])) {
dependencies[i] = dependencies[i][0];
}
}
define(dependencies, factory);
} else if (typeof module !== 'undefined' && typeof module.exports === 'object') {
for (var i = 0; i < dependencies.length; i++) {
if (Array.isArray(dependencies[i])) {
dependencies[i] = require(dependencies[i][0]);
} else {
dependencies[i] = require(dependencies[i]);
}
}
module.exports = factory.apply(null, dependencies)
} else {
for (var i = 0; i < dependencies.length; i++) {
if (Array.isArray(dependencies[i])) {
dependencies[i] = context[dependencies[i][1]];
} else {
dependencies[i] = context[dependencies[i]];
}
}
context[moduleName] = factory.apply(null, dependencies);
}
}(this, function (_, Q) {
//The actual module definition
return {'_': _, Q: Q};
}));
})(); |
ViewModel.mixin({
house: {
address: '123 Main St.'
}
});
Person({
mixin: 'house',
name: '',
render() {
<div class="item">
<div class="content">
<input type="text" b="value: name" />
<input type="text" b="value: address" />
</div>
</div>
}
}); |
module.exports={
consumer_key:'2AeydC4JAdKUckgXsDGVdHkNS',
consumer_secret:'wPVBNCK2E2iRn1AcIaTEEmzx9ACH1JDKfOVC7VjnwGfC6gwXsc',
access_token:'725467234915610624-plFXxpxwaJp3TIaGbVjiPirPdcmvjbf',
access_token_secret:'TXCYTRMe4mDL9iKeJQHcLME5bK8kjNCVjVzbWmEGUhw4b'
} |
'use strict';
var serviceHeadsup = angular.module('headsupServices', []);
var port = '';
//var port = '3003';
serviceHeadsup.factory('headsupService', ['$http', '$location', function($http, $location){
var protocol = $location.protocol().concat('://');
var host = $location.host();
return {
headsups: function(yFrom, yTo, callback) {
$http({ method: 'GET',
//url: 'http://localhost:3003/api/headsups'
url: protocol.concat(host,':', port, '/api/headsups/',yFrom, '/',yTo)
})
.success(function(data) {
console.log(data);
callback(data);
})
.error(function(data) {
console.log('Error: ' + data);
callback(data);
});
}
}}]);
|
// @flow
const WebSocket = require('ws');
class WebSocketServer {
wss: WebSocket.Server;
constructor(port: number) {
this.wss = new WebSocket.Server({
port,
clientTracking: true
}, () => {
console.log('WebSocket Server Listening at port ' + port);
});
this.wss.on('connection', (client, request) => {
const clientAddress = request.socket.remoteAddress, clientPort = request.socket.remotePort;
console.log(`New connection from ${clientAddress} (port ${clientPort})`);
client.on('close', () => { console.log(`Connection from ${clientAddress} (port ${clientPort}) closed`) });
client.on('error', () => { client.close() });
});
}
broadcast(data: mixed) {
for(const client of this.wss.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
}
}
}
module.exports = WebSocketServer;
|
var fs = require('fs');
/**
* Get the text of an SQL query from a file.
*
* @param {String} path The name of the file to read the query from, prefixed by the path relative to the project's directory, if appropriate.
* @return {String} The content of the file.
*/
function getQuery(path) {
return fs.readFileSync(__dirname + path, 'UTF-8');
}
exports.getQuery = getQuery;
function testGetQuery() {
console.log(getQuery('/commons/licensesOverTime.sql'));
}
//testGetQuery();
|
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File: jquery.refinery.wymeditor.js
*
* Main JS file with core classes and functions.
* See the documentation for more info.
*
* About: authors
*
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Volker Mische (vmx a-t gmx dotde)
* Scott Lewis (lewiscot a-t gmail dotcom)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Daniel Reszka (d.reszka a-t wymeditor dotorg)
* Jonatan Lundin (jonatan.lundin _at_ gmail.com)
*/
/*
Namespace: WYMeditor
Global WYMeditor namespace.
*/
if(!WYMeditor) var WYMeditor = {};
//Wrap the Firebug console in WYMeditor.console
(function() {
if ( !window.console || !console.firebug ) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
WYMeditor.console = {};
for (var i = 0; i < names.length; ++i)
WYMeditor.console[names[i]] = function() {}
} else WYMeditor.console = window.console;
})();
jQuery.extend(WYMeditor, {
/*
Constants: Global WYMeditor constants.
VERSION - Defines WYMeditor version.
INSTANCES - An array of loaded WYMeditor.editor instances.
STRINGS - An array of loaded WYMeditor language pairs/values.
SKINS - An array of loaded WYMeditor skins.
NAME - The "name" attribute.
INDEX - A string replaced by the instance index.
WYM_INDEX - A string used to get/set the instance index.
BASE_PATH - A string replaced by WYMeditor's base path.
SKIN_PATH - A string replaced by WYMeditor's skin path.
WYM_PATH - A string replaced by WYMeditor's main JS file path.
SKINS_DEFAULT_PATH - The skins default base path.
SKINS_DEFAULT_CSS - The skins default CSS file.
LANG_DEFAULT_PATH - The language files default path.
IFRAME_BASE_PATH - A string replaced by the designmode iframe's base path.
IFRAME_DEFAULT - The iframe's default base path.
JQUERY_PATH - A string replaced by the computed jQuery path.
DIRECTION - A string replaced by the text direction (rtl or ltr).
LOGO - A string replaced by WYMeditor logo.
TOOLS - A string replaced by the toolbar's HTML.
TOOLS_ITEMS - A string replaced by the toolbar items.
TOOL_NAME - A string replaced by a toolbar item's name.
TOOL_TITLE - A string replaced by a toolbar item's title.
TOOL_CLASS - A string replaced by a toolbar item's class.
CLASSES - A string replaced by the classes panel's HTML.
CLASSES_ITEMS - A string replaced by the classes items.
CLASS_NAME - A string replaced by a class item's name.
CLASS_TITLE - A string replaced by a class item's title.
CONTAINERS - A string replaced by the containers panel's HTML.
CONTAINERS_ITEMS - A string replaced by the containers items.
CONTAINER_NAME - A string replaced by a container item's name.
CONTAINER_TITLE - A string replaced by a container item's title.
CONTAINER_CLASS - A string replaced by a container item's class.
HTML - A string replaced by the HTML view panel's HTML.
IFRAME - A string replaced by the designmode iframe.
STATUS - A string replaced by the status panel's HTML.
DIALOG_TITLE - A string replaced by a dialog's title.
DIALOG_BODY - A string replaced by a dialog's HTML body.
BODY - The BODY element.
STRING - The "string" type.
BODY,DIV,P,
H1,H2,H3,H4,H5,H6,
PRE,BLOCKQUOTE,
A,BR,IMG,
TABLE,TD,TH,
UL,OL,LI - HTML elements string representation.
CLASS,HREF,SRC,
TITLE,ALT - HTML attributes string representation.
DIALOG_LINK - A link dialog type.
DIALOG_IMAGE - An image dialog type.
DIALOG_TABLE - A table dialog type.
DIALOG_PASTE - A 'Paste from Word' dialog type.
BOLD - Command: (un)set selection to <strong>.
ITALIC - Command: (un)set selection to <em>.
CREATE_LINK - Command: open the link dialog or (un)set link.
INSERT_IMAGE - Command: open the image dialog or insert an image.
INSERT_TABLE - Command: open the table dialog.
PASTE - Command: open the paste dialog.
INDENT - Command: nest a list item.
OUTDENT - Command: unnest a list item.
TOGGLE_HTML - Command: display/hide the HTML view.
FORMAT_BLOCK - Command: set a block element to another type.
PREVIEW - Command: open the preview dialog.
UNLINK - Command: unset a link.
INSERT_UNORDEREDLIST- Command: insert an unordered list.
INSERT_ORDEREDLIST - Command: insert an ordered list.
MAIN_CONTAINERS - An array of the main HTML containers used in WYMeditor.
BLOCKS - An array of the HTML block elements.
KEY - Standard key codes.
NODE - Node types.
*/
VERSION : "0.5-b2-refinery",
INSTANCES : [],
STRINGS : [],
SKINS : [],
NAME : "name",
INDEX : "{Wym_Index}",
WYM_INDEX : "wym_index",
BASE_PATH : "{Wym_Base_Path}",
CSS_PATH : "{Wym_Css_Path}",
WYM_PATH : "{Wym_Wym_Path}",
SKINS_DEFAULT_PATH : "/images/wymeditor/skins/",
SKINS_DEFAULT_CSS : "skin.css",
SKINS_DEFAULT_JS : "skin.js",
LANG_DEFAULT_PATH : "lang/",
IFRAME_BASE_PATH : "{Wym_Iframe_Base_Path}",
IFRAME_DEFAULT : "iframe/default/",
JQUERY_PATH : "{Wym_Jquery_Path}",
DIRECTION : "{Wym_Direction}",
LOGO : "{Wym_Logo}",
TOOLS : "{Wym_Tools}",
TOOLS_ITEMS : "{Wym_Tools_Items}",
TOOL_NAME : "{Wym_Tool_Name}",
TOOL_TITLE : "{Wym_Tool_Title}",
TOOL_CLASS : "{Wym_Tool_Class}",
CLASSES : "{Wym_Classes}",
CLASSES_ITEMS : "{Wym_Classes_Items}",
CLASS_NAME : "{Wym_Class_Name}",
CLASS_TITLE : "{Wym_Class_Title}",
CONTAINERS : "{Wym_Containers}",
CONTAINERS_ITEMS : "{Wym_Containers_Items}",
CONTAINER_NAME : "{Wym_Container_Name}",
CONTAINER_TITLE : "{Wym_Containers_Title}",
CONTAINER_CLASS : "{Wym_Container_Class}",
HTML : "{Wym_Html}",
IFRAME : "{Wym_Iframe}",
STATUS : "{Wym_Status}",
DIALOG_TITLE : "{Wym_Dialog_Title}",
DIALOG_BODY : "{Wym_Dialog_Body}",
STRING : "string",
BODY : "body",
DIV : "div",
P : "p",
H1 : "h1",
H2 : "h2",
H3 : "h3",
H4 : "h4",
H5 : "h5",
H6 : "h6",
PRE : "pre",
BLOCKQUOTE : "blockquote",
A : "a",
BR : "br",
IMG : "img",
TABLE : "table",
TD : "td",
TH : "th",
UL : "ul",
OL : "ol",
LI : "li",
CLASS : "class",
HREF : "href",
SRC : "src",
TITLE : "title",
TARGET : "target",
ALT : "alt",
DIALOG_LINK : "Link",
DIALOG_IMAGE : "Image",
DIALOG_TABLE : "Table",
DIALOG_PASTE : "Paste_From_Word",
DIALOG_CLASS : "Css_Class",
BOLD : "Bold",
ITALIC : "Italic",
CREATE_LINK : "CreateLink",
INSERT_IMAGE : "InsertImage",
INSERT_TABLE : "InsertTable",
INSERT_HTML : "InsertHTML",
APPLY_CLASS : "Apply_Style",
PASTE : "Paste",
INDENT : "Indent",
OUTDENT : "Outdent",
TOGGLE_HTML : "ToggleHtml",
FORMAT_BLOCK : "FormatBlock",
PREVIEW : "Preview",
UNLINK : "Unlink",
INSERT_UNORDEREDLIST : "InsertUnorderedList",
INSERT_ORDEREDLIST : "InsertOrderedList",
MAIN_CONTAINERS : new Array("p","h1","h2","h3","h4","h5","h6","pre","blockquote"),
BLOCKS : new Array("address", "blockquote", "div", "dl",
"fieldset", "form", "h1", "h2", "h3", "h4", "h5", "h6", "hr",
"noscript", "ol", "p", "pre", "table", "ul", "dd", "dt",
"li", "tbody", "td", "tfoot", "th", "thead", "tr"),
KEY : {
BACKSPACE: 8,
ENTER: 13,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
CURSOR: new Array(37, 38, 39, 40),
DELETE: 46
},
NODE : {
ELEMENT: 1,
ATTRIBUTE: 2,
TEXT: 3
},
/*
Class: WYMeditor.editor
WYMeditor editor main class, instanciated for each editor occurrence.
*/
editor : function(elem, options) {
/*
Constructor: WYMeditor.editor
Initializes main values (index, elements, paths, ...)
and call WYMeditor.editor.init which initializes the editor.
Parameters:
elem - The HTML element to be replaced by the editor.
options - The hash of options.
Returns:
Nothing.
See Also:
<WYMeditor.editor.init>
*/
//store the instance in the INSTANCES array and store the index
this._index = WYMeditor.INSTANCES.push(this) - 1;
//store the element replaced by the editor
this._element = elem;
//store the options
this._options = options;
//store the element's inner value
this._html = jQuery(elem).val();
//store the HTML option, if any
if(this._options.html) this._html = this._options.html;
//get or compute the base path (where the main JS file is located)
this._options.basePath = this._options.basePath || this.computeBasePath();
//get or set the skin path (where the skin files are located)
this._options.skinPath = this._options.skinPath || this._options.basePath + WYMeditor.SKINS_DEFAULT_PATH + this._options.skin + '/';
// set css and js skin paths
this._options.cssSkinPath = (this._options.cssSkinPath || this._options.skinPath) + this._options.skin + "/";
this._options.jsSkinPath = (this._options.jsSkinPath || this._options.skinPath) + this._options.skin + "/";
//get or compute the main JS file location
this._options.wymPath = this._options.wymPath || this.computeWymPath();
//get or set the language files path
this._options.langPath = this._options.langPath || this._options.basePath + WYMeditor.LANG_DEFAULT_PATH;
//get or set the designmode iframe's base path
this._options.iframeBasePath = this._options.iframeBasePath || this._options.basePath + WYMeditor.IFRAME_DEFAULT;
//get or compute the jQuery JS file location
this._options.jQueryPath = this._options.jQueryPath || this.computeJqueryPath();
//initialize the editor instance
this.init();
}
});
/********** JQUERY **********/
/**
* Replace an HTML element by WYMeditor
*
* @example jQuery(".wymeditor").wymeditor(
* {
*
* }
* );
* @desc Example description here
*
* @name WYMeditor
* @description WYMeditor is a web-based WYSIWYM XHTML editor
* @param Hash hash A hash of parameters
* @option Integer iExample Description here
* @option String sExample Description here
*
* @type jQuery
* @cat Plugins/WYMeditor
* @author Jean-Francois Hovinne
*/
jQuery.fn.wymeditor = function(options) {
options = jQuery.extend({
html: "",
basePath: false,
skinPath: false,
jsSkinPath: false,
cssSkinPath: false,
wymPath: false,
iframeBasePath: false,
jQueryPath: false,
styles: false,
stylesheet: false,
skin: "default",
initSkin: true,
loadSkin: true,
lang: "en",
direction: "ltr",
boxHtml: "<div class='wym_box'>"
+ "<div class='wym_area_top'>"
+ WYMeditor.TOOLS
+ "</div>"
+ "<div class='wym_area_left'></div>"
+ "<div class='wym_area_right'>"
+ WYMeditor.CONTAINERS
+ WYMeditor.CLASSES
+ "</div>"
+ "<div class='wym_area_main'>"
+ WYMeditor.HTML
+ WYMeditor.IFRAME
+ WYMeditor.STATUS
+ "</div>"
+ "<div class='wym_area_bottom'>"
+ WYMeditor.LOGO
+ "</div>"
+ "</div>",
logoHtml: "<a class='wym_wymeditor_link' "
+ "href='http://www.wymeditor.org/'>WYMeditor</a>",
iframeHtml:"<div class='wym_iframe wym_section'>"
+ "<iframe "
+ "src='"
+ WYMeditor.IFRAME_BASE_PATH
+ "wymiframe.html' "
+ "onload='this.contentWindow.parent.WYMeditor.INSTANCES["
+ WYMeditor.INDEX + "].initIframe(this)'"
+ "></iframe>"
+ "</div>",
editorStyles: [],
toolsHtml: "<div class='wym_tools wym_section'>"
+ "<h2>{Tools}</h2>"
+ "<ul>"
+ WYMeditor.TOOLS_ITEMS
+ "</ul>"
+ "</div>",
toolsItemHtml: "<li class='"
+ WYMeditor.TOOL_CLASS
+ "'><a href='#' name='"
+ WYMeditor.TOOL_NAME
+ "' title='"
+ WYMeditor.TOOL_TITLE
+ "'>"
+ WYMeditor.TOOL_TITLE
+ "</a></li>",
toolsItems: [
{'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'},
{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
{'name': 'Superscript', 'title': 'Superscript',
'css': 'wym_tools_superscript'},
{'name': 'Subscript', 'title': 'Subscript',
'css': 'wym_tools_subscript'},
{'name': 'InsertOrderedList', 'title': 'Ordered_List',
'css': 'wym_tools_ordered_list'},
{'name': 'InsertUnorderedList', 'title': 'Unordered_List',
'css': 'wym_tools_unordered_list'},
{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'},
{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'},
{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},
{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'},
{'name': 'Paste', 'title': 'Paste_From_Word',
'css': 'wym_tools_paste'},
{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'},
{'name': 'Preview', 'title': 'Preview', 'css': 'wym_tools_preview'}
],
containersHtml: "<div class='wym_containers wym_section'>"
+ "<h2>{Containers}</h2>"
+ "<ul>"
+ WYMeditor.CONTAINERS_ITEMS
+ "</ul>"
+ "</div>",
containersItemHtml:"<li class='"
+ WYMeditor.CONTAINER_CLASS
+ "'>"
+ "<a href='#' name='"
+ WYMeditor.CONTAINER_NAME
+ "'>"
+ WYMeditor.CONTAINER_TITLE
+ "</a></li>",
containersItems: [
{'name': 'P', 'title': 'Paragraph', 'css': 'wym_containers_p'},
{'name': 'H1', 'title': 'Heading_1', 'css': 'wym_containers_h1'},
{'name': 'H2', 'title': 'Heading_2', 'css': 'wym_containers_h2'},
{'name': 'H3', 'title': 'Heading_3', 'css': 'wym_containers_h3'},
{'name': 'H4', 'title': 'Heading_4', 'css': 'wym_containers_h4'},
{'name': 'H5', 'title': 'Heading_5', 'css': 'wym_containers_h5'},
{'name': 'H6', 'title': 'Heading_6', 'css': 'wym_containers_h6'},
{'name': 'PRE', 'title': 'Preformatted', 'css': 'wym_containers_pre'},
{'name': 'BLOCKQUOTE', 'title': 'Blockquote',
'css': 'wym_containers_blockquote'},
{'name': 'TH', 'title': 'Table_Header', 'css': 'wym_containers_th'}
],
classesHtml: "<div class='wym_classes wym_section'>"
+ "<h2>{Classes}</h2><ul>"
+ WYMeditor.CLASSES_ITEMS
+ "</ul></div>",
classesItemHtml: "<li><a href='#' name='"
+ WYMeditor.CLASS_NAME
+ "'>"
+ WYMeditor.CLASS_TITLE
+ "</a></li>",
classesItems: [],
statusHtml: "<div class='wym_status wym_section'>"
+ "<h2>{Status}</h2>"
+ "</div>",
htmlHtml: "<div class='wym_html wym_section'>"
+ "<h2>{Source_Code}</h2>"
+ "<textarea class='wym_html_val'></textarea>"
+ "</div>",
boxSelector: ".wym_box",
toolsSelector: ".wym_tools",
toolsListSelector: " ul",
containersSelector:".wym_containers",
classesSelector: ".wym_classes",
htmlSelector: ".wym_html",
iframeSelector: ".wym_iframe iframe",
iframeBodySelector:".wym_iframe",
statusSelector: ".wym_status",
toolSelector: ".wym_tools a",
containerSelector: ".wym_containers a",
classSelector: ".wym_classes a",
classUnhiddenSelector: ".wym_classes",
classHiddenSelector: ".wym_classes_hidden",
htmlValSelector: ".wym_html_val",
hrefSelector: ".wym_href",
srcSelector: ".wym_src",
titleSelector: ".wym_title",
targetSelector: ".wym_target",
altSelector: ".wym_alt",
textSelector: ".wym_text",
rowsSelector: ".wym_rows",
colsSelector: ".wym_cols",
captionSelector: ".wym_caption",
summarySelector: ".wym_summary",
submitSelector: ".wym_submit",
cancelSelector: ".wym_cancel",
previewSelector: "",
dialogTypeSelector: ".wym_dialog_type",
dialogLinkSelector: ".wym_dialog_link",
dialogImageSelector: ".wym_dialog_image",
dialogTableSelector: ".wym_dialog_table",
dialogPasteSelector: ".wym_dialog_paste",
dialogPreviewSelector: ".wym_dialog_preview",
updateSelector: ".wymupdate",
updateEvent: "click",
dialogFeatures: "menubar=no,titlebar=no,toolbar=no,resizable=no"
+ ",width=560,height=300,top=0,left=0",
dialogHtml: "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'"
+ " 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
+ "<html dir='"
+ WYMeditor.DIRECTION
+ "'><head>"
+ "<link rel='stylesheet' type='text/css' media='screen'"
+ " href='"
+ WYMeditor.CSS_PATH
+ "' />"
+ "<title>"
+ WYMeditor.DIALOG_TITLE
+ "</title>"
+ "<script type='text/javascript'"
+ " src='"
+ WYMeditor.JQUERY_PATH
+ "'></script>"
+ "<script type='text/javascript'"
+ " src='"
+ WYMeditor.WYM_PATH
+ "'></script>"
+ "</head>"
+ WYMeditor.DIALOG_BODY
+ "</html>",
dialogLinkHtml: "<div class='wym_dialog wym_dialog_link'>"
+ "<form>"
+ "<fieldset>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_LINK
+ "' />"
+ "<legend>{Link}</legend>"
+ "<div class='row'>"
+ "<label>{URL}</label>"
+ "<input type='text' class='wym_href' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Title}</label>"
+ "<input type='text' class='wym_title' value='' size='40' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogImageHtml: "<div class='wym_dialog wym_dialog_image'>"
+ "<form>"
+ "<fieldset>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_IMAGE
+ "' />"
+ "<legend>{Image}</legend>"
+ "<div class='row'>"
+ "<label>{URL}</label>"
+ "<input type='text' class='wym_src' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Alternative_Text}</label>"
+ "<input type='text' class='wym_alt' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Title}</label>"
+ "<input type='text' class='wym_title' value='' size='40' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogTableHtml: "<div class='wym_dialog wym_dialog_table'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_TABLE
+ "' />"
+ "<div class='row'>"
+ "<label>{Caption}</label>"
+ "<input type='text' class='wym_caption' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Summary}</label>"
+ "<input type='text' class='wym_summary' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Number_Of_Rows}</label>"
+ "<input type='text' class='wym_rows' value='3' size='3' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Number_Of_Cols}</label>"
+ "<input type='text' class='wym_cols' value='2' size='3' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</form>"
+ "</div>",
dialogPasteHtml: "<div class='wym_dialog wym_dialog_paste'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_PASTE
+ "' />"
+ "<fieldset>"
+ "<legend>{Paste_From_Word}</legend>"
+ "<div class='row'>"
+ "<textarea class='wym_text' rows='10' cols='50'></textarea>"
+ "</div>"
+ "<div class='row'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogPreviewHtml: "<div class='wym_dialog wym_dialog_preview'></div>",
dialogStyles: [],
stringDelimiterLeft: "{",
stringDelimiterRight:"}",
preInit: null,
preBind: null,
postInit: null,
preInitDialog: null,
postInitDialog: null
}, options);
return this.each(function() {
new WYMeditor.editor(jQuery(this),options);
});
};
/* @name extend
* @description Returns the WYMeditor instance based on its index
*/
jQuery.extend({
wymeditors: function(i) {
return (WYMeditor.INSTANCES[i]);
}
});
/********** WYMeditor **********/
/* @name Wymeditor
* @description WYMeditor class
*/
/* @name init
* @description Initializes a WYMeditor instance
*/
WYMeditor.editor.prototype.init = function() {
//load subclass - browser specific
//unsupported browsers: do nothing
if (jQuery.browser.msie) {
var WymClass = new WYMeditor.WymClassExplorer(this);
}
else if (jQuery.browser.mozilla) {
var WymClass = new WYMeditor.WymClassMozilla(this);
}
else if (jQuery.browser.opera) {
var WymClass = new WYMeditor.WymClassOpera(this);
}
else if (jQuery.browser.safari) {
var WymClass = new WYMeditor.WymClassSafari(this);
}
if(WymClass) {
if(jQuery.isFunction(this._options.preInit)) this._options.preInit(this);
var SaxListener = new WYMeditor.XhtmlSaxListener();
jQuery.extend(SaxListener, WymClass);
this.parser = new WYMeditor.XhtmlParser(SaxListener);
if(this._options.styles || this._options.stylesheet){
this.configureEditorUsingRawCss();
}
this.helper = new WYMeditor.XmlHelper();
//extend the Wymeditor object
//don't use jQuery.extend since 1.1.4
//jQuery.extend(this, WymClass);
for (var prop in WymClass) { this[prop] = WymClass[prop]; }
//load wymbox
this._box = jQuery(this._element).hide().after(this._options.boxHtml).next();
//store the instance index in the wymbox element
//but keep it compatible with jQuery < 1.2.3, see #122
if( jQuery.isFunction( jQuery.fn.data ) )
jQuery.data(this._box.get(0), WYMeditor.WYM_INDEX, this._index);
var h = WYMeditor.Helper;
//construct the iframe
var iframeHtml = this._options.iframeHtml;
iframeHtml = h.replaceAll(iframeHtml, WYMeditor.INDEX, this._index);
iframeHtml = h.replaceAll(iframeHtml, WYMeditor.IFRAME_BASE_PATH, this._options.iframeBasePath);
//construct wymbox
var boxHtml = jQuery(this._box).html();
boxHtml = h.replaceAll(boxHtml, WYMeditor.LOGO, this._options.logoHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS, this._options.toolsHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS,this._options.containersHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES, this._options.classesHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.HTML, this._options.htmlHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.IFRAME, iframeHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.STATUS, this._options.statusHtml);
//construct tools list
var aTools = eval(this._options.toolsItems);
var sTools = "";
for(var i = 0; i < aTools.length; i++) {
var oTool = aTools[i];
if(oTool.name && oTool.title)
var sTool = this._options.toolsItemHtml;
var sTool = h.replaceAll(sTool, WYMeditor.TOOL_NAME, oTool.name);
sTool = h.replaceAll(sTool, WYMeditor.TOOL_TITLE, this._options.stringDelimiterLeft
+ oTool.title
+ this._options.stringDelimiterRight);
sTool = h.replaceAll(sTool, WYMeditor.TOOL_CLASS, oTool.css);
sTools += sTool;
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS_ITEMS, sTools);
//construct classes list
var aClasses = eval(this._options.classesItems);
var sClasses = "";
for(var i = 0; i < aClasses.length; i++) {
var oClass = aClasses[i];
if(oClass.name) {
if (oClass.rules && oClass.rules.length > 0) {
var sRules = "";
oClass.rules.each(function(rule){
sClass = this._options.classesItemHtml;
sClass = h.replaceAll(sClass, WYMeditor.CLASS_NAME, oClass.name + (oClass.join || "") + rule);
sClass = h.replaceAll(sClass, WYMeditor.CLASS_TITLE, rule.title || titleize(rule));
sRules += sClass;
}.bind(this)); // need to bind 'this' or else it will think 'this' is the window.
var sClassMultiple = this._options.classesItemHtmlMultiple;
sClassMultiple = h.replaceAll(sClassMultiple, WYMeditor.CLASS_TITLE, oClass.title || titleize(oClass.name));
sClassMultiple = h.replaceAll(sClassMultiple, '{classesItemHtml}', sRules);
sClasses += sClassMultiple;
}
else {
sClass = this._options.classesItemHtml;
sClass = h.replaceAll(sClass, WYMeditor.CLASS_NAME, oClass.name);
sClass = h.replaceAll(sClass, WYMeditor.CLASS_TITLE, oClass.title || titleize(oClass.name));
sClasses += sClass;
}
}
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES_ITEMS, sClasses);
//construct containers list
var aContainers = eval(this._options.containersItems);
var sContainers = "";
for(var i = 0; i < aContainers.length; i++) {
var oContainer = aContainers[i];
if(oContainer.name && oContainer.title)
var sContainer = this._options.containersItemHtml;
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_NAME, oContainer.name);
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_TITLE,
this._options.stringDelimiterLeft
+ oContainer.title
+ this._options.stringDelimiterRight);
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_CLASS, oContainer.css);
sContainers += sContainer;
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS_ITEMS, sContainers);
//l10n
boxHtml = this.replaceStrings(boxHtml);
//load html in wymbox
jQuery(this._box).html(boxHtml);
//hide the html value
jQuery(this._box).find(this._options.htmlSelector).hide();
//enable the skin
this.loadSkin();
}
};
WYMeditor.editor.prototype.bindEvents = function() {
//copy the instance
var wym = this;
//handle click event on tools buttons
jQuery(this._box).find(this._options.toolSelector).click(function() {
wym.exec(jQuery(this).attr(WYMeditor.NAME));
return(false);
});
//handle click event on containers buttons
jQuery(this._box).find(this._options.containerSelector).click(function() {
wym.container(jQuery(this).attr(WYMeditor.NAME));
return(false);
});
//handle keyup event on html value: set the editor value
jQuery(this._box).find(this._options.htmlValSelector).keyup(function() {
jQuery(wym._doc.body).html(jQuery(this).val());
});
//handle click event on classes buttons
jQuery(this._box).find(this._options.classSelector).click(function() {
var aClasses = eval(wym._options.classesItems);
var sName = jQuery(this).attr(WYMeditor.NAME);
var oClass = WYMeditor.Helper.findByName(aClasses, sName);
var replacers = [];
if (oClass == null) {
aClasses.each(function(classRule){
if (oClass == null && classRule.rules && classRule.rules.length > 0){
indexOf = classRule.rules.indexOf(sName.gsub(classRule.name + (classRule.join || ""), ""));
if (indexOf > -1) {
for (i=0;i<classRule.rules.length;i++){
if (i != indexOf){
replacers.push(classRule.name + (classRule.join || "") + classRule.rules[i]);
}
}
oClass = {expr: (classRule.rules[indexOf].expr || null)}
}
}
}.bind(this));
}
if(oClass) {
var jqexpr = oClass.expr;
// remove all related classes.
replacers.each(function(removable_class){
wym.removeClass(removable_class, jqexpr);
});
wym.toggleClass(sName, jqexpr);
}
// now hide the menu
wym.exec(WYMeditor.APPLY_CLASS);
return(false);
});
//handle event on update element
jQuery(this._options.updateSelector).bind(this._options.updateEvent, function() {
wym.update();
});
};
WYMeditor.editor.prototype.ready = function() {
return(this._doc != null);
};
/********** METHODS **********/
/* @name box
* @description Returns the WYMeditor container
*/
WYMeditor.editor.prototype.box = function() {
return(this._box);
};
/* @name html
* @description Get/Set the html value
*/
WYMeditor.editor.prototype.html = function(html) {
if(typeof html === 'string') jQuery(this._doc.body).html(html);
else return(jQuery(this._doc.body).html());
};
/* @name xhtml
* @description Cleans up the HTML
*/
WYMeditor.editor.prototype.xhtml = function() {
return this.parser.parse(this.html());
};
/* @name exec
* @description Executes a button command
*/
WYMeditor.editor.prototype.exec = function(cmd) {
//base function for execCommand
//open a dialog or exec
switch(cmd) {
case WYMeditor.CREATE_LINK:
var container = this.container();
if(container || this._selected_image) this.dialog(WYMeditor.DIALOG_LINK);
break;
case WYMeditor.INSERT_IMAGE:
this.dialog(WYMeditor.DIALOG_IMAGE);
break;
case WYMeditor.INSERT_TABLE:
this.dialog(WYMeditor.DIALOG_TABLE);
break;
case WYMeditor.PASTE:
this.dialog(WYMeditor.DIALOG_PASTE);
break;
case WYMeditor.TOGGLE_HTML:
this.update();
this.toggleHtml();
//partially fixes #121 when the user manually inserts an image
if(!jQuery(this._box).find(this._options.htmlSelector).is(':visible'))
this.listen();
break;
case WYMeditor.PREVIEW:
this.dialog(WYMeditor.PREVIEW);
break;
case WYMeditor.APPLY_CLASS:
jQuery(this._box).find(this._options.classUnhiddenSelector).toggleClass(this._options.classHiddenSelector.substring(1)); // substring(1) to remove the . at the start
jQuery(this._box).find("a[name=" + WYMeditor.APPLY_CLASS +"]").toggleClass('selected');
//this.dialog(WYMeditor.DIALOG_CLASS);
break;
default:
this._exec(cmd);
break;
}
};
/* @name container
* @description Get/Set the selected container
*/
WYMeditor.editor.prototype.container = function(sType) {
if(sType) {
var container = null;
if(sType.toLowerCase() == WYMeditor.TH) {
container = this.container();
//find the TD or TH container
switch(container.tagName.toLowerCase()) {
case WYMeditor.TD: case WYMeditor.TH:
break;
default:
var aTypes = new Array(WYMeditor.TD,WYMeditor.TH);
container = this.findUp(this.container(), aTypes);
break;
}
//if it exists, switch
if(container!=null) {
sType = (container.tagName.toLowerCase() == WYMeditor.TD)? WYMeditor.TH: WYMeditor.TD;
this.switchTo(container,sType);
this.update();
}
} else {
//set the container type
var aTypes=new Array(WYMeditor.P,WYMeditor.H1,WYMeditor.H2,WYMeditor.H3,WYMeditor.H4,WYMeditor.H5,
WYMeditor.H6,WYMeditor.PRE,WYMeditor.BLOCKQUOTE);
container = this.findUp(this.container(), aTypes);
if(container) {
var newNode = null;
//blockquotes must contain a block level element
if(sType.toLowerCase() == WYMeditor.BLOCKQUOTE) {
var blockquote = this.findUp(this.container(), WYMeditor.BLOCKQUOTE);
if(blockquote == null) {
newNode = this._doc.createElement(sType);
container.parentNode.insertBefore(newNode,container);
newNode.appendChild(container);
this.setFocusToNode(newNode.firstChild);
} else {
var nodes = blockquote.childNodes;
var lgt = nodes.length;
var firstNode = null;
if(lgt > 0) firstNode = nodes.item(0);
for(var x=0; x<lgt; x++) {
blockquote.parentNode.insertBefore(nodes.item(0),blockquote);
}
blockquote.parentNode.removeChild(blockquote);
if(firstNode) this.setFocusToNode(firstNode);
}
}
else this.switchTo(container,sType);
this.update();
}
}
}
else return(this.selected());
};
/* @name toggleClass
* @description Toggles class on selected element, or one of its parents
*/
WYMeditor.editor.prototype.toggleClass = function(sClass, jqexpr) {
var container = jQuery((this._selected_image ? this._selected_image : this.selected(true)));
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.toggleClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
};
/* @name removeClass
* @description Removes class on selected element, or one of its parents
*/
WYMeditor.editor.prototype.removeClass = function(sClass, jqexpr) {
var container = jQuery((this._selected_image ? this._selected_image : jQuery(this.selected(true))));
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.removeClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
}
/* @name findUp
* @description Returns the first parent or self container, based on its type
*/
WYMeditor.editor.prototype.findUp = function(node, filter) {
//filter is a string or an array of strings
if(node) {
var tagname = node.tagName.toLowerCase();
if(typeof(filter) == WYMeditor.STRING) {
while(tagname != filter && tagname != WYMeditor.BODY) {
node = node.parentNode;
tagname = node.tagName.toLowerCase();
}
} else {
var bFound = false;
while(!bFound && tagname != WYMeditor.BODY) {
for(var i = 0; i < filter.length; i++) {
if(tagname == filter[i]) {
bFound = true;
break;
}
}
if(!bFound) {
node = node.parentNode;
tagname = node.tagName.toLowerCase();
}
}
}
if(tagname != WYMeditor.BODY) return(node);
else return(null);
} else return(null);
};
/* @name switchTo
* @description Switch the node's type
*/
WYMeditor.editor.prototype.switchTo = function(selectionOrNode,sType) {
if (selectionOrNode.getRangeAt) {
// We have a selection object so we need to create a temporary node around it (bold is easy). This node will be replaced anyway.
this.exec(WYMeditor.BOLD);
selectionOrNode = selectionOrNode.focusNode.parentNode;
}
// we have a node.
var html = jQuery(selectionOrNode).html();
var newNode = this._doc.createElement(sType);
selectionOrNode.parentNode.replaceChild(newNode,selectionOrNode);
jQuery(newNode).html(html);
this.setFocusToNode(newNode);
return newNode;
};
WYMeditor.editor.prototype.replaceStrings = function(sVal) {
//check if the language file has already been loaded
//if not, get it via a synchronous ajax call
if(!WYMeditor.STRINGS[this._options.lang]) {
try {
eval(jQuery.ajax({url:this._options.langPath
+ this._options.lang + '.js', async:false}).responseText);
} catch(e) {
if (WYMeditor.console) {
WYMeditor.console.error("WYMeditor: error while parsing language file.");
}
return sVal;
}
}
//replace all the strings in sVal and return it
for (var key in WYMeditor.STRINGS[this._options.lang]) {
sVal = WYMeditor.Helper.replaceAll(sVal, this._options.stringDelimiterLeft + key
+ this._options.stringDelimiterRight,
WYMeditor.STRINGS[this._options.lang][key]);
};
return(sVal);
};
WYMeditor.editor.prototype.encloseString = function(sVal) {
return(this._options.stringDelimiterLeft
+ sVal
+ this._options.stringDelimiterRight);
};
/* @name status
* @description Prints a status message
*/
WYMeditor.editor.prototype.status = function(sMessage) {
//print status message
jQuery(this._box).find(this._options.statusSelector).html(sMessage);
};
/* @name update
* @description Updates the element and textarea values
*/
WYMeditor.editor.prototype.update = function() {
var html = this.xhtml().gsub(/<\/([A-Za-z0-9]*)></, function(m){return "</" + m[1] +">\n<"});
jQuery(this._element).val(html);
jQuery(this._box).find(this._options.htmlValSelector).val(html);
};
/* @name dialog
* @description Opens a dialog box
*/
WYMeditor.editor.prototype.dialog = function( dialogType ) {
var path = this._wym._options.dialogPath + dialogType + this._wym._options.dialogFeatures;
this._current_unique_stamp = this.uniqueStamp();
// change undo or redo on cancel to true to have this happen when a user closes (cancels) a dialogue
this._undo_on_cancel = false;
this._redo_on_cancel = false;
//set to P if parent = BODY
if (![WYMeditor.DIALOG_TABLE, WYMeditor.DIALOG_PASTE].include(dialogType))
{
var container = this.selected();
if (container != null){
if(container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
}
else {
// somehow select the wymeditor textarea or simulate a click or a keydown on it.
}
}
selected = this.selected();
// set up handlers.
imageGroup = null;
ajax_loaded_callback = function(){this.dialog_ajax_callback(selected)}.bind(this, selected);
var parent_node = null;
if (this._selected_image) {
parent_node = this._selected_image.parentNode;
}
else {
parent_node = selected;
}
if (parent_node != null && parent_node.tagName.toLowerCase() != WYMeditor.A)
{
// wrap the current selection with a funky span (not required for safari)
if (!this._selected_image && !jQuery.browser.safari)
{
this.wrap("<span id='replace_me_with_" + this._current_unique_stamp + "'>", "</span>");
}
}
else {
if (!this._selected_image) {
parent_node._id_before_replaceable = parent.id;
parent_node.id = 'replace_me_with_' + this._current_unique_stamp;
}
path += (this._wym._options.dialogFeatures.length == 0) ? "?" : "&"
port = (window.location.port.length > 0 ? (":" + window.location.port) : "")
path += "current_link=" + parent_node.href.gsub(window.location.protocol + "//" + window.location.hostname + port, "");
path += "&target_blank=" + (parent_node.target == "_blank" ? "true" : "false")
}
// launch thickbox
dialog_title = this.replaceStrings(this.encloseString( dialogType ));
switch(dialogType) {
case WYMeditor.DIALOG_TABLE: {
dialog_container = document.createElement("div");
dialog_container.id = 'inline_dialog_container';
dialog_container.innerHTML = this.replaceStrings(this._options.dialogTableHtml);
jQuery(document.body).after(dialog_container);
tb_show(dialog_title, "#" + this._options.dialogInlineFeatures + "&inlineId=inline_dialog_container&TB_inline=true&modal=true", imageGroup);
ajax_loaded_callback();
break;
}
case WYMeditor.DIALOG_PASTE: {
dialog_container = document.createElement("div");
dialog_container.id = 'inline_dialog_container';
dialog_container.innerHTML = this.replaceStrings(this._options.dialogPasteHtml);
jQuery(document.body).after(dialog_container);
tb_show(dialog_title, "#" + this._options.dialogInlineFeatures + "&inlineId=inline_dialog_container&TB_inline=true&modal=true", imageGroup);
ajax_loaded_callback();
break;
}
default:
{
tb_show(dialog_title, path, imageGroup, ajax_loaded_callback);
break;
}
}
};
WYMeditor.editor.prototype.dialog_ajax_callback = function(selected) {
// look for iframes
if ((iframes = $(this._options.dialogId).select('iframe')).length > 0 && (iframe = $(iframes[0])) != null)
{
iframe.observe('load', function(selected, e)
{
WYMeditor.INIT_DIALOG(this, selected);
iframe.stopObserving('load');
}.bind(this, selected));
}
else
{
WYMeditor.INIT_DIALOG(this, selected);
}
};
/* @name toggleHtml
* @description Shows/Hides the HTML
*/
WYMeditor.editor.prototype.toggleHtml = function() {
jQuery(this._box).find(this._options.htmlSelector).toggle();
};
WYMeditor.editor.prototype.uniqueStamp = function() {
return("wym-" + new Date().getTime());
};
WYMeditor.editor.prototype.paste = function(sData) {
var sTmp;
var container = this.selected();
//split the data, using double newlines as the separator
var aP = sData.split(this._newLine + this._newLine);
var rExp = new RegExp(this._newLine, "g");
//add a P for each item
if(container && container.tagName.toLowerCase() != WYMeditor.BODY) {
for(x = aP.length - 1; x >= 0; x--) {
sTmp = aP[x];
//simple newlines are replaced by a break
sTmp = sTmp.replace(rExp, "<br />");
jQuery(container).after("<p>" + sTmp + "</p>");
}
} else {
for(x = 0; x < aP.length; x++) {
sTmp = aP[x];
//simple newlines are replaced by a break
sTmp = sTmp.replace(rExp, "<br />");
jQuery(this._doc.body).append("<p>" + sTmp + "</p>");
}
}
};
WYMeditor.editor.prototype.insert = function(html) {
// Do we have a selection?
if (this._iframe.contentWindow.getSelection().focusNode != null) {
// Overwrite selection with provided html
this._exec( WYMeditor.INSERT_HTML, html);
} else {
// Fall back to the internal paste function if there's no selection
this.paste(html);
}
};
WYMeditor.editor.prototype.wrap = function(left, right, selection) {
// Do we have a selection?
if (selection == null) { selection = this._iframe.contentWindow.getSelection();}
if (selection.focusNode != null) {
// Wrap selection with provided html
this._exec( WYMeditor.INSERT_HTML, left + selection.toString() + right);
}
};
WYMeditor.editor.prototype.unwrap = function(selection) {
// Do we have a selection?
if (selection == null) { selection = this._iframe.contentWindow.getSelection();}
if (selection.focusNode != null) {
// Unwrap selection
this._exec( WYMeditor.INSERT_HTML, selection.toString() );
}
};
WYMeditor.editor.prototype.addCssRules = function(doc, aCss) {
var styles = doc.styleSheets[0];
if(styles) {
for(var i = 0; i < aCss.length; i++) {
var oCss = aCss[i];
if(oCss.name && oCss.css) this.addCssRule(styles, oCss);
}
}
};
/********** CONFIGURATION **********/
WYMeditor.editor.prototype.computeBasePath = function() {
if ((script_path = this.computeWymPath()) != null) {
if ((src_parts = script_path.split('/')).length > 1) { src_parts.pop(); }
return src_parts.join('/') + "/";
}
else {
return null;
}
};
WYMeditor.editor.prototype.computeWymPath = function() {
return jQuery('script[src*=jquery.refinery.wymeditor]').attr('src');
};
WYMeditor.editor.prototype.computeJqueryPath = function() {
return jQuery(jQuery.grep(jQuery('script'), function(s){
return (s.src && s.src.match(/jquery(-(.*)){0,1}(\.pack|\.min|\.packed)?\.js(\?.*)?$/ ))
})).attr('src');
};
WYMeditor.editor.prototype.computeCssPath = function() {
return jQuery(jQuery.grep(jQuery('link'), function(s){
return (s.href && s.href.match(/wymeditor\/skins\/(.*)screen\.css(\?.*)?$/ ))
})).attr('href');
};
WYMeditor.editor.prototype.configureEditorUsingRawCss = function() {
var CssParser = new WYMeditor.WymCssParser();
if(this._options.stylesheet){
CssParser.parse(jQuery.ajax({url: this._options.stylesheet,async:false}).responseText);
}else{
CssParser.parse(this._options.styles, false);
}
if(this._options.classesItems.length == 0) {
this._options.classesItems = CssParser.css_settings.classesItems;
}
if(this._options.editorStyles.length == 0) {
this._options.editorStyles = CssParser.css_settings.editorStyles;
}
if(this._options.dialogStyles.length == 0) {
this._options.dialogStyles = CssParser.css_settings.dialogStyles;
}
};
/********** EVENTS **********/
WYMeditor.editor.prototype.listen = function() {
//don't use jQuery.find() on the iframe body
//because of MSIE + jQuery + expando issue (#JQ1143)
//jQuery(this._doc.body).find("*").bind("mouseup", this.mouseup);
jQuery(this._doc.body).bind("mousedown", this.mousedown);
var images = this._doc.body.getElementsByTagName("img");
for(var i=0; i < images.length; i++) {
jQuery(images[i]).bind("mousedown", this.mousedown);
}
};
WYMeditor.editor.prototype.mousedown = function(evt) {
var wym = WYMeditor.INSTANCES[this.ownerDocument.title];
wym._selected_image = (this.tagName.toLowerCase() == WYMeditor.IMG) ? this : null;
evt.stopPropagation();
};
/********** SKINS **********/
/*
* Function: WYMeditor.loadCss
* Loads a stylesheet in the document.
*
* Parameters:
* href - The CSS path.
*/
WYMeditor.loadCss = function(href) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
var head = jQuery('head').get(0);
head.appendChild(link);
};
/*
* Function: WYMeditor.editor.loadSkin
* Loads the skin CSS and initialization script (if needed).
*/
WYMeditor.editor.prototype.loadSkin = function() {
//does the user want to automatically load the CSS (default: yes)?
//we also test if it hasn't been already loaded by another instance
//see below for a better (second) test
if(this._options.loadSkin && !WYMeditor.SKINS[this._options.skin]) {
//check if it hasn't been already loaded
//so we don't load it more than once
//(we check the existing <link> elements)
var found = false;
var rExp = new RegExp(this._options.skin
+ '\/' + WYMeditor.SKINS_DEFAULT_CSS + '$');
jQuery('link').each( function() {
if(this.href.match(rExp)) found = true;
});
//load it, using the skin path
if(!found) WYMeditor.loadCss( this._options.cssSkinPath
+ WYMeditor.SKINS_DEFAULT_CSS );
}
//put the classname (ex. wym_skin_default) on wym_box
jQuery(this._box).addClass( "wym_skin_" + this._options.skin );
//does the user want to use some JS to initialize the skin (default: yes)?
//also check if it hasn't already been loaded by another instance
if(this._options.initSkin && !WYMeditor.SKINS[this._options.skin]) {
eval(jQuery.ajax({url:this._options.jsSkinPath
+ WYMeditor.SKINS_DEFAULT_JS, async:false}).responseText);
}
//init the skin, if needed
if(WYMeditor.SKINS[this._options.skin] && WYMeditor.SKINS[this._options.skin].init)
WYMeditor.SKINS[this._options.skin].init(this);
};
/********** DIALOGS **********/
WYMeditor.INIT_DIALOG = function(wym, selected, isIframe) {
var selected = selected || wym.selected();
var dialog = $(wym._options.dialogId);
var doc = (isIframe ? dialog.select('iframe')[0].document() : document);
var dialogType = doc.getElementById('wym_dialog_type').value;
var replaceable = wym._selected_image ? jQuery(wym._selected_image) : jQuery(wym._doc.body).find('#replace_me_with_' + wym._current_unique_stamp);
[dialog.select(".close_dialog"), $(doc.body).select(".close_dialog")].flatten().uniq().each(function(button)
{
button.observe('click', function(e){this.close_dialog(e, true)}.bind(wym));
});
/*
switch(dialogType) {
case WYMeditor.DIALOG_LINK:
//ensure that we select the link to populate the fields
if (replaceable[0] != null && replaceable[0].tagName.toLowerCase() == WYMeditor.A)
{
jQuery(wym._options.hrefSelector).val(jQuery(replaceable).attr(WYMeditor.HREF));
jQuery(wym._options.hrefSelector);
}
//fix MSIE selection if link image has been clicked
if(!selected && wym._selected_image)
selected = jQuery(wym._selected_image).parentsOrSelf(WYMeditor.A);
break;
}
*/
//pre-init functions
if(jQuery.isFunction(wym._options.preInitDialog))
wym._options.preInitDialog(wym,window);
/*
//auto populate fields if selected container (e.g. A)
if(selected) {
jQuery(wym._options.hrefSelector).val(jQuery(selected).attr(WYMeditor.HREF));
jQuery(wym._options.srcSelector).val(jQuery(selected).attr(WYMeditor.SRC));
jQuery(wym._options.titleSelector).val(jQuery(selected).attr(WYMeditor.TITLE));
jQuery(wym._options.altSelector).val(jQuery(selected).attr(WYMeditor.ALT));
}*/
//auto populate image fields if selected image
if(wym._selected_image) {
jQuery(wym._options.dialogImageSelector + " " + wym._options.srcSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.SRC));
jQuery(wym._options.dialogImageSelector + " " + wym._options.titleSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.TITLE));
jQuery(wym._options.dialogImageSelector + " " + wym._options.altSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.ALT));
}
jQuery(wym._options.dialogLinkSelector + " " + wym._options.submitSelector).click(function()
{
var sUrl = jQuery(wym._options.hrefSelector).val();
if(sUrl.length > 0)
{
if (replaceable[0] != null) {
link = wym._doc.createElement("a");
link.href = sUrl;
link.title = jQuery(wym._options.titleSelector).val();
target = jQuery(wym._options.targetSelector).val();
if (target != null && target.length > 0) {
link.target = target;
}
// now grab what was selected in the editor and chuck it inside the link.
if (!wym._selected_image)
{
replaceable.after(link);
link.innerHTML = replaceable.html();
replaceable.remove();
}
else
{
if ((parent = replaceable[0].parentNode) != null && parent.tagName.toUpperCase() == "A") {
parent.href = link.href;
parent.title = jQuery(wym._options.titleSelector).val();
parent.target = target;
}
else {
replaceable.before(link);
jQuery(link).append(replaceable[0]);
}
}
}
else {
wym._exec(WYMeditor.CREATE_LINK, wym._current_unique_stamp);
jQuery("a[@href=" + wym._current_unique_stamp + "]", wym._doc.body)
.attr(WYMeditor.HREF, sUrl)
.attr(WYMeditor.TITLE, jQuery(wym._options.titleSelector).val())
.attr(WYMeditor.TARGET, jQuery(wym._options.targetSelector).val());
}
}
// fire a click event on the dialogs close button
wym.close_dialog()
});
jQuery(wym._options.dialogImageSelector + " " + wym._options.submitSelector).click(function() {
form = jQuery(this.form);
var sUrl = form.find(wym._options.srcSelector).val();
var sTitle = form.find(wym._options.titleSelector).val();
var sAlt = form.find(wym._options.altSelector).val();
if (sUrl != null && sUrl.length > 0) {
wym._exec(WYMeditor.INSERT_IMAGE, wym._current_unique_stamp, selected);
//don't use jQuery.find() see #JQ1143
//var image = jQuery(wym._doc.body).find("img[@src=" + sStamp + "]");
var image = null;
var nodes = wym._doc.body.getElementsByTagName(WYMeditor.IMG);
for(var i=0; i < nodes.length; i++)
{
if(jQuery(nodes[i]).attr(WYMeditor.SRC) == wym._current_unique_stamp)
{
image = jQuery(nodes[i]);
break;
}
}
if(image) {
image.attr(WYMeditor.SRC, sUrl);
image.attr(WYMeditor.TITLE, sTitle);
image.attr(WYMeditor.ALT, sAlt);
if (!jQuery.browser.safari)
{
if (replaceable != null)
{
if (this._selected_image == null || (this._selected_image != null && replaceable.parentNode != null))
{
replaceable.after(image);
replaceable.remove();
}
}
}
}
// fire a click event on the dialogs close button
wym.close_dialog();
}
});
jQuery(wym._options.dialogTableSelector + " " + wym._options.submitSelector).click(function() {
var iRows = jQuery(wym._options.rowsSelector).val();
var iCols = jQuery(wym._options.colsSelector).val();
if(iRows > 0 && iCols > 0)
{
var table = wym._doc.createElement(WYMeditor.TABLE);
var newRow = null;
var newCol = null;
var sCaption = jQuery(wym._options.captionSelector).val();
//we create the caption
var newCaption = table.createCaption();
newCaption.innerHTML = sCaption;
//we create the rows and cells
for(x=0; x<iRows; x++) {
newRow = table.insertRow(x);
for(y=0; y<iCols; y++) {newRow.insertCell(y);}
}
//append the table after the selected container
var node = jQuery(wym.findUp(wym.container(),
WYMeditor.MAIN_CONTAINERS)).get(0);
if(!node || !node.parentNode) jQuery(wym._doc.body).append(table);
else jQuery(node).after(table);
}
// fire a click event on the dialogs close button
wym.close_dialog();
});
jQuery(wym._options.dialogPasteSelector + " " + wym._options.submitSelector).click(function() {
var sText = jQuery(wym._options.textSelector).val();
wym.paste(sText);
// fire a click event on the dialogs close button
wym.close_dialog();
});
jQuery(wym._options.dialogPreviewSelector + " "
+ wym._options.previewSelector)
.html(wym.xhtml());
//post-init functions
if(jQuery.isFunction(wym._options.postInitDialog))
wym._options.postInitDialog(wym,window);
};
WYMeditor.editor.prototype.close_dialog = function(e, cancelled) {
if (cancelled)
{
// if span exists, repalce it with its own html contents.
replaceable = jQuery(this._doc.body).find('#replace_me_with_' + this._current_unique_stamp);
if (replaceable[0] != null) {
if (replaceable[0].tagName.toLowerCase() != WYMeditor.A) {
replaceable.replaceWith(replaceable.html());
}
else {
replaceable[0].id = replaceable[0]._id_before_replaceable;
}
}
if (this._undo_on_cancel == true) {
this._exec("undo");
}
else if (this._redo_on_cancel == true) {
this._exec("redo");
}
}
if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8)
{
this._iframe.contentWindow.focus();
}
if ((inline_dialog_container = $('inline_dialog_container')) != null)
{
inline_dialog_container.remove();
}
tb_remove();
if (e) {
e.stop();
}
}
/********** XHTML LEXER/PARSER **********/
/*
* @name xml
* @description Use these methods to generate XML and XHTML compliant tags and
* escape tag attributes correctly
* @author Bermi Ferrer - http://bermi.org
* @author David Heinemeier Hansson http://loudthinking.com
*/
WYMeditor.XmlHelper = function()
{
this._entitiesDiv = document.createElement('div');
return this;
};
/*
* @name tag
* @description
* Returns an empty HTML tag of type *name* which by default is XHTML
* compliant. Setting *open* to true will create an open tag compatible
* with HTML 4.0 and below. Add HTML attributes by passing an attributes
* array to *options*. For attributes with no value like (disabled and
* readonly), give it a value of true in the *options* array.
*
* Examples:
*
* this.tag('br')
* # => <br />
* this.tag ('br', false, true)
* # => <br>
* this.tag ('input', jQuery({type:'text',disabled:true }) )
* # => <input type="text" disabled="disabled" />
*/
WYMeditor.XmlHelper.prototype.tag = function(name, options, open)
{
options = options || false;
open = open || false;
return '<'+name+(options ? this.tagOptions(options) : '')+(open ? '>' : ' />');
};
/*
* @name contentTag
* @description
* Returns a XML block tag of type *name* surrounding the *content*. Add
* XML attributes by passing an attributes array to *options*. For attributes
* with no value like (disabled and readonly), give it a value of true in
* the *options* array. You can use symbols or strings for the attribute names.
*
* this.contentTag ('p', 'Hello world!' )
* # => <p>Hello world!</p>
* this.contentTag('div', this.contentTag('p', "Hello world!"), jQuery({class : "strong"}))
* # => <div class="strong"><p>Hello world!</p></div>
* this.contentTag("select", options, jQuery({multiple : true}))
* # => <select multiple="multiple">...options...</select>
*/
WYMeditor.XmlHelper.prototype.contentTag = function(name, content, options)
{
options = options || false;
return '<'+name+(options ? this.tagOptions(options) : '')+'>'+content+'</'+name+'>';
};
/*
* @name cdataSection
* @description
* Returns a CDATA section for the given +content+. CDATA sections
* are used to escape blocks of text containing characters which would
* otherwise be recognized as markup. CDATA sections begin with the string
* <tt><![CDATA[</tt> and } with (and may not contain) the string
* <tt>]]></tt>.
*/
WYMeditor.XmlHelper.prototype.cdataSection = function(content)
{
return '<![CDATA['+content+']]>';
};
/*
* @name escapeOnce
* @description
* Returns the escaped +xml+ without affecting existing escaped entities.
*
* this.escapeOnce( "1 > 2 & 3")
* # => "1 > 2 & 3"
*/
WYMeditor.XmlHelper.prototype.escapeOnce = function(xml)
{
return this._fixDoubleEscape(this.escapeEntities(xml));
};
/*
* @name _fixDoubleEscape
* @description
* Fix double-escaped entities, such as &amp;, &#123;, etc.
*/
WYMeditor.XmlHelper.prototype._fixDoubleEscape = function(escaped)
{
return escaped.replace(/&([a-z]+|(#\d+));/ig, "&$1;");
};
/*
* @name tagOptions
* @description
* Takes an array like the one generated by Tag.parseAttributes
* [["src", "http://www.editam.com/?a=b&c=d&f=g"], ["title", "Editam, <Simplified> CMS"]]
* or an object like {src:"http://www.editam.com/?a=b&c=d&f=g", title:"Editam, <Simplified> CMS"}
* and returns a string properly escaped like
* ' src = "http://www.editam.com/?a=b&c=d&f=g" title = "Editam, <Simplified> CMS"'
* which is valid for strict XHTML
*/
WYMeditor.XmlHelper.prototype.tagOptions = function(options)
{
var xml = this;
xml._formated_options = '';
for (var key in options) {
var formated_options = '';
var value = options[key];
if(typeof value != 'function' && value.length > 0) {
if(parseInt(key) == key && typeof value == 'object'){
key = value.shift();
value = value.pop();
}
if(key != '' && value != ''){
xml._formated_options += ' '+key+'="'+xml.escapeOnce(value)+'"';
}
}
}
return xml._formated_options;
};
/*
* @name escapeEntities
* @description
* Escapes XML/HTML entities <, >, & and ". If seccond parameter is set to false it
* will not escape ". If set to true it will also escape '
*/
WYMeditor.XmlHelper.prototype.escapeEntities = function(string, escape_quotes)
{
this._entitiesDiv.innerHTML = string;
this._entitiesDiv.textContent = string;
var result = this._entitiesDiv.innerHTML;
if(typeof escape_quotes == 'undefined'){
if(escape_quotes != false) result = result.replace('"', '"');
if(escape_quotes == true) result = result.replace('"', ''');
}
return result;
};
/*
* Parses a string conatining tag attributes and values an returns an array formated like
* [["src", "http://www.editam.com"], ["title", "Editam, Simplified CMS"]]
*/
WYMeditor.XmlHelper.prototype.parseAttributes = function(tag_attributes)
{
// Use a compounded regex to match single quoted, double quoted and unquoted attribute pairs
var result = [];
var matches = tag_attributes.split(/((=\s*")(")("))|((=\s*\')(\')(\'))|((=\s*[^>\s]*))/g);
if(matches.toString() != tag_attributes){
for (var k in matches) {
var v = matches[k];
if(typeof v != 'function' && v.length != 0){
var re = new RegExp('(\\w+)\\s*'+v);
if(match = tag_attributes.match(re) ){
var value = v.replace(/^[\s=]+/, "");
var delimiter = value.charAt(0);
delimiter = delimiter == '"' ? '"' : (delimiter=="'"?"'":'');
if(delimiter != ''){
value = delimiter == '"' ? value.replace(/^"|"+$/g, '') : value.replace(/^'|'+$/g, '');
}
tag_attributes = tag_attributes.replace(match[0],'');
result.push([match[1] , value]);
}
}
}
}
return result;
};
/**
* XhtmlValidator for validating tag attributes
*
* @author Bermi Ferrer - http://bermi.org
*/
WYMeditor.XhtmlValidator = {
"_attributes":
{
"core":
{
"except":[
"base",
"head",
"html",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"class",
"id",
"style",
"title",
"accesskey",
"tabindex"
]
},
"language":
{
"except":[
"base",
"br",
"hr",
"iframe",
"param",
"script"
],
"attributes":
{
"dir":[
"ltr",
"rtl"
],
"0":"lang",
"1":"xml:lang"
}
},
"keyboard":
{
"attributes":
{
"accesskey":/^(\w){1}$/,
"tabindex":/^(\d)+$/
}
}
},
"_events":
{
"window":
{
"only":[
"body"
],
"attributes":[
"onload",
"onunload"
]
},
"form":
{
"only":[
"form",
"input",
"textarea",
"select",
"a",
"label",
"button"
],
"attributes":[
"onchange",
"onsubmit",
"onreset",
"onselect",
"onblur",
"onfocus"
]
},
"keyboard":
{
"except":[
"base",
"bdo",
"br",
"frame",
"frameset",
"head",
"html",
"iframe",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"onkeydown",
"onkeypress",
"onkeyup"
]
},
"mouse":
{
"except":[
"base",
"bdo",
"br",
"head",
"html",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"onclick",
"ondblclick",
"onmousedown",
"onmousemove",
"onmouseover",
"onmouseout",
"onmouseup"
]
}
},
"_tags":
{
"a":
{
"attributes":
{
"0":"charset",
"1":"coords",
"2":"href",
"3":"hreflang",
"4":"name",
"rel":/^(alternate|designates|stylesheet|start|next|prev|contents|index|glossary|copyright|chapter|section|subsection|appendix|help|bookmark| |shortcut|icon|moodalbox)+$/,
"rev":/^(alternate|designates|stylesheet|start|next|prev|contents|index|glossary|copyright|chapter|section|subsection|appendix|help|bookmark| |shortcut|icon|moodalbox)+$/,
"shape":/^(rect|rectangle|circ|circle|poly|polygon)$/,
"5":"type",
"target":/^(_blank)+$/
}
},
"0":"abbr",
"1":"acronym",
"2":"address",
"area":
{
"attributes":
{
"0":"alt",
"1":"coords",
"2":"href",
"nohref":/^(true|false)$/,
"shape":/^(rect|rectangle|circ|circle|poly|polygon)$/
},
"required":[
"alt"
]
},
"3":"b",
"base":
{
"attributes":[
"href"
],
"required":[
"href"
]
},
"bdo":
{
"attributes":
{
"dir":/^(ltr|rtl)$/
},
"required":[
"dir"
]
},
"4":"big",
"blockquote":
{
"attributes":[
"cite"
]
},
"5":"body",
"6":"br",
"button":
{
"attributes":
{
"disabled":/^(disabled)$/,
"type":/^(button|reset|submit)$/,
"0":"value"
},
"inside":"form"
},
"7":"caption",
"8":"cite",
"9":"code",
"col":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"span":/^(\d)+$/,
"valign":/^(top|middle|bottom|baseline)$/,
"2":"width"
},
"inside":"colgroup"
},
"colgroup":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"span":/^(\d)+$/,
"valign":/^(top|middle|bottom|baseline)$/,
"2":"width"
}
},
"10":"dd",
"del":
{
"attributes":
{
"0":"cite",
"datetime":/^([0-9]){8}/
}
},
"11":"div",
"12":"dfn",
"13":"dl",
"14":"dt",
"15":"em",
"fieldset":
{
"inside":"form"
},
"form":
{
"attributes":
{
"0":"action",
"1":"accept",
"2":"accept-charset",
"3":"enctype",
"method":/^(get|post)$/
},
"required":[
"action"
]
},
"head":
{
"attributes":[
"profile"
]
},
"16":"h1",
"17":"h2",
"18":"h3",
"19":"h4",
"20":"h5",
"21":"h6",
"22":"hr",
"html":
{
"attributes":[
"xmlns"
]
},
"23":"i",
"iframe":
{
"attributes":[
"src",
"width",
"height",
"frameborder",
"scrolling",
"marginheight",
"marginwidth"
],
"required":[
"src"
]
},
"img":
{
"attributes":{
"align":/^(right|left|center|justify)$/,
"0":"alt",
"1":"src",
"2":"height",
"3":"ismap",
"4":"longdesc",
"5":"usemap",
"6":"width"
},
"required":[
"alt",
"src"
]
},
"input":
{
"attributes":
{
"0":"accept",
"1":"alt",
"checked":/^(checked)$/,
"disabled":/^(disabled)$/,
"maxlength":/^(\d)+$/,
"2":"name",
"readonly":/^(readonly)$/,
"size":/^(\d)+$/,
"3":"src",
"type":/^(button|checkbox|file|hidden|image|password|radio|reset|submit|text)$/,
"4":"value"
},
"inside":"form"
},
"ins":
{
"attributes":
{
"0":"cite",
"datetime":/^([0-9]){8}/
}
},
"24":"kbd",
"label":
{
"attributes":[
"for"
],
"inside":"form"
},
"25":"legend",
"26":"li",
"link":
{
"attributes":
{
"0":"charset",
"1":"href",
"2":"hreflang",
"media":/^(all|braille|print|projection|screen|speech|,|;| )+$/i,
//next comment line required by Opera!
/*"rel":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,*/
"rel":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,
"rev":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,
"3":"type"
},
"inside":"head"
},
"map":
{
"attributes":[
"id",
"name"
],
"required":[
"id"
]
},
"meta":
{
"attributes":
{
"0":"content",
"http-equiv":/^(content\-type|expires|refresh|set\-cookie)$/i,
"1":"name",
"2":"scheme"
},
"required":[
"content"
]
},
"27":"noscript",
"28":"ol",
"optgroup":
{
"attributes":
{
"0":"label",
"disabled": /^(disabled)$/
},
"required":[
"label"
]
},
"option":
{
"attributes":
{
"0":"label",
"disabled":/^(disabled)$/,
"selected":/^(selected)$/,
"1":"value"
},
"inside":"select"
},
"29":"p",
"param":
{
"attributes":
[
"type",
"value",
"name"
],
"required":[
"name"
],
"inside":"object"
},
"embed":
{
"attributes":
[
"width",
"height",
"allowfullscreen",
"allowscriptaccess",
"wmode",
"type",
"src"
],
"inside":"object"
},
"object":
{
"attributes":[
"archive",
"classid",
"codebase",
"codetype",
"data",
"declare",
"height",
"name",
"standby",
"type",
"usemap",
"width"
]
},
"30":"pre",
"q":
{
"attributes":[
"cite"
]
},
"31":"samp",
"script":
{
"attributes":
{
"type":/^(text\/ecmascript|text\/javascript|text\/jscript|text\/vbscript|text\/vbs|text\/xml)$/,
"0":"charset",
"defer":/^(defer)$/,
"1":"src"
},
"required":[
"type"
]
},
"select":
{
"attributes":
{
"disabled":/^(disabled)$/,
"multiple":/^(multiple)$/,
"0":"name",
"1":"size"
},
"inside":"form"
},
"32":"small",
"33":"span",
"34":"strong",
"style":
{
"attributes":
{
"0":"type",
"media":/^(screen|tty|tv|projection|handheld|print|braille|aural|all)$/
},
"required":[
"type"
]
},
"35":"sub",
"36":"sup",
"table":
{
"attributes":
{
"0":"border",
"1":"cellpadding",
"2":"cellspacing",
"frame":/^(void|above|below|hsides|lhs|rhs|vsides|box|border)$/,
"rules":/^(none|groups|rows|cols|all)$/,
"3":"summary",
"4":"width"
}
},
"tbody":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"td":
{
"attributes":
{
"0":"abbr",
"align":/^(left|right|center|justify|char)$/,
"1":"axis",
"2":"char",
"3":"charoff",
"colspan":/^(\d)+$/,
"4":"headers",
"rowspan":/^(\d)+$/,
"scope":/^(col|colgroup|row|rowgroup)$/,
"valign":/^(top|middle|bottom|baseline)$/
}
},
"textarea":
{
"attributes":[
"cols",
"rows",
"disabled",
"name",
"readonly"
],
"required":[
"cols",
"rows"
],
"inside":"form"
},
"tfoot":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom)$/,
"2":"baseline"
}
},
"th":
{
"attributes":
{
"0":"abbr",
"align":/^(left|right|center|justify|char)$/,
"1":"axis",
"2":"char",
"3":"charoff",
"colspan":/^(\d)+$/,
"4":"headers",
"rowspan":/^(\d)+$/,
"scope":/^(col|colgroup|row|rowgroup)$/,
"valign":/^(top|middle|bottom|baseline)$/
}
},
"thead":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"37":"title",
"tr":
{
"attributes":
{
"align":/^(right|left|center|justify|char)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"38":"tt",
"39":"ul",
"40":"var"
},
// Temporary skiped attributes
skiped_attributes : [],
skiped_attribute_values : [],
getValidTagAttributes: function(tag, attributes)
{
var valid_attributes = {};
var possible_attributes = this.getPossibleTagAttributes(tag);
for(var attribute in attributes) {
var value = attributes[attribute];
var h = WYMeditor.Helper;
if(!h.contains(this.skiped_attributes, attribute) && !h.contains(this.skiped_attribute_values, value)){
if (typeof value != 'function' && h.contains(possible_attributes, attribute)) {
if (this.doesAttributeNeedsValidation(tag, attribute)) {
if(this.validateAttribute(tag, attribute, value)){
valid_attributes[attribute] = value;
}
}else{
valid_attributes[attribute] = value;
}
}
}
}
return valid_attributes;
},
getUniqueAttributesAndEventsForTag : function(tag)
{
var result = [];
if (this._tags[tag] && this._tags[tag]['attributes']) {
for (k in this._tags[tag]['attributes']) {
result.push(parseInt(k) == k ? this._tags[tag]['attributes'][k] : k);
}
}
return result;
},
getDefaultAttributesAndEventsForTags : function()
{
var result = [];
for (var key in this._events){
result.push(this._events[key]);
}
for (var key in this._attributes){
result.push(this._attributes[key]);
}
return result;
},
isValidTag : function(tag)
{
if(this._tags[tag]){
return true;
}
for(var key in this._tags){
if(this._tags[key] == tag){
return true;
}
}
return false;
},
getDefaultAttributesAndEventsForTag : function(tag)
{
var default_attributes = [];
if (this.isValidTag(tag)) {
var default_attributes_and_events = this.getDefaultAttributesAndEventsForTags();
for(var key in default_attributes_and_events) {
var defaults = default_attributes_and_events[key];
if(typeof defaults == 'object'){
var h = WYMeditor.Helper;
if ((defaults['except'] && h.contains(defaults['except'], tag)) || (defaults['only'] && !h.contains(defaults['only'], tag))) {
continue;
}
var tag_defaults = defaults['attributes'] ? defaults['attributes'] : defaults['events'];
for(var k in tag_defaults) {
default_attributes.push(typeof tag_defaults[k] != 'string' ? k : tag_defaults[k]);
}
}
}
}
return default_attributes;
},
doesAttributeNeedsValidation: function(tag, attribute)
{
return this._tags[tag] && ((this._tags[tag]['attributes'] && this._tags[tag]['attributes'][attribute]) || (this._tags[tag]['required'] &&
WYMeditor.Helper.contains(this._tags[tag]['required'], attribute)));
},
validateAttribute : function(tag, attribute, value)
{
if ( this._tags[tag] &&
(this._tags[tag]['attributes'] && this._tags[tag]['attributes'][attribute] && value.length > 0 && !value.match(this._tags[tag]['attributes'][attribute])) || // invalid format
(this._tags[tag] && this._tags[tag]['required'] && WYMeditor.Helper.contains(this._tags[tag]['required'], attribute) && value.length == 0) // required attribute
) {
return false;
}
return typeof this._tags[tag] != 'undefined';
},
getPossibleTagAttributes : function(tag)
{
if (!this._possible_tag_attributes) {
this._possible_tag_attributes = {};
}
if (!this._possible_tag_attributes[tag]) {
this._possible_tag_attributes[tag] = this.getUniqueAttributesAndEventsForTag(tag).concat(this.getDefaultAttributesAndEventsForTag(tag));
}
return this._possible_tag_attributes[tag];
}
};
/**
* Compounded regular expression. Any of
* the contained patterns could match and
* when one does, it's label is returned.
*
* Constructor. Starts with no patterns.
* @param boolean case True for case sensitive, false
* for insensitive.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.ParallelRegex = function(case_sensitive)
{
this._case = case_sensitive;
this._patterns = [];
this._labels = [];
this._regex = null;
return this;
};
/**
* Adds a pattern with an optional label.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string label Label of regex to be returned
* on a match.
* @access public
*/
WYMeditor.ParallelRegex.prototype.addPattern = function(pattern, label)
{
label = label || true;
var count = this._patterns.length;
this._patterns[count] = pattern;
this._labels[count] = label;
this._regex = null;
};
/**
* Attempts to match all patterns at once against
* a string.
* @param string subject String to match against.
*
* @return boolean True on success.
* @return string match First matched portion of
* subject.
* @access public
*/
WYMeditor.ParallelRegex.prototype.match = function(subject)
{
if (this._patterns.length == 0) {
return [false, ''];
}
var matches = subject.match(this._getCompoundedRegex());
if(!matches){
return [false, ''];
}
var match = matches[0];
for (var i = 1; i < matches.length; i++) {
if (matches[i]) {
return [this._labels[i-1], match];
}
}
return [true, matches[0]];
};
/**
* Compounds the patterns into a single
* regular expression separated with the
* "or" operator. Caches the regex.
* Will automatically escape (, ) and / tokens.
* @param array patterns List of patterns in order.
* @access private
*/
WYMeditor.ParallelRegex.prototype._getCompoundedRegex = function()
{
if (this._regex == null) {
for (var i = 0, count = this._patterns.length; i < count; i++) {
this._patterns[i] = '(' + this._untokenizeRegex(this._tokenizeRegex(this._patterns[i]).replace(/([\/\(\)])/g,'\\$1')) + ')';
}
this._regex = new RegExp(this._patterns.join("|") ,this._getPerlMatchingFlags());
}
return this._regex;
};
/**
* Escape lookahead/lookbehind blocks
*/
WYMeditor.ParallelRegex.prototype._tokenizeRegex = function(regex)
{
return regex.
replace(/\(\?(i|m|s|x|U)\)/, '~~~~~~Tk1\$1~~~~~~').
replace(/\(\?(\-[i|m|s|x|U])\)/, '~~~~~~Tk2\$1~~~~~~').
replace(/\(\?\=(.*)\)/, '~~~~~~Tk3\$1~~~~~~').
replace(/\(\?\!(.*)\)/, '~~~~~~Tk4\$1~~~~~~').
replace(/\(\?\<\=(.*)\)/, '~~~~~~Tk5\$1~~~~~~').
replace(/\(\?\<\!(.*)\)/, '~~~~~~Tk6\$1~~~~~~').
replace(/\(\?\:(.*)\)/, '~~~~~~Tk7\$1~~~~~~');
};
/**
* Unscape lookahead/lookbehind blocks
*/
WYMeditor.ParallelRegex.prototype._untokenizeRegex = function(regex)
{
return regex.
replace(/~~~~~~Tk1(.{1})~~~~~~/, "(?\$1)").
replace(/~~~~~~Tk2(.{2})~~~~~~/, "(?\$1)").
replace(/~~~~~~Tk3(.*)~~~~~~/, "(?=\$1)").
replace(/~~~~~~Tk4(.*)~~~~~~/, "(?!\$1)").
replace(/~~~~~~Tk5(.*)~~~~~~/, "(?<=\$1)").
replace(/~~~~~~Tk6(.*)~~~~~~/, "(?<!\$1)").
replace(/~~~~~~Tk7(.*)~~~~~~/, "(?:\$1)");
};
/**
* Accessor for perl regex mode flags to use.
* @return string Perl regex flags.
* @access private
*/
WYMeditor.ParallelRegex.prototype._getPerlMatchingFlags = function()
{
return (this._case ? "m" : "mi");
};
/**
* States for a stack machine.
*
* Constructor. Starts in named state.
* @param string start Starting state name.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.StateStack = function(start)
{
this._stack = [start];
return this;
};
/**
* Accessor for current state.
* @return string State.
* @access public
*/
WYMeditor.StateStack.prototype.getCurrent = function()
{
return this._stack[this._stack.length - 1];
};
/**
* Adds a state to the stack and sets it
* to be the current state.
* @param string state New state.
* @access public
*/
WYMeditor.StateStack.prototype.enter = function(state)
{
this._stack.push(state);
};
/**
* Leaves the current state and reverts
* to the previous one.
* @return boolean False if we drop off
* the bottom of the list.
* @access public
*/
WYMeditor.StateStack.prototype.leave = function()
{
if (this._stack.length == 1) {
return false;
}
this._stack.pop();
return true;
};
// GLOBALS
WYMeditor.LEXER_ENTER = 1;
WYMeditor.LEXER_MATCHED = 2;
WYMeditor.LEXER_UNMATCHED = 3;
WYMeditor.LEXER_EXIT = 4;
WYMeditor.LEXER_SPECIAL = 5;
/**
* Accepts text and breaks it into tokens.
* Some optimisation to make the sure the
* content is only scanned by the PHP regex
* parser once. Lexer modes must not start
* with leading underscores.
*
* Sets up the lexer in case insensitive matching
* by default.
* @param Parser parser Handling strategy by reference.
* @param string start Starting handler.
* @param boolean case True for case sensitive.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.Lexer = function(parser, start, case_sensitive)
{
start = start || 'accept';
this._case = case_sensitive || false;
this._regexes = {};
this._parser = parser;
this._mode = new WYMeditor.StateStack(start);
this._mode_handlers = {};
this._mode_handlers[start] = start;
return this;
};
/**
* Adds a token search pattern for a particular
* parsing mode. The pattern does not change the
* current mode.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @access public
*/
WYMeditor.Lexer.prototype.addPattern = function(pattern, mode)
{
var mode = mode || "accept";
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern);
if (typeof this._mode_handlers[mode] == 'undefined') {
this._mode_handlers[mode] = mode;
}
};
/**
* Adds a pattern that will enter a new parsing
* mode. Useful for entering parenthesis, strings,
* tags, etc.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @param string new_mode Change parsing to this new
* nested mode.
* @access public
*/
WYMeditor.Lexer.prototype.addEntryPattern = function(pattern, mode, new_mode)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, new_mode);
if (typeof this._mode_handlers[new_mode] == 'undefined') {
this._mode_handlers[new_mode] = new_mode;
}
};
/**
* Adds a pattern that will exit the current mode
* and re-enter the previous one.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Mode to leave.
* @access public
*/
WYMeditor.Lexer.prototype.addExitPattern = function(pattern, mode)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, "__exit");
if (typeof this._mode_handlers[mode] == 'undefined') {
this._mode_handlers[mode] = mode;
}
};
/**
* Adds a pattern that has a special mode. Acts as an entry
* and exit pattern in one go, effectively calling a special
* parser handler for this token only.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @param string special Use this mode for this one token.
* @access public
*/
WYMeditor.Lexer.prototype.addSpecialPattern = function(pattern, mode, special)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, '_'+special);
if (typeof this._mode_handlers[special] == 'undefined') {
this._mode_handlers[special] = special;
}
};
/**
* Adds a mapping from a mode to another handler.
* @param string mode Mode to be remapped.
* @param string handler New target handler.
* @access public
*/
WYMeditor.Lexer.prototype.mapHandler = function(mode, handler)
{
this._mode_handlers[mode] = handler;
};
/**
* Splits the page text into tokens. Will fail
* if the handlers report an error or if no
* content is consumed. If successful then each
* unparsed and parsed token invokes a call to the
* held listener.
* @param string raw Raw HTML text.
* @return boolean True on success, else false.
* @access public
*/
WYMeditor.Lexer.prototype.parse = function(raw)
{
if (typeof this._parser == 'undefined') {
return false;
}
var length = raw.length;
var parsed;
while (typeof (parsed = this._reduce(raw)) == 'object') {
var raw = parsed[0];
var unmatched = parsed[1];
var matched = parsed[2];
var mode = parsed[3];
if (! this._dispatchTokens(unmatched, matched, mode)) {
return false;
}
if (raw == '') {
return true;
}
if (raw.length == length) {
return false;
}
length = raw.length;
}
if (! parsed ) {
return false;
}
return this._invokeParser(raw, WYMeditor.LEXER_UNMATCHED);
};
/**
* Sends the matched token and any leading unmatched
* text to the parser changing the lexer to a new
* mode if one is listed.
* @param string unmatched Unmatched leading portion.
* @param string matched Actual token match.
* @param string mode Mode after match. A boolean
* false mode causes no change.
* @return boolean False if there was any error
* from the parser.
* @access private
*/
WYMeditor.Lexer.prototype._dispatchTokens = function(unmatched, matched, mode)
{
mode = mode || false;
if (! this._invokeParser(unmatched, WYMeditor.LEXER_UNMATCHED)) {
return false;
}
if (typeof mode == 'boolean') {
return this._invokeParser(matched, WYMeditor.LEXER_MATCHED);
}
if (this._isModeEnd(mode)) {
if (! this._invokeParser(matched, WYMeditor.LEXER_EXIT)) {
return false;
}
return this._mode.leave();
}
if (this._isSpecialMode(mode)) {
this._mode.enter(this._decodeSpecial(mode));
if (! this._invokeParser(matched, WYMeditor.LEXER_SPECIAL)) {
return false;
}
return this._mode.leave();
}
this._mode.enter(mode);
return this._invokeParser(matched, WYMeditor.LEXER_ENTER);
};
/**
* Tests to see if the new mode is actually to leave
* the current mode and pop an item from the matching
* mode stack.
* @param string mode Mode to test.
* @return boolean True if this is the exit mode.
* @access private
*/
WYMeditor.Lexer.prototype._isModeEnd = function(mode)
{
return (mode === "__exit");
};
/**
* Test to see if the mode is one where this mode
* is entered for this token only and automatically
* leaves immediately afterwoods.
* @param string mode Mode to test.
* @return boolean True if this is the exit mode.
* @access private
*/
WYMeditor.Lexer.prototype._isSpecialMode = function(mode)
{
return (mode.substring(0,1) == "_");
};
/**
* Strips the magic underscore marking single token
* modes.
* @param string mode Mode to decode.
* @return string Underlying mode name.
* @access private
*/
WYMeditor.Lexer.prototype._decodeSpecial = function(mode)
{
return mode.substring(1);
};
/**
* Calls the parser method named after the current
* mode. Empty content will be ignored. The lexer
* has a parser handler for each mode in the lexer.
* @param string content Text parsed.
* @param boolean is_match Token is recognised rather
* than unparsed data.
* @access private
*/
WYMeditor.Lexer.prototype._invokeParser = function(content, is_match)
{
if (!/ +/.test(content) && ((content === '') || (content === false))) {
return true;
}
var current = this._mode.getCurrent();
var handler = this._mode_handlers[current];
var result;
eval('result = this._parser.' + handler + '(content, is_match);');
return result;
};
/**
* Tries to match a chunk of text and if successful
* removes the recognised chunk and any leading
* unparsed data. Empty strings will not be matched.
* @param string raw The subject to parse. This is the
* content that will be eaten.
* @return array/boolean Three item list of unparsed
* content followed by the
* recognised token and finally the
* action the parser is to take.
* True if no match, false if there
* is a parsing error.
* @access private
*/
WYMeditor.Lexer.prototype._reduce = function(raw)
{
var matched = this._regexes[this._mode.getCurrent()].match(raw);
var match = matched[1];
var action = matched[0];
if (action) {
var unparsed_character_count = raw.indexOf(match);
var unparsed = raw.substr(0, unparsed_character_count);
raw = raw.substring(unparsed_character_count + match.length);
return [raw, unparsed, match, action];
}
return true;
};
/**
* This are the rules for breaking the XHTML code into events
* handled by the provided parser.
*
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlLexer = function(parser)
{
jQuery.extend(this, new WYMeditor.Lexer(parser, 'Text'));
this.mapHandler('Text', 'Text');
this.addTokens();
this.init();
return this;
};
WYMeditor.XhtmlLexer.prototype.init = function()
{
};
WYMeditor.XhtmlLexer.prototype.addTokens = function()
{
this.addCommentTokens('Text');
this.addScriptTokens('Text');
this.addCssTokens('Text');
this.addTagTokens('Text');
};
WYMeditor.XhtmlLexer.prototype.addCommentTokens = function(scope)
{
this.addEntryPattern("<!--", scope, 'Comment');
this.addExitPattern("-->", 'Comment');
};
WYMeditor.XhtmlLexer.prototype.addScriptTokens = function(scope)
{
this.addEntryPattern("<script", scope, 'Script');
this.addExitPattern("</script>", 'Script');
};
WYMeditor.XhtmlLexer.prototype.addCssTokens = function(scope)
{
this.addEntryPattern("<style", scope, 'Css');
this.addExitPattern("</style>", 'Css');
};
WYMeditor.XhtmlLexer.prototype.addTagTokens = function(scope)
{
this.addSpecialPattern("<\\s*[a-z0-9:\-]+\\s*>", scope, 'OpeningTag');
this.addEntryPattern("<[a-z0-9:\-]+"+'[\\\/ \\\>]+', scope, 'OpeningTag');
this.addInTagDeclarationTokens('OpeningTag');
this.addSpecialPattern("</\\s*[a-z0-9:\-]+\\s*>", scope, 'ClosingTag');
};
WYMeditor.XhtmlLexer.prototype.addInTagDeclarationTokens = function(scope)
{
this.addSpecialPattern('\\s+', scope, 'Ignore');
this.addAttributeTokens(scope);
this.addExitPattern('/>', scope);
this.addExitPattern('>', scope);
};
WYMeditor.XhtmlLexer.prototype.addAttributeTokens = function(scope)
{
this.addSpecialPattern("\\s*[a-z-_0-9]*:?[a-z-_0-9]+\\s*(?=\=)\\s*", scope, 'TagAttributes');
this.addEntryPattern('=\\s*"', scope, 'DoubleQuotedAttribute');
this.addPattern("\\\\\"", 'DoubleQuotedAttribute');
this.addExitPattern('"', 'DoubleQuotedAttribute');
this.addEntryPattern("=\\s*'", scope, 'SingleQuotedAttribute');
this.addPattern("\\\\'", 'SingleQuotedAttribute');
this.addExitPattern("'", 'SingleQuotedAttribute');
this.addSpecialPattern('=\\s*[^>\\s]*', scope, 'UnquotedAttribute');
};
/**
* XHTML Parser.
*
* This XHTML parser will trigger the events available on on
* current SaxListener
*
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlParser = function(Listener, mode)
{
var mode = mode || 'Text';
this._Lexer = new WYMeditor.XhtmlLexer(this);
this._Listener = Listener;
this._mode = mode;
this._matches = [];
this._last_match = '';
this._current_match = '';
return this;
};
WYMeditor.XhtmlParser.prototype.parse = function(raw)
{
this._Lexer.parse(this.beforeParsing(raw));
return this.afterParsing(this._Listener.getResult());
};
WYMeditor.XhtmlParser.prototype.beforeParsing = function(raw)
{
if(raw.match(/class="MsoNormal"/) || raw.match(/ns = "urn:schemas-microsoft-com/)){
// Usefull for cleaning up content pasted from other sources (MSWord)
this._Listener.avoidStylingTagsAndAttributes();
}
return this._Listener.beforeParsing(raw);
};
WYMeditor.XhtmlParser.prototype.afterParsing = function(parsed)
{
if(this._Listener._avoiding_tags_implicitly){
this._Listener.allowStylingTagsAndAttributes();
}
return this._Listener.afterParsing(parsed);
};
WYMeditor.XhtmlParser.prototype.Ignore = function(match, state)
{
return true;
};
WYMeditor.XhtmlParser.prototype.Text = function(text)
{
this._Listener.addContent(text);
return true;
};
WYMeditor.XhtmlParser.prototype.Comment = function(match, status)
{
return this._addNonTagBlock(match, status, 'addComment');
};
WYMeditor.XhtmlParser.prototype.Script = function(match, status)
{
return this._addNonTagBlock(match, status, 'addScript');
};
WYMeditor.XhtmlParser.prototype.Css = function(match, status)
{
return this._addNonTagBlock(match, status, 'addCss');
};
WYMeditor.XhtmlParser.prototype._addNonTagBlock = function(match, state, type)
{
switch (state){
case WYMeditor.LEXER_ENTER:
this._non_tag = match;
break;
case WYMeditor.LEXER_UNMATCHED:
this._non_tag += match;
break;
case WYMeditor.LEXER_EXIT:
switch(type) {
case 'addComment':
this._Listener.addComment(this._non_tag+match);
break;
case 'addScript':
this._Listener.addScript(this._non_tag+match);
break;
case 'addCss':
this._Listener.addCss(this._non_tag+match);
break;
}
}
return true;
};
WYMeditor.XhtmlParser.prototype.OpeningTag = function(match, state)
{
switch (state){
case WYMeditor.LEXER_ENTER:
this._tag = this.normalizeTag(match);
this._tag_attributes = {};
break;
case WYMeditor.LEXER_SPECIAL:
this._callOpenTagListener(this.normalizeTag(match));
break;
case WYMeditor.LEXER_EXIT:
this._callOpenTagListener(this._tag, this._tag_attributes);
}
return true;
};
WYMeditor.XhtmlParser.prototype.ClosingTag = function(match, state)
{
this._callCloseTagListener(this.normalizeTag(match));
return true;
};
WYMeditor.XhtmlParser.prototype._callOpenTagListener = function(tag, attributes)
{
var attributes = attributes || {};
this.autoCloseUnclosedBeforeNewOpening(tag);
if(this._Listener.isBlockTag(tag)){
this._Listener._tag_stack.push(tag);
this._Listener.fixNestingBeforeOpeningBlockTag(tag, attributes);
this._Listener.openBlockTag(tag, attributes);
this._increaseOpenTagCounter(tag);
}else if(this._Listener.isInlineTag(tag)){
this._Listener.inlineTag(tag, attributes);
}else{
this._Listener.openUnknownTag(tag, attributes);
this._increaseOpenTagCounter(tag);
}
this._Listener.last_tag = tag;
this._Listener.last_tag_opened = true;
this._Listener.last_tag_attributes = attributes;
};
WYMeditor.XhtmlParser.prototype._callCloseTagListener = function(tag)
{
if(this._decreaseOpenTagCounter(tag)){
this.autoCloseUnclosedBeforeTagClosing(tag);
if(this._Listener.isBlockTag(tag)){
var expected_tag = this._Listener._tag_stack.pop();
if(expected_tag == false){
return;
}else if(expected_tag != tag){
tag = expected_tag;
}
this._Listener.closeBlockTag(tag);
}else{
this._Listener.closeUnknownTag(tag);
}
}else{
this._Listener.closeUnopenedTag(tag);
}
this._Listener.last_tag = tag;
this._Listener.last_tag_opened = false;
};
WYMeditor.XhtmlParser.prototype._increaseOpenTagCounter = function(tag)
{
this._Listener._open_tags[tag] = this._Listener._open_tags[tag] || 0;
this._Listener._open_tags[tag]++;
};
WYMeditor.XhtmlParser.prototype._decreaseOpenTagCounter = function(tag)
{
if(this._Listener._open_tags[tag]){
this._Listener._open_tags[tag]--;
if(this._Listener._open_tags[tag] == 0){
this._Listener._open_tags[tag] = undefined;
}
return true;
}
return false;
};
WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeNewOpening = function(new_tag)
{
this._autoCloseUnclosed(new_tag, false);
};
WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeTagClosing = function(tag)
{
this._autoCloseUnclosed(tag, true);
};
WYMeditor.XhtmlParser.prototype._autoCloseUnclosed = function(new_tag, closing)
{
var closing = closing || false;
if(this._Listener._open_tags){
for (var tag in this._Listener._open_tags) {
var counter = this._Listener._open_tags[tag];
if(counter > 0 && this._Listener.shouldCloseTagAutomatically(tag, new_tag, closing)){
this._callCloseTagListener(tag, true);
}
}
}
};
WYMeditor.XhtmlParser.prototype.getTagReplacements = function()
{
return this._Listener.getTagReplacements();
};
WYMeditor.XhtmlParser.prototype.normalizeTag = function(tag)
{
tag = tag.replace(/^([\s<\/>]*)|([\s<\/>]*)$/gm,'').toLowerCase();
var tags = this._Listener.getTagReplacements();
if(tags[tag]){
return tags[tag];
}
return tag;
};
WYMeditor.XhtmlParser.prototype.TagAttributes = function(match, state)
{
if(WYMeditor.LEXER_SPECIAL == state){
this._current_attribute = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.DoubleQuotedAttribute = function(match, state)
{
if(WYMeditor.LEXER_UNMATCHED == state){
this._tag_attributes[this._current_attribute] = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.SingleQuotedAttribute = function(match, state)
{
if(WYMeditor.LEXER_UNMATCHED == state){
this._tag_attributes[this._current_attribute] = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.UnquotedAttribute = function(match, state)
{
this._tag_attributes[this._current_attribute] = match.replace(/^=/,'');
return true;
};
/**
* XHTML Sax parser.
*
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlSaxListener = function()
{
this.output = '';
this.helper = new WYMeditor.XmlHelper();
this._open_tags = {};
this.validator = WYMeditor.XhtmlValidator;
this._tag_stack = [];
this.avoided_tags = [];
this.entities = {
' ':' ','¡':'¡','¢':'¢',
'£':'£','¤':'¤','¥':'¥',
'¦':'¦','§':'§','¨':'¨',
'©':'©','ª':'ª','«':'«',
'¬':'¬','­':'­','®':'®',
'¯':'¯','°':'°','±':'±',
'²':'²','³':'³','´':'´',
'µ':'µ','¶':'¶','·':'·',
'¸':'¸','¹':'¹','º':'º',
'»':'»','¼':'¼','½':'½',
'¾':'¾','¿':'¿','À':'À',
'Á':'Á','Â':'Â','Ã':'Ã',
'Ä':'Ä','Å':'Å','Æ':'Æ',
'Ç':'Ç','È':'È','É':'É',
'Ê':'Ê','Ë':'Ë','Ì':'Ì',
'Í':'Í','Î':'Î','Ï':'Ï',
'Ð':'Ð','Ñ':'Ñ','Ò':'Ò',
'Ó':'Ó','Ô':'Ô','Õ':'Õ',
'Ö':'Ö','×':'×','Ø':'Ø',
'Ù':'Ù','Ú':'Ú','Û':'Û',
'Ü':'Ü','Ý':'Ý','Þ':'Þ',
'ß':'ß','à':'à','á':'á',
'â':'â','ã':'ã','ä':'ä',
'å':'å','æ':'æ','ç':'ç',
'è':'è','é':'é','ê':'ê',
'ë':'ë','ì':'ì','í':'í',
'î':'î','ï':'ï','ð':'ð',
'ñ':'ñ','ò':'ò','ó':'ó',
'ô':'ô','õ':'õ','ö':'ö',
'÷':'÷','ø':'ø','ù':'ù',
'ú':'ú','û':'û','ü':'ü',
'ý':'ý','þ':'þ','ÿ':'ÿ',
'Œ':'Œ','œ':'œ','Š':'Š',
'š':'š','Ÿ':'Ÿ','ƒ':'ƒ',
'ˆ':'ˆ','˜':'˜','Α':'Α',
'Β':'Β','Γ':'Γ','Δ':'Δ',
'Ε':'Ε','Ζ':'Ζ','Η':'Η',
'Θ':'Θ','Ι':'Ι','Κ':'Κ',
'Λ':'Λ','Μ':'Μ','Ν':'Ν',
'Ξ':'Ξ','Ο':'Ο','Π':'Π',
'Ρ':'Ρ','Σ':'Σ','Τ':'Τ',
'Υ':'Υ','Φ':'Φ','Χ':'Χ',
'Ψ':'Ψ','Ω':'Ω','α':'α',
'β':'β','γ':'γ','δ':'δ',
'ε':'ε','ζ':'ζ','η':'η',
'θ':'θ','ι':'ι','κ':'κ',
'λ':'λ','μ':'μ','ν':'ν',
'ξ':'ξ','ο':'ο','π':'π',
'ρ':'ρ','ς':'ς','σ':'σ',
'τ':'τ','υ':'υ','φ':'φ',
'χ':'χ','ψ':'ψ','ω':'ω',
'ϑ':'ϑ','ϒ':'ϒ','ϖ':'ϖ',
' ':' ',' ':' ',' ':' ',
'‌':'‌','‍':'‍','‎':'‎',
'‏':'‏','–':'–','—':'—',
'‘':'‘','’':'’','‚':'‚',
'“':'“','”':'”','„':'„',
'†':'†','‡':'‡','•':'•',
'…':'…','‰':'‰','′':'′',
'″':'″','‹':'‹','›':'›',
'‾':'‾','⁄':'⁄','€':'€',
'ℑ':'ℑ','℘':'℘','ℜ':'ℜ',
'™':'™','ℵ':'ℵ','←':'←',
'↑':'↑','→':'→','↓':'↓',
'↔':'↔','↵':'↵','⇐':'⇐',
'⇑':'⇑','⇒':'⇒','⇓':'⇓',
'⇔':'⇔','∀':'∀','∂':'∂',
'∃':'∃','∅':'∅','∇':'∇',
'∈':'∈','∉':'∉','∋':'∋',
'∏':'∏','∑':'∑','−':'−',
'∗':'∗','√':'√','∝':'∝',
'∞':'∞','∠':'∠','∧':'∧',
'∨':'∨','∩':'∩','∪':'∪',
'∫':'∫','∴':'∴','∼':'∼',
'≅':'≅','≈':'≈','≠':'≠',
'≡':'≡','≤':'≤','≥':'≥',
'⊂':'⊂','⊃':'⊃','⊄':'⊄',
'⊆':'⊆','⊇':'⊇','⊕':'⊕',
'⊗':'⊗','⊥':'⊥','⋅':'⋅',
'⌈':'⌈','⌉':'⌉','⌊':'⌊',
'⌋':'⌋','⟨':'〈','⟩':'〉',
'◊':'◊','♠':'♠','♣':'♣',
'♥':'♥','♦':'♦'};
this.block_tags = ["a", "abbr", "acronym", "address", "area", "b",
"base", "bdo", "big", "blockquote", "body", "button",
"caption", "cite", "code", "col", "colgroup", "dd", "del", "div",
"dfn", "dl", "dt", "em", "fieldset", "form", "head", "h1", "h2",
"h3", "h4", "h5", "h6", "html", "i", "iframe", "ins",
"kbd", "label", "legend", "li", "map", "noscript",
"object", "ol", "optgroup", "option", "p", "pre", "q",
"samp", "script", "select", "small", "span", "strong", "style",
"sub", "sup", "table", "tbody", "td", "textarea", "tfoot", "th",
"thead", "title", "tr", "tt", "ul", "var", "extends"];
this.inline_tags = ["br", "embed", "hr", "img", "input", "param"];
return this;
};
WYMeditor.XhtmlSaxListener.prototype.shouldCloseTagAutomatically = function(tag, now_on_tag, closing)
{
var closing = closing || false;
if(tag == 'td'){
if((closing && now_on_tag == 'tr') || (!closing && now_on_tag == 'td')){
return true;
}
}
if(tag == 'option'){
if((closing && now_on_tag == 'select') || (!closing && now_on_tag == 'option')){
return true;
}
}
return false;
};
WYMeditor.XhtmlSaxListener.prototype.beforeParsing = function(raw)
{
this.output = '';
return raw;
};
WYMeditor.XhtmlSaxListener.prototype.afterParsing = function(xhtml)
{
xhtml = this.replaceNamedEntities(xhtml);
xhtml = this.joinRepeatedEntities(xhtml);
xhtml = this.removeEmptyTags(xhtml);
return xhtml;
};
WYMeditor.XhtmlSaxListener.prototype.replaceNamedEntities = function(xhtml)
{
for (var entity in this.entities) {
xhtml = xhtml.replace(entity, this.entities[entity]);
}
return xhtml;
};
WYMeditor.XhtmlSaxListener.prototype.joinRepeatedEntities = function(xhtml)
{
var tags = 'em|strong|sub|sup|acronym|pre|del|address';
return xhtml.replace(new RegExp('<\/('+tags+')><\\1>' ,''),'').
replace(new RegExp('(\s*<('+tags+')>\s*){2}(.*)(\s*<\/\\2>\s*){2}' ,''),'<\$2>\$3<\$2>');
};
WYMeditor.XhtmlSaxListener.prototype.removeEmptyTags = function(xhtml)
{
return xhtml.replace(new RegExp('<('+this.block_tags.join("|").replace(/\|td/,'')+')>(<br \/>| | |\\s)*<\/\\1>' ,'g'),'');
};
WYMeditor.XhtmlSaxListener.prototype.getResult = function()
{
return this.output;
};
WYMeditor.XhtmlSaxListener.prototype.getTagReplacements = function()
{
return {'b':'strong', 'i':'em'};
};
WYMeditor.XhtmlSaxListener.prototype.addContent = function(text)
{
this.output += text;
};
WYMeditor.XhtmlSaxListener.prototype.addComment = function(text)
{
if(this.remove_comments){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.addScript = function(text)
{
if(!this.remove_scripts){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.addCss = function(text)
{
if(!this.remove_embeded_styles){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.openBlockTag = function(tag, attributes)
{
this.output += this.helper.tag(tag, this.validator.getValidTagAttributes(tag, attributes), true);
};
WYMeditor.XhtmlSaxListener.prototype.inlineTag = function(tag, attributes)
{
this.output += this.helper.tag(tag, this.validator.getValidTagAttributes(tag, attributes));
};
WYMeditor.XhtmlSaxListener.prototype.openUnknownTag = function(tag, attributes)
{
//this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.XhtmlSaxListener.prototype.closeBlockTag = function(tag)
{
this.output = this.output.replace(/<br \/>$/, '')+this._getClosingTagContent('before', tag)+"</"+tag+">"+this._getClosingTagContent('after', tag);
};
WYMeditor.XhtmlSaxListener.prototype.closeUnknownTag = function(tag)
{
//this.output += "</"+tag+">";
};
WYMeditor.XhtmlSaxListener.prototype.closeUnopenedTag = function(tag)
{
this.output += "</"+tag+">";
};
WYMeditor.XhtmlSaxListener.prototype.avoidStylingTagsAndAttributes = function()
{
this.avoided_tags = ['div','span'];
this.validator.skiped_attributes = ['style'];
this.validator.skiped_attribute_values = ['MsoNormal','main1']; // MS Word attributes for class
this._avoiding_tags_implicitly = true;
};
WYMeditor.XhtmlSaxListener.prototype.allowStylingTagsAndAttributes = function()
{
this.avoided_tags = [];
this.validator.skiped_attributes = [];
this.validator.skiped_attribute_values = [];
this._avoiding_tags_implicitly = false;
};
WYMeditor.XhtmlSaxListener.prototype.isBlockTag = function(tag)
{
return !WYMeditor.Helper.contains(this.avoided_tags, tag) && WYMeditor.Helper.contains(this.block_tags, tag);
};
WYMeditor.XhtmlSaxListener.prototype.isInlineTag = function(tag)
{
return !WYMeditor.Helper.contains(this.avoided_tags, tag) && WYMeditor.Helper.contains(this.inline_tags, tag);
};
WYMeditor.XhtmlSaxListener.prototype.insertContentAfterClosingTag = function(tag, content)
{
this._insertContentWhenClosingTag('after', tag, content);
};
WYMeditor.XhtmlSaxListener.prototype.insertContentBeforeClosingTag = function(tag, content)
{
this._insertContentWhenClosingTag('before', tag, content);
};
WYMeditor.XhtmlSaxListener.prototype.fixNestingBeforeOpeningBlockTag = function(tag, attributes)
{
if(tag != 'li' && (tag == 'ul' || tag == 'ol') && this.last_tag && !this.last_tag_opened && this.last_tag == 'li'){
this.output = this.output.replace(/<\/li>$/, '');
this.insertContentAfterClosingTag(tag, '</li>');
}
};
WYMeditor.XhtmlSaxListener.prototype._insertContentWhenClosingTag = function(position, tag, content)
{
if(!this['_insert_'+position+'_closing']){
this['_insert_'+position+'_closing'] = [];
}
if(!this['_insert_'+position+'_closing'][tag]){
this['_insert_'+position+'_closing'][tag] = [];
}
this['_insert_'+position+'_closing'][tag].push(content);
};
WYMeditor.XhtmlSaxListener.prototype._getClosingTagContent = function(position, tag)
{
if( this['_insert_'+position+'_closing'] &&
this['_insert_'+position+'_closing'][tag] &&
this['_insert_'+position+'_closing'][tag].length > 0){
return this['_insert_'+position+'_closing'][tag].pop();
}
return '';
};
/********** CSS PARSER **********/
WYMeditor.WymCssLexer = function(parser, only_wym_blocks)
{
var only_wym_blocks = (typeof only_wym_blocks == 'undefined' ? true : only_wym_blocks);
jQuery.extend(this, new WYMeditor.Lexer(parser, (only_wym_blocks?'Ignore':'WymCss')));
this.mapHandler('WymCss', 'Ignore');
if(only_wym_blocks == true){
this.addEntryPattern("/\\\x2a[<\\s]*WYMeditor[>\\s]*\\\x2a/", 'Ignore', 'WymCss');
this.addExitPattern("/\\\x2a[<\/\\s]*WYMeditor[>\\s]*\\\x2a/", 'WymCss');
}
this.addSpecialPattern("\\\x2e[a-z-_0-9]+[\\sa-z1-6]*", 'WymCss', 'WymCssStyleDeclaration');
this.addEntryPattern("/\\\x2a", 'WymCss', 'WymCssComment');
this.addExitPattern("\\\x2a/", 'WymCssComment');
this.addEntryPattern("\x7b", 'WymCss', 'WymCssStyle');
this.addExitPattern("\x7d", 'WymCssStyle');
this.addEntryPattern("/\\\x2a", 'WymCssStyle', 'WymCssFeddbackStyle');
this.addExitPattern("\\\x2a/", 'WymCssFeddbackStyle');
return this;
};
WYMeditor.WymCssParser = function()
{
this._in_style = false;
this._has_title = false;
this.only_wym_blocks = true;
this.css_settings = {'classesItems':[], 'editorStyles':[], 'dialogStyles':[]};
return this;
};
WYMeditor.WymCssParser.prototype.parse = function(raw, only_wym_blocks)
{
var only_wym_blocks = (typeof only_wym_blocks == 'undefined' ? this.only_wym_blocks : only_wym_blocks);
this._Lexer = new WYMeditor.WymCssLexer(this, only_wym_blocks);
this._Lexer.parse(raw);
};
WYMeditor.WymCssParser.prototype.Ignore = function(match, state)
{
return true;
};
WYMeditor.WymCssParser.prototype.WymCssComment = function(text, status)
{
if(text.match(/end[a-z0-9\s]*wym[a-z0-9\s]*/mi)){
return false;
}
if(status == WYMeditor.LEXER_UNMATCHED){
if(!this._in_style){
this._has_title = true;
this._current_item = {'title':WYMeditor.Helper.trim(text)};
}else{
if(this._current_item[this._current_element]){
if(!this._current_item[this._current_element].expressions){
this._current_item[this._current_element].expressions = [text];
}else{
this._current_item[this._current_element].expressions.push(text);
}
}
}
this._in_style = true;
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssStyle = function(match, status)
{
if(status == WYMeditor.LEXER_UNMATCHED){
match = WYMeditor.Helper.trim(match);
if(match != ''){
this._current_item[this._current_element].style = match;
}
}else if (status == WYMeditor.LEXER_EXIT){
this._in_style = false;
this._has_title = false;
this.addStyleSetting(this._current_item);
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssFeddbackStyle = function(match, status)
{
if(status == WYMeditor.LEXER_UNMATCHED){
this._current_item[this._current_element].feedback_style = match.replace(/^([\s\/\*]*)|([\s\/\*]*)$/gm,'');
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssStyleDeclaration = function(match)
{
match = match.replace(/^([\s\.]*)|([\s\.*]*)$/gm, '');
var tag = '';
if(match.indexOf(' ') > 0){
var parts = match.split(' ');
this._current_element = parts[0];
var tag = parts[1];
}else{
this._current_element = match;
}
if(!this._has_title){
this._current_item = {'title':(!tag?'':tag.toUpperCase()+': ')+this._current_element};
this._has_title = true;
}
if(!this._current_item[this._current_element]){
this._current_item[this._current_element] = {'name':this._current_element};
}
if(tag){
if(!this._current_item[this._current_element].tags){
this._current_item[this._current_element].tags = [tag];
}else{
this._current_item[this._current_element].tags.push(tag);
}
}
return true;
};
WYMeditor.WymCssParser.prototype.addStyleSetting = function(style_details)
{
for (var name in style_details){
var details = style_details[name];
if(typeof details == 'object' && name != 'title'){
this.css_settings.classesItems.push({
'name': WYMeditor.Helper.trim(details.name),
'title': style_details.title,
'expr' : WYMeditor.Helper.trim((details.expressions||details.tags).join(', '))
});
if(details.feedback_style){
this.css_settings.editorStyles.push({
'name': '.'+ WYMeditor.Helper.trim(details.name),
'css': details.feedback_style
});
}
if(details.style){
this.css_settings.dialogStyles.push({
'name': '.'+ WYMeditor.Helper.trim(details.name),
'css': details.style
});
}
}
}
};
/********** HELPERS **********/
// Returns true if it is a text node with whitespaces only
jQuery.fn.isPhantomNode = function() {
if (this[0].nodeType == 3)
return !(/[^\t\n\r ]/.test(this[0].data));
return false;
};
WYMeditor.isPhantomNode = function(n) {
if (n.nodeType == 3)
return !(/[^\t\n\r ]/.test(n.data));
return false;
};
WYMeditor.isPhantomString = function(str) {
return !(/[^\t\n\r ]/.test(str));
};
// Returns the Parents or the node itself
// jqexpr = a jQuery expression
jQuery.fn.parentsOrSelf = function(jqexpr) {
var n = this;
if (n[0].nodeType == 3)
n = n.parents().slice(0,1);
// if (n.is(jqexpr)) // XXX should work, but doesn't (probably a jQuery bug)
if (n.filter(jqexpr).size() == 1)
return n;
else
return n.parents(jqexpr).slice(0,1);
};
// String & array helpers
WYMeditor.Helper = {
//replace all instances of 'old' by 'rep' in 'str' string
replaceAll: function(str, old, rep) {
var rExp = new RegExp(old, "g");
return(str.replace(rExp, rep));
},
//insert 'inserted' at position 'pos' in 'str' string
insertAt: function(str, inserted, pos) {
return(str.substr(0,pos) + inserted + str.substring(pos));
},
//trim 'str' string
trim: function(str) {
return str.replace(/^(\s*)|(\s*)$/gm,'');
},
//return true if 'arr' array contains 'elem', or false
contains: function(arr, elem) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === elem) return true;
}
return false;
},
//return 'item' position in 'arr' array, or -1
indexOf: function(arr, item) {
var ret=-1;
for(var i = 0; i < arr.length; i++) {
if (arr[i] == item) {
ret = i;
break;
}
}
return(ret);
},
//return 'item' object in 'arr' array, checking its 'name' property, or null
findByName: function(arr, name) {
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(item.name == name) return(item);
}
return(null);
}
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.explorer.js
* MSIE specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
* Jonatan Lundin (jonatan.lundin _at_ gmail.com)
*/
WYMeditor.WymClassExplorer = function(wym) {
this._wym = wym;
this._class = "className";
this._newLine = "\r\n";
};
WYMeditor.WymClassExplorer.prototype.initIframe = function(iframe) {
//This function is executed twice, though it is called once!
//But MSIE needs that, otherwise designMode won't work.
//Weird.
this._iframe = iframe;
this._doc = iframe.contentWindow.document;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init html value
jQuery(this._doc.body).html(this._wym._html);
//handle events
var wym = this;
this._doc.body.onfocus = function()
{wym._doc.designMode = "on"; wym._doc = iframe.contentWindow.document;};
this._doc.onbeforedeactivate = function() {wym.saveCaret();};
this._doc.onkeyup = function() {
wym.saveCaret();
wym.keyup();
};
this._doc.onclick = function() {wym.saveCaret();};
this._doc.body.onbeforepaste = function() {
wym._iframe.contentWindow.event.returnValue = false;
};
this._doc.body.onpaste = function() {
wym._iframe.contentWindow.event.returnValue = false;
wym.paste(window.clipboardData.getData("Text"));
};
//callback can't be executed twice, so we check
if(this._initialized) {
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
}
this._initialized = true;
//init designMode
this._doc.designMode="on";
try{
// (bermi's note) noticed when running unit tests on IE6
// Is this really needed, it trigger an unexisting property on IE6
this._doc = iframe.contentWindow.document;
}catch(e){}
};
WYMeditor.WymClassExplorer.prototype._exec = function(cmd,param) {
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var container = this.findUp(this.container(), WYMeditor.LI);
if(container)
this._doc.execCommand(cmd);
break;
default:
if(param) this._doc.execCommand(cmd,false,param);
else this._doc.execCommand(cmd);
break;
}
this.listen();
};
WYMeditor.WymClassExplorer.prototype.selected = function() {
var caretPos = this._iframe.contentWindow.document.caretPos;
if(caretPos!=null) {
if(caretPos.parentElement!=undefined)
return(caretPos.parentElement());
}
};
WYMeditor.WymClassExplorer.prototype.saveCaret = function() {
this._doc.caretPos = this._doc.selection.createRange();
};
WYMeditor.WymClassExplorer.prototype.addCssRule = function(styles, oCss) {
styles.addRule(oCss.name, oCss.css);
};
WYMeditor.WymClassExplorer.prototype.insert = function(html) {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Overwrite selection with provided html
range.pasteHTML(html);
} catch (e) { }
} else {
// Fall back to the internal paste function if there's no selection
this.paste(html);
}
};
WYMeditor.WymClassExplorer.prototype.wrap = function(left, right) {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Overwrite selection with provided html
range.pasteHTML(left + range.text + right);
} catch (e) { }
}
};
WYMeditor.WymClassExplorer.prototype.unwrap = function() {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Unwrap selection
var text = range.text;
this._exec( 'Cut' );
range.pasteHTML( text );
} catch (e) { }
}
};
//keyup handler
WYMeditor.WymClassExplorer.prototype.keyup = function() {
this._selected_image = null;
};
WYMeditor.WymClassExplorer.prototype.setFocusToNode = function(node) {
try{
var range = this._doc.selection.createRange();
range.moveToElementText(node);
range.collapse(false);
range.move('character',-1);
range.select();
node.focus();
}
catch($e){this._iframe.contentWindow.focus()}
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.mozilla.js
* Gecko specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Volker Mische (vmx a-t gmx dotde)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
*/
WYMeditor.WymClassMozilla = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\n";
};
WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentDocument;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init html value
this.html(this._wym._html);
//init designMode
this.enableDesignMode();
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor keyup events
jQuery(this._doc).bind("keyup", this.keyup);
//bind editor focus events (used to reset designmode - Gecko bug)
jQuery(this._doc).bind("focus", this.enableDesignMode);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
/* @name html
* @description Get/Set the html value
*/
WYMeditor.WymClassMozilla.prototype.html = function(html) {
if(typeof html === 'string') {
//disable designMode
try { this._doc.designMode = "off"; } catch(e) { };
//replace em by i and strong by bold
//(designMode issue)
html = html.replace(/<em(\b[^>]*)>/gi, "<i$1>")
.replace(/<\/em>/gi, "</i>")
.replace(/<strong(\b[^>]*)>/gi, "<b$1>")
.replace(/<\/strong>/gi, "</b>");
//update the html body
jQuery(this._doc.body).html(html);
//re-init designMode
this.enableDesignMode();
}
else return(jQuery(this._doc.body).html());
};
WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {
if(!this.selected()) return(false);
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var focusNode = this.selected();
var sel = this._iframe.contentWindow.getSelection();
var anchorNode = sel.anchorNode;
if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
if(focusNode && focusNode == anchorNode && focusNode.tagName.toLowerCase() == WYMeditor.LI) {
var ancestor = focusNode.parentNode.parentNode;
if(focusNode.parentNode.childNodes.length>1
|| ancestor.tagName.toLowerCase() == WYMeditor.OL
|| ancestor.tagName.toLowerCase() == WYMeditor.UL)
this._doc.execCommand(cmd,'',null);
}
break;
default:
if(param) this._doc.execCommand(cmd,'',param);
else this._doc.execCommand(cmd,'',null);
}
//set to P if parent = BODY
var container = this.selected();
if(container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
//add event handlers on doc elements
this.listen();
};
/* @name selected
* @description Returns the selected container
*/
WYMeditor.WymClassMozilla.prototype.selected = function(upgrade_text_nodes) {
if (upgrade_text_nodes == null || upgrade_text_nodes.toString() != "true") { upgrade_text_nodes = false; }
var sel = this._iframe.contentWindow.getSelection();
var node = sel.focusNode;
if(node) {
if(node.nodeName == "#text"){
if (upgrade_text_nodes && sel.toString().length > 0) {
actual_node = null;
parent_node = sel.focusNode.parentNode;
if (parent_node != null) {
for (i=0;i<parent_node.childNodes.length;i++){
child_node = parent_node.childNodes[i];
if (child_node.nodeName != "#text" && child_node.innerHTML == sel.toString()){
actual_node = child_node;
}
}
}
if (actual_node == null) {
return this.switchTo(sel, 'span');
} else {
return actual_node;
}
}
else {
return node.parentNode;
}
}
else return(node);
}
else return(null);
};
WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}", styles.cssRules.length);
};
//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
if(evt.ctrlKey){
if(evt.keyCode == 66){
//CTRL+b => STRONG
wym._exec(WYMeditor.BOLD);
return false;
}
if(evt.keyCode == 73){
//CTRL+i => EMPHASIS
wym._exec(WYMeditor.ITALIC);
return false;
}
}
};
//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
var container = null;
if(evt.keyCode == 13 && !evt.shiftKey) {
//RETURN key
//cleanup <br><br> between paragraphs
jQuery(wym._doc.body).children(WYMeditor.BR).remove();
//fix PRE bug #73
container = wym.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
}
else if(evt.keyCode != 8
&& evt.keyCode != 17
&& evt.keyCode != 46
&& evt.keyCode != 224
&& !evt.metaKey
&& !evt.ctrlKey) {
//NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
//text nodes replaced by P
container = wym.selected();
var name = container.tagName.toLowerCase();
//fix forbidden main containers
if(
name == "strong" ||
name == "b" ||
name == "em" ||
name == "i" ||
name == "sub" ||
name == "sup" ||
name == "a"
) name = container.parentNode.tagName.toLowerCase();
if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
}
};
WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
if(this.designMode == "off") {
try {
this.designMode = "on";
this.execCommand("styleWithCSS", '', false);
} catch(e) { }
}
};
WYMeditor.WymClassMozilla.prototype.setFocusToNode = function(node) {
var range = document.createRange();
range.selectNode(node);
var selected = this._iframe.contentWindow.getSelection();
selected.addRange(range);
selected.collapse(node, node.childNodes.length);
this._iframe.contentWindow.focus();
};
WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
var attributes = this.validator.getValidTagAttributes(tag, attributes);
// Handle Mozilla styled spans
if(tag == 'span' && attributes.style){
var new_tag = this.getTagForStyle(attributes.style);
if(new_tag){
this._tag_stack.pop();
var tag = new_tag;
this._tag_stack.push(new_tag);
attributes.style = '';
}else{
return;
}
}
this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {
if(/bold/.test(style)) return 'strong';
if(/italic/.test(style)) return 'em';
if(/sub/.test(style)) return 'sub';
if(/sub/.test(style)) return 'super';
return false;
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.opera.js
* Opera specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
*/
WYMeditor.WymClassOpera = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\r\n";
};
WYMeditor.WymClassOpera.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentWindow.document;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init designMode
this._doc.designMode = "on";
//init html value
this.html(this._wym._html);
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor events
jQuery(this._doc).bind("keyup", this.keyup);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
WYMeditor.WymClassOpera.prototype._exec = function(cmd,param) {
if(param) this._doc.execCommand(cmd,false,param);
else this._doc.execCommand(cmd);
this.listen();
};
WYMeditor.WymClassOpera.prototype.selected = function() {
var sel=this._iframe.contentWindow.getSelection();
var node=sel.focusNode;
if(node) {
if(node.nodeName=="#text")return(node.parentNode);
else return(node);
} else return(null);
};
WYMeditor.WymClassOpera.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}",
styles.cssRules.length);
};
//keydown handler
WYMeditor.WymClassOpera.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
var sel = wym._iframe.contentWindow.getSelection();
startNode = sel.getRangeAt(0).startContainer;
//Get a P instead of no container
if(!jQuery(startNode).parentsOrSelf(
WYMeditor.MAIN_CONTAINERS.join(","))[0]
&& !jQuery(startNode).parentsOrSelf('li')
&& evt.keyCode != WYMeditor.KEY.ENTER
&& evt.keyCode != WYMeditor.KEY.LEFT
&& evt.keyCode != WYMeditor.KEY.UP
&& evt.keyCode != WYMeditor.KEY.RIGHT
&& evt.keyCode != WYMeditor.KEY.DOWN
&& evt.keyCode != WYMeditor.KEY.BACKSPACE
&& evt.keyCode != WYMeditor.KEY.DELETE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
};
//keyup handler
WYMeditor.WymClassOpera.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
};
// TODO: implement me
WYMeditor.WymClassOpera.prototype.setFocusToNode = function(node) {
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.safari.js
* Safari specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Scott Lewis (lewiscot a-t gmail dotcom)
*/
WYMeditor.WymClassSafari = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\n";
};
WYMeditor.WymClassSafari.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentDocument;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init designMode
this._doc.designMode = "on";
//init html value
this.html(this._wym._html);
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor keyup events
jQuery(this._doc).bind("keyup", this.keyup);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
WYMeditor.WymClassSafari.prototype._exec = function(cmd,param) {
if(!this.selected()) return(false);
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var focusNode = this.selected();
var sel = this._iframe.contentWindow.getSelection();
var anchorNode = sel.anchorNode;
if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
if(focusNode && focusNode == anchorNode
&& focusNode.tagName.toLowerCase() == WYMeditor.LI) {
var ancestor = focusNode.parentNode.parentNode;
if(focusNode.parentNode.childNodes.length>1
|| ancestor.tagName.toLowerCase() == WYMeditor.OL
|| ancestor.tagName.toLowerCase() == WYMeditor.UL)
this._doc.execCommand(cmd,'',null);
}
break;
case WYMeditor.INSERT_ORDEREDLIST: case WYMeditor.INSERT_UNORDEREDLIST:
this._doc.execCommand(cmd,'',null);
//Safari creates lists in e.g. paragraphs.
//Find the container, and remove it.
var focusNode = this.selected();
var container = this.findUp(focusNode, WYMeditor.MAIN_CONTAINERS);
if(container) jQuery(container).replaceWith(jQuery(container).html());
break;
default:
if(param) this._doc.execCommand(cmd,'',param);
else this._doc.execCommand(cmd,'',null);
}
//set to P if parent = BODY
var container = this.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
//add event handlers on doc elements
this.listen();
};
/* @name selected
* @description Returns the selected container
*/
WYMeditor.WymClassSafari.prototype.selected = function(upgrade_text_nodes) {
if (upgrade_text_nodes == null || upgrade_text_nodes.toString() != "true") { upgrade_text_nodes = false; }
var sel = this._iframe.contentWindow.getSelection();
var node = sel.focusNode;
if(node) {
if(node.nodeName == "#text"){
if (upgrade_text_nodes && sel.toString().length > 0) {
actual_node = null;
parent_node = sel.focusNode.parentNode;
if (parent_node != null) {
for (i=0;i<parent_node.childNodes.length;i++){
child_node = parent_node.childNodes[i];
if (child_node.textContent == sel.toString()){
actual_node = child_node.parentNode;
}
}
}
if (actual_node == null) {
this._selected_item = this.switchTo(sel, 'span');
return this._selected_item;
} else {
return actual_node;
}
}
else {
return node.parentNode;
}
}
else return(node);
}
else return(null);
};
/* @name toggleClass
* @description Toggles class on selected element, or one of its parents
*/
WYMeditor.WymClassSafari.prototype.toggleClass = function(sClass, jqexpr) {
var container = null;
if (this._selected_image) {
container = jQuery(this._selected_image);
}
else {
container = jQuery(this.selected(true) || this._selected_item);
}
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.toggleClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
};
WYMeditor.WymClassSafari.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}",
styles.cssRules.length);
};
//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassSafari.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
if(evt.ctrlKey){
if(evt.keyCode == 66){
//CTRL+b => STRONG
wym._exec(WYMeditor.BOLD);
return false;
}
if(evt.keyCode == 73){
//CTRL+i => EMPHASIS
wym._exec(WYMeditor.ITALIC);
return false;
}
}
};
//keyup handler, mainly used for cleanups
WYMeditor.WymClassSafari.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
var container = null;
if(evt.keyCode == 13 && !evt.shiftKey) {
//RETURN key
//cleanup <br><br> between paragraphs
jQuery(wym._doc.body).children(WYMeditor.BR).remove();
//fix PRE bug #73
container = wym.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
}
//fix #112
if(evt.keyCode == 13 && evt.shiftKey) {
wym._exec('InsertLineBreak');
}
if(evt.keyCode != 8
&& evt.keyCode != 17
&& evt.keyCode != 46
&& evt.keyCode != 224
&& !evt.metaKey
&& !evt.ctrlKey) {
//NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
//text nodes replaced by P
container = wym.selected();
var name = container.tagName.toLowerCase();
//fix forbidden main containers
if(
name == "strong" ||
name == "b" ||
name == "em" ||
name == "i" ||
name == "sub" ||
name == "sup" ||
name == "a" ||
name == "span" //fix #110
) name = container.parentNode.tagName.toLowerCase();
if(name == WYMeditor.BODY || name == WYMeditor.DIV) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //fix #110 for DIV
}
};
//TODO
WYMeditor.WymClassSafari.prototype.setFocusToNode = function(node) {
/*var range = document.createRange();
range.selectNode(node);
var selected = this._iframe.contentWindow.getSelection();
selected.addRange(range);
selected.collapse(node, node.childNodes.length);
this._iframe.contentWindow.focus();*/
};
WYMeditor.WymClassSafari.prototype.openBlockTag = function(tag, attributes)
{
var attributes = this.validator.getValidTagAttributes(tag, attributes);
// Handle Safari styled spans
if(tag == 'span' && attributes.style) {
var new_tag = this.getTagForStyle(attributes.style);
if(new_tag){
this._tag_stack.pop();
var tag = new_tag;
this._tag_stack.push(new_tag);
attributes.style = '';
//should fix #125 - also removed the xhtml() override
if(typeof attributes['class'] == 'string')
attributes['class'] = attributes['class'].replace(/apple-style-span/gi, '');
} else {
return;
}
}
this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.WymClassSafari.prototype.getTagForStyle = function(style) {
if(/bold/.test(style)) return 'strong';
if(/italic/.test(style)) return 'em';
if(/sub/.test(style)) return 'sub';
if(/super/.test(style)) return 'sup';
return false;
};
function titleize(words) {
parts = [];
words.gsub(/\./, '').gsub(/[-_]/, ' ').split(' ').each(function(part){
parts.push(part[0].toUpperCase() + part.substring(1));
});
return parts.join(" ");
} |
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
const userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
roles: {
type:[String]
},
organization: {
type:String
},
agenda:[{
type:Schema.Types.ObjectId,
ref: 'Event'
}],
profile_email: {
type:String
},
profile_description:{
type: String
},
profile_image:{
type: String
},
profile_website:{
type: String
},
profile_twitter:{
type:String
},
hidden_email: {
type: Boolean,
default: true
},
hidden_twitter: {
type: Boolean,
default: true
}
});
userSchema.methods.generateHash = function(password) {
return this.password = bcrypt.hashSync(password, 8);
};
userSchema.methods.compareHash = function(password) {
return bcrypt.compareSync(password, this.password);
};
const User = module.exports = mongoose.model ('User', userSchema);
// create new Admin user if there are no users in the collection
const newAdmin = function() {
const adminData = { username: 'Admin', firstName:'Admin', lastName: 'User', roles: ['admin']};
const user = new User(adminData);
user.generateHash('password');
user.save();
};
User.find()
.then(users => {
if (users.length === 0) {
newAdmin();
}
});
|
/**
* @file Project Constants
* @author leonlu(ludafa@outlook.com)
*/
/*eslint-env node*/
module.exports = {
ADD: 'PROJECT_ADD',
UPDATE: 'PROJECT_UPDATE',
CLOSE_FORM_DIALOG: 'PROJECT_CLOSE_DIALOG',
OPEN_EDIT_DIALOG: 'PROJECT_OPEN_EDIT_DIALOG',
OPEN_CREATE_DIALOG: 'PROJECT_OPEN_CREATE_DIALOG'
};
|
import React from 'react';
/** @jsx jsx */
import { css, jsx } from '@emotion/core';
import { fontSize } from '../utils/rocketbelt';
import meatball from '../images/meatball.svg';
const footerCss = css`
position: relative;
left: 50%;
display: flex;
padding: 2rem 1rem;
width: 100vw;
background: #e8edf3;
color: #45474a;
font-size: ${fontSize(-1)};
transform: translateX(-50%);
grid-area: footer;
justify-content: center;
align-items: center;
`;
const Footer = () => (
<footer css={[footerCss]}>
<div
className="header-footer_wrap"
css={css`
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
`}
>
<div
className="footer_logo"
css={css`
margin-bottom: 1rem;
height: 56px;
`}
>
<a
href="https://www.pier1.com/"
css={css`
height: 100%;
`}
>
<img
src={meatball}
css={css`
height: 100%;
`}
/>
</a>
</div>
<div className="footer_text">
Rocketbelt was collaboratively assembled at Pier 1 Imports and is
distributed under an MIT license. 🚀 © {new Date().getFullYear()} Pier 1
Imports.
</div>
</div>
</footer>
);
export default Footer;
|
// # Ghost Configuration
// Setup your Ghost install for various environments
// Documentation can be found at http://support.ghost.org/config/
var path = require('path'),
config;
var config;
if (process.env.OPENSHIFT_MYSQL_DB_HOST != undefined) {
config = {
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://'+process.env.OPENSHIFT_APP_DNS_ALIAS,
mail: {
transport: 'SMTP',
options: {
service: 'Mailgun',
auth: {
user: 'postmaster@sandbox2391.mailgun.org',
pass: '6d3lytuzlbc7'
}
}
},
database: {
client: 'mysql',
connection: {
host : process.env.OPENSHIFT_MYSQL_DB_HOST,
port : process.env.OPENSHIFT_MYSQL_DB_PORT,
user : process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password : process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database : process.env.OPENSHIFT_APP_NAME,
charset : 'utf8'
}
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: process.env.OPENSHIFT_NODEJS_IP,
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.OPENSHIFT_NODEJS_PORT
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
}
}
} else if (process.env.OPENSHIFT_POSTGRESQL_DB_HOST != undefined) {
config = {
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://'+process.env.OPENSHIFT_APP_DNS_ALIAS,
mail: {
transport: 'SMTP',
options: {
service: 'Mailgun',
auth: {
user: 'postmaster@sandbox2391.mailgun.org',
pass: '6d3lytuzlbc7'
}
}
},
database: {
client: 'pg',
connection: {
host : process.env.OPENSHIFT_POSTGRESQL_DB_HOST,
port : process.env.OPENSHIFT_POSTGRESQL_DB_PORT,
user : process.env.OPENSHIFT_POSTGRESQL_DB_USERNAME,
password : process.env.OPENSHIFT_POSTGRESQL_DB_PASSWORD,
database : process.env.OPENSHIFT_APP_NAME,
charset : 'utf8'
}
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: process.env.OPENSHIFT_NODEJS_IP,
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.OPENSHIFT_NODEJS_PORT
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
}
}
} else {
config = {
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
url: 'http://localhost:1337',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '0.0.0.0',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '1337'
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://'+process.env.OPENSHIFT_APP_DNS,
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: process.env.OPENSHIFT_NODEJS_IP,
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.OPENSHIFT_NODEJS_PORT
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
}
// Export config
module.exports = config;
|
$(document).ready(function(){
$('.flexslider').flexslider({
directionNav: true,
pauseOnAction: false
});
// this is for search
// $('.search-input input').click(()=>{
// $('.search-place').css('display','block');
// });
// $('.search-input input').blur(()=>{
// $('.search-place').css('display','none');
// });
Vue.component('card',{
template : '#card',
props : ['casa']
});
//scroll 是记录是否已经进行了滚动操作,
//为了防止在重新进行turn的时候再次执行scrollTo
new Vue({
el: '#app',
data: function () {
return {
casas: null,
themes: null,
series: null,
city: null,
scroll: null
};
},
ready:function(){
this.firstCasas();
},
methods: {
firstCasas (){
$(".loader").css('display','block');
$.getJSON('/api/home/recom/'+this.city, (data) => {
this.casas = data;
$(".loader").css('display','none');
this.setActive(this.city);
this.getthemes();
})
},
turn (event){
$(".loader").css('display','block');
this.city = event;
$.getJSON('/api/home/recom/'+event, (data) => {
this.casas = data;
$(".loader").css('display','none');
this.setActive(event);
this.changeBr();
})
},
getthemes(){
$.getJSON('/api/home/themes', (data) => {
this.themes = data;
this.getseries();
})
},
getseries(){
$.getJSON('/api/home/series', (data) => {
this.series = data;
this.scrollTo();
this.changeBr();
})
},
scrollTo(){
if(this.scroll){
return;
}
var thisId = window.location.hash;
if(thisId){
$("html,body").animate({scrollTop:$(thisId).offset().top});
this.scroll = 1;
}
},
setActive(event){
$('.city-list a').each(function(){
let clickdom = $(this).data("index");
$(this).removeClass('active');
if(clickdom == event){
$(this).addClass('active');
}
});
},
changeBr:function(){
//对info中的br进行处理
$('.middle p').each(function () {
let str = $(this).html();
str = str.split('<BR/>').join('\n');
str = str.split('<BR/>').join('\n');
$(this).text(str);
});
}
}
});
});
|
(function($) {
var radio_boxes = {};
function add_box_to_list(yradio) {
var list = radio_boxes[yradio.form_id] || {};
if (list[yradio.name]) {
list[yradio.name] = list[yradio.name].add(yradio.$el);
} else {
list[yradio.name] = yradio.$el;
}
radio_boxes[yradio.form_id] = list;
}
function Yradio($radio_btn) {
var self = this;
this.$original = $radio_btn;
this.form_id = $radio_btn.closest('form').attr('id');
this.name = $radio_btn.attr('name');
$radio_btn.hide();
if (!$radio_btn.prop('tabindex')) {
$radio_btn.prop('tabindex', 0);
}
this.$el = $("<span class='yradio' />")
.prop('tabindex', $radio_btn.prop('tabindex'))
.data('yradio', this);
if( $radio_btn.is(':checked') ) {
this.$el.addClass('checked');
} else {
this.$el.addClass('unchecked');
}
$radio_btn.after(this.$el);
this.$el.click(function(ev) {
self.change();
ev.preventDefault();
})
.keydown(function(ev) {
// spacebar
if (ev.keyCode == 32) {
self.change();
ev.preventDefault();
}
})
$radio_btn.change(function() {
if($radio_btn.is(':checked') && self.$el.is(':not(.checked)') ) {
self.check();
}
});
this.change = function() {
if (!this.$original.is(':checked')) {
this.check();
}
}
this.check = function() {
radio_boxes[this.form_id][this.name].filter('.checked')
.addClass('unchecked').removeClass('checked');
this.$el.addClass('checked').removeClass('unchecked')
this.$original.prop('checked', true);
this.$original.change();
}
add_box_to_list(this);
}
$.fn.yradio = function() {
return $(this).each(function() {
var $checkbox = $(this);
if( ! $checkbox.is('input[type="radio"]') ) {
return;
}
new Yradio($checkbox);
});
}
}(jQuery));
|
/*
Product Name: dhtmlxSuite
Version: 4.0.3
Edition: Professional
License: content of this file is covered by DHTMLX Commercial or Enterprise license. Usage without proper license is prohibited. To obtain it contact sales@dhtmlx.com
Copyright UAB Dinamenta http://www.dhtmlx.com
*/
/*
Copyright DHTMLX LTD. http://www.dhtmlx.com
You allowed to use this component or parts of it under GPL terms
To use it on other terms or get Professional edition of the component please contact us at sales@dhtmlx.com
*/
/*
2014 March 19
*/
/* DHX DEPEND FROM FILE 'assert.js'*/
if (!window.dhtmlx)
dhtmlx={};
//check some rule, show message as error if rule is not correct
dhtmlx.assert = function(test, message){
if (!test) dhtmlx.error(message);
};
dhtmlx.assert_enabled=function(){ return false; };
//register names of event, which can be triggered by the object
dhtmlx.assert_event = function(obj, evs){
if (!obj._event_check){
obj._event_check = {};
obj._event_check_size = {};
}
for (var a in evs){
obj._event_check[a.toLowerCase()]=evs[a];
var count=-1; for (var t in evs[a]) count++;
obj._event_check_size[a.toLowerCase()]=count;
}
};
dhtmlx.assert_method_info=function(obj, name, descr, rules){
var args = [];
for (var i=0; i < rules.length; i++) {
args.push(rules[i][0]+" : "+rules[i][1]+"\n "+rules[i][2].describe()+(rules[i][3]?"; optional":""));
}
return obj.name+"."+name+"\n"+descr+"\n Arguments:\n - "+args.join("\n - ");
};
dhtmlx.assert_method = function(obj, config){
for (var key in config)
dhtmlx.assert_method_process(obj, key, config[key].descr, config[key].args, (config[key].min||99), config[key].skip);
};
dhtmlx.assert_method_process = function (obj, name, descr, rules, min, skip){
var old = obj[name];
if (!skip)
obj[name] = function(){
if (arguments.length != rules.length && arguments.length < min)
dhtmlx.log("warn","Incorrect count of parameters\n"+obj[name].describe()+"\n\nExpecting "+rules.length+" but have only "+arguments.length);
else
for (var i=0; i<rules.length; i++)
if (!rules[i][3] && !rules[i][2](arguments[i]))
dhtmlx.log("warn","Incorrect method call\n"+obj[name].describe()+"\n\nActual value of "+(i+1)+" parameter: {"+(typeof arguments[i])+"} "+arguments[i]);
return old.apply(this, arguments);
};
obj[name].describe = function(){ return dhtmlx.assert_method_info(obj, name, descr, rules); };
};
dhtmlx.assert_event_call = function(obj, name, args){
if (obj._event_check){
if (!obj._event_check[name])
dhtmlx.log("warn","Not expected event call :"+name);
else if (dhtmlx.isNotDefined(args))
dhtmlx.log("warn","Event without parameters :"+name);
else if (obj._event_check_size[name] != args.length)
dhtmlx.log("warn","Incorrect event call, expected "+obj._event_check_size[name]+" parameter(s), but have "+args.length +" parameter(s), for "+name+" event");
}
};
dhtmlx.assert_event_attach = function(obj, name){
if (obj._event_check && !obj._event_check[name])
dhtmlx.log("warn","Unknown event name: "+name);
};
//register names of properties, which can be used in object's configuration
dhtmlx.assert_property = function(obj, evs){
if (!obj._settings_check)
obj._settings_check={};
dhtmlx.extend(obj._settings_check, evs);
};
//check all options in collection, against list of allowed properties
dhtmlx.assert_check = function(data,coll){
if (typeof data == "object"){
for (var key in data){
dhtmlx.assert_settings(key,data[key],coll);
}
}
};
//check if type and value of property is the same as in scheme
dhtmlx.assert_settings = function(mode,value,coll){
coll = coll || this._settings_check;
//if value is not in collection of defined ones
if (coll){
if (!coll[mode]) //not registered property
return dhtmlx.log("warn","Unknown propery: "+mode);
var descr = "";
var error = "";
var check = false;
for (var i=0; i<coll[mode].length; i++){
var rule = coll[mode][i];
if (typeof rule == "string")
continue;
if (typeof rule == "function")
check = check || rule(value);
else if (typeof rule == "object" && typeof rule[1] == "function"){
check = check || rule[1](value);
if (check && rule[2])
dhtmlx["assert_check"](value, rule[2]); //temporary fix , for sources generator
}
if (check) break;
}
if (!check )
dhtmlx.log("warn","Invalid configuration\n"+dhtmlx.assert_info(mode,coll)+"\nActual value: {"+(typeof value)+"} "+value);
}
};
dhtmlx.assert_info=function(name, set){
var ruleset = set[name];
var descr = "";
var expected = [];
for (var i=0; i<ruleset.length; i++){
if (typeof rule == "string")
descr = ruleset[i];
else if (ruleset[i].describe)
expected.push(ruleset[i].describe());
else if (ruleset[i][1] && ruleset[i][1].describe)
expected.push(ruleset[i][1].describe());
}
return "Property: "+name+", "+descr+" \nExpected value: \n - "+expected.join("\n - ");
};
if (dhtmlx.assert_enabled()){
dhtmlx.assert_rule_color=function(check){
if (typeof check != "string") return false;
if (check.indexOf("#")!==0) return false;
if (check.substr(1).replace(/[0-9A-F]/gi,"")!=="") return false;
return true;
};
dhtmlx.assert_rule_color.describe = function(){
return "{String} Value must start from # and contain hexadecimal code of color";
};
dhtmlx.assert_rule_template=function(check){
if (typeof check == "function") return true;
if (typeof check == "string") return true;
return false;
};
dhtmlx.assert_rule_template.describe = function(){
return "{Function},{String} Value must be a function which accepts data object and return text string, or a sting with optional template markers";
};
dhtmlx.assert_rule_boolean=function(check){
if (typeof check == "boolean") return true;
return false;
};
dhtmlx.assert_rule_boolean.describe = function(){
return "{Boolean} true or false";
};
dhtmlx.assert_rule_object=function(check, sub){
if (typeof check == "object") return true;
return false;
};
dhtmlx.assert_rule_object.describe = function(){
return "{Object} Configuration object";
};
dhtmlx.assert_rule_string=function(check){
if (typeof check == "string") return true;
return false;
};
dhtmlx.assert_rule_string.describe = function(){
return "{String} Plain string";
};
dhtmlx.assert_rule_htmlpt=function(check){
return !!dhtmlx.toNode(check);
};
dhtmlx.assert_rule_htmlpt.describe = function(){
return "{Object},{String} HTML node or ID of HTML Node";
};
dhtmlx.assert_rule_notdocumented=function(check){
return false;
};
dhtmlx.assert_rule_notdocumented.describe = function(){
return "This options wasn't documented";
};
dhtmlx.assert_rule_key=function(obj){
var t = function (check){
return obj[check];
};
t.describe=function(){
var opts = [];
for(var key in obj)
opts.push(key);
return "{String} can take one of next values: "+opts.join(", ");
};
return t;
};
dhtmlx.assert_rule_dimension=function(check){
if (check*1 == check && !isNaN(check) && check >= 0) return true;
return false;
};
dhtmlx.assert_rule_dimension.describe=function(){
return "{Integer} value must be a positive number";
};
dhtmlx.assert_rule_number=function(check){
if (typeof check == "number") return true;
return false;
};
dhtmlx.assert_rule_number.describe=function(){
return "{Integer} value must be a number";
};
dhtmlx.assert_rule_function=function(check){
if (typeof check == "function") return true;
return false;
};
dhtmlx.assert_rule_function.describe=function(){
return "{Function} value must be a custom function";
};
dhtmlx.assert_rule_any=function(check){
return true;
};
dhtmlx.assert_rule_any.describe=function(){
return "Any value";
};
dhtmlx.assert_rule_mix=function(a,b){
var t = function(check){
if (a(check)||b(check)) return true;
return false;
};
t.describe = function(){
return a.describe();
};
return t;
};
}
/* DHX DEPEND FROM FILE 'dhtmlx.js'*/
/*DHX:Depend assert.js*/
/*
Common helpers
*/
dhtmlx.version="3.0";
dhtmlx.codebase="./";
//coding helpers
dhtmlx.copy = function(source){
var f = dhtmlx.copy._function;
f.prototype = source;
return new f();
};
dhtmlx.copy._function = function(){};
//copies methods and properties from source to the target
dhtmlx.extend = function(target, source){
for (var method in source)
target[method] = source[method];
//applying asserts
if (dhtmlx.assert_enabled() && source._assert){
target._assert();
target._assert=null;
}
dhtmlx.assert(target,"Invalid nesting target");
dhtmlx.assert(source,"Invalid nesting source");
//if source object has init code - call init against target
if (source._init)
target._init();
return target;
};
dhtmlx.proto_extend = function(){
var origins = arguments;
var compilation = origins[0];
var construct = [];
for (var i=origins.length-1; i>0; i--) {
if (typeof origins[i]== "function")
origins[i]=origins[i].prototype;
for (var key in origins[i]){
if (key == "_init")
construct.push(origins[i][key]);
else if (!compilation[key])
compilation[key] = origins[i][key];
}
};
if (origins[0]._init)
construct.push(origins[0]._init);
compilation._init = function(){
for (var i=0; i<construct.length; i++)
construct[i].apply(this, arguments);
};
compilation.base = origins[1];
var result = function(config){
this._init(config);
if (this._parseSettings)
this._parseSettings(config, this.defaults);
};
result.prototype = compilation;
compilation = origins = null;
return result;
};
//creates function with specified "this" pointer
dhtmlx.bind=function(functor, object){
return function(){ return functor.apply(object,arguments); };
};
//loads module from external js file
dhtmlx.require=function(module){
if (!dhtmlx._modules[module]){
dhtmlx.assert(dhtmlx.ajax,"load module is required");
//load and exec the required module
dhtmlx.exec( dhtmlx.ajax().sync().get(dhtmlx.codebase+module).responseText );
dhtmlx._modules[module]=true;
}
};
dhtmlx._modules = {}; //hash of already loaded modules
//evaluate javascript code in the global scoope
dhtmlx.exec=function(code){
if (window.execScript) //special handling for IE
window.execScript(code);
else window.eval(code);
};
/*
creates method in the target object which will transfer call to the source object
if event parameter was provided , each call of method will generate onBefore and onAfter events
*/
dhtmlx.methodPush=function(object,method,event){
return function(){
var res = false;
//if (!event || this.callEvent("onBefore"+event,arguments)){ //not used anymore, probably can be removed
res=object[method].apply(object,arguments);
// if (event) this.callEvent("onAfter"+event,arguments);
//}
return res; //result of wrapped method
};
};
//check === undefined
dhtmlx.isNotDefined=function(a){
return typeof a == "undefined";
};
//delay call to after-render time
dhtmlx.delay=function(method, obj, params, delay){
setTimeout(function(){
var ret = method.apply(obj,params);
method = obj = params = null;
return ret;
},delay||1);
};
//common helpers
//generates unique ID (unique per window, nog GUID)
dhtmlx.uid = function(){
if (!this._seed) this._seed=(new Date).valueOf(); //init seed with timestemp
this._seed++;
return this._seed;
};
//resolve ID as html object
dhtmlx.toNode = function(node){
if (typeof node == "string") return document.getElementById(node);
return node;
};
//adds extra methods for the array
dhtmlx.toArray = function(array){
return dhtmlx.extend((array||[]),dhtmlx.PowerArray);
};
//resolve function name
dhtmlx.toFunctor=function(str){
return (typeof(str)=="string") ? eval(str) : str;
};
//dom helpers
//hash of attached events
dhtmlx._events = {};
//attach event to the DOM element
dhtmlx.event=function(node,event,handler,master){
node = dhtmlx.toNode(node);
var id = dhtmlx.uid();
dhtmlx._events[id]=[node,event,handler]; //store event info, for detaching
if (master)
handler=dhtmlx.bind(handler,master);
//use IE's of FF's way of event's attaching
if (node.addEventListener)
node.addEventListener(event, handler, false);
else if (node.attachEvent)
node.attachEvent("on"+event, handler);
return id; //return id of newly created event, can be used in eventRemove
};
//remove previously attached event
dhtmlx.eventRemove=function(id){
if (!id) return;
dhtmlx.assert(this._events[id],"Removing non-existing event");
var ev = dhtmlx._events[id];
//browser specific event removing
if (ev[0].removeEventListener)
ev[0].removeEventListener(ev[1],ev[2],false);
else if (ev[0].detachEvent)
ev[0].detachEvent("on"+ev[1],ev[2]);
delete this._events[id]; //delete all traces
};
//debugger helpers
//anything starting from error or log will be removed during code compression
//add message in the log
dhtmlx.log = function(type,message,details){
if (window.console && console.log){
type=type.toLowerCase();
if (window.console[type])
window.console[type](message||"unknown error");
else
window.console.log(type +": "+message);
if (details)
window.console.log(details);
}
};
//register rendering time from call point
dhtmlx.log_full_time = function(name){
dhtmlx._start_time_log = new Date();
dhtmlx.log("Info","Timing start ["+name+"]");
window.setTimeout(function(){
var time = new Date();
dhtmlx.log("Info","Timing end ["+name+"]:"+(time.valueOf()-dhtmlx._start_time_log.valueOf())/1000+"s");
},1);
};
//register execution time from call point
dhtmlx.log_time = function(name){
var fname = "_start_time_log"+name;
if (!dhtmlx[fname]){
dhtmlx[fname] = new Date();
dhtmlx.log("Info","Timing start ["+name+"]");
} else {
var time = new Date();
dhtmlx.log("Info","Timing end ["+name+"]:"+(time.valueOf()-dhtmlx[fname].valueOf())/1000+"s");
dhtmlx[fname] = null;
}
};
//log message with type=error
dhtmlx.error = function(message,details){
dhtmlx.log("error",message,details);
};
//event system
dhtmlx.EventSystem={
_init:function(){
this._events = {}; //hash of event handlers, name => handler
this._handlers = {}; //hash of event handlers, ID => handler
this._map = {};
},
//temporary block event triggering
block : function(){
this._events._block = true;
},
//re-enable event triggering
unblock : function(){
this._events._block = false;
},
mapEvent:function(map){
dhtmlx.extend(this._map, map);
},
//trigger event
callEvent:function(type,params){
if (this._events._block) return true;
type = type.toLowerCase();
dhtmlx.assert_event_call(this, type, params);
var event_stack =this._events[type.toLowerCase()]; //all events for provided name
var return_value = true;
if (dhtmlx.debug) //can slowdown a lot
dhtmlx.log("info","["+this.name+"] event:"+type,params);
if (event_stack)
for(var i=0; i<event_stack.length; i++)
/*
Call events one by one
If any event return false - result of whole event will be false
Handlers which are not returning anything - counted as positive
*/
if (event_stack[i].apply(this,(params||[]))===false) return_value=false;
if (this._map[type] && !this._map[type].callEvent(type,params))
return_value = false;
return return_value;
},
//assign handler for some named event
attachEvent:function(type,functor,id){
type=type.toLowerCase();
dhtmlx.assert_event_attach(this, type);
id=id||dhtmlx.uid(); //ID can be used for detachEvent
functor = dhtmlx.toFunctor(functor); //functor can be a name of method
var event_stack=this._events[type]||dhtmlx.toArray();
//save new event handler
event_stack.push(functor);
this._events[type]=event_stack;
this._handlers[id]={ f:functor,t:type };
return id;
},
//remove event handler
detachEvent:function(id){
if(this._handlers[id]){
var type=this._handlers[id].t;
var functor=this._handlers[id].f;
//remove from all collections
var event_stack=this._events[type];
event_stack.remove(functor);
delete this._handlers[id];
}
}
};
//array helper
//can be used by dhtmlx.toArray()
dhtmlx.PowerArray={
//remove element at specified position
removeAt:function(pos,len){
if (pos>=0) this.splice(pos,(len||1));
},
//find element in collection and remove it
remove:function(value){
this.removeAt(this.find(value));
},
//add element to collection at specific position
insertAt:function(data,pos){
if (!pos && pos!==0) //add to the end by default
this.push(data);
else {
var b = this.splice(pos,(this.length-pos));
this[pos] = data;
this.push.apply(this,b); //reconstruct array without loosing this pointer
}
},
//return index of element, -1 if it doesn't exists
find:function(data){
for (i=0; i<this.length; i++)
if (data==this[i]) return i;
return -1;
},
//execute some method for each element of array
each:function(functor,master){
for (var i=0; i < this.length; i++)
functor.call((master||this),this[i]);
},
//create new array from source, by using results of functor
map:function(functor,master){
for (var i=0; i < this.length; i++)
this[i]=functor.call((master||this),this[i]);
return this;
}
};
dhtmlx.env = {};
//environment detection
if (navigator.userAgent.indexOf('Opera') != -1)
dhtmlx._isOpera=true;
else{
//very rough detection, but it is enough for current goals
dhtmlx._isIE=!!document.all;
dhtmlx._isFF=!document.all;
dhtmlx._isWebKit=(navigator.userAgent.indexOf("KHTML")!=-1);
if (navigator.appVersion.indexOf("MSIE 8.0")!= -1 && document.compatMode != "BackCompat")
dhtmlx._isIE=8;
if (navigator.appVersion.indexOf("MSIE 9.0")!= -1 && document.compatMode != "BackCompat")
dhtmlx._isIE=9;
}
dhtmlx.env = {};
// dhtmlx.env.transform
// dhtmlx.env.transition
(function(){
dhtmlx.env.transform = false;
dhtmlx.env.transition = false;
var options = {};
options.names = ['transform', 'transition'];
options.transform = ['transform', 'WebkitTransform', 'MozTransform', 'oTransform','msTransform'];
options.transition = ['transition', 'WebkitTransition', 'MozTransition', 'oTransition'];
var d = document.createElement("DIV");
var property;
for(var i=0; i<options.names.length; i++) {
while (p = options[options.names[i]].pop()) {
if(typeof d.style[p] != 'undefined')
dhtmlx.env[options.names[i]] = true;
}
}
})();
dhtmlx.env.transform_prefix = (function(){
var prefix;
if(dhtmlx._isOpera)
prefix = '-o-';
else {
prefix = ''; // default option
if(dhtmlx._isFF)
prefix = '-moz-';
if(dhtmlx._isWebKit)
prefix = '-webkit-';
}
return prefix;
})();
dhtmlx.env.svg = (function(){
return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
})();
//store maximum used z-index
dhtmlx.zIndex={ drag : 10000 };
//html helpers
dhtmlx.html={
create:function(name,attrs,html){
attrs = attrs || {};
var node = document.createElement(name);
for (var attr_name in attrs)
node.setAttribute(attr_name, attrs[attr_name]);
if (attrs.style)
node.style.cssText = attrs.style;
if (attrs["class"])
node.className = attrs["class"];
if (html)
node.innerHTML=html;
return node;
},
//return node value, different logic for different html elements
getValue:function(node){
node = dhtmlx.toNode(node);
if (!node) return "";
return dhtmlx.isNotDefined(node.value)?node.innerHTML:node.value;
},
//remove html node, can process an array of nodes at once
remove:function(node){
if (node instanceof Array)
for (var i=0; i < node.length; i++)
this.remove(node[i]);
else
if (node && node.parentNode)
node.parentNode.removeChild(node);
},
//insert new node before sibling, or at the end if sibling doesn't exist
insertBefore: function(node,before,rescue){
if (!node) return;
if (before)
before.parentNode.insertBefore(node, before);
else
rescue.appendChild(node);
},
//return custom ID from html element
//will check all parents starting from event's target
locate:function(e,id){
e=e||event;
var trg=e.target||e.srcElement;
while (trg){
if (trg.getAttribute){ //text nodes has not getAttribute
var test = trg.getAttribute(id);
if (test) return test;
}
trg=trg.parentNode;
}
return null;
},
//returns position of html element on the page
offset:function(elem) {
if (elem.getBoundingClientRect) { //HTML5 method
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { y: Math.round(top), x: Math.round(left) };
} else { //fallback to naive approach
var top=0, left=0;
while(elem) {
top = top + parseInt(elem.offsetTop,10);
left = left + parseInt(elem.offsetLeft,10);
elem = elem.offsetParent;
}
return {y: top, x: left};
}
},
//returns position of event
pos:function(ev){
ev = ev || event;
if(ev.pageX || ev.pageY) //FF, KHTML
return {x:ev.pageX, y:ev.pageY};
//IE
var d = ((dhtmlx._isIE)&&(document.compatMode != "BackCompat"))?document.documentElement:document.body;
return {
x:ev.clientX + d.scrollLeft - d.clientLeft,
y:ev.clientY + d.scrollTop - d.clientTop
};
},
//prevent event action
preventEvent:function(e){
if (e && e.preventDefault) e.preventDefault();
dhtmlx.html.stopEvent(e);
},
//stop event bubbling
stopEvent:function(e){
(e||event).cancelBubble=true;
return false;
},
//add css class to the node
addCss:function(node,name){
node.className+=" "+name;
},
//remove css class from the node
removeCss:function(node,name){
node.className=node.className.replace(RegExp(name,"g"),"");
}
};
//autodetect codebase folder
(function(){
var temp = document.getElementsByTagName("SCRIPT"); //current script, most probably
dhtmlx.assert(temp.length,"Can't locate codebase");
if (temp.length){
//full path to script
temp = (temp[temp.length-1].getAttribute("src")||"").split("/");
//get folder name
temp.splice(temp.length-1, 1);
dhtmlx.codebase = temp.slice(0, temp.length).join("/")+"/";
}
})();
if (!dhtmlx.ui)
dhtmlx.ui={};
/* DHX DEPEND FROM FILE 'destructor.js'*/
/*
Behavior:Destruction
@export
destructor
*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.Destruction = {
_init:function(){
//register self in global list of destructors
dhtmlx.destructors.push(this);
},
//will be called automatically on unload, can be called manually
//simplifies job of GC
destructor:function(){
this.destructor=function(){}; //destructor can be called only once
//html collection
this._htmlmap = null;
this._htmlrows = null;
//temp html element, used by toHTML
if (this._html)
document.body.appendChild(this._html); //need to attach, for IE's GC
this._html = null;
if (this._obj) {
this._obj.innerHTML="";
this._obj._htmlmap = null;
}
this._obj = this._dataobj=null;
this.data = null;
this._events = this._handlers = {};
if(this.render)
this.render = function(){};//need in case of delayed method calls (virtual render case)
}
};
//global list of destructors
dhtmlx.destructors = [];
dhtmlx.event(window,"unload",function(){
//call all registered destructors
if (dhtmlx.destructors){
for (var i=0; i<dhtmlx.destructors.length; i++)
dhtmlx.destructors[i].destructor();
dhtmlx.destructors = [];
}
//detach all known DOM events
for (var a in dhtmlx._events){
var ev = dhtmlx._events[a];
if (ev[0].removeEventListener)
ev[0].removeEventListener(ev[1],ev[2],false);
else if (ev[0].detachEvent)
ev[0].detachEvent("on"+ev[1],ev[2]);
delete dhtmlx._events[a];
}
});
/* DHX DEPEND FROM FILE 'load.js'*/
/*
ajax operations
can be used for direct loading as
dhtmlx.ajax(ulr, callback)
or
dhtmlx.ajax().item(url)
dhtmlx.ajax().post(url)
*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.ajax = function(url,call,master){
//if parameters was provided - made fast call
if (arguments.length!==0){
var http_request = new dhtmlx.ajax();
if (master) http_request.master=master;
http_request.get(url,null,call);
}
if (!this.getXHR) return new dhtmlx.ajax(); //allow to create new instance without direct new declaration
return this;
};
dhtmlx.ajax.prototype={
//creates xmlHTTP object
getXHR:function(){
if (dhtmlx._isIE)
return new ActiveXObject("Microsoft.xmlHTTP");
else
return new XMLHttpRequest();
},
/*
send data to the server
params - hash of properties which will be added to the url
call - callback, can be an array of functions
*/
send:function(url,params,call){
var x=this.getXHR();
if (typeof call == "function")
call = [call];
//add extra params to the url
if (typeof params == "object"){
var t=[];
for (var a in params){
var value = params[a];
if (value === null || value === dhtmlx.undefined)
value = "";
t.push(a+"="+encodeURIComponent(value));// utf-8 escaping
}
params=t.join("&");
}
if (params && !this.post){
url=url+(url.indexOf("?")!=-1 ? "&" : "?")+params;
params=null;
}
x.open(this.post?"POST":"GET",url,!this._sync);
if (this.post)
x.setRequestHeader('Content-type','application/x-www-form-urlencoded');
//async mode, define loading callback
//if (!this._sync){
var self=this;
x.onreadystatechange= function(){
if (!x.readyState || x.readyState == 4){
//dhtmlx.log_full_time("data_loading"); //log rendering time
if (call && self)
for (var i=0; i < call.length; i++) //there can be multiple callbacks
if (call[i])
call[i].call((self.master||self),x.responseText,x.responseXML,x);
self.master=null;
call=self=null; //anti-leak
}
};
//}
x.send(params||null);
return x; //return XHR, which can be used in case of sync. mode
},
//GET request
get:function(url,params,call){
this.post=false;
return this.send(url,params,call);
},
//POST request
post:function(url,params,call){
this.post=true;
return this.send(url,params,call);
},
sync:function(){
this._sync = true;
return this;
}
};
dhtmlx.AtomDataLoader={
_init:function(config){
//prepare data store
this.data = {};
if (config){
this._settings.datatype = config.datatype||"json";
this._after_init.push(this._load_when_ready);
}
},
_load_when_ready:function(){
this._ready_for_data = true;
if (this._settings.url)
this.url_setter(this._settings.url);
if (this._settings.data)
this.data_setter(this._settings.data);
},
url_setter:function(value){
if (!this._ready_for_data) return value;
this.load(value, this._settings.datatype);
return value;
},
data_setter:function(value){
if (!this._ready_for_data) return value;
this.parse(value, this._settings.datatype);
return true;
},
//loads data from external URL
load:function(url,call){
this.callEvent("onXLS",[]);
if (typeof call == "string"){ //second parameter can be a loading type or callback
this.data.driver = dhtmlx.DataDriver[call];
call = arguments[2];
}
else
this.data.driver = dhtmlx.DataDriver["xml"];
//load data by async ajax call
dhtmlx.ajax(url,[this._onLoad,call],this);
},
//loads data from object
parse:function(data,type){
this.callEvent("onXLS",[]);
this.data.driver = dhtmlx.DataDriver[type||"xml"];
this._onLoad(data,null);
},
//default after loading callback
_onLoad:function(text,xml,loader){
var driver = this.data.driver;
var top = driver.getRecords(driver.toObject(text,xml))[0];
this.data=(driver?driver.getDetails(top):text);
this.callEvent("onXLE",[]);
},
_check_data_feed:function(data){
if (!this._settings.dataFeed || this._ignore_feed || !data) return true;
var url = this._settings.dataFeed;
if (typeof url == "function")
return url.call(this, (data.id||data), data);
url = url+(url.indexOf("?")==-1?"?":"&")+"action=get&id="+encodeURIComponent(data.id||data);
this.callEvent("onXLS",[]);
dhtmlx.ajax(url, function(text,xml){
this._ignore_feed=true;
this.setValues(dhtmlx.DataDriver.json.toObject(text)[0]);
this._ignore_feed=false;
this.callEvent("onXLE",[]);
}, this);
return false;
}
};
/*
Abstraction layer for different data types
*/
dhtmlx.DataDriver={};
dhtmlx.DataDriver.json={
//convert json string to json object if necessary
toObject:function(data){
if (!data) data="[]";
if (typeof data == "string"){
eval ("dhtmlx.temp="+data);
return dhtmlx.temp;
}
return data;
},
//get array of records
getRecords:function(data){
if (data && !(data instanceof Array))
return [data];
return data;
},
//get hash of properties for single record
getDetails:function(data){
return data;
},
//get count of data and position at which new data need to be inserted
getInfo:function(data){
return {
_size:(data.total_count||0),
_from:(data.pos||0),
_key:(data.dhx_security)
};
}
};
dhtmlx.DataDriver.json_ext={
//convert json string to json object if necessary
toObject:function(data){
if (!data) data="[]";
if (typeof data == "string"){
var temp;
eval ("temp="+data);
dhtmlx.temp = [];
var header = temp.header;
for (var i = 0; i < temp.data.length; i++) {
var item = {};
for (var j = 0; j < header.length; j++) {
if (typeof(temp.data[i][j]) != "undefined")
item[header[j]] = temp.data[i][j];
}
dhtmlx.temp.push(item);
}
return dhtmlx.temp;
}
return data;
},
//get array of records
getRecords:function(data){
if (data && !(data instanceof Array))
return [data];
return data;
},
//get hash of properties for single record
getDetails:function(data){
return data;
},
//get count of data and position at which new data need to be inserted
getInfo:function(data){
return {
_size:(data.total_count||0),
_from:(data.pos||0)
};
}
};
dhtmlx.DataDriver.html={
/*
incoming data can be
- collection of nodes
- ID of parent container
- HTML text
*/
toObject:function(data){
if (typeof data == "string"){
var t=null;
if (data.indexOf("<")==-1) //if no tags inside - probably its an ID
t = dhtmlx.toNode(data);
if (!t){
t=document.createElement("DIV");
t.innerHTML = data;
}
return t.getElementsByTagName(this.tag);
}
return data;
},
//get array of records
getRecords:function(data){
if (data.tagName)
return data.childNodes;
return data;
},
//get hash of properties for single record
getDetails:function(data){
return dhtmlx.DataDriver.xml.tagToObject(data);
},
//dyn loading is not supported by HTML data source
getInfo:function(data){
return {
_size:0,
_from:0
};
},
tag: "LI"
};
dhtmlx.DataDriver.jsarray={
//eval jsarray string to jsarray object if necessary
toObject:function(data){
if (typeof data == "string"){
eval ("dhtmlx.temp="+data);
return dhtmlx.temp;
}
return data;
},
//get array of records
getRecords:function(data){
return data;
},
//get hash of properties for single record, in case of array they will have names as "data{index}"
getDetails:function(data){
var result = {};
for (var i=0; i < data.length; i++)
result["data"+i]=data[i];
return result;
},
//dyn loading is not supported by js-array data source
getInfo:function(data){
return {
_size:0,
_from:0
};
}
};
dhtmlx.DataDriver.csv={
//incoming data always a string
toObject:function(data){
return data;
},
//get array of records
getRecords:function(data){
return data.split(this.row);
},
//get hash of properties for single record, data named as "data{index}"
getDetails:function(data){
data = this.stringToArray(data);
var result = {};
for (var i=0; i < data.length; i++)
result["data"+i]=data[i];
return result;
},
//dyn loading is not supported by csv data source
getInfo:function(data){
return {
_size:0,
_from:0
};
},
//split string in array, takes string surrounding quotes in account
stringToArray:function(data){
data = data.split(this.cell);
for (var i=0; i < data.length; i++)
data[i] = data[i].replace(/^[ \t\n\r]*(\"|)/g,"").replace(/(\"|)[ \t\n\r]*$/g,"");
return data;
},
row:"\n", //default row separator
cell:"," //default cell separator
};
dhtmlx.DataDriver.xml={
//convert xml string to xml object if necessary
toObject:function(text,xml){
if (xml && (xml=this.checkResponse(text,xml))) //checkResponse - fix incorrect content type and extra whitespaces errors
return xml;
if (typeof text == "string"){
return this.fromString(text);
}
return text;
},
//get array of records
getRecords:function(data){
return this.xpath(data,this.records);
},
records:"/*/item",
//get hash of properties for single record
getDetails:function(data){
return this.tagToObject(data,{});
},
//get count of data and position at which new data_loading need to be inserted
getInfo:function(data){
return {
_size:(data.documentElement.getAttribute("total_count")||0),
_from:(data.documentElement.getAttribute("pos")||0),
_key:(data.documentElement.getAttribute("dhx_security"))
};
},
//xpath helper
xpath:function(xml,path){
if (window.XPathResult){ //FF, KHTML, Opera
var node=xml;
if(xml.nodeName.indexOf("document")==-1)
xml=xml.ownerDocument;
var res = [];
var col = xml.evaluate(path, node, null, XPathResult.ANY_TYPE, null);
var temp = col.iterateNext();
while (temp){
res.push(temp);
temp = col.iterateNext();
}
return res;
}
else {
var test = true;
try {
if (typeof(xml.selectNodes)=="undefined")
test = false;
} catch(e){ /*IE7 and below can't operate with xml object*/ }
//IE
if (test)
return xml.selectNodes(path);
else {
//Google hate us, there is no interface to do XPath
//use naive approach
var name = path.split("/").pop();
return xml.getElementsByTagName(name);
}
}
},
//convert xml tag to js object, all subtags and attributes are mapped to the properties of result object
tagToObject:function(tag,z){
z=z||{};
var flag=false;
//map attributes
var a=tag.attributes;
if(a && a.length){
for (var i=0; i<a.length; i++)
z[a[i].name]=a[i].value;
flag = true;
}
//map subtags
var b=tag.childNodes;
var state = {};
for (var i=0; i<b.length; i++){
if (b[i].nodeType==1){
var name = b[i].tagName;
if (typeof z[name] != "undefined"){
if (!(z[name] instanceof Array))
z[name]=[z[name]];
z[name].push(this.tagToObject(b[i],{}));
}
else
z[b[i].tagName]=this.tagToObject(b[i],{}); //sub-object for complex subtags
flag=true;
}
}
if (!flag)
return this.nodeValue(tag);
//each object will have its text content as "value" property
z.value = this.nodeValue(tag);
return z;
},
//get value of xml node
nodeValue:function(node){
if (node.firstChild)
return node.firstChild.wholeText||node.firstChild.data;
return "";
},
//convert XML string to XML object
fromString:function(xmlString){
if (window.DOMParser && !dhtmlx._isIE) // FF, KHTML, Opera
return (new DOMParser()).parseFromString(xmlString,"text/xml");
if (window.ActiveXObject){ // IE, utf-8 only
var temp=new ActiveXObject("Microsoft.xmlDOM");
temp.loadXML(xmlString);
return temp;
}
dhtmlx.error("Load from xml string is not supported");
},
//check is XML correct and try to reparse it if its invalid
checkResponse:function(text,xml){
if (xml && ( xml.firstChild && xml.firstChild.tagName != "parsererror") )
return xml;
//parsing as string resolves incorrect content type
//regexp removes whitespaces before xml declaration, which is vital for FF
var a=this.fromString(text.replace(/^[\s]+/,""));
if (a) return a;
dhtmlx.error("xml can't be parsed",text);
}
};
/* DHX DEPEND FROM FILE 'datastore.js'*/
/*DHX:Depend load.js*/
/*DHX:Depend dhtmlx.js*/
/*
Behavior:DataLoader - load data in the component
@export
load
parse
*/
dhtmlx.DataLoader={
_init:function(config){
//prepare data store
config = config || "";
this.name = "DataStore";
this.data = (config.datastore)||(new dhtmlx.DataStore());
this._readyHandler = this.data.attachEvent("onStoreLoad",dhtmlx.bind(this._call_onready,this));
},
//loads data from external URL
load:function(url,call){
dhtmlx.AtomDataLoader.load.apply(this, arguments);
//prepare data feed for dyn. loading
if (!this.data.feed)
this.data.feed = function(from,count){
//allow only single request at same time
if (this._load_count)
return this._load_count=[from,count]; //save last ignored request
else
this._load_count=true;
this.load(url+((url.indexOf("?")==-1)?"?":"&")+"posStart="+from+"&count="+count,function(){
//after loading check if we have some ignored requests
var temp = this._load_count;
this._load_count = false;
if (typeof temp =="object")
this.data.feed.apply(this, temp); //load last ignored request
});
};
},
//default after loading callback
_onLoad:function(text,xml,loader){
this.data._parse(this.data.driver.toObject(text,xml));
this.callEvent("onXLE",[]);
if(this._readyHandler){
this.data.detachEvent(this._readyHandler);
this._readyHandler = null;
}
},
dataFeed_setter:function(value){
this.data.attachEvent("onBeforeFilter", dhtmlx.bind(function(text, value){
if (this._settings.dataFeed){
var filter = {};
if (!text && !filter) return;
if (typeof text == "function"){
if (!value) return;
text(value, filter);
} else
filter = { text:value };
this.clearAll();
var url = this._settings.dataFeed;
if (typeof url == "function")
return url.call(this, value, filter);
var urldata = [];
for (var key in filter)
urldata.push("dhx_filter["+key+"]="+encodeURIComponent(filter[key]));
this.load(url+(url.indexOf("?")<0?"?":"&")+urldata.join("&"), this._settings.datatype);
return false;
}
},this));
return value;
},
_call_onready:function(){
if (this._settings.ready){
var code = dhtmlx.toFunctor(this._settings.ready);
if (code && code.call) code.apply(this, arguments);
}
}
};
/*
DataStore is not a behavior, it standalone object, which represents collection of data.
Call provideAPI to map data API
@export
exists
idByIndex
indexById
get
set
refresh
dataCount
sort
filter
next
previous
clearAll
first
last
*/
dhtmlx.DataStore = function(){
this.name = "DataStore";
dhtmlx.extend(this, dhtmlx.EventSystem);
this.setDriver("xml"); //default data source is an XML
this.pull = {}; //hash of IDs
this.order = dhtmlx.toArray(); //order of IDs
};
dhtmlx.DataStore.prototype={
//defines type of used data driver
//data driver is an abstraction other different data formats - xml, json, csv, etc.
setDriver:function(type){
dhtmlx.assert(dhtmlx.DataDriver[type],"incorrect DataDriver");
this.driver = dhtmlx.DataDriver[type];
},
//process incoming raw data
_parse:function(data){
this.callEvent("onParse", [this.driver, data]);
if (this._filter_order)
this.filter();
//get size and position of data
var info = this.driver.getInfo(data);
if (info._key)
dhtmlx.security_key = info._key;
//get array of records
var recs = this.driver.getRecords(data);
var from = (info._from||0)*1;
if (from === 0 && this.order[0]) //update mode
from = this.order.length;
var j=0;
for (var i=0; i<recs.length; i++){
//get has of details for each record
var temp = this.driver.getDetails(recs[i]);
var id = this.id(temp); //generate ID for the record
if (!this.pull[id]){ //if such ID already exists - update instead of insert
this.order[j+from]=id;
j++;
}
this.pull[id]=temp;
//if (this._format) this._format(temp);
if (this.extraParser)
this.extraParser(temp);
if (this._scheme){
if (this._scheme.$init)
this._scheme.$update(temp);
else if (this._scheme.$update)
this._scheme.$update(temp);
}
}
//for all not loaded data
for (var i=0; i < info._size; i++)
if (!this.order[i]){
var id = dhtmlx.uid();
var temp = {id:id, $template:"loading"}; //create fake records
this.pull[id]=temp;
this.order[i]=id;
}
this.callEvent("onStoreLoad",[this.driver, data]);
//repaint self after data loading
this.refresh();
},
//generate id for data object
id:function(data){
return data.id||(data.id=dhtmlx.uid());
},
changeId:function(old, newid){
dhtmlx.assert(this.pull[old],"Can't change id, for non existing item: "+old);
this.pull[newid] = this.pull[old];
this.pull[newid].id = newid;
this.order[this.order.find(old)]=newid;
if (this._filter_order)
this._filter_order[this._filter_order.find(old)]=newid;
this.callEvent("onIdChange", [old, newid]);
if (this._render_change_id)
this._render_change_id(old, newid);
},
get:function(id){
return this.item(id);
},
set:function(id, data){
return this.update(id, data);
},
//get data from hash by id
item:function(id){
return this.pull[id];
},
//assigns data by id
update:function(id,data){
if (this._scheme && this._scheme.$update)
this._scheme.$update(data);
if (this.callEvent("onBeforeUpdate", [id, data]) === false) return false;
this.pull[id]=data;
this.refresh(id);
},
//sends repainting signal
refresh:function(id){
if (this._skip_refresh) return;
if (id)
this.callEvent("onStoreUpdated",[id, this.pull[id], "update"]);
else
this.callEvent("onStoreUpdated",[null,null,null]);
},
silent:function(code){
this._skip_refresh = true;
code.call(this);
this._skip_refresh = false;
},
//converts range IDs to array of all IDs between them
getRange:function(from,to){
//if some point is not defined - use first or last id
//BEWARE - do not use empty or null ID
if (from)
from = this.indexById(from);
else
from = this.startOffset||0;
if (to)
to = this.indexById(to);
else {
to = Math.min((this.endOffset||Infinity),(this.dataCount()-1));
if (to<0) to = 0; //we have not data in the store
}
if (from>to){ //can be in case of backward shift-selection
var a=to; to=from; from=a;
}
return this.getIndexRange(from,to);
},
//converts range of indexes to array of all IDs between them
getIndexRange:function(from,to){
to=Math.min((to||Infinity),this.dataCount()-1);
var ret=dhtmlx.toArray(); //result of method is rich-array
for (var i=(from||0); i <= to; i++)
ret.push(this.item(this.order[i]));
return ret;
},
//returns total count of elements
dataCount:function(){
return this.order.length;
},
//returns truy if item with such ID exists
exists:function(id){
return !!(this.pull[id]);
},
//nextmethod is not visible on component level, check DataMove.move
//moves item from source index to the target index
move:function(sindex,tindex){
if (sindex<0 || tindex<0){
dhtmlx.error("DataStore::move","Incorrect indexes");
return;
}
var id = this.idByIndex(sindex);
var obj = this.item(id);
this.order.removeAt(sindex); //remove at old position
//if (sindex<tindex) tindex--; //correct shift, caused by element removing
this.order.insertAt(id,Math.min(this.order.length, tindex)); //insert at new position
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"move"]);
},
scheme:function(config){
/*
some.scheme({
order:1,
name:"dummy",
title:""
})
*/
this._scheme = config;
},
sync:function(source, filter, silent){
if (typeof filter != "function"){
silent = filter;
filter = null;
}
if (dhtmlx.debug_bind){
this.debug_sync_master = source;
dhtmlx.log("[sync] "+this.debug_bind_master.name+"@"+this.debug_bind_master._settings.id+" <= "+this.debug_sync_master.name+"@"+this.debug_sync_master._settings.id);
}
var topsource = source;
if (source.name != "DataStore")
source = source.data;
var sync_logic = dhtmlx.bind(function(id, data, mode){
if (mode != "update" || filter)
id = null;
if (!id){
this.order = dhtmlx.toArray([].concat(source.order));
this._filter_order = null;
this.pull = source.pull;
if (filter)
this.silent(filter);
if (this._on_sync)
this._on_sync();
}
if (dhtmlx.debug_bind)
dhtmlx.log("[sync:request] "+this.debug_sync_master.name+"@"+this.debug_sync_master._settings.id + " <= "+this.debug_bind_master.name+"@"+this.debug_bind_master._settings.id);
if (!silent)
this.refresh(id);
else
silent = false;
}, this);
source.attachEvent("onStoreUpdated", sync_logic);
this.feed = function(from, count){
topsource.loadNext(count, from);
};
sync_logic();
},
//adds item to the store
add:function(obj,index){
if (this._scheme){
obj = obj||{};
for (var key in this._scheme)
obj[key] = obj[key]||this._scheme[key];
if (this._scheme){
if (this._scheme.$init)
this._scheme.$update(obj);
else if (this._scheme.$update)
this._scheme.$update(obj);
}
}
//generate id for the item
var id = this.id(obj);
//by default item is added to the end of the list
var data_size = this.dataCount();
if (dhtmlx.isNotDefined(index) || index < 0)
index = data_size;
//check to prevent too big indexes
if (index > data_size){
dhtmlx.log("Warning","DataStore:add","Index of out of bounds");
index = Math.min(this.order.length,index);
}
if (this.callEvent("onBeforeAdd", [id, obj, index]) === false) return false;
if (this.exists(id)) return dhtmlx.error("Not unique ID");
this.pull[id]=obj;
this.order.insertAt(id,index);
if (this._filter_order){ //adding during filtering
//we can't know the location of new item in full dataset, making suggestion
//put at end by default
var original_index = this._filter_order.length;
//put at start only if adding to the start and some data exists
if (!index && this.order.length)
original_index = 0;
this._filter_order.insertAt(id,original_index);
}
this.callEvent("onafterAdd",[id,index]);
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"add"]);
return id;
},
//removes element from datastore
remove:function(id){
//id can be an array of IDs - result of getSelect, for example
if (id instanceof Array){
for (var i=0; i < id.length; i++)
this.remove(id[i]);
return;
}
if (this.callEvent("onBeforeDelete",[id]) === false) return false;
if (!this.exists(id)) return dhtmlx.error("Not existing ID",id);
var obj = this.item(id); //save for later event
//clear from collections
this.order.remove(id);
if (this._filter_order)
this._filter_order.remove(id);
delete this.pull[id];
this.callEvent("onafterdelete",[id]);
//repaint signal
this.callEvent("onStoreUpdated",[id,obj,"delete"]);
},
//deletes all records in datastore
clearAll:function(){
//instead of deleting one by one - just reset inner collections
this.pull = {};
this.order = dhtmlx.toArray();
this.feed = null;
this._filter_order = null;
this.callEvent("onClearAll",[]);
this.refresh();
},
//converts id to index
idByIndex:function(index){
if (index>=this.order.length || index<0)
dhtmlx.log("Warning","DataStore::idByIndex Incorrect index");
return this.order[index];
},
//converts index to id
indexById:function(id){
var res = this.order.find(id); //slower than idByIndex
//if (!this.pull[id])
// dhtmlx.log("Warning","DataStore::indexById Non-existing ID: "+ id);
return res;
},
//returns ID of next element
next:function(id,step){
return this.order[this.indexById(id)+(step||1)];
},
//returns ID of first element
first:function(){
return this.order[0];
},
//returns ID of last element
last:function(){
return this.order[this.order.length-1];
},
//returns ID of previous element
previous:function(id,step){
return this.order[this.indexById(id)-(step||1)];
},
/*
sort data in collection
by - settings of sorting
or
by - sorting function
dir - "asc" or "desc"
or
by - property
dir - "asc" or "desc"
as - type of sortings
Sorting function will accept 2 parameters and must return 1,0,-1, based on desired order
*/
sort:function(by, dir, as){
var sort = by;
if (typeof by == "function")
sort = {as:by, dir:dir};
else if (typeof by == "string")
sort = {by:by, dir:dir, as:as};
var parameters = [sort.by, sort.dir, sort.as];
if (!this.callEvent("onbeforesort",parameters)) return;
if (this.order.length){
var sorter = dhtmlx.sort.create(sort);
//get array of IDs
var neworder = this.getRange(this.first(), this.last());
neworder.sort(sorter);
this.order = neworder.map(function(obj){ return this.id(obj); },this);
}
//repaint self
this.refresh();
this.callEvent("onaftersort",parameters);
},
/*
Filter datasource
text - property, by which filter
value - filter mask
or
text - filter method
Filter method will receive data object and must return true or false
*/
filter:function(text,value){
if (!this.callEvent("onBeforeFilter", [text, value])) return;
//remove previous filtering , if any
if (this._filter_order){
this.order = this._filter_order;
delete this._filter_order;
}
if (!this.order.length) return;
//if text not define -just unfilter previous state and exit
if (text){
var filter = text;
value = value||"";
if (typeof text == "string"){
text = dhtmlx.Template.fromHTML(text);
value = value.toString().toLowerCase();
filter = function(obj,value){ //default filter - string start from, case in-sensitive
return text(obj).toLowerCase().indexOf(value)!=-1;
};
}
var neworder = dhtmlx.toArray();
for (var i=0; i < this.order.length; i++){
var id = this.order[i];
if (filter(this.item(id),value))
neworder.push(id);
}
//set new order of items, store original
this._filter_order = this.order;
this.order = neworder;
}
//repaint self
this.refresh();
this.callEvent("onAfterFilter", []);
},
/*
Iterate through collection
*/
each:function(method,master){
for (var i=0; i<this.order.length; i++)
method.call((master||this), this.item(this.order[i]));
},
/*
map inner methods to some distant object
*/
provideApi:function(target,eventable){
this.debug_bind_master = target;
if (eventable){
this.mapEvent({
onbeforesort: target,
onaftersort: target,
onbeforeadd: target,
onafteradd: target,
onbeforedelete: target,
onafterdelete: target,
onbeforeupdate: target/*,
onafterfilter: target,
onbeforefilter: target*/
});
}
var list = ["get","set","sort","add","remove","exists","idByIndex","indexById","item","update","refresh","dataCount","filter","next","previous","clearAll","first","last","serialize"];
for (var i=0; i < list.length; i++)
target[list[i]]=dhtmlx.methodPush(this,list[i]);
if (dhtmlx.assert_enabled())
this.assert_event(target);
},
/*
serializes data to a json object
*/
serialize: function(){
var ids = this.order;
var result = [];
for(var i=0; i< ids.length;i++)
result.push(this.pull[ids[i]]);
return result;
}
};
dhtmlx.sort = {
create:function(config){
return dhtmlx.sort.dir(config.dir, dhtmlx.sort.by(config.by, config.as));
},
as:{
"int":function(a,b){
a = a*1; b=b*1;
return a>b?1:(a<b?-1:0);
},
"string_strict":function(a,b){
a = a.toString(); b=b.toString();
return a>b?1:(a<b?-1:0);
},
"string":function(a,b){
a = a.toString().toLowerCase(); b=b.toString().toLowerCase();
return a>b?1:(a<b?-1:0);
}
},
by:function(prop, method){
if (!prop)
return method;
if (typeof method != "function")
method = dhtmlx.sort.as[method||"string"];
prop = dhtmlx.Template.fromHTML(prop);
return function(a,b){
return method(prop(a),prop(b));
};
},
dir:function(prop, method){
if (prop == "asc")
return method;
return function(a,b){
return method(a,b)*-1;
};
}
};
/* DHX DEPEND FROM FILE 'key.js'*/
/*
Behavior:KeyEvents - hears keyboard
*/
dhtmlx.KeyEvents = {
_init:function(){
//attach handler to the main container
dhtmlx.event(this._obj,"keypress",this._onKeyPress,this);
},
//called on each key press , when focus is inside of related component
_onKeyPress:function(e){
e=e||event;
var code = e.which||e.keyCode; //FIXME better solution is required
this.callEvent((this._edit_id?"onEditKeyPress":"onKeyPress"),[code,e.ctrlKey,e.shiftKey,e]);
}
};
/* DHX DEPEND FROM FILE 'mouse.js'*/
/*
Behavior:MouseEvents - provides inner evnets for mouse actions
*/
dhtmlx.MouseEvents={
_init: function(){
//attach dom events if related collection is defined
if (this.on_click){
dhtmlx.event(this._obj,"click",this._onClick,this);
dhtmlx.event(this._obj,"contextmenu",this._onContext,this);
}
if (this.on_dblclick)
dhtmlx.event(this._obj,"dblclick",this._onDblClick,this);
if (this.on_mouse_move){
dhtmlx.event(this._obj,"mousemove",this._onMouse,this);
dhtmlx.event(this._obj,(dhtmlx._isIE?"mouseleave":"mouseout"),this._onMouse,this);
}
},
//inner onclick object handler
_onClick: function(e) {
return this._mouseEvent(e,this.on_click,"ItemClick");
},
//inner ondblclick object handler
_onDblClick: function(e) {
return this._mouseEvent(e,this.on_dblclick,"ItemDblClick");
},
//process oncontextmenu events
_onContext: function(e) {
var id = dhtmlx.html.locate(e, this._id);
if (id && !this.callEvent("onBeforeContextMenu", [id,e]))
return dhtmlx.html.preventEvent(e);
},
/*
event throttler - ignore events which occurs too fast
during mouse moving there are a lot of event firing - we need no so much
also, mouseout can fire when moving inside the same html container - we need to ignore such fake calls
*/
_onMouse:function(e){
if (dhtmlx._isIE) //make a copy of event, will be used in timed call
e = document.createEventObject(event);
if (this._mouse_move_timer) //clear old event timer
window.clearTimeout(this._mouse_move_timer);
//this event just inform about moving operation, we don't care about details
this.callEvent("onMouseMoving",[e]);
//set new event timer
this._mouse_move_timer = window.setTimeout(dhtmlx.bind(function(){
//called only when we have at least 100ms after previous event
if (e.type == "mousemove")
this._onMouseMove(e);
else
this._onMouseOut(e);
},this),500);
},
//inner mousemove object handler
_onMouseMove: function(e) {
if (!this._mouseEvent(e,this.on_mouse_move,"MouseMove"))
this.callEvent("onMouseOut",[e||event]);
},
//inner mouseout object handler
_onMouseOut: function(e) {
this.callEvent("onMouseOut",[e||event]);
},
//common logic for click and dbl-click processing
_mouseEvent:function(e,hash,name){
e=e||event;
var trg=e.target||e.srcElement;
var css = "";
var id = null;
var found = false;
//loop through all parents
while (trg && trg.parentNode){
if (!found && trg.getAttribute){ //if element with ID mark is not detected yet
id = trg.getAttribute(this._id); //check id of current one
if (id){
if (trg.getAttribute("userdata"))
this.callEvent("onLocateData",[id,trg]);
if (!this.callEvent("on"+name,[id,e,trg])) return; //it will be triggered only for first detected ID, in case of nested elements
found = true; //set found flag
}
}
css=trg.className;
if (css){ //check if pre-defined reaction for element's css name exists
css = css.split(" ");
css = css[0]||css[1]; //FIXME:bad solution, workaround css classes which are starting from whitespace
if (hash[css])
return hash[css].call(this,e,id||dhtmlx.html.locate(e, this._id),trg);
}
trg=trg.parentNode;
}
return found; //returns true if item was located and event was triggered
}
};
/* DHX DEPEND FROM FILE 'config.js'*/
/*
Behavior:Settings
@export
customize
config
*/
/*DHX:Depend template.js*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.Settings={
_init:function(){
/*
property can be accessed as this.config.some
in same time for inner call it have sense to use _settings
because it will be minified in final version
*/
this._settings = this.config= {};
},
define:function(property, value){
if (typeof property == "object")
return this._parseSeetingColl(property);
return this._define(property, value);
},
_define:function(property,value){
dhtmlx.assert_settings.call(this,property,value);
//method with name {prop}_setter will be used as property setter
//setter is optional
var setter = this[property+"_setter"];
return this._settings[property]=setter?setter.call(this,value):value;
},
//process configuration object
_parseSeetingColl:function(coll){
if (coll){
for (var a in coll) //for each setting
this._define(a,coll[a]); //set value through config
}
},
//helper for object initialization
_parseSettings:function(obj,initial){
//initial - set of default values
var settings = dhtmlx.extend({},initial);
//code below will copy all properties over default one
if (typeof obj == "object" && !obj.tagName)
dhtmlx.extend(settings,obj);
//call config for each setting
this._parseSeetingColl(settings);
},
_mergeSettings:function(config, defaults){
for (var key in defaults)
switch(typeof config[key]){
case "object":
config[key] = this._mergeSettings((config[key]||{}), defaults[key]);
break;
case "undefined":
config[key] = defaults[key];
break;
default: //do nothing
break;
}
return config;
},
//helper for html container init
_parseContainer:function(obj,name,fallback){
/*
parameter can be a config object, in such case real container will be obj.container
or it can be html object or ID of html object
*/
if (typeof obj == "object" && !obj.tagName)
obj=obj.container;
this._obj = this.$view = dhtmlx.toNode(obj);
if (!this._obj && fallback)
this._obj = fallback(obj);
dhtmlx.assert(this._obj, "Incorrect html container");
this._obj.className+=" "+name;
this._obj.onselectstart=function(){return false;}; //block selection by default
this._dataobj = this._obj;//separate reference for rendering modules
},
//apply template-type
_set_type:function(name){
//parameter can be a hash of settings
if (typeof name == "object")
return this.type_setter(name);
dhtmlx.assert(this.types, "RenderStack :: Types are not defined");
dhtmlx.assert(this.types[name],"RenderStack :: Inccorect type name",name);
//or parameter can be a name of existing template-type
this.type=dhtmlx.extend({},this.types[name]);
this.customize(); //init configs
},
customize:function(obj){
//apply new properties
if (obj) dhtmlx.extend(this.type,obj);
//init tempaltes for item start and item end
this.type._item_start = dhtmlx.Template.fromHTML(this.template_item_start(this.type));
this.type._item_end = this.template_item_end(this.type);
//repaint self
this.render();
},
//config.type - creates new template-type, based on configuration object
type_setter:function(value){
this._set_type(typeof value == "object"?dhtmlx.Type.add(this,value):value);
return value;
},
//config.template - creates new template-type with defined template string
template_setter:function(value){
return this.type_setter({template:value});
},
//config.css - css name for top level container
css_setter:function(value){
this._obj.className += " "+value;
return value;
}
};
/* DHX DEPEND FROM FILE 'template.js'*/
/*
Template - handles html templates
*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.Template={
_cache:{
},
empty:function(){
return "";
},
setter:function(value){
return dhtmlx.Template.fromHTML(value);
},
obj_setter:function(value){
var f = dhtmlx.Template.setter(value);
var obj = this;
return function(){
return f.apply(obj, arguments);
};
},
fromHTML:function(str){
if (typeof str == "function") return str;
if (this._cache[str])
return this._cache[str];
//supported idioms
// {obj} => value
// {obj.attr} => named attribute or value of sub-tag in case of xml
// {obj.attr?some:other} conditional output
// {-obj => sub-template
str=(str||"").toString();
str=str.replace(/[\r\n]+/g,"\\n");
str=str.replace(/\{obj\.([^}?]+)\?([^:]*):([^}]*)\}/g,"\"+(obj.$1?\"$2\":\"$3\")+\"");
str=str.replace(/\{common\.([^}\(]*)\}/g,"\"+common.$1+\"");
str=str.replace(/\{common\.([^\}\(]*)\(\)\}/g,"\"+(common.$1?common.$1(obj):\"\")+\"");
str=str.replace(/\{obj\.([^}]*)\}/g,"\"+obj.$1+\"");
str=str.replace(/#([a-z0-9_]+)#/gi,"\"+obj.$1+\"");
str=str.replace(/\{obj\}/g,"\"+obj+\"");
str=str.replace(/\{-obj/g,"{obj");
str=str.replace(/\{-common/g,"{common");
str="return \""+str+"\";";
return this._cache[str]= Function("obj","common",str);
}
};
dhtmlx.Type={
/*
adds new template-type
obj - object to which template will be added
data - properties of template
*/
add:function(obj, data){
//auto switch to prototype, if name of class was provided
if (!obj.types && obj.prototype.types)
obj = obj.prototype;
//if (typeof data == "string")
// data = { template:data };
if (dhtmlx.assert_enabled())
this.assert_event(data);
var name = data.name||"default";
//predefined templates - autoprocessing
this._template(data);
this._template(data,"edit");
this._template(data,"loading");
obj.types[name]=dhtmlx.extend(dhtmlx.extend({},(obj.types[name]||this._default)),data);
return name;
},
//default template value - basically empty box with 5px margin
_default:{
css:"default",
template:function(){ return ""; },
template_edit:function(){ return ""; },
template_loading:function(){ return "..."; },
width:150,
height:80,
margin:5,
padding:0
},
//template creation helper
_template:function(obj,name){
name = "template"+(name?("_"+name):"");
var data = obj[name];
//if template is a string - check is it plain string or reference to external content
if (data && (typeof data == "string")){
if (data.indexOf("->")!=-1){
data = data.split("->");
switch(data[0]){
case "html": //load from some container on the page
data = dhtmlx.html.getValue(data[1]).replace(/\"/g,"\\\"");
break;
case "http": //load from external file
data = new dhtmlx.ajax().sync().get(data[1],{uid:(new Date()).valueOf()}).responseText;
break;
default:
//do nothing, will use template as is
break;
}
}
obj[name] = dhtmlx.Template.fromHTML(data);
}
}
};
/* DHX DEPEND FROM FILE 'single_render.js'*/
/*
REnders single item.
Can be used for elements without datastore, or with complex custom rendering logic
@export
render
*/
/*DHX:Depend template.js*/
dhtmlx.SingleRender={
_init:function(){
},
//convert item to the HTML text
_toHTML:function(obj){
/*
this one doesn't support per-item-$template
it has not sense, because we have only single item per object
*/
return this.type._item_start(obj,this.type)+this.type.template(obj,this.type)+this.type._item_end;
},
//render self, by templating data object
render:function(){
if (!this.callEvent || this.callEvent("onBeforeRender",[this.data])){
if (this.data)
this._dataobj.innerHTML = this._toHTML(this.data);
if (this.callEvent) this.callEvent("onAfterRender",[]);
}
}
};
/* DHX DEPEND FROM FILE 'tooltip.js'*/
/*
UI: Tooltip
@export
show
hide
*/
/*DHX:Depend tooltip.css*/
/*DHX:Depend template.js*/
/*DHX:Depend single_render.js*/
dhtmlx.ui.Tooltip=function(container){
this.name = "Tooltip";
this.version = "3.0";
if (dhtmlx.assert_enabled()) this._assert();
if (typeof container == "string"){
container = { template:container };
}
dhtmlx.extend(this, dhtmlx.Settings);
dhtmlx.extend(this, dhtmlx.SingleRender);
this._parseSettings(container,{
type:"default",
dy:0,
dx:20
});
//create container for future tooltip
this._dataobj = this._obj = document.createElement("DIV");
this._obj.className="dhx_tooltip";
dhtmlx.html.insertBefore(this._obj,document.body.firstChild);
};
dhtmlx.ui.Tooltip.prototype = {
//show tooptip
//pos - object, pos.x - left, pox.y - top
show:function(data,pos){
if (this._disabled) return;
//render sefl only if new data was provided
if (this.data!=data){
this.data=data;
this.render(data);
}
//show at specified position
this._obj.style.top = pos.y+this._settings.dy+"px";
this._obj.style.left = pos.x+this._settings.dx+"px";
this._obj.style.display="block";
},
//hide tooltip
hide:function(){
this.data=null; //nulify, to be sure that on next show it will be fresh-rendered
this._obj.style.display="none";
},
disable:function(){
this._disabled = true;
},
enable:function(){
this._disabled = false;
},
types:{
"default":dhtmlx.Template.fromHTML("{obj.id}")
},
template_item_start:dhtmlx.Template.empty,
template_item_end:dhtmlx.Template.empty
};
/* DHX DEPEND FROM FILE 'autotooltip.js'*/
/*
Behavior: AutoTooltip - links tooltip to data driven item
*/
/*DHX:Depend tooltip.js*/
dhtmlx.AutoTooltip = {
tooltip_setter:function(value){
var t = new dhtmlx.ui.Tooltip(value);
this.attachEvent("onMouseMove",function(id,e){ //show tooltip on mousemove
t.show(this.get(id),dhtmlx.html.pos(e));
});
this.attachEvent("onMouseOut",function(id,e){ //hide tooltip on mouseout
t.hide();
});
this.attachEvent("onMouseMoving",function(id,e){ //hide tooltip just after moving start
t.hide();
});
return t;
}
};
/* DHX DEPEND FROM FILE 'compatibility.js'*/
/*
Collection of compatibility hacks
*/
/*DHX:Depend dhtmlx.js*/
dhtmlx.compat=function(name, obj){
//check if name hash present, and applies it when necessary
if (dhtmlx.compat[name])
dhtmlx.compat[name](obj);
};
(function(){
if (!window.dhtmlxError){
//dhtmlxcommon is not included
//create fake error tracker for connectors
var dummy = function(){};
window.dhtmlxError={ catchError:dummy, throwError:dummy };
//helpers instead of ones from dhtmlxcommon
window.convertStringToBoolean=function(value){
return !!value;
};
window.dhtmlxEventable = function(node){
dhtmlx.extend(node,dhtmlx.EventSystem);
};
//imitate ajax layer of dhtmlxcommon
var loader = {
getXMLTopNode:function(name){
},
doXPath:function(path){
return dhtmlx.DataDriver.xml.xpath(this.xml,path);
},
xmlDoc:{
responseXML:true
}
};
//wrap ajax methods of dataprocessor
dhtmlx.compat.dataProcessor=function(obj){
//FIXME
//this is pretty ugly solution - we replace whole method , so changes in dataprocessor need to be reflected here
var sendData = "_sendData";
var in_progress = "_in_progress";
var tMode = "_tMode";
var waitMode = "_waitMode";
obj[sendData]=function(a1,rowId){
if (!a1) return; //nothing to send
if (rowId)
this[in_progress][rowId]=(new Date()).valueOf();
if (!this.callEvent("onBeforeDataSending",rowId?[rowId,this.getState(rowId)]:[])) return false;
var a2 = this;
var a3=this.serverProcessor;
if (this[tMode]!="POST")
//use dhtmlx.ajax instead of old ajax layer
dhtmlx.ajax().get(a3+((a3.indexOf("?")!=-1)?"&":"?")+this.serialize(a1,rowId),"",function(t,x,xml){
loader.xml = dhtmlx.DataDriver.xml.checkResponse(t,x);
a2.afterUpdate(a2, null, null, null, loader);
});
else
dhtmlx.ajax().post(a3,this.serialize(a1,rowId),function(t,x,xml){
loader.xml = dhtmlx.DataDriver.xml.checkResponse(t,x);
a2.afterUpdate(a2, null, null, null, loader);
});
this[waitMode]++;
};
};
}
})();
/* DHX DEPEND FROM FILE 'compatibility_layout.js'*/
/*DHX:Depend dhtmlx.js*/
/*DHX:Depend compatibility.js*/
if (!dhtmlx.attaches)
dhtmlx.attaches = {};
dhtmlx.attaches.attachAbstract=function(name, conf){
var obj = document.createElement("DIV");
obj.id = "CustomObject_"+dhtmlx.uid();
obj.style.width = "100%";
obj.style.height = "100%";
obj.cmp = "grid";
document.body.appendChild(obj);
this.attachObject(obj.id);
conf.container = obj.id;
var that = this.vs[this.av];
that.grid = new window[name](conf);
that.gridId = obj.id;
that.gridObj = obj;
that.grid.setSizes = function(){
if (this.resize) this.resize();
else this.render();
};
var method_name="_viewRestore";
return this.vs[this[method_name]()].grid;
};
dhtmlx.attaches.attachDataView = function(conf){
return this.attachAbstract("dhtmlXDataView",conf);
};
dhtmlx.attaches.attachChart = function(conf){
return this.attachAbstract("dhtmlXChart",conf);
};
dhtmlx.compat.layout = function(){};
|
// flow-typed signature: 2ea4dc8d44d64d5c044be4bc31ad1a9d
// flow-typed version: 2c04631d20/redux_v3.x.x/flow_>=v0.55.x
declare module 'redux' {
/*
S = State
A = Action
D = Dispatch
*/
declare export type DispatchAPI<A> = (action: A) => A;
declare export type Dispatch<A: { type: $Subtype<string> }> = DispatchAPI<A>;
declare export type MiddlewareAPI<S, A, D = Dispatch<A>> = {
dispatch: D;
getState(): S;
};
declare export type Store<S, A, D = Dispatch<A>> = {
// rewrite MiddlewareAPI members in order to get nicer error messages (intersections produce long messages)
dispatch: D;
getState(): S;
subscribe(listener: () => void): () => void;
replaceReducer(nextReducer: Reducer<S, A>): void
};
declare export type Reducer<S, A> = (state: S, action: A) => S;
declare export type CombinedReducer<S, A> = (state: $Shape<S> & {} | void, action: A) => S;
declare export type Middleware<S, A, D = Dispatch<A>> =
(api: MiddlewareAPI<S, A, D>) =>
(next: D) => D;
declare export type StoreCreator<S, A, D = Dispatch<A>> = {
(reducer: Reducer<S, A>, enhancer?: StoreEnhancer<S, A, D>): Store<S, A, D>;
(reducer: Reducer<S, A>, preloadedState: S, enhancer?: StoreEnhancer<S, A, D>): Store<S, A, D>;
};
declare export type StoreEnhancer<S, A, D = Dispatch<A>> = (next: StoreCreator<S, A, D>) => StoreCreator<S, A, D>;
declare export function createStore<S, A, D>(reducer: Reducer<S, A>, enhancer?: StoreEnhancer<S, A, D>): Store<S, A, D>;
declare export function createStore<S, A, D>(reducer: Reducer<S, A>, preloadedState: S, enhancer?: StoreEnhancer<S, A, D>): Store<S, A, D>;
declare export function applyMiddleware<S, A, D>(...middlewares: Array<Middleware<S, A, D>>): StoreEnhancer<S, A, D>;
declare export type ActionCreator<A, B> = (...args: Array<B>) => A;
declare export type ActionCreators<K, A> = { [key: K]: ActionCreator<A, any> };
declare export function bindActionCreators<A, C: ActionCreator<A, any>, D: DispatchAPI<A>>(actionCreator: C, dispatch: D): C;
declare export function bindActionCreators<A, K, C: ActionCreators<K, A>, D: DispatchAPI<A>>(actionCreators: C, dispatch: D): C;
declare export function combineReducers<O: Object, A>(reducers: O): CombinedReducer<$ObjMap<O, <S>(r: Reducer<S, any>) => S>, A>;
declare export var compose: $Compose;
} |
export const CREATE_VERSION = 'CREATE_VERSION';
export const UPDATE_VERSION = 'UPDATE_VERSION';
export const DELETE_VERSION = 'DELETE_VERSION';
export const MOVE_VERSION = 'MOVE_VERSION';
|
import Ember from 'ember';
import {
getEngineParent,
setEngineParent
} from './engine-parent';
import emberRequire from './ext-require';
const EngineInstance = emberRequire('ember-application/system/engine-instance');
const P = emberRequire('container/registry', 'privatize');
const {
Error: EmberError,
assert,
RSVP
} = Ember;
EngineInstance.reopen({
/**
The root DOM element of the `EngineInstance` as an element or a
[jQuery-compatible selector
string](http://api.jquery.com/category/selectors/).
@private
@property {String|DOMElement} rootElement
*/
rootElement: null,
/**
A mapping of dependency names and values, grouped by category.
`dependencies` should be set by the parent of this engine instance upon
instantiation and prior to boot.
During the boot process, engine instances verify that their required
dependencies, as defined on the parent `Engine` class, have been assigned
by the parent.
@private
@property {Object} dependencies
*/
dependencies: null,
/**
A cache of dependency names and values, grouped by engine name.
This cache is maintained by `buildChildEngineInstance()` for every engine
that's a child of this parent instance.
Only dependencies that are singletons are currently allowed, which makes
this safe.
@private
@property {Object} _dependenciesForChildEngines
*/
_dependenciesForChildEngines: null,
buildChildEngineInstance(name, options = {}) {
// Check dependencies cached by engine name
let dependencies = this._dependenciesForChildEngines && this._dependenciesForChildEngines[name];
// Prepare dependencies if none are cached
if (!dependencies) {
dependencies = {};
let camelizedName = Ember.String.camelize(name);
let engineConfiguration = this.base.engines && this.base.engines[camelizedName];
if (engineConfiguration) {
let engineDependencies = engineConfiguration.dependencies;
if (engineDependencies) {
['services'].forEach((category) => {
if (engineDependencies[category]) {
dependencies[category] = {};
let dependencyType = this._dependencyTypeFromCategory(category);
for (let i = 0; i < engineDependencies[category].length; i++) {
let engineDependency = engineDependencies[category][i];
let dependencyName;
let dependencyNameInParent;
if (typeof engineDependency === 'object') {
dependencyName = Object.keys(engineDependency)[0];
dependencyNameInParent = engineDependency[dependencyName];
} else {
dependencyName = dependencyNameInParent = engineDependency;
}
let dependencyKey = `${dependencyType}:${dependencyNameInParent}`;
let dependency = this.lookup(dependencyKey);
assert(`Engine parent failed to lookup '${dependencyKey}' dependency, as declared in 'engines.${camelizedName}.dependencies.${category}'.`, dependency);
dependencies[category][dependencyName] = dependency;
}
}
});
}
if (engineDependencies.externalRoutes) {
dependencies.externalRoutes = engineDependencies.externalRoutes;
}
}
// Cache dependencies for child engines for faster instantiation in the future
this._dependenciesForChildEngines = this._dependenciesForChildEngines || {};
this._dependenciesForChildEngines[name] = dependencies;
}
let Engine = this.lookup(`engine:${name}`);
if (!Engine) {
throw new EmberError(`You attempted to mount the engine '${name}', but it can not be found.`);
}
options.dependencies = dependencies;
let engineInstance = Engine.buildInstance(options);
setEngineParent(engineInstance, this);
return engineInstance;
},
/**
Initialize the `Ember.EngineInstance` and return a promise that resolves
with the instance itself when the boot process is complete.
The primary task here is to run any registered instance initializers.
See the documentation on `BootOptions` for the options it takes.
@private
@method boot
@param options
@return {Promise<Ember.EngineInstance,Error>}
*/
boot(options = {}) {
if (this._bootPromise) { return this._bootPromise; }
assert('An engine instance\'s parent must be set via `setEngineParent(engine, parent)` prior to calling `engine.boot()` ', getEngineParent(this));
this._bootPromise = new RSVP.Promise(resolve => resolve(this._bootSync(options)));
// TODO: Unsure that we should allow boot to be async...
return this._bootPromise;
},
/**
Unfortunately, a lot of existing code assumes booting an instance is
synchronous – specifically, a lot of tests assumes the last call to
`app.advanceReadiness()` or `app.reset()` will result in a new instance
being fully-booted when the current runloop completes.
We would like new code (like the `visit` API) to stop making this assumption,
so we created the asynchronous version above that returns a promise. But until
we have migrated all the code, we would have to expose this method for use
*internally* in places where we need to boot an instance synchronously.
@private
*/
_bootSync(/* options */) {
if (this._booted) { return this; }
// if (isEnabled('ember-application-visit')) {
// options = new BootOptions(options);
//
// let registry = this.__registry__;
//
// registry.register('-environment:main', options.toEnvironment(), { instantiate: false });
// registry.injection('view', '_environment', '-environment:main');
// registry.injection('route', '_environment', '-environment:main');
//
// registry.register('renderer:-dom', {
// create() {
// return new Renderer(new DOMHelper(options.document), options.isInteractive);
// }
// });
//
// if (options.rootElement) {
// this.rootElement = options.rootElement;
// } else {
// this.rootElement = this.application.rootElement;
// }
//
// if (options.location) {
// let router = get(this, 'router');
// set(router, 'location', options.location);
// }
//
// this.base.runInstanceInitializers(this);
//
// if (options.isInteractive) {
// this.setupEventDispatcher();
// }
// } else {
this.base.runInstanceInitializers(this);
// if (environment.hasDOM) {
// this.setupEventDispatcher();
// }
// }
this.cloneCoreDependencies();
this.cloneCustomDependencies();
this._booted = true;
return this;
},
cloneCoreDependencies() {
let parent = getEngineParent(this);
[
'view:toplevel',
'route:basic',
'event_dispatcher:main',
P`-bucket-cache:main`,
'service:-routing'
].forEach((key) => {
this.register(key, parent.resolveRegistration(key));
});
[
'renderer:-dom',
'router:main',
'-view-registry:main'
].forEach((key) => {
this.register(key, parent.lookup(key), { instantiate: false });
});
},
/*
Gets the application-scoped route path for an external route.
@private
@method _getExternalRoute
@param {String} routeName
@return {String} route
*/
_getExternalRoute(routeName) {
const route = this._externalRoutes[routeName];
Ember.assert(`The external route ${routeName} does not exist`, route);
return route;
},
cloneCustomDependencies() {
let requiredDependencies = this.base.dependencies;
if (requiredDependencies) {
Object.keys(requiredDependencies).forEach((category) => {
let dependencyType = this._dependencyTypeFromCategory(category);
if (category === 'externalRoutes') {
this._externalRoutes = {};
}
requiredDependencies[category].forEach((dependencyName) => {
let dependency = this.dependencies[category] && this.dependencies[category][dependencyName];
assert(`A dependency mapping for '${category}.${dependencyName}' must be declared on this engine's parent.`, dependency);
if (category === 'externalRoutes') {
this._externalRoutes[dependencyName] = dependency;
} else {
let key = `${dependencyType}:${dependencyName}`;
this.register(key, dependency, { instantiate: false });
}
});
});
}
},
_dependencyTypeFromCategory(category) {
switch(category) {
case 'services':
return 'service';
case 'externalRoutes':
return 'externalRoute';
}
assert(`Dependencies of category '${category}' can not be shared with engines.`, false);
},
// mount(view) {
// assert('EngineInstance must be booted before it can be mounted', this._booted);
//
// view.append()
// },
/**
This hook is called by the root-most Route (a.k.a. the ApplicationRoute)
when it has finished creating the root View. By default, we simply take the
view and append it to the `rootElement` specified on the Application.
In cases like FastBoot and testing, we can override this hook and implement
custom behavior, such as serializing to a string and sending over an HTTP
socket rather than appending to DOM.
@param view {Ember.View} the root-most view
@private
*/
didCreateRootView(view) {
view.appendTo(this.rootElement);
},
});
|
import { createBufferRefragPool } from 'source/node/data/Buffer.js'
import { BUFFER_MAX_LENGTH, applyMaskQuadletBufferInPlace } from './function.js'
const NULL_ERROR = (error) => { __DEV__ && error && console.log('[NULL_ERROR] get error', error) }
/** @deprecated */ const createFrameReceiverStore = (frameLengthLimit) => {
let promiseTail = Promise.resolve('HEAD') // used to coordinate send and receive
let doClearSocketListener = null
return {
dispose: () => {
promiseTail.then(NULL_ERROR, NULL_ERROR)
promiseTail = null
doClearSocketListener && doClearSocketListener()
doClearSocketListener = null
},
queuePromise: (resolve, reject) => (promiseTail = promiseTail.then(resolve, reject)),
setClearSocketListener: (nextDoClearSocketListener) => { doClearSocketListener = nextDoClearSocketListener },
frameDecoder: createFrameDecoder(frameLengthLimit),
frameLengthLimit
}
}
/** @deprecated */ const listenAndReceiveFrame = (frameReceiverStore, socket, onFrame, onError = frameReceiverStore.dispose) => {
let receiveResolve = null
let receiveReject = null
const reset = () => {
__DEV__ && console.log('[Frame] reset')
receiveReject && socket.off('error', receiveReject)
receiveResolve = null
receiveReject = null
frameReceiverStore.frameDecoder.resetDecode()
}
const onPromiseReject = (error) => {
reset()
onError(error)
}
const promiseReceive = () => {
__DEV__ && console.log('[Frame] promiseReceive first chunk')
const receivePromise = new Promise((resolve, reject) => { // HACK: first pick out resolve to delay Promise resolve
receiveResolve = resolve
receiveReject = reject
})
socket.on('error', receiveReject)
frameReceiverStore.queuePromise(() => receivePromise.then(onFrame), onPromiseReject)
}
const onSocketData = (chunk) => {
__DEV__ && console.log(`[Frame] onSocketData +${chunk.length}`)
frameReceiverStore.frameDecoder.pushFrag(chunk)
while (true) {
receiveResolve === null && promiseReceive()
const hasMore = frameReceiverStore.frameDecoder.decode()
if (!hasMore) break // wait for more data
const frame = frameReceiverStore.frameDecoder.tryGetDecodedFrame()
if (frame === undefined) continue // wait for more data
__DEV__ && console.log('[Frame] onSocketData got one frame', frame)
receiveResolve(frame)
reset()
}
}
socket.on('data', onSocketData)
frameReceiverStore.setClearSocketListener(() => {
socket.off('data', onSocketData)
reset()
})
}
const DECODE_STAGE_INITIAL_OCTET = 0
const DECODE_STAGE_EXTEND_DATA_LENGTH_2 = 1
const DECODE_STAGE_EXTEND_DATA_LENGTH_8 = 2
const DECODE_STAGE_MASK_QUADLET = 3
const DECODE_STAGE_DATA_BUFFER = 4
const DECODE_STAGE_END_FRAME = 5
const createFrameDecoder = (frameLengthLimit) => {
const { pushFrag, tryGetRefragBuffer } = createBufferRefragPool()
let mergedBuffer = null
let stage = DECODE_STAGE_INITIAL_OCTET
let decodedIsMask = false
let decodedMaskQuadletBuffer = null
let decodedIsFIN = false
let decodedDataType = null
let decodedDataBuffer = null
let decodedDataBufferLength = 0
const decode = () => {
__DEV__ && console.log('decode', { stage })
switch (stage) {
case DECODE_STAGE_INITIAL_OCTET:
if ((mergedBuffer = tryGetRefragBuffer(2))) {
const initialQuadlet = mergedBuffer.readUInt16BE(0)
const quadbitFIN = (initialQuadlet >>> 12) & 0b1000
const quadbitOpcode = (initialQuadlet >>> 8) & 0b1111
const initialLength = initialQuadlet & 0b01111111
decodedIsMask = ((initialQuadlet & 0b10000000) !== 0)
decodedIsFIN = (quadbitFIN === 0b1000)
decodedDataType = quadbitOpcode
if (initialLength === 0) {
decodedDataBufferLength = 0
stage = decodedIsMask ? DECODE_STAGE_MASK_QUADLET : DECODE_STAGE_END_FRAME // complete, a 16bit frame
} else if (initialLength <= 125) {
decodedDataBufferLength = initialLength
if (decodedDataBufferLength > frameLengthLimit) throw new Error(`dataBuffer length ${decodedDataBufferLength} exceeds limit: ${frameLengthLimit}`)
stage = decodedIsMask ? DECODE_STAGE_MASK_QUADLET : DECODE_STAGE_DATA_BUFFER
} else if (initialLength === 126) stage = DECODE_STAGE_EXTEND_DATA_LENGTH_2
else stage = DECODE_STAGE_EXTEND_DATA_LENGTH_8
// __DEV__ && console.log('[DECODE_STAGE_INITIAL_OCTET]', { quadbitFIN, quadbitOpcode, initialLength })
return true
}
break
case DECODE_STAGE_EXTEND_DATA_LENGTH_2:
if ((mergedBuffer = tryGetRefragBuffer(2))) {
decodedDataBufferLength = mergedBuffer.readUInt16BE(0)
if (decodedDataBufferLength > frameLengthLimit) throw new Error(`dataBuffer length ${decodedDataBufferLength} exceeds limit: ${frameLengthLimit}`)
stage = decodedIsMask ? DECODE_STAGE_MASK_QUADLET : DECODE_STAGE_DATA_BUFFER
// __DEV__ && console.log('[DECODE_STAGE_EXTEND_DATA_LENGTH_2]', { decodedDataBufferLength })
return true
}
break
case DECODE_STAGE_EXTEND_DATA_LENGTH_8:
if ((mergedBuffer = tryGetRefragBuffer(8))) {
decodedDataBufferLength = mergedBuffer.readUInt32BE(0) * 0x100000000 + mergedBuffer.readUInt32BE(4)
if (decodedDataBufferLength > BUFFER_MAX_LENGTH) throw new Error('decodedDataBufferLength too big')
if (decodedDataBufferLength > frameLengthLimit) throw new Error(`dataBuffer length ${decodedDataBufferLength} exceeds limit: ${frameLengthLimit}`)
stage = decodedIsMask ? DECODE_STAGE_MASK_QUADLET : DECODE_STAGE_DATA_BUFFER
// __DEV__ && console.log('[DECODE_STAGE_EXTEND_DATA_LENGTH_8]', { decodedDataBufferLength })
return true
}
break
case DECODE_STAGE_MASK_QUADLET:
if ((mergedBuffer = tryGetRefragBuffer(4))) {
decodedMaskQuadletBuffer = mergedBuffer
stage = decodedDataBufferLength ? DECODE_STAGE_DATA_BUFFER : DECODE_STAGE_END_FRAME
// __DEV__ && console.log('[DECODE_STAGE_MASK_QUADLET]', { decodedMaskQuadletBuffer })
return true
}
break
case DECODE_STAGE_DATA_BUFFER:
if ((mergedBuffer = tryGetRefragBuffer(decodedDataBufferLength))) {
decodedDataBuffer = mergedBuffer
decodedIsMask && applyMaskQuadletBufferInPlace(decodedDataBuffer, decodedMaskQuadletBuffer)
stage = DECODE_STAGE_END_FRAME
// __DEV__ && console.log('[DECODE_STAGE_DATA_BUFFER]', { decodedDataBuffer }, String(decodedDataBuffer))
return true
}
break
}
return false // no parse-able buffer
}
const resetDecode = () => {
stage = DECODE_STAGE_INITIAL_OCTET
decodedIsMask = false
decodedMaskQuadletBuffer = null
decodedIsFIN = false
decodedDataType = null
decodedDataBuffer = null
decodedDataBufferLength = 0
}
const tryGetDecodedFrame = () => stage !== DECODE_STAGE_END_FRAME
? undefined
: {
isFIN: decodedIsFIN,
dataType: decodedDataType,
dataBuffer: decodedDataBuffer,
dataBufferLength: decodedDataBufferLength
}
return {
pushFrag,
decode,
resetDecode,
tryGetDecodedFrame
}
}
export { // TODO: DEPRECATE: use `node/server/WS`
createFrameReceiverStore,
listenAndReceiveFrame
}
|
var _ = require('underscore')._;
var Redobl = require('./redobl').Redobl;
var ZSet = exports.ZSet = function() {
}
// Alias...
var SortedSet = exports.SortedSet = ZSet;
Redobl.addClass('zset', ZSet);
Redobl.addClass('sortedset', ZSet);
ZSet.define = function(name, config, proto) {
// The name argument is optional.
if (typeof name !== 'string') {
proto = config; config = name;
name = config.name;
}
if (! config) { config = {}; }
config.name = name;
config.type = 'zset';
return Redobl.define(config, proto);
};
ZSet.prototype = _.extend(new Redobl(), {
});
ZSet.classMethods = _.extend(_.clone(Redobl.classMethods), {
_setup: function(comps) {
// Initialize serialization of a class...
if (comps.of) {
this.serializer = Redobl.of_serializer(comps.of);
}
}
});
// And associate these classMethods with the class.
_.extend(ZSet, ZSet.classMethods);
// Define the mediated functions for this class.
(function(options) {
for (var name in options) {
var opts = options[name];
ZSet.define_client_func(name, options[name]);
}
})({
length: {rfunc: 'zcard'},
add: {rfunc: 'zadd', serialize: [0]},
remove: {rfunc: 'zrem', serialize: true},
rank: {rfunc: 'zrank', serialize: true},
revrank: {rfunc: 'zrevrank', serialize: true},
range: {rfunc: 'zrange', deserialize: true},
revrange: {rfunc: 'zrevrange', deserialize: true},
rangebyscore: {rfunc: 'zrangebyscore', deserialize: true},
count: {rfunc: 'zcount'},
score: {rfunc: 'zscore', serialize: true},
remrangebyrank: {rfunc: 'remrangebyrank'},
remrangebyscore: {rfunc: 'remrangebyscore'}
});
|
'use strict';
var gulp = tars.packages.gulp;
var gutil = tars.packages.gutil;
var gulpif = tars.packages.gulpif;
var concat = tars.packages.concat;
var sass = tars.packages.sass;
var autoprefixer = tars.packages.autoprefixer;
tars.packages.promisePolyfill.polyfill();
var postcss = tars.packages.postcss;
var replace = tars.packages.replace;
var sourcemaps = tars.packages.sourcemaps;
var plumber = tars.packages.plumber;
var importify = tars.packages.importify;
var notifier = tars.helpers.notifier;
var browserSync = tars.packages.browserSync;
var bowerFiles = tars.packages.bowerFiles();
var addStream = tars.packages.addStream;
var postcssProcessors = tars.config.postcss;
var scssFolderPath = './markup/' + tars.config.fs.staticFolderName + '/scss';
var patterns = [];
var processors = [];
var processorsIE9 = [];
var generateSourceMaps = tars.config.sourcemaps.css.active && !tars.flags.release && !tars.flags.min;
var sourceMapsDest = tars.config.sourcemaps.css.inline ? '' : '.';
if (postcssProcessors && postcssProcessors.length) {
postcssProcessors.forEach(function (processor) {
processors.push(require(processor.name)(processor.options));
processorsIE9.push(require(processor.name)(processor.options));
});
}
processorsIE9.push(autoprefixer({browsers: ['ie 9']}));
if (tars.config.autoprefixerConfig) {
processors.push(
autoprefixer({browsers: tars.config.autoprefixerConfig})
);
}
var scssFilesToConcatinate = [
scssFolderPath + '/normalize.{scss,sass}',
scssFolderPath + '/libraries/**/*.{scss,sass,css}',
scssFolderPath + '/mixins.{scss,sass}',
scssFolderPath + '/sprites-scss/sprite_96.{scss,sass}'
];
var scssFilesToConcatinateForIe9;
var dependencies = bowerFiles.ext('css').files;
//scssFilesToConcatinate = scssFilesToConcatinate.concat(dependencies);
if (tars.config.useSVG) {
scssFilesToConcatinate.push(
scssFolderPath + '/sprites-scss/svg-sprite.{scss,sass}'
);
}
scssFilesToConcatinate.push(
scssFolderPath + '/fonts.{scss,sass}',
scssFolderPath + '/vars.{scss,sass}',
scssFolderPath + '/GUI.{scss,sass}',
scssFolderPath + '/common.{scss,sass,css}',
scssFolderPath + '/plugins/**/*.{scss,sass,css}',
'./markup/modules/*/*.{scss,sass}',
'!./**/_*.{scss,sass,css}'
);
scssFilesToConcatinateForIe9 = scssFilesToConcatinate.slice();
scssFilesToConcatinate.push(scssFolderPath + '/etc/**/*.{scss,sass,css}');
scssFilesToConcatinateForIe9.push(
'./markup/modules/*/ie/ie9.{scss,sass}',
scssFolderPath + '/etc/**/*.{scss,sass,css}'
);
patterns.push(
{
match: '%=staticPrefixForCss=%',
replacement: tars.config.staticPrefixForCss()
}
);
/**
* Scss compilation
*/
module.exports = function () {
return gulp.task('css:compile-css', function () {
var mainStream = gulp.src(scssFilesToConcatinate, { base: process.cwd() });
var ie9Stream = gulp.src(scssFilesToConcatinateForIe9, { base: process.cwd() });
if (tars.flags.ie9 || tars.flags.ie) {
ie9Stream
.pipe(plumber({
errorHandler: function (error) {
notifier.error('An error occurred while compiling css for IE9.', error);
this.emit('end');
}
}))
.pipe(importify('main_ie9.scss', {
cssPreproc: 'scss'
}))
.pipe(sass({
outputStyle: 'expanded',
includePaths: process.cwd()
}))
.pipe(replace({
patterns: patterns,
usePrefix: false
}))
.pipe(postcss(processorsIE9))
.pipe(concat('main_ie9' + tars.options.build.hash + '.css'))
.pipe(gulp.dest('./dev/' + tars.config.fs.staticFolderName + '/css/'))
.pipe(browserSync.reload({ stream: true }))
.pipe(
notifier.success('Scss-files for IE9 have been compiled')
);
}
return mainStream
.pipe(gulpif(generateSourceMaps, sourcemaps.init()))
.pipe(plumber({
errorHandler: function (error) {
notifier.error('An error occurred while compressing css.', error);
this.emit('end');
}
}))
.pipe(importify('main.scss', {
cssPreproc: 'scss'
}))
.pipe(sass({
outputStyle: 'expanded',
includePaths: process.cwd()
}))
.pipe(replace({
patterns: patterns,
usePrefix: false
}))
.pipe(postcss(processors))
.pipe(addStream.obj(gulp.src(dependencies)))
.pipe(concat('main' + tars.options.build.hash + '.css'))
.pipe(gulpif(generateSourceMaps, sourcemaps.write(sourceMapsDest)))
.pipe(gulp.dest('./dev/' + tars.config.fs.staticFolderName + '/css/'))
.pipe(browserSync.reload({ stream: true }))
.pipe(
notifier.success('Scss-files\'ve been compiled')
);
});
};
|
import Component from 'react-pure-render/component';
import React from 'react-native';
import {connect} from 'react-redux';
// yahoo/react-intl still does not support React Native, but we can use format.
// https://github.com/yahoo/react-intl/issues/119
import {format} from '../../common/intl/format';
const {
PropTypes, StyleSheet, Text, View
} = React;
const styles = StyleSheet.create({
container: {
alignItems: 'center',
backgroundColor: '#31AACC',
justifyContent: 'center',
marginTop: -5,
paddingBottom: 20,
paddingTop: 10
},
header: {
color: '#fff',
fontSize: 20,
}
});
class Header extends Component {
static propTypes = {
msg: PropTypes.object.isRequired,
todos: PropTypes.object.isRequired
};
render() {
const {msg, todos} = this.props;
const leftTodos = todos.filter(todo => !todo.completed).size;
return (
<View style={styles.container}>
<Text style={styles.header}>
{(format(msg.leftList, {size: leftTodos}))}
</Text>
</View>
);
}
}
export default connect(state => ({
msg: state.intl.msg.todos,
todos: state.todos.map
}))(Header);
|
import AppDispatcher from '../../scripts/dispatcher/appDispatcher';
import { ActionConstants as Constants } from '../../scripts/constants/constants';
import { EventEmitter } from 'events';
// Define the store as an empty array
let _store = {
rawText : "Paste JSON here",
parsedJson : {},
jsonNode : {childList : []},
};
class JsonStoreClass extends EventEmitter{
addChangeListener(cb) {
this.on(Constants.CHANGE_EVENT, cb);
}
removeChangeListener(cb) {
this.removeListener(Constants.CHANGE_EVENT, cb);
}
getRawText() {
return _store.rawText;
}
getParsedJson() {
return _store.parsedJson;
}
getJsonNode() {
return _store.jsonNode;
}
}
const JsonStore = new JsonStoreClass();
// Register each of the actions with the dispatcher
// by changing the store's data and emitting a
// change
AppDispatcher.register(function(payload) {
var action = payload.action;
switch(action.actionType) {
case Constants.NEW_JSON:
// Add the data defined in the TodoActions
// which the View will pass as a payload
_store.rawText = payload.action.rawText();
_store.parsedJson = payload.action.parseRawText();
JsonStore.emit(Constants.CHANGE_EVENT);
break;
case Constants.INSPECT_JSON:
// Add the data defined in the TodoActions
// which the View will pass as a payload
_store.jsonNode = payload.action.jsonNode();
JsonStore.emit(Constants.CHANGE_EVENT);
break;
default:
return true;
}
});
export default JsonStore; |
/**
* Created by Shawn Liu on 2014/11/10.
*/
var path = require("path");
process.env.NODE_CONFIG_DIR = path.join(__dirname, "../../config");
var logger = require("../../lib/log").getLogger("test/lib/log.test.js");
describe("Test lib/log.js",function(){
it("output log levels",function(done){
logger.debug("this is debug level");
logger.info("This is info level");
logger.warn("This is warning level");
logger.error("This is error level");
logger.fatal("This is fatal level");
done();
});
it("replace console by log4js",function(done){
console.log("This is console info");
done()
})
}) |
define(['exports'], function(exports) {
// we are using a static instance to avoid unnecessary Function#bind and also
// to avoid extra closures. less == more
var _queue = [];
var _willFlush = false;
var nextTick = window.requestAnimationFrame || window.setTimeout;
// ---
exports.push = push;
function push(task) {
var shouldPush = true;
task.pending = true;
// we override old actions for same element (only if it wasn't executed yet)
var item, i = -1, n = _queue.length;
while (++i < n) {
item = _queue[i];
if (item.element === task.element && item.id === task.id && item.pending) {
_queue[i] = task;
shouldPush = false;
break;
}
}
if (shouldPush) {
_queue.push(task);
}
if (!_willFlush) {
_willFlush = true;
nextTick(flush);
}
}
exports.flush = flush;
function flush() {
// TODO: throttle this loop, it should not block thread for too long
var task, i = 0;
while ((task = _queue[i++])) {
if (task.pending) {
task.execute(task.arg || task);
task.pending = false;
}
}
reset();
}
exports.reset = reset;
function reset() {
_queue = [];
_willFlush = false;
}
exports.cancel = cancel;
function cancel(group) {
var task, i = 0;
while ((task = _queue[i++])) {
if (task.group === group) {
task.pending = false;
}
}
}
});
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const online = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
socket: String,
createdAt: {
type: Date,
default: Date.now()
}
})
online.statics.findOneOnline = function (op) {
return new Promise((resolve,reject) => {
this.find(op,(err,rows) => {
if(err) reject(err);
resolve(rows[0]);
})
})
}
online.statics.findAll = function (op = {}) {
return new Promise((resolve,reject) => {
this.find(op,(err,rows) => {
if(err) reject(err);
resolve(rows);
})
})
}
online.statics.removeAll = function () {
return new Promise((resolve,reject) => {
this.remove({},function (err) {
if(err) reject(err);
resolve(null);
})
})
}
online.statics.removeOnline = function (op) {
return new Promise((resolve,reject) => {
this.remove(op,function (err,resault) {
if(err) reject(err);
resolve(resault);
})
})
}
online.statics.createOnline = function (user) {
return new Promise((resolve,reject) => {
this.create(user, (err,resault) => {
if(err) reject(err);
resolve(resault);
})
})
}
online.statics.updateAvatar = function (info) {
return new Promise((resolve,reject) => {
this.update({nickname:info.nickname},{avatar:info.avatar}, (err,resault)=>{
if(err) reject(err);
resolve(resault);
})
})
}
module.exports = mongoose.model('online',online);
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.remotipart
// Note: Foundation 5 won't work with turbolinks
//= require foundation/foundation
//= require foundation/foundation.offcanvas
//= require foundation/foundation.alert
//= require_tree .
//initialize Foundation framework
$(function() {
$(document).foundation();
});
|
$(document).ready(function() {
var data = {};
$('.examine').click( function() {
console.log(data);
});
$('#testform').render({
ifaces: ['viewform'],
data: data,
form: {
widgets: [
{
ifaces: ['repeatingField'],
name: 'repeating',
title: 'Repeating',
widgets: [{
ifaces: ['integerField'],
name: 'b',
title: 'B'
},{
ifaces: ['textlineField'],
name: 'c',
title: 'C'
}]
}
]
}
});
});
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2021 https://www.igorski.nl
*
* 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.
*/
import zMIDI from "./src/zMIDI";
import zMIDIEvent from "./src/zMIDIEvent";
import MIDINotes from "./src/MIDINotes";
/**
* expose the separate actors of
* the zMIDI library
*/
export {
zMIDI, zMIDIEvent, MIDINotes
};
|
//broken chord 4
__().gain({id:"main"}).overdrive().overdrive().overdrive().dac(1);
for(var z=0;z<16;z++) {
var v = Math.floor(z/4)+1;
var p = {v1:-1,v2:1,v3:-1/2,v4:1/2};
__().sine({id:"s"+z}).gain({class:"v"+v}).panner(p["v"+v]).connect("#main");
}
__().sine(120).lowpass({q:200,frequency:60}).adsr(1/16).gain({id:"kick"}).connect("#main");
/////////////////////////////
var throttle = __.throttle_factory(4);
var chord = [0,4,7,10,12];
var chord2 = [0,4,7,10,12];
var chord3 = [0,4,7,10,12];
var chord4 = [0,4,7,10,12]
var step = 0;
__("gain").volume(0);
__("#main,#kick").volume(1);
__(".v1,.v2,.v3,.v4").volume(1/20);
__.loop({interval:75,steps:16},function(idx,data) {
/////////////////////////////
if(data > 1) {
var p = __.array_next(chord,0,0,function(){
if(throttle()) {
//step = __.array_next(progression,0,0);
}
});
for(var i=0;i<chord.length;i++) {
__("#s"+i).frequency(__.pitch2freq(p+i*12+48+step));
}
__("adsr").adsr("trigger");
}
/////////////////////////////
if(data) {
var p2 = __.array_next(chord2,0,0);
for(var y=0;y<chord2.length;y++) {
__("#s"+(y+5)).frequency(__.pitch2freq(p2+y*12+36+step));
}
//__("adsr").adsr("trigger");
}
/////////////////////////////
if(data > 2) {
var p3 = __.array_next(chord3,0,0,function(){
if(throttle()) {
//step = __.array_next(progression,0,0);
}
});
for(var i=0;i<chord3.length;i++) {
__("#s"+(i+10)).frequency(__.pitch2freq(p3+i*12+24+step));
}
}
/////////////////////////////
var p4 = __.array_next(chord4,0,0);
for(var y=0;y<chord2.length;y++) {
__("#s"+(y+15)).frequency(__.pitch2freq(p4+y*12+84+step));
}
},[3,0,1,0,2,0,1,0,2,0,1,0,2,0,1,0]);
__.loop("start");
__.play();
|
// This is where any explicit script odering should
// be declared.
module.exports = {
app: [
'./src/app.js',
'./src/**/!(init.js).js',
'./src/init.js'
],
vendor: []
};
|
///<reference path="../main.js">
/**
* Copyright 2016 Select Interactive, LLC. All rights reserved.
* @author: The Select Interactive dev team (www.select-interactive.com)
*/
(function( doc ) {
'use strict';
app.obj = function() {
};
app.obj.prototype = {
};
}( document ) ); |
(function() {
'use strict';
angular.module('LibraryBoxApp').filter('startFrom', [
function() {
return function(input, start) {
if (!input) {
return [];
}
start = +start;
return input.slice(start);
};
}
]);
}).call(this);
|
this.NesDb = this.NesDb || {};
NesDb[ '1128ED677399F969E25D9453320B85EF3D3BA35A' ] = {
"$": {
"name": "Mahjong",
"altname": "麻雀",
"class": "Licensed",
"catalog": "HVC-MJ",
"publisher": "Nintendo",
"developer": "Nintendo",
"region": "Japan",
"players": "1",
"date": "1983-08-27"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"revision": "B",
"crc": "23D91BC6",
"sha1": "1128ED677399F969E25D9453320B85EF3D3BA35A",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2009-11-03"
},
"board": [
{
"$": {
"type": "HVC-NROM-128",
"pcb": "2I",
"mapper": "0"
},
"prg": [
{
"$": {
"size": "16k",
"crc": "F86D8D8A",
"sha1": "2904137A030AE2370A8CD3E068078A1D59A4F229"
}
}
],
"chr": [
{
"$": {
"size": "8k",
"crc": "6BB45576",
"sha1": "5974787496DFA27A4B7FE6023473FAE930EA41DC"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
},
{
"$": {
"system": "Famicom",
"revision": "B",
"crc": "23D91BC6",
"sha1": "1128ED677399F969E25D9453320B85EF3D3BA35A",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-04-28"
},
"board": [
{
"$": {
"type": "HVC-NROM-128",
"pcb": "9011-04",
"mapper": "0"
},
"prg": [
{
"$": {
"size": "16k",
"crc": "F86D8D8A",
"sha1": "2904137A030AE2370A8CD3E068078A1D59A4F229"
}
}
],
"chr": [
{
"$": {
"size": "8k",
"crc": "6BB45576",
"sha1": "5974787496DFA27A4B7FE6023473FAE930EA41DC"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
}
]
};
|
"use strict"
import { Emitter, CompositeDisposable } from "atom"
import MinimapElement from "./minimap-element"
import Minimap from "./minimap"
import * as config from "./config.json"
import * as PluginManagement from "./plugin-management"
import { treeSitterWarning } from "./performance-monitor"
import { StyleReader } from "atom-ide-base/commons-ui/dom-style-reader"
import { debounce } from "./deps/underscore-plus"
export * as config from "./config.json"
export * from "./plugin-management"
export { default as Minimap } from "./minimap"
export { default as MinimapElement } from "./minimap-element"
/**
* The `Minimap` package provides an eagle-eye view of text buffers.
*
* It also provides API for plugin packages that want to interact with the minimap and be available to the user through
* the minimap settings.
*/
/**
* The activation state of the package.
*
* @type {boolean}
* @access private
*/
let active = false
/**
* The toggle state of the package.
*
* @type {boolean}
* @access private
*/
let toggled = false
/**
* The `Map` where Minimap instances are stored with the text editor they target as key.
*
* @type {Map}
* @access private
*/
export let editorsMinimaps = null
/**
* The composite disposable that stores the package's subscriptions.
*
* @type {CompositeDisposable}
* @access private
*/
let subscriptions = null
/**
* The disposable that stores the package's commands subscription.
*
* @type {Disposable}
* @access private
*/
let subscriptionsOfCommands = null
/**
* The package's events emitter.
*
* @type {Emitter}
* @access private
*/
export const emitter = new Emitter()
/** StyleReader cache used for storing token colors */
export let styleReader = null
/** Activates the minimap package. */
export function activate() {
if (active) {
return
}
subscriptionsOfCommands = atom.commands.add("atom-workspace", {
"minimap:toggle": () => {
toggle()
},
"minimap:generate-coffee-plugin": async () => {
await generatePlugin("coffee")
},
"minimap:generate-javascript-plugin": async () => {
await generatePlugin("javascript")
},
"minimap:generate-babel-plugin": async () => {
await generatePlugin("babel")
},
})
editorsMinimaps = new Map()
styleReader = new StyleReader()
subscriptions = new CompositeDisposable()
active = true
if (atom.config.get("minimap.autoToggle")) {
toggle()
}
}
/**
* Returns a {MinimapElement} for the passed-in model if it's a {Minimap}.
*
* @param {Minimap} model The model for which returning a view
* @returns {MinimapElement}
*/
export function minimapViewProvider(model) {
if (model instanceof Minimap) {
let element = model.getMinimapElement()
if (!element) {
element = new MinimapElement()
element.setModel(model)
}
return element
}
}
/** Deactivates the minimap package. */
export function deactivate() {
if (!active) {
return
}
PluginManagement.deactivateAllPlugins()
if (editorsMinimaps) {
editorsMinimaps.forEach((value) => {
value.destroy()
})
editorsMinimaps.clear()
}
subscriptions.dispose()
subscriptionsOfCommands.dispose()
styleReader.invalidateDOMStylesCache()
toggled = false
active = false
}
export function getConfigSchema() {
return config || atom.packages.getLoadedPackage("minimap").metadata.configSchema
}
/** Toggles the minimap display. */
export function toggle() {
if (!active) {
return
}
if (toggled) {
toggled = false
if (editorsMinimaps) {
editorsMinimaps.forEach((minimap) => {
minimap.destroy()
})
editorsMinimaps.clear()
}
subscriptions.dispose()
// HACK: this hack forces rerendering editor size which moves the scrollbar to the right once minimap is removed
const wasMaximized = atom.isMaximized()
const { width, height } = atom.getSize()
atom.setSize(width, height)
if (wasMaximized) {
atom.maximize()
}
} else {
toggled = true
initSubscriptions()
}
styleReader.invalidateDOMStylesCache()
}
/**
* Opens the plugin generation view.
*
* @param {string} template The name of the template to use
*/
async function generatePlugin(template) {
const { default: MinimapPluginGeneratorElement } = await import("./minimap-plugin-generator-element")
const view = new MinimapPluginGeneratorElement()
view.template = template
view.attach()
}
/**
* Registers a callback to listen to the `did-activate` event of the package.
*
* @param {function(event:Object):void} callback The callback function
* @returns {Disposable} A disposable to stop listening to the event
*/
export function onDidActivate(callback) {
return emitter.on("did-activate", callback)
}
/**
* Registers a callback to listen to the `did-deactivate` event of the package.
*
* @param {function(event:Object):void} callback The callback function
* @returns {Disposable} A disposable to stop listening to the event
*/
export function onDidDeactivate(callback) {
return emitter.on("did-deactivate", callback)
}
/**
* Registers a callback to listen to the `did-create-minimap` event of the package.
*
* @param {function(event:Object):void} callback The callback function
* @returns {Disposable} A disposable to stop listening to the event
*/
export function onDidCreateMinimap(callback) {
return emitter.on("did-create-minimap", callback)
}
/**
* Registers a callback to listen to the `did-add-plugin` event of the package.
*
* @param {function(event:Object):void} callback The callback function
* @returns {Disposable} A disposable to stop listening to the event
*/
export function onDidAddPlugin(callback) {
return emitter.on("did-add-plugin", callback)
}
/**
* Registers a callback to listen to the `did-remove-plugin` event of the package.
*
* @param {function(event:Object):void} callback The callback function
* @returns {Disposable} A disposable to stop listening to the event
*/
export function onDidRemovePlugin(callback) {
return emitter.on("did-remove-plugin", callback)
}
/**
* Registers a callback to listen to the `did-activate-plugin` event of the package.
*
* @param {function(event:Object):void} callback The callback function
* @returns {Disposable} A disposable to stop listening to the event
*/
export function onDidActivatePlugin(callback) {
return emitter.on("did-activate-plugin", callback)
}
/**
* Registers a callback to listen to the `did-deactivate-plugin` event of the package.
*
* @param {function(event:Object):void} callback The callback function
* @returns {Disposable} A disposable to stop listening to the event
*/
export function onDidDeactivatePlugin(callback) {
return emitter.on("did-deactivate-plugin", callback)
}
/**
* Registers a callback to listen to the `did-change-plugin-order` event of the package.
*
* @param {function(event:Object):void} callback The callback function
* @returns {Disposable} A disposable to stop listening to the event
*/
export function onDidChangePluginOrder(callback) {
return emitter.on("did-change-plugin-order", callback)
}
/**
* Returns the `Minimap` class
*
* @returns {Function} The `Minimap` class constructor
*/
export function minimapClass() {
return Minimap
}
/**
* Returns the `Minimap` object associated to the passed-in `TextEditorElement`.
*
* @param {TextEditorElement} editorElement A text editor element
* @returns {Minimap} The associated minimap
*/
export function minimapForEditorElement(editorElement) {
if (!editorElement) {
return
}
return minimapForEditor(editorElement.getModel())
}
/**
* Returns the `Minimap` object associated to the passed-in `TextEditor`.
*
* @param {TextEditor} textEditor A text editor
* @returns {Minimap} The associated minimap
*/
export function minimapForEditor(textEditor) {
if (!textEditor) {
return
}
if (!editorsMinimaps) {
return
}
let minimap = editorsMinimaps.get(textEditor)
if (minimap === undefined || minimap.destroyed) {
minimap = new Minimap({ textEditor })
editorsMinimaps.set(textEditor, minimap)
const editorSubscription = textEditor.onDidDestroy(() => {
if (editorsMinimaps) {
editorsMinimaps.delete(textEditor)
}
if (minimap) {
// just in case
minimap.destroy()
}
editorSubscription.dispose()
})
// dispose the editorSubscription if minimap is deactivated before destroying the editor
subscriptions.add(editorSubscription)
}
return minimap
}
/**
* Returns a new stand-alone {Minimap} for the passed-in `TextEditor`.
*
* @param {TextEditor} textEditor A text editor instance to create a minimap for
* @returns {Minimap} A new stand-alone Minimap for the passed-in editor
*/
export function standAloneMinimapForEditor(textEditor) {
if (!textEditor) {
return
}
return new Minimap({
textEditor,
standAlone: true,
})
}
/**
* Returns the `Minimap` associated to the active `TextEditor`.
*
* @returns {Minimap} The active Minimap
*/
export function getActiveMinimap() {
return minimapForEditor(atom.workspace.getActiveTextEditor())
}
/**
* Calls a function for each present and future minimaps.
*
* @param {function(minimap:Minimap):void} iterator A function to call with the existing and future minimaps
* @returns {Disposable} A disposable to unregister the observer
*/
export function observeMinimaps(iterator) {
if (!iterator) {
return
}
if (editorsMinimaps) {
editorsMinimaps.forEach((minimap) => {
iterator(minimap)
})
}
return onDidCreateMinimap((minimap) => {
iterator(minimap)
})
}
/**
* Registers to the `observeTextEditors` method.
*
* @access private
*/
function initSubscriptions() {
const debounceUpdateStyles = debounce(updateStyles, 300)
subscriptions.add(
atom.workspace.observeTextEditors((textEditor) => {
const minimap = minimapForEditor(textEditor)
const minimapElement = minimapViewProvider(minimap)
emitter.emit("did-create-minimap", minimap)
minimapElement.attach(textEditor.getElement())
}),
// empty color cache if the theme changes
atom.themes.onDidChangeActiveThemes(debounceUpdateStyles),
atom.styles.onDidUpdateStyleElement(debounceUpdateStyles),
atom.styles.onDidAddStyleElement(debounceUpdateStyles),
atom.styles.onDidRemoveStyleElement(debounceUpdateStyles),
treeSitterWarning()
)
}
/** Force update styles of minimap */
function updateStyles() {
styleReader.invalidateDOMStylesCache()
editorsMinimaps.forEach((minimap) => {
atom.views.getView(minimap).requestForcedUpdate()
})
}
// The public exports included in the service:
const MinimapServiceV1 = {
minimapViewProvider,
getConfigSchema,
onDidActivate,
onDidDeactivate,
onDidCreateMinimap,
onDidAddPlugin,
onDidRemovePlugin,
onDidActivatePlugin,
onDidDeactivatePlugin,
onDidChangePluginOrder,
minimapClass,
minimapForEditorElement,
minimapForEditor,
standAloneMinimapForEditor,
getActiveMinimap,
observeMinimaps,
registerPlugin: PluginManagement.registerPlugin,
unregisterPlugin: PluginManagement.unregisterPlugin,
togglePluginActivation: PluginManagement.togglePluginActivation,
deactivateAllPlugins: PluginManagement.deactivateAllPlugins,
activatePlugin: PluginManagement.activatePlugin,
deactivatePlugin: PluginManagement.deactivatePlugin,
getPluginsOrder: PluginManagement.getPluginsOrder,
}
/**
* Returns the Minimap main module instance.
*
* @returns {Main} The Minimap main module instance.
*/
export function provideMinimapServiceV1() {
return MinimapServiceV1
}
|
/**
* @Author: Matteo Zambon <Matteo>
* @Date: 2017-04-13 06:55:18
* @Last modified by: Matteo
* @Last modified time: 2017-07-30 01:06:47
*/
'use strict'
const faker = require('faker')
const objectPath = require('object-path')
const inflect = require('i')()
const Service = require('trails/service')
let modelMap = []
const modelRelations = {}
const modelPopulates = {}
const cachedModels = {}
let standardBasePath = ''
let passportBasePath = ''
/**
* @module SwaggerService
* @description Service to generate Swagger documentation
*/
module.exports = class SwaggerService extends Service {
// Example
extractExampleDirective (propertyExample) {
const directive = {}
// Clean Example
let propertyExampleClean = propertyExample.replace(/^{{|}}$/g, '')
// Check if there's any after
if (propertyExampleClean.match(/\|.*$/)) {
directive.after = propertyExampleClean.split('|')
directive.after.shift()
propertyExampleClean = propertyExampleClean.replace(/\|.*$/, '')
}
// Check if it's a self
if (propertyExampleClean.match(/^self\./)) {
directive.self = propertyExampleClean.replace(/^self\./, '')
}
// Check if it's a model
else if (propertyExampleClean.match(/^model\.[a-zA-Z]/)) {
const modelName = propertyExampleClean.replace(/^model\./, '')
directive.model = modelName
}
// Faker
else {
const directiveFaker = propertyExampleClean.split('.')
if (directiveFaker.length === 2 &&
faker[directiveFaker[0]] &&
typeof faker[directiveFaker[0]][directiveFaker[1]] === 'function') {
directive.faker = faker[directiveFaker[0]][directiveFaker[1]]()
}
else {
directive.faker = faker.fake(propertyExample)
}
}
return directive
}
genPropertyExample (propertyExample, modelExample, withRel) {
let example = null
if (typeof propertyExample === 'string') {
const directive = this.extractExampleDirective(propertyExample)
if (directive.faker) {
example = directive.faker
}
else if (directive.self) {
if (objectPath.has(modelExample, directive.self)) {
example = objectPath.get(modelExample, directive.self)
}
else {
return null
}
}
else if (directive.model && !withRel) {
return null
}
else if (directive.model && withRel) {
if (!cachedModels[directive.model]) {
cachedModels[directive.model] = this.getModelExample(
this.app.api.models[directive.model],
false
)
}
example = cachedModels[directive.model]
}
if (directive.after) {
for (const directiveAfterIndex in directive.after) {
const directiveAfter = directive.after[directiveAfterIndex]
switch (directiveAfter) {
case 'int':
example = parseInt(example, 10)
break
}
}
}
return example
}
else if (Array.isArray(propertyExample)) {
example = []
for (const itemIndex in propertyExample) {
const item = propertyExample[itemIndex]
example.push(this.genPropertyExample(item, modelExample, false))
}
}
}
getModelExample(model, withRel) {
if (!model.example) {
return undefined
}
const modelExampleMap = model.example()
const modelExample = {}
for (const propertyName in modelExampleMap) {
const propertyExample = modelExampleMap[propertyName]
modelExample[propertyName] = this.genPropertyExample(propertyExample, modelExample, withRel)
}
return modelExample
}
// End Example
// Swagger Doc
getInfoTitle(config) {
if (config.swagger.title) {
return config.swagger.title
}
else {
return 'Project API'
}
}
getInfoDescription(config) {
if (config.swagger.description) {
return config.swagger.description
}
else {
return undefined
}
}
getInfoTermsOfService(config) {
if (config.swagger.termsOfService) {
return config.swagger.termsOfService
}
else {
return undefined
}
}
getInfoContact(config) {
if (config.swagger.contact) {
return config.swagger.contact
}
else {
return undefined
}
}
getInfoLicense(config) {
if (config.swagger.license) {
return config.swagger.license
}
else {
return undefined
}
}
getInfoVersion(config) {
if (config.swagger.version) {
return config.swagger.version
}
else if (config.footprints && config.footprints.prefix) {
const matches = config.footprints.prefix.match(/(^|\/)v[0-9.]+($|\/)/)
if (matches) {
return matches[0].replace(/\//g, '')
}
}
return 'v1'
}
getInfo(config) {
const info = {}
info.title = this.getInfoTitle(config)
info.description = this.getInfoDescription(config)
info.termsOfService = this.getInfoTermsOfService(config)
info.contact = this.getInfoContact(config)
info.license = this.getInfoLicense(config)
info.version = this.getInfoVersion(config)
return info
}
getBasePath(config) {
if (config.swagger.basePath) {
return config.swagger.basePath
}
else if (config.footprints && config.footprints.prefix) {
if (config.passport && config.passport.prefix) {
if (config.footprints.prefix !== config.passport.prefix) {
const footprintsPrefix = config.footprints.prefix.toLowerCase()
const passportPrefix = config.passport.prefix.toLowerCase()
standardBasePath = ''
passportBasePath = ''
let basePath = []
let path1 = footprintsPrefix.length < passportPrefix.length ?
footprintsPrefix :
passportPrefix
let path2 = footprintsPrefix.length > passportPrefix.length ?
footprintsPrefix :
passportPrefix
path1 = path1.split('/')
path2 = path2.split('/')
for (const p in path1) {
if (path1[p] === path2[p]) {
basePath.push(path1[p])
}
else {
break
}
}
basePath = basePath.join('/')
const regExp = new RegExp('^' + basePath)
standardBasePath = footprintsPrefix.replace(regExp, '')
passportBasePath = passportPrefix.replace(regExp, '')
basePath = (!basePath.match(/^\//) ? '/' : '') + basePath
standardBasePath = (!standardBasePath.match(/^\//) ? '/' : '') + standardBasePath
passportBasePath = (!passportBasePath.match(/^\//) ? '/' : '') + passportBasePath
standardBasePath = standardBasePath.replace(/\/$/, '')
passportBasePath = passportBasePath.replace(/\/$/, '')
return basePath
}
}
return config.footprints.prefix
}
else {
return '/api'
}
}
getSchemes(config) {
if (config.swagger.schemes) {
return config.swagger.schemes
}
else if (config.web && config.web.ssl) {
return [
'http',
'https'
]
}
else {
return [
'http'
]
}
}
getConsumes(config) {
return config.swagger.consumes || [
'application/json'
]
}
getProduces(config) {
return config.swagger.produces || [
'application/json'
]
}
getHost(config) {
if (config.swagger.host) {
return config.swagger.host + ':' + this.getPort(config)
}
else if (config.web && config.web.host) {
return config.web.host + ':' + this.getPort(config)
}
else {
return '0.0.0.0:' + this.getPort(config)
}
}
getPort(config) {
if (config.swagger.port) {
return config.swagger.port
}
else if (config.web && config.web.port) {
return config.web.port
}
else {
return 3000
}
}
getSecurityDefinitions(config) {
if (config.swagger.securityDefinitions) {
return config.swagger.securityDefinitions
}
else if (config.passport && config.passport.strategies && config.passport.strategies.jwt) {
return {
jwt: {
type: 'apiKey',
in: 'header',
name: 'Authorization'
}
}
}
else {
return {}
}
}
getSecurity(config) {
if (config.swagger.security) {
return config.swagger.security
}
else {
return undefined
}
}
getTags(config, doc) {
const tags = []
if (config.passport && config.passport.strategies && config.passport.strategies.jwt) {
tags.push({
'name': 'Auth'
})
}
for (const modelName in this.app.api.models) {
tags.push({
'name': modelName
})
}
tags.sort((a, b) => {
return (a.name > b.name)
})
return tags
}
getModelNameFromModelMap(modelName) {
const modelNames = modelMap.filter((el) => {
if (el.toLowerCase() === modelName.toLowerCase()) {
return el
}
})
if (modelNames.length > 0) {
return modelNames[0]
}
return 'x-any'
}
parseDefinitionModelProperty(property) {
property.type = property.type.toLowerCase()
if (property.type === 'integer') {
property.type = 'integer'
property.format = 'int32'
}
else if (property.type === 'long') {
property.type = 'integer'
property.format = 'int64'
}
else if (property.type === 'float') {
property.type = 'number'
property.format = 'float'
}
else if (property.type === 'double') {
property.type = 'number'
property.format = 'double'
}
else if (property.type === 'byte') {
property.type = 'string'
property.format = 'byte'
}
else if (property.type === 'binary') {
property.type = 'string'
property.format = 'binary'
}
else if (property.type === 'date') {
property.type = 'string'
property.format = 'date'
}
else if (property.type === 'dateTime' || property.type === 'time') {
property.type = 'string'
property.format = 'date-time'
}
else if (property.type === 'password') {
property.type = 'string'
property.format = 'password'
}
else if (property.type === 'json') {
property.type = 'object'
}
else if (property.type === 'array' && (!property.items)) {
property.items = {
'$ref': '#/definitions/x-any'
}
}
else if (!property.type.match(/^object$|^array$|^number$/)) {
property.format = property.type
property.type = 'string'
}
return property
}
getDefinitionModel(config, doc, models, modelName) {
modelRelations[modelName] = []
modelPopulates[modelName] = []
// Get Models
const model = models[modelName]
// Get Schema
const modelProperties = model.schema(this.app)
// Get Description
const modelDescription = model.description ? model.description() : {}
// Swagger Definition
const swaggerDefinition = {
type: 'object',
required: [],
description: modelDescription.model || (inflect.titleize(modelName) + ' object'),
properties: null
}
for (const propertyName in modelProperties) {
const property = modelProperties[propertyName]
let prop = {}
// Description
prop.description = modelName + ' ' + inflect.titleize(propertyName)
if (modelDescription.schema) {
prop.description = modelDescription.schema[propertyName] || prop.description
}
// Required
if (property.required) {
swaggerDefinition.required.push(propertyName)
}
// Default
if (property.defaultTo) {
if (typeof property.defaultTo !== 'function') {
prop.default = property.defaultTo
}
}
// Has Many
if (property.collection && !property.through) {
const collectionFilter = this.getModelNameFromModelMap(property.collection)
prop['type'] = 'array'
prop['items'] = {
'$ref': '#/definitions/' + inflect.camelize(collectionFilter)
}
// Add to Relations
modelRelations[modelName].push({
property: propertyName,
model: collectionFilter,
type: 'hasMany'
})
// Add to Populate
modelPopulates[modelName].push(propertyName)
}
// Has Many Through
else if (property.collection && property.through) {
const throughFilter = this.getModelNameFromModelMap(property.through)
prop['type'] = 'array'
prop['items'] = {
'$ref': '#/definitions/' + inflect.camelize(throughFilter)
}
// Add to Relations
modelRelations[modelName].push({
property: propertyName,
model: throughFilter,
type: 'hasManyThrough'
})
// Add to Populate
modelPopulates[modelName].push(propertyName)
}
// Has One / Belongs To
else if (property.model) {
const modelFilter = this.getModelNameFromModelMap(property.model)
prop['type'] = 'object'
prop['$ref'] = '#/definitions/' + inflect.camelize(modelFilter)
// Add to Relations
modelRelations[modelName].push({
'property': propertyName,
'model': modelFilter,
'type': 'hasOne'
})
// Add to Populate
modelPopulates[modelName].push(propertyName)
}
else if (Array.isArray(property.type)) {
prop.type = 'array'
}
else {
prop.type = property.type
}
prop = this.parseDefinitionModelProperty(prop)
modelProperties[propertyName] = prop
}
// Add Formatted Properties to Swagger Definition
swaggerDefinition.properties = modelProperties
if (swaggerDefinition.required.length === 0) {
swaggerDefinition.required = undefined
}
return swaggerDefinition
}
getDefinitions(config, doc) {
const definitions = {}
definitions['x-any'] = {
'properties': {}
}
const models = this.app.api.models
for (const modelName in models) {
// Add Definition to SwaggerJson
definitions[modelName] = this.getDefinitionModel(config, doc, models, modelName)
if (modelName === 'User' &&
config.passport &&
config.passport.strategies &&
config.passport.strategies.local
) {
const localStrategy = config.passport.strategies.local
let usernameField = 'username'
if (localStrategy.options && localStrategy.options.usernameField) {
usernameField = localStrategy.options.usernameField
}
const passportModelProperties = {}
passportModelProperties[usernameField] = {
type: 'string'
}
passportModelProperties['password'] = {
type: 'string',
format: 'password'
}
// Swagger Definition
definitions['UserLogin'] = {
type: 'object',
required: [
usernameField,
'password'
],
description: 'User credentials',
properties: passportModelProperties
}
definitions['UserRegister'] = definitions[modelName]
if (definitions['UserRegister'].required) {
definitions['UserRegister'].required.push('password')
}
else {
definitions['UserRegister'].required = [
usernameField,
'password'
]
}
definitions['UserRegister'].properties['password'] = passportModelProperties['password']
}
}
const responses = this.getResponses(config, doc)
for (const responseName in responses) {
definitions[responseName] = responses[responseName]
}
return definitions
}
genResponseObject(httpCode, responseName, description) {
const responseObject = {}
switch (httpCode) {
case '200':
responseObject.description = description || 'Request was successful'
if (this.app.api.models[responseName]) {
responseObject.schema = {
type: 'object',
'$ref': '#/definitions/' + responseName
}
/** Try example
const produces = this.getProduces(this.app.config)
const model = this.app.api.models[responseName]
const definitionExample = this.getModelExample(model, true)
if (definitionExample) {
responseObject.examples = {}
for (const produceIndex in produces) {
const produce = produces[produceIndex]
responseObject.examples[produce] = definitionExample
}
}
*/
}
else if (this.app.api.models[inflect.singularize(responseName)]) {
responseObject.schema = {
type: 'array',
items: {
'$ref': '#/definitions/' + inflect.singularize(responseName)
}
}
/** Try example
const produces = this.getProduces(this.app.config)
const model = this.app.api.models[inflect.singularize(responseName)]
const definitionExample = this.getModelExample(model, true)
if (definitionExample) {
responseObject.examples = {}
for (const produceIndex in produces) {
const produce = produces[produceIndex]
responseObject.examples[produce] = definitionExample
}
}
*/
}
else {
responseObject.schema = {
type: 'object',
'$ref': '#/definitions/' + (responseName || 'x-GenericSuccess')
}
}
break
case '400':
responseObject.description = description || 'Bad Request'
responseObject.schema = {
type: 'object',
'$ref': '#/definitions/' + (responseName || 'BadRequest')
}
break
case '401':
responseObject.description = description || 'Unauthorized'
responseObject.schema = {
type: 'object',
'$ref': '#/definitions/' + (responseName || 'Unauthorized')
}
break
case '404':
responseObject.description = description || 'Not Found'
responseObject.schema = {
type: 'object',
'$ref': '#/definitions/' + (responseName || 'NotFound')
}
break
case '500':
responseObject.description = description || 'Unexpected Error'
responseObject.schema = {
type: 'object',
'$ref': '#/definitions/' + (responseName || 'UnexpectedError')
}
break
}
return responseObject
}
genResponseObjects(directives) {
const responses = {}
for (const directiveIndex in directives) {
const directive = directives[directiveIndex]
const httpCode = directive[0] || '200'
const responseName = directive[1] || undefined
const description = directive[2] || undefined
const response = this.genResponseObject(httpCode, responseName, description)
responses[httpCode] = response
}
return responses
}
genResponseObjectModel(modelName, isPlural){
return this.genResponseObjects([
['200', isPlural ? inflect.pluralize(modelName) : modelName],
['400'],
['401'],
['404'],
['500']
])
}
getResponses(config, doc) {
const responses = {}
responses['x-GenericSuccess'] = {
description: 'Generic Successful Response',
properties: {}
}
if (config.passport && config.passport.strategies) {
for (const authType in config.passport.strategies) {
switch (authType) {
case 'local':
responses['PassportLocalSuccess'] = {
description: 'Successful Response',
required: [
'redirect',
'user',
'token'
],
properties: {
redirect: {
type: 'string'
},
user: {
type: 'object',
'$ref': '#/definitions/User'
},
token: {
type: 'string'
}
}
}
break
}
}
}
responses.BadRequest = {
description: 'Bad Request',
required: [
'error'
],
properties: {
'error': {
'type': 'string'
}
}
}
responses.Unauthorized = {
description: 'Unauthorized',
required: [
'error'
],
properties: {
'error': {
'type': 'string'
}
}
}
responses.NotFound = {
description: 'Not Found',
required: [
'error'
],
properties: {
'error': {
'type': 'string'
}
}
}
responses.UnexpectedError = {
description: 'Unexpected Error',
required: [
'error',
'status',
'summary'
],
properties: {
'error': {
'type': 'string'
},
'status': {
'type': 'integer',
'format': 'int32'
},
'summary': {
'type': 'string'
},
'raw': {
'type': 'object'
}
}
}
/*
const models = this.app.api.models
for (const modelName in models) {
const modelNameCamelized = inflect.camelize(modelName)
const modelNameCamelizedPluralized = inflect.pluralize(modelNameCamelized)
responses[modelNameCamelized] = {
type: 'object',
schema: {
'$ref': '#/definitions/' + modelNameCamelized
}
}
responses[modelNameCamelizedPluralized] = {
type: 'array',
items: {
'$ref': '#/definitions/' + modelNameCamelized
}
}
if (this.app.api.models[modelName]) {
const model = this.app.api.models[modelName]
const config = this.app.config
const produces = this.getProduces(config)
// Try example
const definitionExample = this.getModelExample(model, true)
if (definitionExample) {
for (const produceIndex in produces) {
const produce = produces[produceIndex]
responses[modelNameCamelized].examples[produce] = definitionExample
responses[modelNameCamelizedPluralized].examples[produce] = [definitionExample]
}
}
}
}
*/
return responses
}
getPathLocalRegister(paths, config) {
const pathItem = {}
const localStrategy = config.passport.strategies.local
let usernameField = 'username'
if (localStrategy.options && localStrategy.options.usernameField) {
usernameField = localStrategy.options.usernameField
}
pathItem.post = {}
pathItem.post.summary = 'Register a User object with ' +
usernameField +
' and password as login credentials'
pathItem.post.operationId = 'auth.localRegister'
pathItem.post.tags = [
'Auth',
'User'
]
pathItem.post.parameters = [
{
name: 'data',
in: 'body',
description: 'Data to register a new User (password field is required)',
required: true,
schema: {
description: 'User object including password',
'$ref': '#/definitions/UserRegister'
}
}
]
pathItem.post.responses = this.genResponseObjects([
['200', 'PassportLocalSuccess'],
['400']
])
paths[passportBasePath + '/auth/local/register'] = pathItem
return paths
}
getPathLocalLogin(paths, config) {
const pathItem = {}
const localStrategy = config.passport.strategies.local
let usernameField = 'username'
if (localStrategy.options && localStrategy.options.usernameField) {
usernameField = localStrategy.options.usernameField
}
pathItem.post = {}
pathItem.post.summary = 'Login a User object with ' + usernameField + ' and password'
pathItem.post.operationId = 'auth.localLogin'
pathItem.post.tags = [
'Auth',
'User'
]
pathItem.post.parameters = [
{
name: 'data',
in: 'body',
description: 'Login credentials',
required: true,
schema: {
description: 'User object including password',
'$ref': '#/definitions/UserLogin'
}
}
]
pathItem.post.responses = this.genResponseObjectModel('PassportLocalSuccess')
paths[passportBasePath + '/auth/local'] = pathItem
return paths
}
getPathLocalLogout(paths, config) {
const pathItem = {}
pathItem.get = {}
pathItem.get.summary = 'Logout a User object'
pathItem.get.operationId = 'auth.localLogout'
pathItem.get.tags = [
'Auth',
'User'
]
pathItem.get.parameters = []
pathItem.get.security = [
{
jwt: []
}
]
pathItem.get.responses = this.genResponseObjects([
['200', 'PassportLocalSuccess'],
['401']
])
paths[passportBasePath + '/auth/local/logout'] = pathItem
return paths
}
getPathDefaultLimit(config) {
let defaultLimit = 100
if (config.footprints && config.footprints.models && config.footprints.models.options &&
config.footprints.models.options.defaultLimit) {
defaultLimit = config.footprints.models.options.defaultLimit
}
return defaultLimit
}
getPathSecurity(doc, modelName) {
if (this.app.api.models[modelName].security) {
return this.app.api.models[modelName].security()
}
if (doc.security) {
return doc.security
}
if (doc.securityDefinitions) {
const pathSecurity = []
for (const securityName in doc.securityDefinitions) {
const security = {}
security[securityName] = []
pathSecurity.push(security)
}
return pathSecurity
}
return undefined
}
getModelCriteria(config, doc, modelName, keepId) {
const definition = doc.definitions[modelName]
const criterias = []
for (const propertyName in definition.properties) {
if (propertyName.match(/(populate|limit|offset)/)) {
continue
}
if (propertyName === 'id' && !keepId) {
continue
}
const property = definition.properties[propertyName]
if (property['$ref']) {
continue
}
if (property.type === 'array' && property.items['$ref']) {
continue
}
if (property.type === 'object') {
continue
}
const criteria = {
name: propertyName,
in: 'query',
description: 'Filter ' +
inflect.titleize(modelName) +
' by ' +
inflect.titleize(propertyName),
required: false,
type: property.type,
format: property.format,
items: property.items
}
criterias.push(criteria)
}
return criterias
}
getPathModel(paths, config, doc, modelName) {
const pathItem = {}
const pathId = standardBasePath + '/' + modelName.toLowerCase()
pathItem.get = {}
pathItem.get.summary = 'List all ' + inflect.titleize(inflect.pluralize(modelName))
pathItem.get.operationId = modelName + '.find'
pathItem.get.tags = [
modelName
]
pathItem.get.parameters = this.getModelCriteria(config, doc, modelName, true)
pathItem.get.parameters.push({
name: 'populate',
in: 'query',
description: 'Properties to populate (valid: ' + modelPopulates[modelName].join(', ') + ')',
required: false,
type: 'array',
items: {
type: 'string'
}
})
pathItem.get.parameters.push({
name: 'limit',
in: 'query',
description: 'Pagination size',
required: false,
type: 'integer',
format: 'int32',
default: this.getPathDefaultLimit(config)
})
pathItem.get.parameters.push({
name: 'offset',
in: 'query',
description: 'Pagination cusrsor',
required: false,
type: 'integer',
format: 'int32',
default: 0
})
pathItem.get.responses = this.genResponseObjectModel(modelName, true)
pathItem.get.security = this.getPathSecurity(doc, modelName)
pathItem.post = {}
pathItem.post.summary = 'Create a ' + inflect.titleize(inflect.pluralize(modelName))
pathItem.post.operationId = modelName + '.create'
pathItem.post.tags = [
modelName
]
pathItem.post.parameters = []
pathItem.post.parameters.push({
name: 'data',
in: 'body',
description: 'Data to create a new ' + inflect.titleize(modelName),
required: true,
schema: {
description: inflect.titleize(modelName) + ' object',
'$ref': '#/definitions/' + modelName
}
})
pathItem.post.responses = this.genResponseObjectModel(modelName)
pathItem.post.security = this.getPathSecurity(doc, modelName)
pathItem.put = {}
pathItem.put.summary = 'Update a ' + inflect.titleize(modelName)
pathItem.put.operationId = modelName + '.update'
pathItem.put.tags = [
modelName
]
pathItem.put.parameters = this.getModelCriteria(config, doc, modelName, true)
pathItem.put.parameters.push({
name: 'data',
in: 'body',
description: 'Data to create a new ' + inflect.titleize(modelName),
required: true,
schema: {
description: inflect.titleize(modelName) + ' object',
'$ref': '#/definitions/' + modelName
}
})
pathItem.put.responses = this.genResponseObjectModel(modelName)
pathItem.put.security = this.getPathSecurity(doc, modelName)
pathItem.delete = {}
pathItem.delete.summary = 'Destroy a ' + inflect.titleize(inflect.pluralize(modelName))
pathItem.delete.operationId = modelName + '.destroy'
pathItem.delete.tags = [
modelName
]
pathItem.delete.parameters = this.getModelCriteria(config, doc, modelName, true)
pathItem.delete.responses = this.genResponseObjectModel(modelName)
pathItem.delete.security = this.getPathSecurity(doc, modelName)
paths[pathId] = pathItem
return paths
}
getPathModelById(paths, config, doc, modelName) {
const pathItem = {}
const pathId = standardBasePath + '/' + modelName.toLowerCase() + '/{id}'
pathItem.get = {}
pathItem.get.summary = 'Get a ' + inflect.titleize(modelName)
pathItem.get.operationId = modelName + '.findById'
pathItem.get.tags = [
modelName
]
pathItem.get.parameters = this.getModelCriteria(config, doc, modelName)
pathItem.get.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.get.parameters.push({
name: 'populate',
in: 'query',
description: 'Properties to populate (valid: ' + modelPopulates[modelName].join(', ') + ')',
required: false,
type: 'array',
items: {
type: 'string'
}
})
pathItem.get.responses = this.genResponseObjectModel(modelName)
pathItem.get.security = this.getPathSecurity(doc, modelName)
pathItem.put = {}
pathItem.put.summary = 'Update a ' + inflect.titleize(modelName)
pathItem.put.operationId = modelName + '.updateById'
pathItem.put.tags = [
modelName
]
pathItem.put.parameters = this.getModelCriteria(config, doc, modelName)
pathItem.put.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.put.parameters.push({
name: 'data',
in: 'body',
description: 'Data to update a ' + inflect.titleize(modelName),
required: true,
schema: {
description: inflect.titleize(modelName) + ' object',
'$ref': '#/definitions/' + modelName
}
})
pathItem.put.responses = this.genResponseObjectModel(modelName)
pathItem.put.security = this.getPathSecurity(doc, modelName)
pathItem.delete = {}
pathItem.delete.summary = 'Destroy a ' + inflect.titleize(modelName)
pathItem.delete.operationId = modelName + '.destroyById'
pathItem.delete.tags = [
modelName
]
pathItem.delete.parameters = this.getModelCriteria(config, doc, modelName)
pathItem.delete.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.delete.responses = this.genResponseObjectModel(modelName)
pathItem.delete.security = this.getPathSecurity(doc, modelName)
paths[pathId] = pathItem
return paths
}
getPathModelByIdAndRelation(paths, config, doc, modelName, modelRelation) {
const pathItem = {}
const pathId = standardBasePath +
'/' +
modelName.toLowerCase() +
'/{id}/' +
modelRelation.property.toLowerCase()
pathItem.get = {}
pathItem.get.summary = 'List all ' +
inflect.titleize(inflect.pluralize(modelRelation.property)) +
' on ' +
inflect.titleize(modelRelation.model)
pathItem.get.operationId = modelName + '.find' + inflect.camelize(modelRelation.property)
pathItem.get.tags = [
modelName
]
if (modelName.toLowerCase() !== modelRelation.model.toLowerCase()) {
pathItem.get.tags.push(modelRelation.model)
}
pathItem.get.parameters = this.getModelCriteria(config, doc, modelRelation.model, true)
pathItem.get.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.get.parameters.push({
name: 'populate',
in: 'query',
description: 'Properties to populate (check populate for ' +
inflect.titleize(modelRelation.model) +
')',
required: false,
type: 'array',
items: {
type: 'string'
}
})
pathItem.get.parameters.push({
name: 'limit',
in: 'query',
description: 'Pagination size',
required: false,
type: 'integer',
format: 'int32',
default: this.getPathDefaultLimit(config)
})
pathItem.get.parameters.push({
name: 'offset',
in: 'query',
description: 'Pagination cusrsor',
required: false,
type: 'integer',
format: 'int32',
default: 0
})
pathItem.get.responses = this.genResponseObjectModel(modelRelation.model, true)
pathItem.get.security = this.getPathSecurity(doc, modelRelation.model)
pathItem.post = {}
pathItem.post.summary = 'Create a ' +
inflect.titleize(inflect.pluralize(modelRelation.property)) +
' on ' +
inflect.titleize(modelRelation.model)
pathItem.post.operationId = modelName + '.create' + inflect.camelize(modelRelation.property)
pathItem.post.tags = [
modelName
]
if (modelName.toLowerCase() !== modelRelation.model.toLowerCase()) {
pathItem.post.tags.push(modelRelation.model)
}
pathItem.post.parameters = []
pathItem.post.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.post.parameters.push({
name: 'data',
in: 'body',
description: 'Data to create a new ' + inflect.titleize(modelRelation.property),
required: true,
schema: {
description: inflect.titleize(modelRelation.property) + ' object',
'$ref': '#/definitions/' + modelRelation.model
}
})
pathItem.post.responses = this.genResponseObjectModel(modelRelation.model)
pathItem.post.security = this.getPathSecurity(doc, modelRelation.model)
pathItem.put = {}
pathItem.put.summary = 'Update a ' +
inflect.titleize(modelRelation.property) +
' on ' +
inflect.titleize(modelName)
pathItem.put.operationId = modelName + '.update' + inflect.camelize(modelRelation.property)
pathItem.put.tags = [
modelName
]
if (modelName.toLowerCase() !== modelRelation.model.toLowerCase()) {
pathItem.put.tags.push(modelRelation.model)
}
pathItem.put.parameters = this.getModelCriteria(config, doc, modelRelation.model, true)
pathItem.put.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.put.parameters.push({
name: 'data',
in: 'body',
description: 'Data to update a ' + inflect.titleize(modelRelation.property),
required: true,
schema: {
description: inflect.titleize(modelRelation.property) + ' object',
'$ref': '#/definitions/' + modelRelation.model
}
})
pathItem.put.responses = this.genResponseObjectModel(modelRelation.model)
pathItem.put.security = this.getPathSecurity(doc, modelRelation.model)
pathItem.delete = {}
pathItem.delete.summary = 'Destroy a ' +
inflect.titleize(modelRelation.property) +
' on ' +
inflect.titleize(modelName)
pathItem.delete.operationId = modelName + '.destroy' + inflect.camelize(modelRelation.property)
pathItem.delete.tags = [
modelName
]
if (modelName.toLowerCase() !== modelRelation.model.toLowerCase()) {
pathItem.delete.tags.push(modelRelation.model)
}
pathItem.delete.parameters = this.getModelCriteria(config, doc, modelRelation.model, true)
pathItem.delete.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.delete.responses = this.genResponseObjectModel(modelRelation.model)
pathItem.delete.security = this.getPathSecurity(doc, modelRelation.model)
paths[pathId] = pathItem
return paths
}
getPathModelByIdAndRelationById(paths, config, doc, modelName, modelRelation) {
const pathItem = {}
const pathId = standardBasePath +
'/' +
modelName.toLowerCase() +
'/{id}/' +
modelRelation.property.toLowerCase() +
'/{cid}'
pathItem.get = {}
pathItem.get.summary = 'Get a ' +
inflect.titleize(modelRelation.property) +
' on ' +
inflect.titleize(modelName)
pathItem.get.operationId = modelName + '.findById' + inflect.camelize(modelRelation.property)
pathItem.get.tags = [
modelName
]
if (modelName.toLowerCase() !== modelRelation.model.toLowerCase()) {
pathItem.get.tags.push(modelRelation.model)
}
pathItem.get.parameters = this.getModelCriteria(config, doc, modelRelation.model)
pathItem.get.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.get.parameters.push({
name: 'cid',
in: 'path',
description: inflect.titleize(modelRelation.property) + ' id',
required: true,
type: 'string'
})
pathItem.get.parameters.push({
name: 'populate',
in: 'query',
description: 'Properties to populate (check populate for ' +
inflect.titleize(modelRelation.model) +
')',
required: false,
type: 'array',
items: {
type: 'string'
}
})
pathItem.get.responses = this.genResponseObjectModel(modelRelation.model)
pathItem.get.security = this.getPathSecurity(doc, modelRelation.model)
pathItem.put = {}
pathItem.put.summary = 'Update a ' +
inflect.titleize(modelRelation.property) +
' on ' +
inflect.titleize(modelName)
pathItem.put.operationId = modelName + '.updateById' + inflect.camelize(modelRelation.property)
pathItem.put.tags = [
modelName
]
if (modelName.toLowerCase() !== modelRelation.model.toLowerCase()) {
pathItem.put.tags.push(modelRelation.model)
}
pathItem.put.parameters = this.getModelCriteria(config, doc, modelRelation.model)
pathItem.put.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.put.parameters.push({
name: 'cid',
in: 'path',
description: inflect.titleize(modelRelation.property) + ' id',
required: true,
type: 'string'
})
pathItem.put.parameters.push({
name: 'data',
in: 'body',
description: 'Data to update a ' + inflect.titleize(modelRelation.property),
required: true,
schema: {
description: inflect.titleize(modelRelation.property) + ' object',
'$ref': '#/definitions/' + modelRelation.model
}
})
pathItem.put.responses = this.genResponseObjectModel(modelRelation.model)
pathItem.put.security = this.getPathSecurity(doc, modelRelation.model)
pathItem.delete = {}
pathItem.delete.summary = 'Destroy a ' +
inflect.titleize(modelRelation.property) +
' on ' +
inflect.titleize(modelName)
pathItem.delete.operationId = modelName +
'.destroyById' +
inflect.camelize(modelRelation.property)
pathItem.delete.tags = [
modelName
]
if (modelName.toLowerCase() !== modelRelation.model.toLowerCase()) {
pathItem.delete.tags.push(modelRelation.model)
}
pathItem.delete.parameters = this.getModelCriteria(config, doc, modelRelation.model)
pathItem.delete.parameters.push({
name: 'id',
in: 'path',
description: inflect.titleize(modelName) + ' id',
required: true,
type: 'string'
})
pathItem.delete.parameters.push({
name: 'cid',
in: 'path',
description: inflect.titleize(modelRelation.model) + ' id',
required: true,
type: 'string'
})
pathItem.delete.responses = this.genResponseObjectModel(modelRelation.model)
pathItem.delete.security = this.getPathSecurity(doc, modelRelation.model)
paths[pathId] = pathItem
return paths
}
getPaths(config, doc) {
let paths = {}
if (config.passport && config.passport.strategies) {
for (const authType in config.passport.strategies) {
switch (authType) {
case 'local':
paths = this.getPathLocalRegister(paths, config)
paths = this.getPathLocalLogin(paths, config)
paths = this.getPathLocalLogout(paths, config)
break
}
}
}
const models = this.app.api.models
for (const modelName in models) {
// /{model}
paths = this.getPathModel(paths, config, doc, modelName)
// /{model}/{id}
paths = this.getPathModelById(paths, config, doc, modelName)
for (const modelRelationIndex in modelRelations[modelName]) {
const modelRelation = modelRelations[modelName][modelRelationIndex]
// /{model}/{id}/{child}
paths = this.getPathModelByIdAndRelation(paths, config, doc, modelName, modelRelation)
// /{model}/{id}/{child}/{cid}
paths = this.getPathModelByIdAndRelationById(paths, config, doc, modelName, modelRelation)
}
}
paths = Object.assign(paths, this.app.config.swagger.paths)
return paths
}
getModelMap() {
modelMap = []
const models = this.app.api.models
for (const modelName in models) {
modelMap.push(modelName)
}
}
getSwaggerDoc() {
const config = this.app.config
this.getModelMap()
const doc = {}
doc.swagger = '2.0'
doc.info = this.getInfo(config)
doc.basePath = this.getBasePath(config)
doc.schemes = this.getSchemes(config)
doc.consumes = this.getConsumes(config)
doc.produces = this.getProduces(config)
doc.host = this.getHost(config)
doc.securityDefinitions = this.getSecurityDefinitions(config)
doc.security = this.getSecurity(config)
doc.tags = this.getTags(config, doc)
doc.definitions = this.getDefinitions(config, doc)
doc.paths = this.getPaths(config, doc)
return doc
}
// End Swagger Doc
}
|
/**
* Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="node" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
var createAggregator = require('../internals/createAggregator');
/** Used for native method references */
var objectProto = Object.prototype;
/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through the callback. The corresponding value
* of each key is the number of times the key was returned by the callback.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
(hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
});
module.exports = countBy;
|
/*! jQuery UI - v1.11.4 - 2015-08-29
* http://jqueryui.com
* Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
})); |
// Generated by CoffeeScript 1.8.0
(function() {
var bindings, interval, os;
bindings = require('bindings')('avahi_pub.node');
os = require('os');
module.exports = {
publish: function(opts) {
var service;
service = bindings.publish(opts);
bindings.poll();
return service;
},
isSupported: function() {
return os.platform() === 'linux';
},
kill: function() {
return clearInterval(interval);
}
};
bindings.init();
if (module.exports.isSupported()) {
interval = setInterval(bindings.poll, 1000);
}
}).call(this);
|
var util = require('util');
var WildEmitter = require('wildemitter');
util.inherits(Socket, WildEmitter);
function Socket(channel, options) {
WildEmitter.call(this);
this.options = options || {};
this.channel = channel;
this._ports = this.options.ports || [];
this.initialize();
}
Socket.prototype.initialize = function() {};
Socket.prototype.addPort = function(port) {
if (this._ports.indexOf(port) < 0) {
this._ports.push(port);
this.emit('portConnected', port);
}
};
module.exports = Socket; |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: {
App
}
})
|
(function(window, undefined) {
'use strict';
/* jshint validthis:true */
function L10nError(message, id, loc) {
this.name = 'L10nError';
this.message = message;
this.id = id;
this.loc = loc;
}
L10nError.prototype = Object.create(Error.prototype);
L10nError.prototype.constructor = L10nError;
/* jshint browser:true */
var io = {
load: function load(url, callback, sync) {
var xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain');
}
xhr.open('GET', url, !sync);
xhr.addEventListener('load', function io_load(e) {
if (e.target.status === 200 || e.target.status === 0) {
callback(null, e.target.responseText);
} else {
callback(new L10nError('Not found: ' + url));
}
});
xhr.addEventListener('error', callback);
xhr.addEventListener('timeout', callback);
// the app: protocol throws on 404, see https://bugzil.la/827243
try {
xhr.send(null);
} catch (e) {
callback(new L10nError('Not found: ' + url));
}
},
loadJSON: function loadJSON(url, callback) {
var xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType('application/json');
}
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.addEventListener('load', function io_loadjson(e) {
if (e.target.status === 200 || e.target.status === 0) {
callback(null, e.target.response);
} else {
callback(new L10nError('Not found: ' + url));
}
});
xhr.addEventListener('error', callback);
xhr.addEventListener('timeout', callback);
// the app: protocol throws on 404, see https://bugzil.la/827243
try {
xhr.send(null);
} catch (e) {
callback(new L10nError('Not found: ' + url));
}
}
};
function EventEmitter() {}
EventEmitter.prototype.emit = function ee_emit() {
if (!this._listeners) {
return;
}
var args = Array.prototype.slice.call(arguments);
var type = args.shift();
if (!this._listeners[type]) {
return;
}
var typeListeners = this._listeners[type].slice();
for (var i = 0; i < typeListeners.length; i++) {
typeListeners[i].apply(this, args);
}
};
EventEmitter.prototype.addEventListener = function ee_add(type, listener) {
if (!this._listeners) {
this._listeners = {};
}
if (!(type in this._listeners)) {
this._listeners[type] = [];
}
this._listeners[type].push(listener);
};
EventEmitter.prototype.removeEventListener = function ee_rm(type, listener) {
if (!this._listeners) {
return;
}
var typeListeners = this._listeners[type];
var pos = typeListeners.indexOf(listener);
if (pos === -1) {
return;
}
typeListeners.splice(pos, 1);
};
function getPluralRule(lang) {
var locales2rules = {
'af': 3,
'ak': 4,
'am': 4,
'ar': 1,
'asa': 3,
'az': 0,
'be': 11,
'bem': 3,
'bez': 3,
'bg': 3,
'bh': 4,
'bm': 0,
'bn': 3,
'bo': 0,
'br': 20,
'brx': 3,
'bs': 11,
'ca': 3,
'cgg': 3,
'chr': 3,
'cs': 12,
'cy': 17,
'da': 3,
'de': 3,
'dv': 3,
'dz': 0,
'ee': 3,
'el': 3,
'en': 3,
'eo': 3,
'es': 3,
'et': 3,
'eu': 3,
'fa': 0,
'ff': 5,
'fi': 3,
'fil': 4,
'fo': 3,
'fr': 5,
'fur': 3,
'fy': 3,
'ga': 8,
'gd': 24,
'gl': 3,
'gsw': 3,
'gu': 3,
'guw': 4,
'gv': 23,
'ha': 3,
'haw': 3,
'he': 2,
'hi': 4,
'hr': 11,
'hu': 0,
'id': 0,
'ig': 0,
'ii': 0,
'is': 3,
'it': 3,
'iu': 7,
'ja': 0,
'jmc': 3,
'jv': 0,
'ka': 0,
'kab': 5,
'kaj': 3,
'kcg': 3,
'kde': 0,
'kea': 0,
'kk': 3,
'kl': 3,
'km': 0,
'kn': 0,
'ko': 0,
'ksb': 3,
'ksh': 21,
'ku': 3,
'kw': 7,
'lag': 18,
'lb': 3,
'lg': 3,
'ln': 4,
'lo': 0,
'lt': 10,
'lv': 6,
'mas': 3,
'mg': 4,
'mk': 16,
'ml': 3,
'mn': 3,
'mo': 9,
'mr': 3,
'ms': 0,
'mt': 15,
'my': 0,
'nah': 3,
'naq': 7,
'nb': 3,
'nd': 3,
'ne': 3,
'nl': 3,
'nn': 3,
'no': 3,
'nr': 3,
'nso': 4,
'ny': 3,
'nyn': 3,
'om': 3,
'or': 3,
'pa': 3,
'pap': 3,
'pl': 13,
'ps': 3,
'pt': 3,
'rm': 3,
'ro': 9,
'rof': 3,
'ru': 11,
'rwk': 3,
'sah': 0,
'saq': 3,
'se': 7,
'seh': 3,
'ses': 0,
'sg': 0,
'sh': 11,
'shi': 19,
'sk': 12,
'sl': 14,
'sma': 7,
'smi': 7,
'smj': 7,
'smn': 7,
'sms': 7,
'sn': 3,
'so': 3,
'sq': 3,
'sr': 11,
'ss': 3,
'ssy': 3,
'st': 3,
'sv': 3,
'sw': 3,
'syr': 3,
'ta': 3,
'te': 3,
'teo': 3,
'th': 0,
'ti': 4,
'tig': 3,
'tk': 3,
'tl': 4,
'tn': 3,
'to': 0,
'tr': 0,
'ts': 3,
'tzm': 22,
'uk': 11,
'ur': 3,
've': 3,
'vi': 0,
'vun': 3,
'wa': 4,
'wae': 3,
'wo': 0,
'xh': 3,
'xog': 3,
'yo': 0,
'zh': 0,
'zu': 3
};
// utility functions for plural rules methods
function isIn(n, list) {
return list.indexOf(n) !== -1;
}
function isBetween(n, start, end) {
return start <= n && n <= end;
}
// list of all plural rules methods:
// map an integer to the plural form name to use
var pluralRules = {
'0': function() {
return 'other';
},
'1': function(n) {
if ((isBetween((n % 100), 3, 10))) {
return 'few';
}
if (n === 0) {
return 'zero';
}
if ((isBetween((n % 100), 11, 99))) {
return 'many';
}
if (n === 2) {
return 'two';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'2': function(n) {
if (n !== 0 && (n % 10) === 0) {
return 'many';
}
if (n === 2) {
return 'two';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'3': function(n) {
if (n === 1) {
return 'one';
}
return 'other';
},
'4': function(n) {
if ((isBetween(n, 0, 1))) {
return 'one';
}
return 'other';
},
'5': function(n) {
if ((isBetween(n, 0, 2)) && n !== 2) {
return 'one';
}
return 'other';
},
'6': function(n) {
if (n === 0) {
return 'zero';
}
if ((n % 10) === 1 && (n % 100) !== 11) {
return 'one';
}
return 'other';
},
'7': function(n) {
if (n === 2) {
return 'two';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'8': function(n) {
if ((isBetween(n, 3, 6))) {
return 'few';
}
if ((isBetween(n, 7, 10))) {
return 'many';
}
if (n === 2) {
return 'two';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'9': function(n) {
if (n === 0 || n !== 1 && (isBetween((n % 100), 1, 19))) {
return 'few';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'10': function(n) {
if ((isBetween((n % 10), 2, 9)) && !(isBetween((n % 100), 11, 19))) {
return 'few';
}
if ((n % 10) === 1 && !(isBetween((n % 100), 11, 19))) {
return 'one';
}
return 'other';
},
'11': function(n) {
if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) {
return 'few';
}
if ((n % 10) === 0 ||
(isBetween((n % 10), 5, 9)) ||
(isBetween((n % 100), 11, 14))) {
return 'many';
}
if ((n % 10) === 1 && (n % 100) !== 11) {
return 'one';
}
return 'other';
},
'12': function(n) {
if ((isBetween(n, 2, 4))) {
return 'few';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'13': function(n) {
if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) {
return 'few';
}
if (n !== 1 && (isBetween((n % 10), 0, 1)) ||
(isBetween((n % 10), 5, 9)) ||
(isBetween((n % 100), 12, 14))) {
return 'many';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'14': function(n) {
if ((isBetween((n % 100), 3, 4))) {
return 'few';
}
if ((n % 100) === 2) {
return 'two';
}
if ((n % 100) === 1) {
return 'one';
}
return 'other';
},
'15': function(n) {
if (n === 0 || (isBetween((n % 100), 2, 10))) {
return 'few';
}
if ((isBetween((n % 100), 11, 19))) {
return 'many';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'16': function(n) {
if ((n % 10) === 1 && n !== 11) {
return 'one';
}
return 'other';
},
'17': function(n) {
if (n === 3) {
return 'few';
}
if (n === 0) {
return 'zero';
}
if (n === 6) {
return 'many';
}
if (n === 2) {
return 'two';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'18': function(n) {
if (n === 0) {
return 'zero';
}
if ((isBetween(n, 0, 2)) && n !== 0 && n !== 2) {
return 'one';
}
return 'other';
},
'19': function(n) {
if ((isBetween(n, 2, 10))) {
return 'few';
}
if ((isBetween(n, 0, 1))) {
return 'one';
}
return 'other';
},
'20': function(n) {
if ((isBetween((n % 10), 3, 4) || ((n % 10) === 9)) && !(
isBetween((n % 100), 10, 19) ||
isBetween((n % 100), 70, 79) ||
isBetween((n % 100), 90, 99)
)) {
return 'few';
}
if ((n % 1000000) === 0 && n !== 0) {
return 'many';
}
if ((n % 10) === 2 && !isIn((n % 100), [12, 72, 92])) {
return 'two';
}
if ((n % 10) === 1 && !isIn((n % 100), [11, 71, 91])) {
return 'one';
}
return 'other';
},
'21': function(n) {
if (n === 0) {
return 'zero';
}
if (n === 1) {
return 'one';
}
return 'other';
},
'22': function(n) {
if ((isBetween(n, 0, 1)) || (isBetween(n, 11, 99))) {
return 'one';
}
return 'other';
},
'23': function(n) {
if ((isBetween((n % 10), 1, 2)) || (n % 20) === 0) {
return 'one';
}
return 'other';
},
'24': function(n) {
if ((isBetween(n, 3, 10) || isBetween(n, 13, 19))) {
return 'few';
}
if (isIn(n, [2, 12])) {
return 'two';
}
if (isIn(n, [1, 11])) {
return 'one';
}
return 'other';
}
};
// return a function that gives the plural form name for a given integer
var index = locales2rules[lang.replace(/-.*$/, '')];
if (!(index in pluralRules)) {
return function() { return 'other'; };
}
return pluralRules[index];
}
var nestedProps = ['style', 'dataset'];
var parsePatterns;
function parse(ctx, source) {
var ast = {};
if (!parsePatterns) {
parsePatterns = {
comment: /^\s*#|^\s*$/,
entity: /^([^=\s]+)\s*=\s*(.+)$/,
multiline: /[^\\]\\$/,
macro: /\{\[\s*(\w+)\(([^\)]*)\)\s*\]\}/i,
unicode: /\\u([0-9a-fA-F]{1,4})/g,
entries: /[\r\n]+/,
controlChars: /\\([\\\n\r\t\b\f\{\}\"\'])/g
};
}
var entries = source.split(parsePatterns.entries);
for (var i = 0; i < entries.length; i++) {
var line = entries[i];
if (parsePatterns.comment.test(line)) {
continue;
}
while (parsePatterns.multiline.test(line) && i < entries.length) {
line = line.slice(0, -1) + entries[++i].trim();
}
var entityMatch = line.match(parsePatterns.entity);
if (entityMatch) {
try {
parseEntity(entityMatch[1], entityMatch[2], ast);
} catch (e) {
if (ctx) {
ctx._emitter.emit('error', e);
} else {
throw e;
}
}
}
}
return ast;
}
function setEntityValue(id, attr, key, value, ast) {
var obj = ast;
var prop = id;
if (attr) {
if (!(id in obj)) {
obj[id] = {};
}
if (typeof(obj[id]) === 'string') {
obj[id] = {'_': obj[id]};
}
obj = obj[id];
prop = attr;
}
if (!key) {
obj[prop] = value;
return;
}
if (!(prop in obj)) {
obj[prop] = {'_': {}};
} else if (typeof(obj[prop]) === 'string') {
obj[prop] = {'_index': parseMacro(obj[prop]), '_': {}};
}
obj[prop]._[key] = value;
}
function parseEntity(id, value, ast) {
var name, key;
var pos = id.indexOf('[');
if (pos !== -1) {
name = id.substr(0, pos);
key = id.substring(pos + 1, id.length - 1);
} else {
name = id;
key = null;
}
var nameElements = name.split('.');
var attr;
if (nameElements.length > 1) {
var attrElements = [];
attrElements.push(nameElements.pop());
if (nameElements.length > 1) {
// Usually the last dot separates an attribute from an id
//
// In case when there are more than one dot in the id
// and the second to last item is "style" or "dataset" then the last two
// items are becoming the attribute.
//
// ex.
// id.style.color = foo =>
//
// id:
// style.color: foo
//
// id.other.color = foo =>
//
// id.other:
// color: foo
if (nestedProps.indexOf(nameElements[nameElements.length - 1]) !== -1) {
attrElements.push(nameElements.pop());
}
}
name = nameElements.join('.');
attr = attrElements.reverse().join('.');
} else {
attr = null;
}
setEntityValue(name, attr, key, unescapeString(value), ast);
}
function unescapeControlCharacters(str) {
return str.replace(parsePatterns.controlChars, '$1');
}
function unescapeUnicode(str) {
return str.replace(parsePatterns.unicode, function(match, token) {
return unescape('%u' + '0000'.slice(token.length) + token);
});
}
function unescapeString(str) {
if (str.lastIndexOf('\\') !== -1) {
str = unescapeControlCharacters(str);
}
return unescapeUnicode(str);
}
function parseMacro(str) {
var match = str.match(parsePatterns.macro);
if (!match) {
throw new L10nError('Malformed macro');
}
return [match[1], match[2]];
}
var MAX_PLACEABLE_LENGTH = 2500;
var MAX_PLACEABLES = 100;
var rePlaceables = /\{\{\s*(.+?)\s*\}\}/g;
function Entity(id, node, env) {
this.id = id;
this.env = env;
// the dirty guard prevents cyclic or recursive references from other
// Entities; see Entity.prototype.resolve
this.dirty = false;
if (typeof node === 'string') {
this.value = node;
} else {
// it's either a hash or it has attrs, or both
for (var key in node) {
if (node.hasOwnProperty(key) && key[0] !== '_') {
if (!this.attributes) {
this.attributes = {};
}
this.attributes[key] = new Entity(this.id + '.' + key, node[key],
env);
}
}
this.value = node._ || null;
this.index = node._index;
}
}
Entity.prototype.resolve = function E_resolve(ctxdata) {
if (this.dirty) {
return undefined;
}
this.dirty = true;
var val;
// if resolve fails, we want the exception to bubble up and stop the whole
// resolving process; however, we still need to clean up the dirty flag
try {
val = resolve(ctxdata, this.env, this.value, this.index);
} finally {
this.dirty = false;
}
return val;
};
Entity.prototype.toString = function E_toString(ctxdata) {
try {
return this.resolve(ctxdata);
} catch (e) {
return undefined;
}
};
Entity.prototype.valueOf = function E_valueOf(ctxdata) {
if (!this.attributes) {
return this.toString(ctxdata);
}
var entity = {
value: this.toString(ctxdata),
attributes: {}
};
for (var key in this.attributes) {
if (this.attributes.hasOwnProperty(key)) {
entity.attributes[key] = this.attributes[key].toString(ctxdata);
}
}
return entity;
};
function subPlaceable(ctxdata, env, match, id) {
if (ctxdata && ctxdata.hasOwnProperty(id) &&
(typeof ctxdata[id] === 'string' ||
(typeof ctxdata[id] === 'number' && !isNaN(ctxdata[id])))) {
return ctxdata[id];
}
if (env.hasOwnProperty(id)) {
if (!(env[id] instanceof Entity)) {
env[id] = new Entity(id, env[id], env);
}
var value = env[id].resolve(ctxdata);
if (typeof value === 'string') {
// prevent Billion Laughs attacks
if (value.length >= MAX_PLACEABLE_LENGTH) {
throw new L10nError('Too many characters in placeable (' +
value.length + ', max allowed is ' +
MAX_PLACEABLE_LENGTH + ')');
}
return value;
}
}
return match;
}
function interpolate(ctxdata, env, str) {
var placeablesCount = 0;
var value = str.replace(rePlaceables, function(match, id) {
// prevent Quadratic Blowup attacks
if (placeablesCount++ >= MAX_PLACEABLES) {
throw new L10nError('Too many placeables (' + placeablesCount +
', max allowed is ' + MAX_PLACEABLES + ')');
}
return subPlaceable(ctxdata, env, match, id);
});
placeablesCount = 0;
return value;
}
function resolve(ctxdata, env, expr, index) {
if (typeof expr === 'string') {
return interpolate(ctxdata, env, expr);
}
if (typeof expr === 'boolean' ||
typeof expr === 'number' ||
!expr) {
return expr;
}
// otherwise, it's a dict
if (index && ctxdata && ctxdata.hasOwnProperty(index[1])) {
var argValue = ctxdata[index[1]];
// special cases for zero, one, two if they are defined on the hash
if (argValue === 0 && 'zero' in expr) {
return resolve(ctxdata, env, expr.zero);
}
if (argValue === 1 && 'one' in expr) {
return resolve(ctxdata, env, expr.one);
}
if (argValue === 2 && 'two' in expr) {
return resolve(ctxdata, env, expr.two);
}
var selector = env.__plural(argValue);
if (expr.hasOwnProperty(selector)) {
return resolve(ctxdata, env, expr[selector]);
}
}
// if there was no index or no selector was found, try 'other'
if ('other' in expr) {
return resolve(ctxdata, env, expr.other);
}
return undefined;
}
function compile(env, ast) {
env = env || {};
for (var id in ast) {
if (ast.hasOwnProperty(id)) {
env[id] = new Entity(id, ast[id], env);
}
}
return env;
}
function Locale(id, ctx) {
this.id = id;
this.ctx = ctx;
this.isReady = false;
this.entries = {
__plural: getPluralRule(id)
};
}
Locale.prototype.getEntry = function L_getEntry(id) {
/* jshint -W093 */
var entries = this.entries;
if (!entries.hasOwnProperty(id)) {
return undefined;
}
if (entries[id] instanceof Entity) {
return entries[id];
}
return entries[id] = new Entity(id, entries[id], entries);
};
Locale.prototype.build = function L_build(callback) {
var sync = !callback;
var ctx = this.ctx;
var self = this;
var l10nLoads = ctx.resLinks.length;
function onL10nLoaded(err) {
if (err) {
ctx._emitter.emit('error', err);
}
if (--l10nLoads <= 0) {
self.isReady = true;
if (callback) {
callback();
}
}
}
if (l10nLoads === 0) {
onL10nLoaded();
return;
}
function onJSONLoaded(err, json) {
if (!err && json) {
self.addAST(json);
}
onL10nLoaded(err);
}
function onPropLoaded(err, source) {
if (!err && source) {
var ast = parse(ctx, source);
self.addAST(ast);
}
onL10nLoaded(err);
}
for (var i = 0; i < ctx.resLinks.length; i++) {
var path = ctx.resLinks[i].replace('{{locale}}', this.id);
var type = path.substr(path.lastIndexOf('.') + 1);
switch (type) {
case 'json':
io.loadJSON(path, onJSONLoaded, sync);
break;
case 'properties':
io.load(path, onPropLoaded, sync);
break;
}
}
};
Locale.prototype.addAST = function(ast) {
for (var id in ast) {
if (ast.hasOwnProperty(id)) {
this.entries[id] = ast[id];
}
}
};
Locale.prototype.getEntity = function(id, ctxdata) {
var entry = this.getEntry(id);
if (!entry) {
return null;
}
return entry.valueOf(ctxdata);
};
function Context(id) {
this.id = id;
this.isReady = false;
this.isLoading = false;
this.supportedLocales = [];
this.resLinks = [];
this.locales = {};
this._emitter = new EventEmitter();
// Getting translations
function getWithFallback(id) {
/* jshint -W084 */
if (!this.isReady) {
throw new L10nError('Context not ready');
}
var cur = 0;
var loc;
var locale;
while (loc = this.supportedLocales[cur]) {
locale = this.getLocale(loc);
if (!locale.isReady) {
// build without callback, synchronously
locale.build(null);
}
var entry = locale.getEntry(id);
if (entry === undefined) {
cur++;
warning.call(this, new L10nError(id + ' not found in ' + loc, id,
loc));
continue;
}
return entry;
}
error.call(this, new L10nError(id + ' not found', id));
return null;
}
this.get = function get(id, ctxdata) {
var entry = getWithFallback.call(this, id);
if (entry === null) {
return '';
}
return entry.toString(ctxdata) || '';
};
this.getEntity = function getEntity(id, ctxdata) {
var entry = getWithFallback.call(this, id);
if (entry === null) {
return null;
}
return entry.valueOf(ctxdata);
};
// Helpers
this.getLocale = function getLocale(code) {
/* jshint -W093 */
var locales = this.locales;
if (locales[code]) {
return locales[code];
}
return locales[code] = new Locale(code, this);
};
// Getting ready
function negotiate(available, requested, defaultLocale) {
if (available.indexOf(requested[0]) === -1 ||
requested[0] === defaultLocale) {
return [defaultLocale];
} else {
return [requested[0], defaultLocale];
}
}
function freeze(supported) {
var locale = this.getLocale(supported[0]);
if (locale.isReady) {
setReady.call(this, supported);
} else {
locale.build(setReady.bind(this, supported));
}
}
function setReady(supported) {
this.supportedLocales = supported;
this.isReady = true;
this._emitter.emit('ready');
}
this.requestLocales = function requestLocales() {
if (this.isLoading && !this.isReady) {
throw new L10nError('Context not ready');
}
this.isLoading = true;
var requested = Array.prototype.slice.call(arguments);
var supported = negotiate(requested.concat('en-US'), requested, 'en-US');
freeze.call(this, supported);
};
// Events
this.addEventListener = function addEventListener(type, listener) {
this._emitter.addEventListener(type, listener);
};
this.removeEventListener = function removeEventListener(type, listener) {
this._emitter.removeEventListener(type, listener);
};
this.ready = function ready(callback) {
if (this.isReady) {
setTimeout(callback);
}
this.addEventListener('ready', callback);
};
this.once = function once(callback) {
/* jshint -W068 */
if (this.isReady) {
setTimeout(callback);
return;
}
var callAndRemove = (function() {
this.removeEventListener('ready', callAndRemove);
callback();
}).bind(this);
this.addEventListener('ready', callAndRemove);
};
// Errors
function warning(e) {
this._emitter.emit('warning', e);
return e;
}
function error(e) {
this._emitter.emit('error', e);
return e;
}
}
/* jshint -W104 */
var DEBUG = false;
var isPretranslated = false;
var rtlList = ['ar', 'he', 'fa', 'ps', 'qps-plocm', 'ur'];
// Public API
navigator.mozL10n = {
ctx: new Context(),
get: function get(id, ctxdata) {
return navigator.mozL10n.ctx.get(id, ctxdata);
},
localize: function localize(element, id, args) {
return localizeElement.call(navigator.mozL10n, element, id, args);
},
translate: function translate(element) {
return translateFragment.call(navigator.mozL10n, element);
},
ready: function ready(callback) {
return navigator.mozL10n.ctx.ready(callback);
},
once: function once(callback) {
return navigator.mozL10n.ctx.once(callback);
},
get readyState() {
return navigator.mozL10n.ctx.isReady ? 'complete' : 'loading';
},
language: {
set code(lang) {
navigator.mozL10n.ctx.requestLocales(lang);
},
get code() {
return navigator.mozL10n.ctx.supportedLocales[0];
},
get direction() {
return getDirection(navigator.mozL10n.ctx.supportedLocales[0]);
}
},
_getInternalAPI: function() {
return {
Error: L10nError,
Context: Context,
Locale: Locale,
Entity: Entity,
getPluralRule: getPluralRule,
rePlaceables: rePlaceables,
getTranslatableChildren: getTranslatableChildren,
getL10nAttributes: getL10nAttributes,
loadINI: loadINI,
fireLocalizedEvent: fireLocalizedEvent,
parse: parse,
compile: compile
};
}
};
navigator.mozL10n.ctx.ready(onReady.bind(navigator.mozL10n));
if (DEBUG) {
navigator.mozL10n.ctx.addEventListener('error', console.error);
navigator.mozL10n.ctx.addEventListener('warning', console.warn);
}
function getDirection(lang) {
return (rtlList.indexOf(lang) >= 0) ? 'rtl' : 'ltr';
}
var readyStates = {
'loading': 0,
'interactive': 1,
'complete': 2
};
function waitFor(state, callback) {
state = readyStates[state];
if (readyStates[document.readyState] >= state) {
callback();
return;
}
document.addEventListener('readystatechange', function l10n_onrsc() {
if (readyStates[document.readyState] >= state) {
document.removeEventListener('readystatechange', l10n_onrsc);
callback();
}
});
}
if (window.document) {
isPretranslated = (document.documentElement.lang === navigator.language);
// this is a special case for netError bug; see https://bugzil.la/444165
if (document.documentElement.dataset.noCompleteBug) {
pretranslate.call(navigator.mozL10n);
return;
}
if (isPretranslated) {
waitFor('interactive', function() {
window.setTimeout(initResources.bind(navigator.mozL10n));
});
} else {
if (document.readyState === 'complete') {
window.setTimeout(initResources.bind(navigator.mozL10n));
} else {
waitFor('interactive', pretranslate.bind(navigator.mozL10n));
}
}
}
function pretranslate() {
/* jshint -W068 */
if (inlineLocalization.call(this)) {
waitFor('interactive', (function() {
window.setTimeout(initResources.bind(this));
}).bind(this));
} else {
initResources.call(this);
}
}
function inlineLocalization() {
var script = document.documentElement
.querySelector('script[type="application/l10n"]' +
'[lang="' + navigator.language + '"]');
if (!script) {
return false;
}
var locale = this.ctx.getLocale(navigator.language);
// the inline localization is happenning very early, when the ctx is not
// yet ready and when the resources haven't been downloaded yet; add the
// inlined JSON directly to the current locale
locale.addAST(JSON.parse(script.innerHTML));
// localize the visible DOM
var l10n = {
ctx: locale,
language: {
code: locale.id,
direction: getDirection(locale.id)
}
};
translateFragment.call(l10n);
// the visible DOM is now pretranslated
isPretranslated = true;
return true;
}
function initResources() {
var resLinks = document.head
.querySelectorAll('link[type="application/l10n"]');
var iniLinks = [];
var i;
for (i = 0; i < resLinks.length; i++) {
var link = resLinks[i];
var url = link.getAttribute('href');
var type = url.substr(url.lastIndexOf('.') + 1);
if (type === 'ini') {
iniLinks.push(url);
}
this.ctx.resLinks.push(url);
}
var iniLoads = iniLinks.length;
if (iniLoads === 0) {
initLocale.call(this);
return;
}
function onIniLoaded(err) {
if (err) {
this.ctx._emitter.emit('error', err);
}
if (--iniLoads === 0) {
initLocale.call(this);
}
}
for (i = 0; i < iniLinks.length; i++) {
loadINI.call(this, iniLinks[i], onIniLoaded.bind(this));
}
}
function initLocale() {
this.ctx.requestLocales(navigator.language);
window.addEventListener('languagechange', function l10n_langchange() {
navigator.mozL10n.language.code = navigator.language;
});
}
function onReady() {
if (!isPretranslated) {
this.translate();
}
isPretranslated = false;
fireLocalizedEvent.call(this);
}
function fireLocalizedEvent() {
var event = new CustomEvent('localized', {
'bubbles': false,
'cancelable': false,
'detail': {
'language': this.ctx.supportedLocales[0]
}
});
window.dispatchEvent(event);
}
/* jshint -W104 */
function loadINI(url, callback) {
var ctx = this.ctx;
io.load(url, function(err, source) {
var pos = ctx.resLinks.indexOf(url);
if (err) {
// remove the ini link from resLinks
ctx.resLinks.splice(pos, 1);
return callback(err);
}
if (!source) {
ctx.resLinks.splice(pos, 1);
return callback(new Error('Empty file: ' + url));
}
var patterns = parseINI(source, url).resources.map(function(x) {
return x.replace('en-US', '{{locale}}');
});
ctx.resLinks.splice.apply(ctx.resLinks, [pos, 1].concat(patterns));
callback();
});
}
function relativePath(baseUrl, url) {
if (url[0] === '/') {
return url;
}
var dirs = baseUrl.split('/')
.slice(0, -1)
.concat(url.split('/'))
.filter(function(path) {
return path !== '.';
});
return dirs.join('/');
}
var iniPatterns = {
'section': /^\s*\[(.*)\]\s*$/,
'import': /^\s*@import\s+url\((.*)\)\s*$/i,
'entry': /[\r\n]+/
};
function parseINI(source, iniPath) {
var entries = source.split(iniPatterns.entry);
var locales = ['en-US'];
var genericSection = true;
var uris = [];
var match;
for (var i = 0; i < entries.length; i++) {
var line = entries[i];
// we only care about en-US resources
if (genericSection && iniPatterns['import'].test(line)) {
match = iniPatterns['import'].exec(line);
var uri = relativePath(iniPath, match[1]);
uris.push(uri);
continue;
}
// but we need the list of all locales in the ini, too
if (iniPatterns.section.test(line)) {
genericSection = false;
match = iniPatterns.section.exec(line);
locales.push(match[1]);
}
}
return {
locales: locales,
resources: uris
};
}
/* jshint -W104 */
function translateFragment(element) {
if (!element) {
element = document.documentElement;
document.documentElement.lang = this.language.code;
document.documentElement.dir = this.language.direction;
}
translateElement.call(this, element);
var nodes = getTranslatableChildren(element);
for (var i = 0; i < nodes.length; i++ ) {
translateElement.call(this, nodes[i]);
}
}
function getTranslatableChildren(element) {
return element ? element.querySelectorAll('*[data-l10n-id]') : [];
}
function localizeElement(element, id, args) {
if (!element) {
return;
}
if (!id) {
element.removeAttribute('data-l10n-id');
element.removeAttribute('data-l10n-args');
setTextContent(element, '');
return;
}
element.setAttribute('data-l10n-id', id);
if (args && typeof args === 'object') {
element.setAttribute('data-l10n-args', JSON.stringify(args));
} else {
element.removeAttribute('data-l10n-args');
}
if (this.ctx.isReady) {
translateElement.call(this, element);
}
}
function getL10nAttributes(element) {
if (!element) {
return {};
}
var l10nId = element.getAttribute('data-l10n-id');
var l10nArgs = element.getAttribute('data-l10n-args');
var args = l10nArgs ? JSON.parse(l10nArgs) : null;
return {id: l10nId, args: args};
}
function translateElement(element) {
var l10n = getL10nAttributes(element);
if (!l10n.id) {
return;
}
var entity = this.ctx.getEntity(l10n.id, l10n.args);
if (!entity) {
return;
}
if (typeof entity === 'string') {
setTextContent(element, entity);
return true;
}
if (entity.value) {
setTextContent(element, entity.value);
}
for (var key in entity.attributes) {
if (entity.attributes.hasOwnProperty(key)) {
var attr = entity.attributes[key];
var pos = key.indexOf('.');
if (pos !== -1) {
element[key.substr(0, pos)][key.substr(pos + 1)] = attr;
} else if (key === 'ariaLabel') {
element.setAttribute('aria-label', attr);
} else {
element[key] = attr;
}
}
}
return true;
}
function setTextContent(element, text) {
// standard case: no element children
if (!element.firstElementChild) {
element.textContent = text;
return;
}
// this element has element children: replace the content of the first
// (non-blank) child textNode and clear other child textNodes
var found = false;
var reNotBlank = /\S/;
for (var child = element.firstChild; child; child = child.nextSibling) {
if (child.nodeType === Node.TEXT_NODE &&
reNotBlank.test(child.nodeValue)) {
if (found) {
child.nodeValue = '';
} else {
child.nodeValue = text;
found = true;
}
}
}
// if no (non-empty) textNode is found, insert a textNode before the
// element's first child.
if (!found) {
element.insertBefore(document.createTextNode(text), element.firstChild);
}
}
})(this);
|
const { Command } = require('discord-akairo');
const Logger = require('../../util/Logger');
const util = require('util');
/* eslint-disable no-unused-vars */
const Reputation = require('../../models/reputations');
const Star = require('../../models/stars');
/* eslint-enable no-unused-vars */
class EvalCommand extends Command {
constructor() {
super('eval', {
aliases: ['eval', 'e'],
category: 'owner',
ownerOnly: true,
quoted: false,
args: [
{
id: 'code',
match: 'content'
}
],
description: {
content: 'Evaluates code.',
usage: '<code>'
}
});
}
async exec(message, { code }) {
if (!code) return message.util.reply('No code provided!');
const evaled = {};
const logs = [];
const token = this.client.token.split('').join('[^]{0,2}');
const rev = this.client.token.split('').reverse().join('[^]{0,2}');
const tokenRegex = new RegExp(`${token}|${rev}`, 'g');
const cb = '```';
const print = (...a) => { // eslint-disable-line no-unused-vars
const cleaned = a.map(obj => {
if (typeof o !== 'string') obj = util.inspect(obj, { depth: 1 });
return obj.replace(tokenRegex, '[TOKEN]');
});
if (!evaled.output) {
logs.push(...cleaned);
return;
}
evaled.output += evaled.output.endsWith('\n') ? cleaned.join(' ') : `\n${cleaned.join(' ')}`;
const title = evaled.errored ? '☠\u2000**Error**' : '📤\u2000**Output**';
if (evaled.output.length + code.length > 1900) evaled.output = 'Output too long.';
evaled.message.edit([
`📥\u2000**Input**${cb}js`,
code,
cb,
`${title}${cb}js`,
evaled.output,
cb
]);
};
try {
// eslint-disable-next-line no-eval
let output = eval(code);
// eslint-disable-next-line eqeqeq
if (output != null && typeof output.then === 'function') output = await output;
if (typeof output !== 'string') output = util.inspect(output, { depth: 0 });
output = `${logs.join('\n')}\n${logs.length && output === 'undefined' ? '' : output}`;
output = output.replace(tokenRegex, '[TOKEN]');
if (output.length + code.length > 1900) output = 'Output too long.';
const sent = await message.util.send([
`📥\u2000**Input**${cb}js`,
code,
cb,
`📤\u2000**Output**${cb}js`,
output,
cb
]);
evaled.message = sent;
evaled.errored = false;
evaled.output = output;
return sent;
} catch (err) {
Logger.error('An eval error occured.');
Logger.stacktrace(err);
let error = err;
error = error.toString();
error = `${logs.join('\n')}\n${logs.length && error === 'undefined' ? '' : error}`;
error = error.replace(tokenRegex, '[TOKEN]');
const sent = await message.util.send([
`📥\u2000**Input**${cb}js`,
code,
cb,
`☠\u2000**Error**${cb}js`,
error,
cb
]);
evaled.message = sent;
evaled.errored = true;
evaled.output = error;
return sent;
}
}
}
module.exports = EvalCommand;
|
'use strict';
angular
.module('docsGeneratorApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'function/main.html',
controller: 'MainCtrl'
})
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/resource', {
templateUrl: 'resource/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var http_1 = require('@angular/http');
require('rxjs/add/operator/toPromise');
var app_config_1 = require('../app.config');
var AssetService = (function () {
function AssetService(_http) {
this._http = _http;
this.headers = new http_1.Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
this.headers.append('x-access-token', localStorage.getItem('token'));
}
AssetService.prototype.getAssets = function () {
return this._http.get(app_config_1.Config.apiServerUrl + '/assets', { headers: this.headers })
.toPromise()
.then(function (response) { return response.json(); })
.catch(this.handleError);
};
AssetService.prototype.getAsset = function (id) {
return this._http.get(app_config_1.Config.apiServerUrl + '/assets/' + id, { headers: this.headers })
.toPromise()
.then(function (response) { return response.json(); })
.catch(this.handleError);
};
AssetService.prototype.update = function (asset) {
return this._http.put(app_config_1.Config.apiServerUrl + '/assets/' + asset.id, JSON.stringify(asset), { headers: this.headers })
.toPromise()
.then(function (response) { return response.json(); })
.catch(this.handleError);
};
AssetService.prototype.create = function (asset) {
return this._http.post(app_config_1.Config.apiServerUrl + '/assets', JSON.stringify(asset), { headers: this.headers })
.toPromise()
.then(function (response) { return response.json(); })
.catch(this.handleError);
};
AssetService.prototype.delete = function (id) {
return this._http.delete(app_config_1.Config.apiServerUrl + '/assets/' + id, { headers: this.headers })
.toPromise()
.then(function () { return null; })
.catch(this.handleError);
};
AssetService.prototype.handleError = function (error) {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
};
AssetService = __decorate([
core_1.Injectable(),
__metadata('design:paramtypes', [http_1.Http])
], AssetService);
return AssetService;
}());
exports.AssetService = AssetService;
//# sourceMappingURL=asset.service.js.map |
function viewport() {
var e = window,
a = 'inner';
if (!('innerWidth' in window)) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ], height : e[ a+'Height' ] };
};
// Device window is < 640px
var isSmall = function() {
var winW = viewport().width;
if (winW < 640) {
return true;
} else {
return false;
}
};
var clearStyles = function(e) {
var windowWidth = viewport().width;
if(!isSmall()) {
$(e).removeAttr("style");
}
}; |
import Rx from 'rxjs';
import calculatorActions from './calculatorActions';
test('Subjects are available', () => {
expect(calculatorActions.actions.addInclusion$).toBeInstanceOf(Rx.Subject);
expect(calculatorActions.actions.removeInclusion$).toBeInstanceOf(Rx.Subject);
expect(calculatorActions.actions.editInclusion$).toBeInstanceOf(Rx.Subject);
expect(calculatorActions.actions.diamondUpdated$).toBeInstanceOf(Rx.Subject);
expect(calculatorActions.actions.inclusionUpdated$).toBeInstanceOf(Rx.Subject);
expect(calculatorActions.actions.clear$).toBeInstanceOf(Rx.Subject);
});
test('actions are available', () => {
expect(calculatorActions.addInclusion).toBeInstanceOf(Function);
expect(calculatorActions.removeInclusion).toBeInstanceOf(Function);
expect(calculatorActions.editInclusion).toBeInstanceOf(Function);
expect(calculatorActions.inclusionUpdated).toBeInstanceOf(Function);
expect(calculatorActions.diamondUpdated).toBeInstanceOf(Function);
expect(calculatorActions.clear).toBeInstanceOf(Function);
});
|
var url = require('url');
exports.init = function (model) {
var filename = model.get('filename') || 'github-btn.html'
, fileurl = model.get('fileurl')
, domain = model.get('domain') || 'ghbtns.com'
, giturl = model.get('giturl')
, height = model.get('height')
, protocol = model.get('secure') ? 'https' : 'http'
, repo = model.get('repo')
, size = model.get('size')
, type = model.get('type')
, user = model.get('user');
if (!giturl && (!user || !repo)) {
return console.error('ghbtns:button: giturl or user/repo required');
}
if (!type) {
return console.error('ghbtns:button: type required');
}
if (!fileurl) {
model.set('fileurl', protocol + '://' + domain + '/' + filename);
}
if (giturl) {
var gitpath = url.parse(giturl).path.split('/');
model.set('repo', gitpath[2].slice(0, -4));
model.set('user', gitpath[1]);
}
if (!height) {
model.set('height', size === 'large' ? '30' : '20');
}
model.set('show', true);
}; |
// as taken from: https://raw.githubusercontent.com/Jxck/assert/master/assert.js
// becuase I don't want to use a stupidly verbose assertion library.
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Copyright (c) 2011 Jxck
//
// Originally from node.js (http://nodejs.org)
// Copyright Joyent, Inc.
//
// 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 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(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(); // CommonJS
} else {
root.assert = factory(); // Global
}
})(this, function() {
// UTILITY
// Object.create compatible in IE
var create = Object.create || function(p) {
if (!p) throw Error('no type');
function f() {};
f.prototype = p;
return new f();
};
// UTILITY
var util = {
inherits: function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
},
isArray: function(ar) {
return Array.isArray(ar);
},
isBoolean: function(arg) {
return typeof arg === 'boolean';
},
isNull: function(arg) {
return arg === null;
},
isNullOrUndefined: function(arg) {
return arg == null;
},
isNumber: function(arg) {
return typeof arg === 'number';
},
isString: function(arg) {
return typeof arg === 'string';
},
isSymbol: function(arg) {
return typeof arg === 'symbol';
},
isUndefined: function(arg) {
return arg === void 0;
},
isRegExp: function(re) {
return util.isObject(re) && util.objectToString(re) === '[object RegExp]';
},
isObject: function(arg) {
return typeof arg === 'object' && arg !== null;
},
isDate: function(d) {
return util.isObject(d) && util.objectToString(d) === '[object Date]';
},
isError: function(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
},
isFunction: function(arg) {
return typeof arg === 'function';
},
isPrimitive: function(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
},
objectToString: function(o) {
return Object.prototype.toString.call(o);
}
};
var pSlice = Array.prototype.slice;
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
var Object_keys = typeof Object.keys === 'function' ? Object.keys : (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
})();
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
} else {
// try to throw an error now, and from the stack property
// work out the line that called in to assert.js.
try {
this.stack = (new Error).stack.toString();
} catch (e) {}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (util.isUndefined(value)) {
return '' + value;
}
if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) {
return value.toString();
}
if (util.isFunction(value) || util.isRegExp(value)) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (util.isString(s)) {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function getMessage(self) {
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
self.operator + ' ' +
truncate(JSON.stringify(self.expected, replacer), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
// } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
// if (actual.length != expected.length) return false;
//
// for (var i = 0; i < actual.length; i++) {
// if (actual[i] !== expected[i]) return false;
// }
//
// return true;
//
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!util.isObject(actual) && !util.isObject(expected)) {
return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
var isArguments = function(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
(function() {
if (!isArguments(arguments)) {
isArguments = function(object) {
return object != null &&
typeof object === 'object' &&
typeof object.callee === 'function' &&
typeof object.length === 'number' || false;
};
}
})();
function objEquiv(a, b) {
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
var aIsArgs = isArguments(a),
bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
try {
var ka = Object_keys(a),
kb = Object_keys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (util.isString(expected)) {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws.apply(this, [true].concat(pSlice.call(arguments)));
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
_throws.apply(this, [false].concat(pSlice.call(arguments)));
};
assert.ifError = function(err) { if (err) {throw err;}};
return assert;
});
|
var testsContext = require.context('./app', true, /\.spec\.js$/);
testsContext.keys().forEach(testsContext);
var srcContext = require.context('./app', true, /!(\.spec\.js)$/);
srcContext.keys().forEach(srcContext);
|
var $Movement = $Movement || {};
(function($) {
$.fn.commentsFeed = function(maxItemsInFeed) {
return $(this).each(function() {
return $Movement.commentsFeed.init(this, maxItemsInFeed);
});
}
})(jQuery);
$Movement.commentsFeed = (function() {
var self = {};
self.init = function(root, maxItemsInFeed) {
self.root = $(root);
self.emptySlots = self.maxItemsInFeed = maxItemsInFeed;
self.commentsContainer = self.root.find('ul');
self.feedPath = self.root.data("feed-path");
self.lastFeedId = null;
fetchFeed();
setInterval(fetchFeed, 10000);
};
var fetchFeed = function() {
$.get(self.feedPath).done(function(feeds) {
var newFeeds = findNewFeeds(feeds);
if (newFeeds.length > 0) {
self.root.show();
self.lastFeedId = newFeeds[newFeeds.length - 1].id;
}
renderResponse(newFeeds);
});
};
var findNewFeeds = function (feeds) {
if(feeds.length == 0) return feeds;
var arr = $.map(feeds, function (feed) {
return feed.id;
});
return feeds.slice(arr.indexOf(self.lastFeedId) + 1, arr.size);
};
var renderResponse = function(feed) {
if(isFirstResponse()) {
feed = splice(feed);
}
var newItem = feed.shift();
if (!newItem) return;
render(newItem, function() {
renderResponse(feed);
});
};
function isFirstResponse() {
return (self.emptySlots == self.maxItemsInFeed);
}
function splice(feed) {
var max = self.maxItemsInFeed;
return feed.splice(feed.length - max, max);
}
function render(newItem, callback) {
var newFeedEntry = createFeedEntry(newItem).prependTo(self.commentsContainer);
if (!hasEmptySlots()) {
newFeedEntry.slideDown('slow', callback);
}
else {
self.emptySlots--;
newFeedEntry.show();
!hasEmptySlots() && lockRootHeight();
callback();
}
}
function hasEmptySlots() {
return (self.emptySlots > 0)
}
function lockRootHeight() {
self.root.css('height', self.root.height());
}
function createFeedEntry(newItem) {
var template = $('#recent_comment_template').html();
newItem.country_iso && (newItem.country_iso = newItem.country_iso.toUpperCase());
newItem.last_name = newItem.last_name.charAt(0) + '.';
return $(Mustache.to_html(template, newItem)).hide();
}
return self;
})();
|
// Begin function declaration.
var sayHello;
sayHello = function() {
// Print a greeting.
return console.log('hi');
};
|
import React from 'react'
const LiveHelp = () =>
<div>
The live help page
</div>
const styles = {
}
export default LiveHelp
|
/**
* Sorts the valid JSON object and returns it.
* @param {JSON object to be sorted} object.
* @param {function containing returned values as 1.Error, 2.Sorted JSON object } callback.
* In this it first creates the valid JSON schema and afterwords validates the object with it
* if it is valid then it sorts it in descending order and returns it.
*/
var sortJsonObject = function (object, callback){
var Validator = require('jsonschema').Validator;
var v = new Validator();
// JSON schema has to create having two schemas as :-
// 'jsonOject' for Student object &
// 'jsonSchema' for actual JSON input.
var jsonObject = {
"id": "/StudentObject",
"type": "object",
"properties": {
"id": {"type": "integer", "minimum": 1, "required": true},
"fName": {"type": "string", "required": true},
"lName": {"type": "string", "required": true},
"score": {"type": "integer", "minimum": 1, "required": true},
},
};
var jsonSchema = {
"id": "/JsonArrayObject",
"type": "object",
"properties": {
"students": {
"type": "array",
"items": {"$ref": "/StudentObject", "minimum": 1, "required": true}
}
}
};
v.addSchema(jsonObject, '/StudentObject');
var result = v.validate(object, jsonSchema);
if(result.errors.length){
// If JSON is not having expected format
// we have to tell user about that and can't
// go further.
callback("Input JSON is not having the required format " + result.errors,null);
} else {
object.students = object.students.sort(function (a, b) {
return b.score - a.score;
});
callback(null, object);
}
}
module.exports = {
sortJsonObject : sortJsonObject
} |
import Ember from 'ember';
import hbs from 'htmlbars-inline-precompile';
import ajax from 'dummy/utilities/ajax';
import connect from 'ember-redux/components/connect';
var stateToComputed = (state) => {
return {
users: state.users.all
};
};
var dispatchToActions = (dispatch) => {
return {
fetch: () => ajax('/api/users', 'GET').then(response => dispatch({type: 'DESERIALIZE_USERS', response: response}))
};
};
var UserListComponent = Ember.Component.extend({
init() {
this._super(...arguments);
this.triggerAction({action: 'fetch', target: this});
},
layout: hbs`
{{#each users as |user|}}
<div class="user-name">{{user.name}}</div>
{{/each}}
`
});
export default connect(stateToComputed, dispatchToActions)(UserListComponent);
|
(function() {
"use strict";
angular.module('bucket-collector').factory('SEDataService', SEDataService);
SEDataService.$inject = ['API_URL', '$http', '$q', 'SettingsService'];
function SEDataService(API_URL, $http, $q, Settings) {
return {
getCustomers: getCustomers
};
function getCustomers() {
var deferred = $q.defer();
Settings.get().then(function(settings) {
if (!settings.apiKey || !angular.isString(settings.apiKey) || settings.apiKey === "") {
deferred.reject('NO VALID APIKEY');
} else {
$http({
method: 'GET',
url: API_URL.v2 + '/customer',
params: {
apiKey: settings.apiKey
}
}).then(function(result) {
var data = result.data;
if (data) {
console.log(data);
if (data.message) {
deferred.reject(data.message);
} else {
deferred.resolve(data);
}
} else {
deferred.reject("NO DATA RECEIVED");
}
}, function(error) {
if (error.data && error.data.message) {
deferred.reject(error.data.message);
} else {
deferred.reject(error.data);
}
});
}
});
return deferred.promise;
}
}
})(); |
import {Ion} from '@ion-cloud/core';
import {easel} from './index';
// This makeItRain demo constantly keeps 100 particles (dollars) on the screen
export function makeItRain() {
let shirtWidth = 0, shirtLeft = 0, shirtHeight = 0, shirtTop = 0,
logoWidth = 0, logoHeight = 0;
const headerText = '<%= name %> Version <%= appVersion %> by <%= authorName %>',
ctx = easel.ctx, //link to canvas 2d drawing context
shirt = new Image(),
logo = new Image(),
dollar = new Image(),
makeItRain = new Ion(easel), //animation class
gatherShirtSize = ()=>{
shirtWidth = easel.viewport.h / shirt.height * shirt.width;
shirtLeft = easel.viewport.w / 2 - shirtWidth / 2;
shirtHeight = easel.viewport.h;
shirtTop = 0;
if(shirtWidth>easel.viewport.w){
shirtLeft = 0;
shirtWidth = easel.viewport.w;
shirtHeight = easel.viewport.w / shirt.width * shirt.height;
shirtTop = easel.viewport.h / 2 - shirtHeight / 2;
} //end if
logoWidth = shirtWidth / 6;
logoHeight = shirtHeight / 4;
};
// Lady shirt in the background
shirt.src = 'http://i.imgur.com/Nvfvy87.png';
shirt.onload = ()=> gatherShirtSize();
easel.config = ()=>{
gatherShirtSize();
};
// Gulp logo ontop of the lady shirt
logo.src = 'http://i.imgur.com/dlwtnzo.png';
// Dollar asset that floats from the top
dollar.src = 'http://i.imgur.com/nLTCnEP.png';
// Declare and initialize the scene
makeItRain.quantity = 100;
makeItRain.startX = ()=> Math.random()*easel.viewport.w; //start x location
makeItRain.startY = 15; //start y location
makeItRain.endX = ()=> Math.random()*easel.viewport.w; //destination x location (minus wind factor)
makeItRain.endY = ()=> easel.viewport.h; //destination y location (minus wind factor)
makeItRain.windX = ()=> Math.random()*0.5-0.25; // wind-x variant factor
makeItRain.windY = 0; //wind-y variant factor
makeItRain.image = dollar; //pass an image for the particle
makeItRain.imageWidth = 25; //lets override the width of the image
makeItRain.imageHeight = 50; //lets override the height of the image
makeItRain.tweenDuration = 1000;
makeItRain.tweenCurrent = ()=> Math.random()*makeItRain.tweenDuration;
makeItRain.tweenType = 'linear';
makeItRain.onParticleEnd = makeItRain.reevaluate;
makeItRain.onEscape = makeItRain.reevaluate;
makeItRain.clearFrame = ()=>{ //overriding the clear frame function
const x = easel.viewport.w/2-logoWidth/2,
y = easel.viewport.h/2-logoHeight/2;
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, easel.viewport.w, easel.viewport.h);
ctx.font = '18px Courier New';
ctx.drawImage(shirt, shirtLeft, shirtTop, shirtWidth, shirtHeight);
ctx.drawImage(logo, x, y, logoWidth, logoHeight);
ctx.fillStyle = 'rgb(255,255,0)';
ctx.fillText(headerText, 5, easel.viewport.h - 5);
};
makeItRain.populate(); //pass a custom wait function between particles
makeItRain.process(); //begin processing the scene
} //end app()
|
define([
'mage/storage',
'Magento_Checkout/js/model/url-builder',
'Magento_Checkout/js/model/error-processor',
'Magento_Checkout/js/model/full-screen-loader'
], function (storage, urlBuilder, errorProcessor, fullScreenLoader) {
'use strict';
return function (orderId, messageContainer) {
var serviceUrl = urlBuilder.createUrl('/swarming_subscribepro/me/get-order-status/:orderId', {
orderId: orderId
});
fullScreenLoader.startLoader();
return storage.post(
serviceUrl, '', true, 'application/json'
).fail(
function (response) {
errorProcessor.process(response, messageContainer);
}
).always(
function () {
fullScreenLoader.stopLoader();
}
);
};
});
|
const mongoose = require('mongoose');
var lightSchema = new mongoose.Schema({
bridgeId: String,
bridgeLightId: { type: String, required: true },
state: { type: Boolean, required: true, default: true },
sat: { type: Number, required: true, default: 254 },
bri: { type: Number, required: true, default: 100 },
hue: { type: Number, required: true, default: 0 },
color: { type: String, default: '#ff0000' },
name: { type: String, require: true },
groups: [String],
effect: { type: String, default: 'none' },
alert: { type: String, default: 'none' }
});
module.exports = mongoose.model('Light', lightSchema);
|
version https://git-lfs.github.com/spec/v1
oid sha256:9252cdf1d10a47742e55a564183a689a04eec289d704a1510933de90369862ab
size 38140
|
function DefectSummaryMatrix() {
var defectData;
var table;
var total = "Total";
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
var header = rally.sdk.ui.AppHeader;
header.showPageTools(true);
header.removePageTool("print");
header.addPageTool({
key:"Previous Version",
label:"Previous Version",
onClick: function() {
if (parent && parent.window && parent.window.location) {
parent.window.location = "http://agilecommons.org/posts/4d4d00c953";
}
else {
window.location = "http://agilecommons.org/posts/4d4d00c953";
}
}
});
function initialize3DArray(rows, cols) {
defectData = [cols];
for (var c = 0; c <= cols; c++) {
defectData[c] = [];
for (var r = 0; r <= rows; r++) {
defectData[c][r] = [];
}
}
}
function addDefect(column, row, defect) {
defectData[column][row].push(defect);
}
function setOwner(defect) {
if (defect.Owner !== null) {
if (defect.Owner.DisplayName !== "") {
defect.Owner = defect.Owner.DisplayName;
} else {
defect.Owner = defect.Owner.LoginName;
}
} else {
defect.Owner = "";
}
}
function findIndex(value, listOfValues) {
for (var i = 0; i < listOfValues.length; i++) {
if (listOfValues[i] == value) {
return i;
}
}
return 0;
/* Returning 0 to accommodate having null values in the priority field even though the object has "None" in WSAPI */
}
// return 3D array by priority, state and list of defects
function countByPriorityAndState(defectResults) {
var maxRow = defectResults.defectPriorities.length;
var maxCol = defectResults.defectStates.length;
initialize3DArray(maxRow, maxCol);
// cycle through defects and increment the appropriate state/priority combo in the array
var row, column;
for (var i = 0; i < defectResults.defects.length; i++) {
column = findIndex(defectResults.defects[i].State, defectResults.defectStates);
row = findIndex(defectResults.defects[i].Priority, defectResults.defectPriorities);
var defect = defectResults.defects[i];
addDefect(column, row, defect);
addDefect(column, maxRow, defect);
addDefect(maxCol, row, defect);
addDefect(maxCol, maxRow, defect);
setOwner(defect);
}
}
var defectQuery = function() {
var selected = releaseDropdown.getSelectedName();
var releaseQuery = '(Release.Name = "' + selected + '")';
var queryObject = [];
queryObject[0] = { key: 'defectStates', type: 'Defect', attribute: 'State' };
queryObject[1] = { key: 'defectPriorities', type: 'Defect', attribute: 'Priority' };
queryObject[2] = {
key: 'defects',
type: 'Defect',
query: releaseQuery,
fetch: 'FormattedID,Name,State,Priority,ScheduleState,ObjectID,Description,owner,DisplayName,LoginName'
};
rallyDataSource.findAll(queryObject, populateTable);
};
var destroyDefectList = function() {
if (defectList) {
defectList.destroy();
defectList = null;
var displayHeader = dojo.byId('displayHeader');
if(displayHeader) {
displayHeader.innerHTML = '';
}
}
};
var populateTable = function (results) {
var tableDiv = document.getElementById('defects');
var states = [];
states[0] = " ";
for (var i = 0; i < results.defectStates.length; i++) {
states[i + 1] = results.defectStates[i];
}
states[results.defectStates.length + 1] = total;
var config = { 'columnKeys': states, 'sortingEnabled' : false };
if (table) {
table.destroy();
}
table = new rally.sdk.ui.Table(config);
var priorities = [];
for (var j = 0; j < results.defectPriorities.length; j++) {
priorities[j] = results.defectPriorities[j];
table.setCell(j, 0, priorities[j]);
}
table.setCell(results.defectPriorities.length, 0, total);
countByPriorityAndState(results);
var onTableClick = function(obj, args) {
var col = args.columnIndex - 1;
if (col < 0) {
return;
}
var row = args.rowIndex;
var displayHeaderDiv = dojo.byId('displayHeader');
var columnText = args.columnHeader + " ";
var rowText = obj.getCell(row, 0) + " ";
var preface = "";
var postface = "";
if (columnText === total + " ") {
columnText = "";
preface = "All ";
}
if (rowText === " ") {
rowText = "";
postface = " Without a Priority";
}
if (rowText === total + " ") {
// rowText = "";
preface = "All ";
}
destroyDefectList();
displayHeaderDiv.innerHTML = preface + columnText + rowText + "Defects " + postface;
var displayDiv = dojo.byId('display');
var defectConfig = {
'columnKeys': ['FormattedID','Name','State','Priority', 'Owner']
};
defectList = new rally.sdk.ui.Table(defectConfig);
defectList.addRows(defectData[col][row]);
for (var i = 0; i < defectData[col][row].length; i++) {
var target = rally.sdk.util.Ref.createRallyDetailUrl(defectData[col][row][i]._ref);
defectList.setCell(i, 0, "<a href=" + target + " target=_blank>" + defectData[col][row][i].FormattedID + "</a>");
}
defectList.display(displayDiv);
};
table.addEventListener("onCellClick", onTableClick);
// make formattedID link to work products
for (var col = 0; col < defectData.length; col++) {
for (var row = 0; row < defectData[col].length; row++) {
table.setCell(row, col + 1, "<a href='#' onclick='return false;'>" + defectData[col][row].length + "</a>");
}
}
table.display(tableDiv);
};
var releaseDiv = dojo.byId('release');
var releaseDropdown = new rally.sdk.ui.ReleaseDropdown({}, rallyDataSource);
var defectList = null;
var releaseDropdownWrapper = function(obj, args) {
destroyDefectList();
defectQuery(obj, args);
};
releaseDropdown.display(releaseDiv, releaseDropdownWrapper);
}
|
import Flickr from "@/flickr"
export default function getPhotos(
{ flickr = Flickr, photosetId = ``, userId = `` } = {},
{ privacyFilter = 0, media = `all`, extras = ``, page = 1, perPage = 500 } = {}
) {
return flickr.fetchResource(
`flickr.photosets.getPhotos`,
{ photosetId, userId },
{ privacyFilter, media, extras, page, perPage }
)
}
|
/**
* Object.getPrototypeOf Polyfill
*/
if( !Object.getPrototypeOf ) Object.getPrototypeOf = function(obj) {
var proto = obj.__proto__;
if (! proto) {
proto = (obj.constructor ? obj.constructor.prototype : Object.prototype);
}
return proto;
}
|
// # Ghost Configuration
// Setup your Ghost install for various environments
var path = require('path'),
config;
config = {
// ### Development **(default)**
development: {
url: 'http://dev.empeeric.com',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
host: '0.0.0.0',
port: '80'
}
},
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://www.justanidea.co',
mail: {
transport: 'SMTP',
options: {
service: 'Sendgrid',
auth: {
user: 'app19038357@heroku.com',
pass: 'c9kk80ik'
}
}
},
database: {
client: 'pg',
connection: {
host: 'ec2-54-247-106-185.eu-west-1.compute.amazonaws.com',
user: 'smknpmkmhpyhmq',
password: 'p-dUmHCjgdR0gin8LzlZlI_VTm',
database: 'daepnk39n56mgg',
port: '5432'
},
debug: false
},
server: {
host: '0.0.0.0',
port: process.env.PORT
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
}
},
// ### Travis
// Automated testing run through Github
travis: {
url: 'http://127.0.0.1:2368',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-travis.db')
}
},
server: {
host: '127.0.0.1',
port: '2368'
}
}
};
// Export config
module.exports = config;
|
/******************************************************************************
almostvanilla.js
https://github.com/cvasseng/almostvanilla.js/
Copyright (c) 2015 Chris Vasseng
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.
******************************************************************************/
/** Perform an Ajax request
*
* Same syntax as jQuery, with the exception that requests can be
* prepared and fired at a later time.
*
* @example
* av.ajax({
* url: 'http://google.com',
* success: function (data) {
* document.body.innerHTML = data;
* }
* });
*
* @emits OK - Emitted when the request suceeds
* > {anything} - the request result
* @emits Error - Emitted when an error occures
* > {string} - the error message
*
* @param p {object} - The settings for the request
* > url {string} - the url
* > type {string} - the request type (get, post, update, delete)
* > dataType {string} - the expected return type (json, xml, text, octet)
* > data {anything} - the payload data
* > autoFire {boolean} - should we run the request right away?
* > headers {object} - headers to send, e.g. `{'Content-Type': 'application/json'}
* > sucess {function} - the function to call on success
* > {anything} - the request result
* > error {function} - the function to call on error
* > {string} - the error message
*
* @returns {object} - an interface to interact with the request
* > on {function} - listen to an event
* > fire {function} - perform the request
* > request {XMLHttpRequest} - the request object
*/
av.ajax = function (p) {
var props = av.merge({
url: false,
type: 'GET',
dataType: 'json',
success: function () {},
error: function () {},
data: {},
autoFire: true,
headers: {}
}, p),
headers = {
json: 'application/json',
xml: 'application/xml',
text: 'text/plain',
octet: 'application/octet-stream'
},
r = new XMLHttpRequest(),
events = av.events()
;
if (!props.url) return false;
r.open(props.type, props.url, true);
if (!props.headers['Content-Type']) {
r.setRequestHeader('Content-Type', headers[props.dataType] || headers.text);
}
Object.keys(props.headers).forEach(function (name) {
r.setRequestHeader(name, props.headers[name]);
});
r.onreadystatechange = function () {
events.emit('ReadyStateChange', r.readyState, r.status);
if (r.readyState === 4 && r.status === 200) {
if (props.dataType === 'json') {
try {
var json = JSON.parse(r.responseText);
if (av.isFn(props.success)) {
props.success(json);
}
events.emit('OK', json);
} catch(e) {
if (av.isFn(props.error)) {
props.error(e.toString(), r.responseText);
}
events.emit('Error', e.toString(), r.status);
}
} else {
if (av.isFn(props.success)) {
props.success(r.responseText);
}
events.emit('OK', r.responseText);
}
} else if (r.readyState === 4) {
events.emit('Error', r.status, r.statusText);
if (av.isFn(props.error)) {
props.error(r.status, r.statusText);
}
}
};
function fire() {
try {
r.send(JSON.stringify(props.data));
} catch (e) {
r.send(props.data || true);
}
}
if (props.autoFire) {
fire();
}
return {
on: events.on,
fire: fire,
request: r
}
};
|
// Custom JavaScript here
// =======================================================================
//= require jquery
//= require jquery.easing/jquery.easing
//= require jquery.stellar/jquery.stellar
//= require mapbox.js/mapbox.uncompressed
//= require formstone/dist/js/core
//= require formstone/dist/js/transition
//= require formstone/dist/js/background
//= require _bootstrap
//= require _grayscale
$(".video-bg").background({
source: {
// poster: "path/to/poster.jpg",
// video: "//www.youtube.com/embed/vLUNWYt3q1w"
// video: "//www.youtube.com/embed/J25CjWf61ks" yesmite (werbung)
// video: "//www.youtube.com/embed/1HZ0iSwqsWA"
// video: "//www.youtube.com/embed/oaU9ZhAi6oU" video background south america
poster: "/img/20120521-yosemite-327.jpg", // http://www.projectyose.com/ https://vimeo.com/87701971
// video: "//www.youtube.com/embed/fb4dpcIYTrc" // night vision cities europe
}
});
/*
$( "#toggle-video" ).click(function() {
$("#toggle-icon").toggleClass("fa-play");
$("#toggle-icon").toggleClass("fa-pause");
if($("#toggle-icon").hasClass("fa-play")){
$(".video-bg").background("pause");
} else {
$(".video-bg").background("play");
}
});
*/
$.stellar({
horizontalScrolling: false
});
|
// Handles all navigation stuff
import {
NAV_LOGIN,
NAV_LOGOUT
} from '../actions/types';
import { AppNavigator } from '../AppNavigator';
// Start with two routes: The Main screen, with the Login screen on top.
const firstAction = AppNavigator.router.getActionForPathAndParams('Login');
const tempNavState = AppNavigator.router.getStateForAction(firstAction);
const secondAction = AppNavigator.router.getActionForPathAndParams('Logout');
const initialNavState = AppNavigator.router.getStateForAction(
firstAction
);
export default NavReducer = (state = initialNavState, action) => {
let nextState;
console.log(action);
switch (action.type) {
case NAV_LOGIN:
// nextState = AppNavigator.router.getStateForAction(
// NavigationActions.back(),
// state
// );
break;
case NAV_LOGOUT:
nextState = AppNavigator.router.getStateForAction(
NavigationActions.navigate({ routeName: 'Logout' }),
state
);
break;
default:
nextState = AppNavigator.router.getStateForAction(action, state);
break;
}
// Simply return the original `state` if `nextState` is null or undefined.
return nextState || state;
}; |
let currentBrowser;
module.exports = {
tags: ['component', 'video'],
'Bolt Video Playback Rate': function(browser) {
const { testingUrl } = browser.globals;
console.log(`global browser url: ${testingUrl}`);
currentBrowser = '--' + browser.currentEnv || 'chrome';
let testName = 'bolt-video-playback-rate';
browser
.url(
`${testingUrl}/pattern-lab/patterns/02-components-video-35-video-with-inline-script-and-external-controls/02-components-video-35-video-with-inline-script-and-external-controls.html`,
)
.waitForElementVisible('.video-js', 1000)
.click('.vjs-big-play-button')
.assert.elementPresent('.vjs-playback-rate')
.execute(function(data) {
return document.querySelector('button.vjs-playback-rate').click();
})
.saveScreenshot(
`screenshots/bolt-video/${testName}--${currentBrowser}.png`,
)
.execute(
function(data) {
return document.querySelector('bolt-video').player.playbackRate();
},
[],
function(result) {
browser.assert.ok(
result.value === 1.25,
`verified that <bolt-video> play rate has sped up to ${result.value}`,
);
},
)
.execute(
function(data) {
return document.querySelector('.vjs-playback-rate-value').textContent;
},
[],
function(result) {
browser.assert.ok(
result.value === '1.25x',
`verified that <bolt-video> play rate text reads 1.25x.`,
);
},
)
.saveScreenshot(
`screenshots/bolt-video/${testName}--playback-at-1.25x--${currentBrowser}.png`,
)
.end();
},
'<bolt-video> plays via <bolt-button> on-click hook': function(browser) {
const { testingUrl } = browser.globals;
currentBrowser = '--' + browser.currentEnv || 'chrome';
let testName = 'bolt-video-external-controls';
browser
.url(
`${testingUrl}/pattern-lab/patterns/02-components-video-25-video-with-external-controls/02-components-video-25-video-with-external-controls.html`,
)
.waitForElementVisible('bolt-button', 1000)
.click('bolt-button')
.pause(1000)
.execute(
function(data) {
return document.querySelector('bolt-video').player.hasStarted_;
},
[],
function(result) {
browser.assert.ok(
result.value === true,
`verified the <bolt-video> has started playing via the "hasStarted" property.`,
);
},
)
.saveScreenshot(
`screenshots/bolt-video/${testName}--has-started-playing--${currentBrowser}.png`,
)
.pause(4000)
.execute(
function(data) {
return document.querySelector('bolt-video').player.currentTime();
},
[],
function(result) {
browser.assert.ok(
result.value > 1,
`<bolt-video> starts playing when <bolt-button> is clicked -- verified since the current video's play time is ${result.value} seconds`,
);
},
)
.saveScreenshot(
`screenshots/bolt-video/${testName}--has-finished--${currentBrowser}.png`,
)
.end();
},
};
|
// @flow
import defineType, {
assertEach,
assertNodeType,
assertValueType,
chain,
} from "./utils";
import { classMethodOrPropertyCommon } from "./es2015";
defineType("AwaitExpression", {
builder: ["argument"],
visitor: ["argument"],
aliases: ["Expression", "Terminatorless"],
fields: {
argument: {
validate: assertNodeType("Expression"),
},
},
});
defineType("BindExpression", {
visitor: ["object", "callee"],
aliases: ["Expression"],
fields: {
// todo
},
});
defineType("ClassProperty", {
visitor: ["key", "value", "typeAnnotation", "decorators"],
builder: ["key", "value", "typeAnnotation", "decorators", "computed"],
aliases: ["Property"],
fields: {
...classMethodOrPropertyCommon,
value: {
validate: assertNodeType("Expression"),
optional: true,
},
definite: {
validate: assertValueType("boolean"),
optional: true,
},
typeAnnotation: {
validate: assertNodeType("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true,
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
readonly: {
validate: assertValueType("boolean"),
optional: true,
},
},
});
defineType("OptionalMemberExpression", {
builder: ["object", "property", "computed", "optional"],
visitor: ["object", "property"],
aliases: ["Expression"],
fields: {
object: {
validate: assertNodeType("Expression"),
},
property: {
validate: (function() {
const normal = assertNodeType("Identifier");
const computed = assertNodeType("Expression");
return function(node, key, val) {
const validator = node.computed ? computed : normal;
validator(node, key, val);
};
})(),
},
computed: {
default: false,
},
optional: {
validate: assertValueType("boolean"),
},
},
});
defineType("OptionalCallExpression", {
visitor: ["callee", "arguments", "typeParameters"],
builder: ["callee", "arguments", "optional"],
aliases: ["Expression"],
fields: {
callee: {
validate: assertNodeType("Expression"),
},
arguments: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType("Expression", "SpreadElement", "JSXNamespacedName"),
),
),
},
optional: {
validate: assertValueType("boolean"),
},
typeArguments: {
validate: assertNodeType("TypeParameterInstantiation"),
optional: true,
},
typeParameters: {
validate: assertNodeType("TSTypeParameterInstantiation"),
optional: true,
},
},
});
defineType("ClassPrivateProperty", {
visitor: ["key", "value"],
builder: ["key", "value"],
aliases: ["Property", "Private"],
fields: {
key: {
validate: assertNodeType("PrivateName"),
},
value: {
validate: assertNodeType("Expression"),
optional: true,
},
},
});
defineType("Import", {
aliases: ["Expression"],
});
defineType("Decorator", {
visitor: ["expression"],
fields: {
expression: {
validate: assertNodeType("Expression"),
},
},
});
defineType("DoExpression", {
visitor: ["body"],
aliases: ["Expression"],
fields: {
body: {
validate: assertNodeType("BlockStatement"),
},
},
});
defineType("ExportDefaultSpecifier", {
visitor: ["exported"],
aliases: ["ModuleSpecifier"],
fields: {
exported: {
validate: assertNodeType("Identifier"),
},
},
});
defineType("ExportNamespaceSpecifier", {
visitor: ["exported"],
aliases: ["ModuleSpecifier"],
fields: {
exported: {
validate: assertNodeType("Identifier"),
},
},
});
defineType("PrivateName", {
visitor: ["id"],
aliases: ["Private"],
fields: {
id: {
validate: assertNodeType("Identifier"),
},
},
});
defineType("BigIntLiteral", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("string"),
},
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:3da8a6eec57798cf88c64374348f0ffdd895462d1653ca948965416b7ff8a2d2
size 15659
|
version https://git-lfs.github.com/spec/v1
oid sha256:3487b2a00e32392d11c09f4cf9238beea7ac51de0c4bafe5dcaf2f04a523b6d9
size 70159
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.