code
stringlengths
1
2.08M
language
stringclasses
1 value
// 1 - wall // 2 - steel wall // 3 - trees module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,2,2,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,2,2,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [2,2,0,0,1,1,1,1,2,2,0,0,0,0,0,0,2,2,1,1,1,1,0,0,2,2], [2,2,0,0,1,1,1,1,2,2,0,0,0,0,0,0,2,2,1,1,1,1,0,0,2,2], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,2,2,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,2,2,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; };
JavaScript
if (!window.availableLangs['default']) { window.availableLangs['default'] = {}; } window.availableLangs['default']['ru'] = { 'enter-nick': 'Введите ник:' , 'legend-play': 'Игра' , 'legend-learn': 'Учебник программирования' , 'submit-play': 'Вход' , 'submit-learn': 'Вход' , 'header-players': 'Игроки' , 'header-public-chat': 'Общий чат' , 'join-existen-game': 'Присоеди&shy;нитесь в идущую игру:' , 'submit': 'Отправить' , 'header-create-game': 'Создать игру' , 'choose-game-type': 'Выберите тип игры:' , 'enter-new-game-name': 'Введите имя новый игры:' , 'submit-create': 'Создать' , 'game-type-classic': 'Классический' , 'game-type-teamvsteam': 'Командный' , 'game-type-classic-desc': 'Тут вы можете пройти все 35 уровней старых добрых танчиков. После завершения каждого уровня нажимайте "Старт!", чтобы начать следующий.' , 'game-type-teamvsteam-desc': 'В командном режиме вы можете сразиться с другимим игроками 2 на 2. Доступен только один уровень. Первые двое подключившихся страртуют снизу карты, третий и четвертый - сверху.' , 'message-connection': 'Подключение...' , 'message-connection-fail': 'Извините, не удалось подключиться к серверу. Возможно вы находитесь за прокси, которая рубит WebSocket трафик (в будущем шанс подключиться через такие прокси будет увеличен с помошью ssl-соединения).' , 'message-connection-closed': 'Извините, подключение прервано. Перезагрузите страницу, чтобы начать заново.' , 'header-premade-chat': 'Чат игры' , 'start': 'Старт!' , 'exit': 'Выход' , 'prompt-level': 'Уровень:' , 'execute-code': 'Выполнить код' , 'restart': 'Начать заново' , 'lack-of-websocket-support': 'Извините, но ваш браузер не поддерживает websocket. Рекомендуемые браузеры - <a href="http://www.google.com/chrome/">Google Chrome</a> версии 14 и выше, и <a href="http://www.mozilla.org/">Firefox</a> версии 7 и выше.' , 'course-pascal-basics': 'Основы Pascal' , 'course-algoritms': 'Алгоритмы' , 'header-available-courses': 'Доступные курсы' , 'header-available-exercises': 'Упражнения' , 'pascal-algoritm1': 'Алгоритм 1' , 'pascal-algoritm1-desc': 'В этом упражнении вам необходимо написать программу управления танком, которая приведет его в точку назначения.' , 'pascal-algoritm2': 'Алгоритм 2' , 'pascal-algoritm2-desc': 'В этом упражнении вам необходимо написать программу управления танком, которая приведет его в точку назначения.' , 'pascal-if-statement': 'Условный оператор IF' , 'pascal-if-statement-desc': 'В этом упражнении вам необходимо написать программу управления танком, которая приведет его в точку назначения.' , 'pascal-for-statement': 'Оператор цикла FOR' , 'pascal-for-statement-desc': 'В этом упражнении вам необходимо написать программу управления танком, которая приведет его в точку назначения.' , 'algoritms-wayfinder': 'Поиск пути' , 'algoritms-wayfinder-desc': 'Поиск пути описание описание описание описание описание описание описание.' , 'tabs-help': 'Помощь' , 'tabs-editor': 'Редактор кода' };
JavaScript
window.availableLangs = {}; window.lang = {current: null}; function applyLang(lang, context, recursive) { if (!lang) { lang = window.lang.current; } else { window.lang.current = lang; } var elements = $('.lang', context); if (context) { elements = elements.add(context.filter('.lang')); } elements.each(function(){ var key = $(this).attr('key'); var file = $(this).attr('langfile') ? $(this).attr('langfile') : 'default'; if (file == 'null') { return; } if (!recursive && (!window.availableLangs[file] || !window.availableLangs[file][lang])) { $.getScript(file + lang + '.js', function(){ applyLang(lang, context, true); }); } else { try { // if 'file' or 'lang' still not exists if (window.availableLangs[file][lang][key]) { $(this).html(window.availableLangs[file][lang][key]); } else { console.log('Unknown lang key "' + file + '", "' + lang + '", "' + key + '"'); } } catch (ex) { console.log('Unknown lang key "' + file + '", "' + lang + '", "' + key + '"'); } var onlang = $(this).attr('onlang'); if (onlang) { eval(onlang + '(this)'); } } }); $('.lang-select li.current').removeClass('current'); $('.lang-select li[lang=' + lang + ']').addClass('current'); } $(function(){ applyLang('ru'); });
JavaScript
if (!window.availableLangs['default']) { window.availableLangs['default'] = {}; } window.availableLangs['default']['en'] = { 'enter-nick': 'Enter nick:' , 'legend-play': 'Game' , 'legend-learn': 'Code tutorials' , 'submit-play': 'Login' , 'submit-learn': 'Login' , 'header-players': 'Players' , 'header-public-chat': 'Public chat' , 'join-existen-game': 'Join the game:' , 'submit': 'Submit' , 'header-create-game': 'Create a new game' , 'choose-game-type': 'Choose game type:' , 'enter-new-game-name': 'Enter new game name:' , 'submit-create': 'Create' , 'game-type-classic': 'Classic' , 'game-type-teamvsteam': 'Team Vs. Team' , 'game-type-classic-desc': 'Here you can play all 35 levels of classic BattleCity game. Click "Start!" after each level to start the next level.' , 'game-type-teamvsteam-desc': 'In this mode you can play against other players. There is only one level. First and second players start on the bottom, third and fourth players start on the top.' , 'message-connection': 'Connection...' , 'message-connection-fail': 'Unable to connect to the server. Maybe you are behind the proxy which don\'t pass WebSocket traffic.' , 'message-connection-closed': 'Sorry, but connection was closed. Reload page to start again.' , 'header-premade-chat': 'Premade chat' , 'start': 'Start!' , 'exit': 'Exit' , 'prompt-level': 'Level:' , 'execute-code': 'Execute code' , 'restart': 'Restart' , 'lack-of-websocket-support': 'Sorry, but your browser doesn\'t support websockets. Recommended browsers are <a href="http://www.google.com/chrome/">Google Chrome</a> version 14 or above, and <a href="http://www.mozilla.org/">Firefox</a> version 7 or above.' , 'course-pascal-basics': 'Pascal basics' , 'course-algoritms': 'Algoritms' , 'header-available-courses': 'Available Courses' , 'header-available-exercises': 'Упражнения' , 'pascal-algoritm1': 'Algoritm 1' , 'pascal-algoritm1-desc': 'In this exercise you will write a program which will lead the tank to the checkpoint.' , 'pascal-algoritm2': 'Algoritm 2' , 'pascal-algoritm2-desc': 'In this exercise you will write a program which will lead the tank to the checkpoint.' , 'pascal-if-statement': 'IF operator' , 'pascal-if-statement-desc': 'In this exercise you will write a program which will lead the tank to the checkpoint.' , 'pascal-for-statement': 'FOR operator' , 'pascal-for-statement-desc': 'In this exercise you will write a program which will lead the tank to the checkpoint.' , 'algoritms-wayfinder': 'Wayfinder' , 'algoritms-wayfinder-desc': 'Wayfinder desc' , 'tabs-help': 'Help' , 'tabs-editor': 'Code editor' };
JavaScript
/** * Интерпритатор эмулирует синхронное выполнение кода оправляя команды обработчику * и дожидаясь выполнения каждой команды. * * @var code массив действий для выполнения */ /* Регистры (любое значение): ax Встроенные функции: move (distance) turn (direction) fire x - get tank x y - get tank y CheckPointX - CheckPointY - */ Vm = function Vm(client) { this.code = []; this.client = client; this.reset(); }; Eventable(Vm.prototype); Vm.prototype.reset = function() { this.registers = { 'ax': 0, 'cx': 0 }; this.stack = []; this.pointer = 0; }; Vm.prototype.step = function() { var command = this.code[this.pointer]; if (command) { this.pointer++; if (typeof(this[command]) == 'function') { this[command](); } else { throw new Error('"' + command + '" is not a valid command'); } } else { this.emit('terminate'); } }; Vm.prototype.getArgs = function(n) { if (n === undefined) { n = parseInt(this.stack.pop()); } var params = []; for (var i = 0 ; i < n ; i++) { params.unshift(this.stack.pop()); } return params; }; Vm.prototype['write'] = function() { var params = this.getArgs(); for (var i = 0 ; i < params.length ; i++) { this.emit('write', params[i]); } }; Vm.prototype['writeln'] = function() { this.write(); this.emit('write', '\n'); }; Vm.prototype['jmp'] = function() { var offset = parseInt(this.code[this.pointer++]); this.pointer += offset; }; Vm.prototype['push-val'] = function() { var value = this.code[this.pointer++]; this.stack.push(value); }; Vm.prototype['push-reg'] = function() { var registerName = this.code[this.pointer++]; this.stack.push(this.registers[registerName]); }; Vm.prototype['push-mem'] = function() { var offset = parseInt(this.code[this.pointer++]); this.stack.push(this.code[offset]); }; Vm.prototype['pop-reg'] = function() { var registerName = this.code[this.pointer++]; this.registers[registerName] = this.stack.pop(); }; Vm.prototype['pop-mem'] = function() { var offset = parseInt(this.code[this.pointer++]); this.code[offset] = this.stack.pop(); }; Vm.prototype['add'] = function() { var arg2 = parseInt(this.stack.pop()); // second argument var arg1 = parseInt(this.stack.pop()); // first argument this.stack.push(arg1 + arg2); }; Vm.prototype['sub'] = function() { var arg2 = parseInt(this.stack.pop()); // second argument var arg1 = parseInt(this.stack.pop()); // first argument this.stack.push(arg1 - arg2); }; Vm.prototype['move-reg-mem'] = function() { var registerName = this.code[this.pointer++]; var address = this.code[this.pointer++]; this.registers[registerName] = this.code[address]; }; Vm.prototype['move-reg-val'] = function() { var registerName = this.code[this.pointer++]; var value = this.code[this.pointer++]; this.registers[registerName] = value; }; Vm.prototype['move-mem-reg'] = function() { var address = this.code[this.pointer++]; var registerName = this.code[this.pointer++]; this.code[address] = this.registers[registerName]; }; Vm.prototype['move-mem-val'] = function() { var address = this.code[this.pointer++]; var value = this.code[this.pointer++]; this.code[address] = value; }; Vm.prototype['move-mem-mem'] = function() { var address1 = this.code[this.pointer++]; var address2 = this.code[this.pointer++]; this.code[address1] = this.code[address2]; }; Vm.prototype['jz'] = function() { var offset = parseInt(this.code[this.pointer++]); if (this.registers['ax'] == 0) { this.pointer += offset; } }; Vm.prototype['jnz'] = function() { var offset = parseInt(this.code[this.pointer++]); if (this.registers['ax'] != 0) { this.pointer += offset; } }; Vm.prototype['ja'] = function() { var offset = parseInt(this.code[this.pointer++]); if (this.registers['ax'] > 0) { this.pointer += offset; } }; Vm.prototype['jae'] = function() { var offset = parseInt(this.code[this.pointer++]); if (this.registers['ax'] >= 0) { this.pointer += offset; } }; Vm.prototype['jb'] = function() { var offset = parseInt(this.code[this.pointer++]); if (this.registers['ax'] < 0) { this.pointer += offset; } }; Vm.prototype['jbe'] = function() { var offset = parseInt(this.code[this.pointer++]); if (this.registers['ax'] <= 0) { this.pointer += offset; } }; Vm.prototype['loop'] = function() { var offset = parseInt(this.code[this.pointer++]); this.registers['cx']--; if (this.registers['cx'] > 0) { this.pointer += offset; } }; Vm.prototype['dec-mem'] = function() { var offset = parseInt(this.code[this.pointer++]); this.code[offset]--; }; Vm.prototype['inc-mem'] = function() { var offset = parseInt(this.code[this.pointer++]); this.code[offset]++; }; Vm.prototype['tank-move'] = function() { var steps = this.stack.pop(); this.emit('action', { 'move': steps * 16 }); }; Vm.prototype['tank-turn'] = function() { var direction = this.stack.pop(); this.emit('action', { 'turn': direction }); }; Vm.prototype['tank-fire'] = function() { this.emit('action', { 'fire': 1 }); }; Vm.prototype['tank-x'] = function() { var field = this.client.field; var tankId = this.client.currentUser.tankId; var x = Math.floor(field.get(tankId).x / 16); this.stack.push(x); }; Vm.prototype['tank-y'] = function() { var field = this.client.field; var tankId = this.client.currentUser.tankId; var y = Math.floor(field.get(tankId).y / 16); this.stack.push(y); }; Vm.prototype['checkpoint-x'] = function() { var checkpoint = this.client.goals.getFirst(function(item){ return (item instanceof GoalCheckPoint) && (item.status == 0); }); if (checkpoint) { this.stack.push(checkpoint.checkpoint.x / 16); } else { this.stack.push(0); throw new Error('No checkpoint found'); } }; Vm.prototype['checkpoint-y'] = function() { var checkpoint = this.client.goals.getFirst(function(item){ return (item instanceof GoalCheckPoint) && (item.status == 0); }); if (checkpoint) { this.stack.push(checkpoint.checkpoint.y / 16); } else { this.stack.push(0); throw new Error('No checkpoint found'); } };
JavaScript
PascalCompiler = function PascalCompiler(codeStr) { this.codeStr = codeStr; this.cur = 0; this.line = 1; this.char = 1; this.posStack = []; // stack to save cursor positions to properly show error place this.buildInFunc = { 'write': { 'signature': 'var', // var args 'inline': 'write' }, 'writeln': { 'signature': 'var', // var args 'inline': 'writeln' }, 'move': { 'signature': ['integer'], 'inline': 'tank-move' }, 'turn': { 'signature': ['string'], 'inline': 'tank-turn' }, 'fire': { 'signature': [], 'inline': 'tank-fire' }, 'x': { 'signature': [], 'inline': 'tank-x', 'type': 'integer' }, 'y': { 'signature': [], 'inline': 'tank-y', 'type': 'integer' }, 'checkpointx': { 'signature': [], 'inline': 'checkpoint-x', 'type': 'integer' }, 'checkpointy': { 'signature': [], 'inline': 'checkpoint-y', 'type': 'integer' } }; }; PascalCompiler.prototype.isSpace = /^\s$/; PascalCompiler.prototype.isNum = /^[0-9]$/; PascalCompiler.prototype.isChar = /^[a-z]$/i; PascalCompiler.prototype.isSymbol = /^\w$/i; PascalCompiler.prototype.isKeyword = /^(program|var|begin|end|if|for)$/i; PascalCompiler.prototype.isRelationOp = /^(<|<=|=|<>|>=|>)$/; PascalCompiler.prototype.parse = function() { return this.parseProgram(); }; PascalCompiler.prototype.parseProgram = function() { this.symbolTable = new SymbolTable(); this.varOffset = 2; var code = ['jmp', 0 /* will changed */]; this.eatIdentifier('program'); var name = this.parseIdentifier(); this.token(';'); var chunk = this.parseBlock(); this.token('.'); // allocate space for global vars for (var i = 0, l = this.symbolTable.length() ; i < l ; i++) { code.push(0); } code = code.concat(chunk); // jump over vars space code[1] = this.symbolTable.length(); return { code: code }; }; PascalCompiler.prototype.parseBlock = function() { if (this.lookIdentifier() == 'var') { this.parseVariableDeclaration(); } return this.parseBlock5(); }; PascalCompiler.prototype.parseVariableDeclaration = function() { var vars, type, v; this.eatIdentifier('var'); while (true) { if (this.isKeyword.test(this.lookIdentifier())) { break; } vars = []; do { vars.push(this.parseIdentifier()); } while (this.look() == ',' && this.token(',')); this.token(':'); type = this.parseIdentifier(); try { while (v = vars.pop()) { this.symbolTable.addVar(v, type); } } catch (ex) { throw new Error(ex.message + ' at ' + this.formatPos()); } if (this.look() == ';') { this.token(';'); } else { break; } } }; PascalCompiler.prototype.parseBlock5 = function() { this.eatIdentifier('begin'); var chunk = this.parseStatementList(); this.eatIdentifier('end'); return chunk; }; PascalCompiler.prototype.parseStatementList = function() { var code = []; while (true) { code = code.concat(this.parseStatement()); if (this.lookIdentifier() == 'end') { break; } this.token(';'); } return code; }; PascalCompiler.prototype.parseStatement = function() { var code = []; var look = this.lookIdentifier(); if (look.length > 0) { if (this.isKeyword.test(look)) { switch (look) { case 'if': code = this.parseIf(); break; case 'begin': this.token('begin'); code = this.parseStatementList(); this.token('end'); break; case 'for': code = this.parseFor(); break; } } else { var name = this.parseIdentifier(); if (this.look() == ':') { code = this.parseAssigment(name); } else if (this.look() == '(' || this.look() == ';' || this.test(this.isChar)) { code = this.parseFunctionCall(name); } } } return code; }; PascalCompiler.prototype.parseFor = function() { // for name := a to b do statement this.token('for'); var name = this.parseIdentifier(); var code = this.parseAssigment(name); var v = this.symbolTable.look(name); if (v.type != 'integer') { throw new Error('Loop variable must be an integer at ' + this.formatPos()); } // if parseAssigment done without expression, then 'v' must exists var dir = this.parseIdentifier(); if (dir != 'to' && dir != 'downto') { throw new Error('"to" or "downto" expected at ' + this.formatPos()); } var b = this.parseExpression(); if (b.type != 'integer') { throw new Error('Loop expression must be an integer at ' + this.formatPos()); } this.token('do'); var statement = this.parseStatement(); code = code.concat(b.code); // loop condition check (7 commands) code.push('push-mem'); code.push(v.offset + this.varOffset); code.push('sub'); // top of the stack is b-a code.push('pop-reg'); code.push('ax'); if (dir == 'to') { // break if b-a < 0 (means "for a:=1 to 1 do" should repeat 1 time) code.push('jb'); code.push(statement.length + 4 /*jmp to start of the loop*/); } else { // downto // break if b-a > 0 code.push('ja'); code.push(statement.length + 4 /*jmp to start of the loop*/); } code = code.concat(statement); // jmp to start of the loop code.push(dir == 'to' ? 'inc-mem' : 'dec-mem'); code.push(v.offset + this.varOffset); code.push('jmp'); code.push(-(statement.length + 4 /*this jmp*/ + 7 /* loop condition check */ + b.code.length)); return code; }; PascalCompiler.prototype.parseIf = function(name) { var code = []; this.token('if'); var ex = this.parseExpression(); this.token('then'); var ifStatement = this.parseStatement(); var elseStatement = []; if (this.lookIdentifier() == 'else') { this.token('else'); elseStatement = this.parseStatement(); } code = code.concat(ex.code); code.push('pop-reg'); code.push('ax'); if (elseStatement.length == 0) { code.push('jz'); code.push(ifStatement.length); code = code.concat(ifStatement); } else { code.push('jz'); code.push(ifStatement.length + 2 /* jmp over elseStatement */); code = code.concat(ifStatement); code.push('jmp'); code.push(elseStatement.length); code = code.concat(elseStatement); } return code; }; PascalCompiler.prototype.parseAssigment = function(name) { var code = []; this.token(':='); var ex = this.parseExpression(); code = code.concat(ex.code); var v; if ((v = this.symbolTable.look(name))) { if (v.type == ex.type) { code.push('pop-reg'); code.push('ax'); code.push('move-mem-reg', v.offset + this.varOffset, 'ax'); } else { throw new Error('Mistmatch types "' + v.type + '" and "' + ex.type + '" at ' + this.formatPos()); } } else { throw new Error('Undefined variable "' + name + '" at ' + this.formatPos()); } return code; }; /** * Call function or procedure. * Result of the functions will be on top of the stack. * @param name * @return */ PascalCompiler.prototype.parseFunctionCall = function(name) { var code = [], ex, func; if ((func = this.buildInFunc[name])) { var param = []; if (this.look() == '(') { this.token('('); do { if (this.look() == ')') { break; } ex = this.parseExpression(); param.push(ex); code = code.concat(ex.code); } while (this.look() == ',' && this.token(',')); this.token(')'); } if (func.signature == 'var') { code.push('push-val'); code.push(param.length); } else { if (func.signature.length == param.length) { for (var i = 0 ; i < param.length ; i++) { if (param[i].type != func.signature[i]) { throw new Error('Mismatch argument type in function "' + name + '" call, argument ' + i + ', at ' + this.formatPos()); } } } else { throw new Error('Mismatch parameters count for function "' + name + '" at ' + this.formatPos()); } } code.push(func.inline); } else { throw new Error('Undefined function or procedure "' + name + '" at ' + this.formatPos()); } return code; }; /** * parse an expression and put result in on top of the stack * @return */ PascalCompiler.prototype.parseExpression = function() { var res = this.parsePrimaryExpression(); if (this.isRelationOp.test(this.look())) { // < <= = <> >= > if (res.type != 'integer') { throw new Error('Mismatch types in relation operation at ' + this.formatPos()); } var op = this.look(); if (this.isRelationOp.test(op + this.look(1))) { op += this.look(1); } this.token(op); var right = this.parsePrimaryExpression(); if (right.type != 'integer') { throw new Error('Mismatch types in relation operation at ' + this.formatPos()); } res.code = res.code.concat(right.code); res.code.push('sub'); res.code.push('pop-reg'); res.code.push('ax'); switch (op) { case '<': res.code.push('jae'); // a - b < 0 so jump to "push-val 0" if above or equal break; case '<=': res.code.push('ja'); // a - b <= 0 so jump to "push-val 0" if above break; case '=': res.code.push('jnz'); // a - b == 0 so jump to "push-val 0" if non zero break; case '<>': res.code.push('jz'); // a - b != 0 so jump to "push-val 0" if zero break; case '>': res.code.push('jbe'); // a - b > 0 so jump to "push-val 0" if below or equal break; case '>=': res.code.push('jb'); // a - b >= 0 so jump to "push-val 0" if below break; } res.code.push('4'); res.code.push('push-val'); res.code.push(1); res.code.push('jmp'); res.code.push('2'); res.code.push('push-val'); res.code.push(0); } return res; }; /** * parse an expression and put result in on top of the stack * @return */ PascalCompiler.prototype.parsePrimaryExpression = function() { var code = [], type, value; if (this.test(this.isChar)) { var name = this.parseIdentifier(); var v; if (v = this.symbolTable.look(name)) { code.push('push-mem'); code.push(v.offset + this.varOffset); type = v.type; } else if (this.buildInFunc[name]) { var chunk = this.parseFunctionCall(name); code = code.concat(chunk); type = this.buildInFunc[name].type; } else { throw new Error('Undefined variable "' + name + '" at ' + this.formatPos()); } } else if (this.test(this.isNum)) { value = this.parseNumber(); code.push('push-val'); code.push(value); type = 'integer'; } else if (this.test("'")) { value = this.parseString(); type = 'string'; code.push('push-val'); code.push(value); } else { throw new Error('Unexpected "' + this.look() + '". Expression expected at ' + this.formatPos()); } return { type: type, code: code }; }; PascalCompiler.prototype.parseNumber = function() { var next; if (next = this.test(this.isNum)) { var res = 0; while (next = this.test(this.isNum)) { res = res * 10 + parseInt(next); this.eat(next); } this.eatWs(); return res; } else { throw new Error('Unexpected "' + this.look() + '". Num expected at ' + this.formatPos()); } }; PascalCompiler.prototype.parseString = function() { this.eat("'"); var next; var res = ''; while (!this.test("'")) { next = this.look(); res += next; this.eat(next); } this.eat("'"); this.eatWs(); return res; }; PascalCompiler.prototype.testIdentifier = function(identifier) { this.pushCur(); var res = this.parseIdentifier(); this.popCur(); return res == identifier; }; PascalCompiler.prototype.eatIdentifier = function(identifier) { this.pushPos(); if (this.parseIdentifier() != identifier) { throw new Error(identifier + ' expected at ' + this.formatPos()); } this.popPos(); }; PascalCompiler.prototype.parseIdentifier = function() { var next; if (next = this.test(this.isChar)) { var res = ''; while (next = this.test(this.isSymbol)) { res += next; this.eat(next); } this.eatWs(); return res.toLowerCase(); } else { throw new Error('Unexpected "' + this.look() + '". Identifier expected at ' + this.formatPos()); } }; PascalCompiler.prototype.look = function(offset) { return this.codeStr.charAt(this.cur + (offset ? offset : 0)); }; PascalCompiler.prototype.lookIdentifier = function() { this.pushCur(); var next, res = false; if (next = this.test(this.isChar)) { res = ''; while (next = this.test(this.isSymbol)) { res += next; this.eat(next); } } this.popCur(); return res; }; /** * @param char char || RegExp * @return */ PascalCompiler.prototype.test = function(check) { var res = this.look(); if (check) { if ((typeof check == 'string') && res != check || (typeof check == 'object') && !check.test(res)) { return false; } } return res; }; /** * @param char should not be '\n' */ PascalCompiler.prototype.eat = function(str) { var look = this.codeStr.substr(this.cur, str.length); if (look == str) { this.cur += str.length; this.char += str.length; } else { throw new Error('"' + str + '" expected at ' + this.formatPos() + ', but "' + look + '" given'); } }; PascalCompiler.prototype.token = function(token) { this.eat(token); this.eatWs(); return true; }; PascalCompiler.prototype.eatWs = function() { while (this.isSpace.test(this.look())) { if (this.look() == '\n') { this.line++; this.char = 1; } else { this.char++; } this.cur++; } }; PascalCompiler.prototype.formatPos = function() { if (this.posStack.length > 0) { var pos = this.popPos(); return 'line: ' + pos.line + ', char: ' + pos.char; } else { return 'line: ' + this.line + ', char: ' + this.char; } }; PascalCompiler.prototype.pushPos = function() { this.posStack.push({line: this.line, char: this.char}); }; PascalCompiler.prototype.popPos = function() { return this.posStack.pop(); }; PascalCompiler.prototype.pushCur = function() { this.posStack.push({line: this.line, char: this.char, cur: this.cur}); }; PascalCompiler.prototype.popCur = function() { var pos = this.posStack.pop(); this.line = pos.line; this.char = pos.char; this.cur = pos.cur; };
JavaScript
function SymbolTable() { this.identifiers = []; }; SymbolTable.prototype._index = function(name, sig) { return name + (sig ? ':' + sig.join(',') : ''); }; SymbolTable.prototype.addVar = function(name, type) { if (this.look(name) == null) { var v = {name: name, type: type}; v.offset = this.identifiers.push(v) - 1; } else { throw new Error('Identifier "' + name + '" already defined'); } }; /** * * @param name * @return index of found var or -1 */ SymbolTable.prototype.look = function(name) { for (var i = 0, l = this.identifiers.length ; i < l ; i++) { if (this.identifiers[i].name == name) { return this.identifiers[i]; } } return null; }; SymbolTable.prototype.length = function() { return this.identifiers.length; };
JavaScript
function VmRunner(client) { this.client = client; this.vm = new Vm(client); this.codeInterval = null; var self = this; client.socket.on('disconnect', function(){ clearInterval(self.codeInterval); }); client.socket.on('unjoined', function(){ clearInterval(self.codeInterval); }); client.socket.on('gameover', function(){ clearInterval(self.codeInterval); }); client.socket.on('task-done', function(message){ if (message) { self.emit('write', message + '\n'); } clearInterval(self.codeInterval); self.codeInterval = setInterval(function(){ self.vm.step(); }, 1); }); this.vm.on('action', function(action){ clearInterval(self.codeInterval); if (action.move) { self.client.move(action.move); } if (action.turn) { self.client.turn(action.turn); } if (action.fire) { self.client.fire(); } }); this.vm.on('write', function(data){ self.client.emit('write', data); }); this.vm.on('terminate', function(action){ clearInterval(self.codeInterval); }); }; VmRunner.prototype.executeCode = function(code) { clearInterval(this.codeInterval); try { var res = new PascalCompiler(code).parse(); console.log(res.code); this.vm.code = res.code; this.vm.reset(); } catch (ex) { this.client.emit('compile-error', ex); } var self = this; this.codeInterval = setInterval(function(){ self.vm.step(); }, 1); }; Eventable(VmRunner.prototype);
JavaScript
Premade = function Premade(name, type) { this.name = name; this.type = type || 'classic'; this.level = 1; this.userCount = 0; this.locked = false; // lock for new users if (!isClient()) { this.users = new TList(); // todo move to clan? switch (this.type) { case 'classic': this.clans = [new Clan(1, 10*30/*~30step per seconds*/), new BotsClan(2, 10*30/*~30step per seconds*/)]; break; case 'createbot': this.clans = [new Clan(1, 10*30/*~30step per seconds*/), new LearnerClan(2, 10*30/*~30step per seconds*/)]; break; case 'teamvsteam': this.clans = [new Clan(1, 2*30/*~30step per seconds*/), new Clan(2, 2*30/*~30step per seconds*/)]; break; } this.clans[0].premade = this.clans[1].premade = this; this.clans[0].enemiesClan = this.clans[1]; this.clans[1].enemiesClan = this.clans[0]; this.messages = new TList(); } }; Eventable(Premade.prototype); Premade.types = { 'classic': { 'levels': 35 }, 'teamvsteam': { 'levels': 1 }, 'createbot': { 'levels': 4 } }; Premade.prototype.say = function(message) { this.messages.add(message); for (var i in this.messages.items) { if (this.messages.items[i].time + 5 * 60 * 1000 < Date.now()) { this.messages.remove(this.messages.items[i]); } } }; Premade.prototype.setClan = function(user, clanId) { this.clans[clanId].attachUser(user); }; Premade.prototype.join = function(user, clanId) { clanId = clanId || 0; if (this.type == 'teamvsteam' && this.clans[clanId].isFull()) { clanId = 1; } if (!this.locked && !this.clans[clanId].isFull()) { // todo extract to user method setPremade() if (user.premade) { user.premade.unjoin(); } user.premade = this; this.clans[clanId].attachUser(user); this.users.add(user); this.userCount++; this.emit('change'); // todo extract to user methods setLives(), setPoints() ? user.lives = 4; user.points = 0; user.emit('change'); user.watchCollection(this.users, 'premade.users'); user.watchCollection(this.messages, 'premade.messages'); } else { throw {message: 'К этой игре уже нельзя присоединиться.'}; } }; Premade.prototype.unjoin = function(user) { user.unwatchCollection('premade.users'); user.unwatchCollection('premade.messages'); user.unwatchCollection('f'); user.unwatchCollection('game.botStack'); user.unwatchCollection('goals'); user.clan.detachUser(user); this.users.remove(user); this.userCount--; user.premade = null; this.emit('change'); if (this.userCount == 0) { registry.premades.remove(this); this.removed = true; // dirty hack } }; Premade.prototype.startGame = function() { this.locked = true; var level = require('../battle-city/maps/' + this.type + '/level' + this.level); this.game = new Game(level.getMap(), this); this.clans[0].startGame(this.game, level); this.clans[1].startGame(this.game, level); this.users.traversal(function(user){ user.watchCollection(this.game.field, 'f'); if (user.clan.enemiesClan.botStack) { user.watchCollection(user.clan.enemiesClan.botStack, 'game.botStack'); } if (user.clan.enemiesClan.goals) { user.watchCollection(user.clan.enemiesClan.goals, 'goals'); } if (user.premade.type == 'teamvsteam') { user.lives = 4; user.emit('change'); } user.clientMessage('started', { // todo this is for client to get lang file 'courseId': user.currentCourse.id, 'courseName': user.currentCourse.name, 'exerciseId': this.level // todo level and exerciseId are the same }); }, this); this.game.start(); this.emit('change'); }; Premade.prototype.gameOver = function(winnerClan, timeout) { if (this.game && this.game.running) { this.game.running = false; var self = this; if (timeout) { setTimeout(function(){ self._gameOver(winnerClan); }, timeout ? timeout : 1000); } else { this._gameOver(winnerClan); } } }; Premade.prototype._gameOver = function(winnerClan) { if (this.game) { this.game.gameOver(); if (this.type == 'teamvsteam') { this.locked = false; } if (this.type == 'classic' && this.clans[0] == winnerClan) { this.level++; if (this.level > Premade.types[this.type].levels) { this.level = 1; } } if (this.removed === undefined) { // todo dirty hack this.emit('change'); } this.users.traversal(function(user){ user.unwatchCollection('f'); user.unwatchCollection('game.botStack'); user.clientMessage('gameover', { winnerClan: winnerClan ? winnerClan.n : 0 }); console.log(new Date().toLocaleTimeString() + ': user ' + user.nick + ' has left game ' + user.premade.name); }, this); this.clans[0].game = this.clans[1].game = this.game = null; } }; Premade.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name], // 0 this.id, // 1 this.name, // 2 this.level, // 3 this.type, // 4 this.locked, // 5 this.userCount, // 6 this.gameRun || this.game && this.game.running // 7 todo avoid this kind of code ]; }; Premade.prototype.unserialize = function(data) { this.id = data[1]; this.name = data[2]; this.level = data[3]; this.type = data[4]; this.locked = data[5]; this.userCount = data[6]; this.gameRun = data[7]; };
JavaScript
/** * public interface: * void add(item) * bool remove(item) * bool move(item, newX, newY) * object[] intersects(item) */ MapTiled = function MapTiled(width, height) { this.all = []; // for fast traversal this.items = []; this.maxX = Math.ceil(width/this.tileSize) - 1; this.maxY = Math.ceil(height/this.tileSize) - 1; for (var x = 0 ; x <= this.maxX ; x++) { this.items[x] = []; for (var y = 0 ; y <= this.maxY ; y++) { this.items[x][y] = {}; } } }; // todo convert to bytes for right shift ">>" MapTiled.prototype.tileSize = 16; MapTiled.prototype.add = function(item) { if (item.id === undefined) { console.trace(); throw {message: 'item.id must be set', item: item}; } if (this.all[item.id] === undefined) { var fromX = Math.floor((item.x-item.hw) / this.tileSize); if (fromX < 0) fromX = 0; else if (fromX > this.maxX) fromX = this.maxX; var toX = Math.ceil ((item.x+item.hw) / this.tileSize); if (toX < 0) toX = 0; else if (toX > this.maxX) toX = this.maxX; var fromY = Math.floor((item.y-item.hh) / this.tileSize); if (fromY < 0) fromY = 0; else if (fromY > this.maxX) fromY = this.maxY; var toY = Math.ceil ((item.y+item.hh) / this.tileSize); if (toY < 0) toY = 0; else if (toY > this.maxX) toY = this.maxY; for (var x = fromX ; x <= toX ; x++) { for (var y = fromY ; y <= toY ; y++) { this.items[x][y][item.id]= item; } } this.all[item.id] = item; } }; MapTiled.prototype.get = function(id) { return this.all[id]; }; MapTiled.prototype.remove = function(item) { if (this.all[item.id]) { delete this.all[item.id]; var fromX = Math.floor((item.x-item.hw) / this.tileSize); if (fromX < 0) fromX = 0; else if (fromX > this.maxX) fromX = this.maxX; var toX = Math.ceil ((item.x+item.hw) / this.tileSize); if (toX < 0) toX = 0; else if (toX > this.maxX) toX = this.maxX; var fromY = Math.floor((item.y-item.hh) / this.tileSize); if (fromY < 0) fromY = 0; else if (fromY > this.maxX) fromY = this.maxY; var toY = Math.ceil ((item.y+item.hh) / this.tileSize); if (toY < 0) toY = 0; else if (toY > this.maxX) toY = this.maxY; for (var x = fromX ; x <= toX ; x++) { for (var y = fromY ; y <= toY ; y++) { delete this.items[x][y][item.id]; } } return true; } else { return false; } }; MapTiled.prototype.setXY = function(item, newX, newY) { this.remove(item); item.x = newX; item.y = newY; this.add(item); }; MapTiled.prototype.move = function(item, newX, newY) { var items = this.intersects(item, newX, newY); if (items.length == 0 || (item.onIntersect && item.onIntersect(items))) { this.setXY(item, newX, newY); return true; } else { return false; } }; /** * * @param item not always needed, but should be object * @param ix int|null * @param iy int|null * @param hw int|null * @param hh int|null * @return */ MapTiled.prototype.intersects = function(item, ix, iy, hw, hh) { var res = [], ix = ix || item.x, iy = iy || item.y, hw = hw || item.boundX, hh = hh || item.boundY; var fromX = Math.floor((ix-hw) / this.tileSize); if (fromX < 0) fromX = 0; else if (fromX > this.maxX) fromX = this.maxX; var toX = Math.ceil ((ix+hw) / this.tileSize); if (toX < 0) toX = 0; else if (toX > this.maxX) toX = this.maxX; var fromY = Math.floor((iy-hh) / this.tileSize); if (fromY < 0) fromY = 0; else if (fromY > this.maxX) fromY = this.maxY; var toY = Math.ceil ((iy+hh) / this.tileSize); if (toY < 0) toY = 0; else if (toY > this.maxX) toY = this.maxY; for (var x = fromX ; x <= toX ; x++) { for (var y = fromY ; y <= toY ; y++) { for (var i in this.items[x][y]) { var each = this.items[x][y][i]; if (each.id == item.id || res[each.id]) continue; if (Math.abs(each.x - ix) < (each.boundX + hw) && Math.abs(each.y - iy) < (each.boundY + hh)) { res[each.id] = each; } } } } return res; }; MapTiled.prototype.traversal = function(callback, thisObj) { for (var i in this.all) { callback.call(thisObj, this.all[i]); } };
JavaScript
/** * this is for both, client and server. */ User = function User() { }; Eventable(User.prototype); /** * @todo hack for BcClient.onUserChange() * @param data * @return */ User.prototype.serialize = function() { var res = []; res[1] = this.id; res[2] = this.nick; res[3] = this.lives; res[4] = this.points; res[5] = this.clan; res[6] = this.premadeId; res[7] = this.positionId; res[8] = this.tankId; res[9] = this.currentCourseId; return res; }; User.prototype.unserialize = function(data) { this.id = data[1]; this.nick = data[2]; this.lives = data[3]; this.points = data[4]; this.clan = data[5]; this.premadeId = data[6]; this.positionId = data[7]; this.tankId = data[8]; this.currentCourseId = data[9]; };
JavaScript
vector = function vector(x) { if (x) { return x/Math.abs(x); } else { return 0; } }; isClient = function isClient() { return !(typeof window == 'undefined' && typeof global == 'object'); }; serializeTypeMatches = { 'Bullet' : 1, 'Tank' : 2, 'TankBot' : 3, 'HeavyTankBot' : 4, 'FastBulletTankBot' : 5, 'FastTankBot' : 6, 'Wall' : 7, 'SteelWall' : 8, 'BonusTimer' : 9, 'BonusShovel' : 10, 'BonusStar' : 11, 'BonusHelmet' : 12, 'BonusLive' : 13, 'BonusGrenade' : 14, 'Water' : 15, 'Trees' : 16, 'Ice' : 17, 'Delimiter' : 18, 'Base' : 19, 'ServerUser' : 20, 'Premade' : 21, 'Message' : 22, 'Checkpoint' : 23, 'GoalCheckPoint' : 24, 'Course' : 25, 'Exercise' : 26 }; unserializeTypeMatches = { 1: 'Bullet', 2: 'Tank', 3: 'TankBot', 4: 'HeavyTankBot', 5: 'FastBulletTankBot', 6: 'FastTankBot', 7: 'Wall', 8: 'SteelWall', 9: 'BonusTimer', 10: 'BonusShovel', 11: 'BonusStar', 12: 'BonusHelmet', 13: 'BonusLive', 14: 'BonusGrenade', 15: 'Water', 16: 'Trees', 17: 'Ice', 18: 'Delimiter', 19: 'Base', 20: 'User', 21: 'Premade', 22: 'Message', 23: 'Checkpoint', 24: 'GoalCheckPoint', 25: 'Course', 26: 'Exercise' };
JavaScript
Game = function Game(map, premade) { this.running = true; // premade set this to false before game over this.premade = premade; this.stepableItems = []; this.field = new Field(13*32, 13*32); this.field.game = this; this.field.on('add', this.onAddObject.bind(this)); this.field.on('remove', this.onRemoveObject.bind(this)); this.field.terrain(map); }; Game.prototype.onAddObject = function(object) { if (object.step && !(object instanceof Tank) && !(object instanceof Base)) { this.stepableItems[object.id] = object; } }; Game.prototype.onRemoveObject = function(object) { delete this.stepableItems[object.id]; }; Game.prototype.start = function() { this.stepIntervalId = setInterval(this.step.bind(this), 30); }; Game.prototype.gameOver = function() { clearInterval(this.stepIntervalId); this.field.removeAllListeners(); // this.field.game = null; // todo when game finished, next item.step() failed // this.field = null; }; Game.prototype.step = function() { for (var i in this.stepableItems) { this.stepableItems[i].step(); // bullets only now } this.premade.clans[0].step(); this.premade.clans[1].step(); };
JavaScript
var path = require("path"); var fs = require("fs"); /** * This object is an interface for "server-side" variables. All access to them * should be done here. * * @param socket EventEmitter */ BcServerInterface = function BcServerInterface(socket) { this.user = null; this.socket = socket; socket.on('login', this.onLogin.bind(this)); socket.on('set-course', this.onSetCourse.bind(this)); socket.on('join', this.onJoin.bind(this)); socket.on('unjoin', this.onUnjoin.bind(this)); socket.on('execute', this.onExecute.bind(this)); socket.on('start', this.onStart.bind(this)); socket.on('stop-game', this.onStopGame.bind(this)); socket.on('control', this.onControl.bind(this)); socket.on('say', this.onSay.bind(this)); socket.on('disconnect', this.onDisconnect.bind(this)); try { var connections = 0; for (var i in socket.manager.connected) { connections++; } } catch(e) {} console.log(new Date().toLocaleTimeString() + ': Connection accepted (' + connections , ' total)'); }; BcServerInterface.prototype.onLogin = function(event) { if (this.user == null && event.nick) { var nick = event.nick && event.nick.substr(0,20); var nickAllowed = true; registry.users.traversal(function(user){ if (nick == user.nick) { nickAllowed = false; } }); if (nickAllowed) { this.user = new ServerUser(registry.courses.get(1)); this.user.lastSync = 0; this.user.socket = this.socket; this.user.nick = nick; registry.users.add(this.user); this.user.updateIntervalId = setInterval(this.user.sendUpdatesToClient.bind(this.user), 50); this.socket.emit('logged', { user: this.user.serialize() }); this.user.watchCollection(registry.users, 'users'); this.user.watchCollection(registry.premades, 'premades'); this.user.watchCollection(registry.messages, 'messages'); this.user.watchCollection(registry.courses, 'courses'); console.log(new Date().toLocaleTimeString() + ': user ' + nick + ' connected'); } else { this.socket.emit('nickNotAllowed'); } } }; BcServerInterface.prototype.onSetCourse = function(event){ var courseId = event.id; var course = registry.courses.get(courseId); if (this.user && course) { this.user.setCurrentCourse(course); } // todo why user.setCurrentCourse() is not enough? this.socket.emit('course-changed', course.id); }; BcServerInterface.prototype.onJoin = function(event){ try { registry.premades.join(event, this.user); this.socket.emit('joined', { // user not likely synced this premade yet premade: this.user.premade.serialize() }); console.log(new Date().toLocaleTimeString() + ': user ' + this.user.nick + ' join premade ' + this.user.premade.name + ' (' + event.gameType + ')'); } catch (ex) { console.log(ex.message, ex.stack); this.socket.emit('user-message', { message: ex.message }); } }; BcServerInterface.prototype.onUnjoin = function(){ if (this.user.premade) { console.log(new Date().toLocaleTimeString() + ': user ' + this.user.nick + ' unjoin premade ' + this.user.premade.name); this.user.premade.unjoin(this.user); this.socket.emit('unjoined'); } }; BcServerInterface.prototype.onExecute = function(event){ var userFolder = path.join(process.cwd(), 'bots/' + this.user.id); try { fs.mkdirSync(userFolder, 0777); } catch (ex) {/*ignore EEXIST*/} var tries = fs.readdirSync(userFolder); var botSourceFile = path.join(userFolder, 'try' + tries.length + '.pas'); fs.writeFileSync(botSourceFile, event.code); this.socket.emit('execute', { script: botSourceFile.substr(process.cwd().length) }); }; BcServerInterface.prototype.onStart = function(event){ if (this.user.premade && !this.user.premade.game) { if (event.level && this.user.premade.level != event.level) { this.user.premade.level = event.level; this.user.premade.emit('change'); } this.user.premade.startGame(); console.log(new Date().toLocaleTimeString() + ': user ' + this.user.nick + ' starts game ' + this.user.premade.name + ', level ' + this.user.premade.level); } }; BcServerInterface.prototype.onStopGame = function(){ if (this.user.premade) { this.user.premade.gameOver(); } }; BcServerInterface.prototype.onControl = function(event) { if (this.user) { try { this.user.control(event); } catch (ex) { console.log(ex.stack); } } }; BcServerInterface.prototype.onSay = function(event) { var message = event.text; if (typeof message == 'string') { message = message.substr(0, 200); } if (this.user.say(message)) { console.log(new Date().toLocaleTimeString() + ': user ' + this.user.nick + ' say ' + message); } else { this.user.clientMessage('doNotFlood'); } }; BcServerInterface.prototype.onDisconnect = function(event) { try { var connections = -1; for (var i in this.socket.manager.connected) { connections++; } } catch(e) {} if (this.user) { console.log(new Date().toLocaleTimeString() + ': user ' + this.user.nick + ' disconnected (' + connections , ' total)'); clearInterval(this.user.updateIntervalId); this.user.unwatchAll(); this.user.socket = null; if (this.user.premade) { this.user.premade.unjoin(this.user); } registry.users.remove(this.user); } else { console.log(new Date().toLocaleTimeString() + ': anonymous disconnected (' + connections , ' total)'); } };
JavaScript
Message = function Message(text) { this.time = Date.now(); this.text = text; }; Eventable(Message.prototype); Message.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name] // 0 , this.id // 1 , this.time // 2 , this.user.id // 3 , this.user.nick // 4 , this.text // 5 ]; }; Message.prototype.unserialize = function(data) { this.id = data[1]; this.time = data[2]; this.userId = data[3]; this.nick = data[4]; this.text = data[5]; };
JavaScript
// test is this node.js or browser if (typeof require == 'function') { EventEmitter = require('events').EventEmitter; } Eventable = function Eventable(object) { for (var i in EventEmitter.prototype) { object[i] = EventEmitter.prototype[i]; } };
JavaScript
/** * Don't call Array methods which modify items, because they don't emit events. */ TList = function TList() { this.items = []; }; Eventable(TList.prototype); TList.prototype.get = function(id) { return this.items[id]; }; TList.prototype.add = function(item) { if (item.id !== undefined) { this.items[item.id] = item; } else { item.id = this.items.push(item) - 1; } this.emit('add', item); var self = this; if (item.on) { item.on('change', function(){ self.emit('change', this); }); } }; TList.prototype.remove = function(item) { this.emit('remove', item); delete this.items[item.id]; }; TList.prototype.clear = function() { for (var i in this.items) { this.emit('remove', this.items[i]); delete this.items[i]; } }; TList.prototype.pop = function() { // do not pop()! beause of "a.pop()" != "delete a[a.length-1]" var i = -1; for (i in this.items); // not mistake if (i == -1) { return null; } var item = this.items[i]; this.emit('remove', item); delete this.items[i]; return item; }; TList.prototype.getFirst = function(filter) { for (var i in this.items) { if (filter) { if (filter(this.items[i])) { return this.items[i]; } } else { return this.items[i]; } } return null; }; TList.prototype.count = function() { var n = 0; for (var i in this.items) { n++; } return n; }; TList.prototype.traversal = function(callback, thisObj) { for (var i in this.items) { callback.call(thisObj, this.items[i]); } }; TList.prototype.updateWith = function(events){ for (var i in events) { var eventType = events[i][0/*type*/]; var eventData = events[i][1/*data*/]; var type = unserializeTypeMatches[eventData[0/*type*/]]; var id = parseInt(eventData[1/*id*/]); switch (eventType) { case 'r'/*remove*/: if (obj = this.items[id]) { obj.unserialize(eventData); // for bullets finalX and finalY this.remove(obj); } break; case 'a'/*add*/: case 'c'/*change*/: var obj = this.items[id]; if (obj) { obj.unserialize(eventData); this.emit('change', obj); } else { obj = new (window[type])(); obj.unserialize(eventData); this.add(obj); } break; } } }; /** * Bind object to list. * All changes in a list's object with same id will reflect in the slaveObject. * @param slaveObject * @return */ TList.prototype.bindSlave = function(slaveObject) { var self = this; var handler = function(each) { if (slaveObject.id === each.id) { // id may be 0 or undefined, so === slaveObject.unserialize(each.serialize()); slaveObject.emit('change'); } }; this.on('add' , handler); this.on('change', handler); this.on('remove', handler); }; TList.prototype.bindSource = function(source, key) { var self = this; source.on('sync', function(data){ if (data[key]) { self.updateWith(data[key]); } }); source.on('clearCollection', function(data) { if (data == key) { self.clear(); } }); return this; };
JavaScript
/** * * @param context * @param client * @return */ function UiGameControls(context, client) { this.context = context; this.resetState(); var self = this; client.socket.on('gameover', this.setStateGameOver.bind(this)); client.socket.on('started', this.setStateGameRunning.bind(this)); client.socket.on('joined', this.resetState.bind(this)); $('.exit-game', context).click(function(){ client.unjoin(); }); $('.exit-exercise', context).click(function(){ client.unjoin(); }); $('.start-game', context).click(function(){ client.startGame($('select[name=level]', context).val()); }); $('.execute-code', context).click(function(){ client.executeCode(window.codeMirror.getValue()); }); $('.stop-game', context).click(function(){ client.stopGame(); }); $('.restart-game', context).click(function(){ client.stopGame(); client.startGame($('select[name=level]', context).val()); }); }; UiGameControls.prototype.resetState = UiGameControls.prototype.setStateGameOver = function() { $('.start-game' , this.context).removeAttr('disabled'); $('.stop-game' , this.context).attr('disabled', 'disabled'); $('.execute-code', this.context).attr('disabled', 'disabled'); }; UiGameControls.prototype.setStateGameRunning = function() { $('.start-game' , this.context).attr('disabled', 'disabled'); $('.stop-game' , this.context).removeAttr('disabled'); $('.execute-code', this.context).removeAttr('disabled'); };
JavaScript
function WidgetPublic(context, client) { this.premades = new UiPremadeList( client.premades, $('.premades', context), 'premade'); this.publicChat = new WidgetPublicChat(context, client); $('.premade', context).live('click', function(){ client.join($('.name', this).text()); return false; }); };
JavaScript
function WidgetPremade(context, client) { this.levelSelector = new WidgetLevelSelector($('.level', context), client); this.chat = new WidgetPremadeChat(context, client); this.gameControls = new UiGameControls(context, client); };
JavaScript
function UiList(list, container, itemClass) { if (arguments.length) { this.container = container; this.itemClass = itemClass; list.on('add', this.onAdd.bind(this)); list.on('change', this.onChange.bind(this)); list.on('remove', this.onRemove.bind(this)); } }; UiList.prototype.itemDomElement = function(item) { throw new Error('subclass responsibility'); }; UiList.prototype.onAdd = function(item) { this.container.append(this.itemDomElement(item)); }; UiList.prototype.onChange = function(item) { $('.' + this.itemClass + item.id, this.container).replaceWith(this.itemDomElement(item)); }; UiList.prototype.onRemove = function(item) { $('.' + this.itemClass + item.id, this.container).remove(); }; //====== UiUserList ============================================================ function UiUserList(list, container, itemClass) { UiList.apply(this, arguments); }; UiUserList.prototype = new UiList(); UiUserList.prototype.constructor = UiUserList; UiUserList.prototype.itemDomElement = function(user) { return $('<div class="' + this.itemClass + ' ' + (window.bcClient.currentUser.id === user.id ? 'current ' : '') + this.itemClass + user.id + '"></div>').text(user.nick); }; //====== UiCoursesList ========================================================= function UiCoursesList(list, container, itemClass, client) { UiList.apply(this, arguments); this.client = client; client.socket.on('course-changed', function(id){ $('.' + itemClass, container).removeClass('current'); $('.' + itemClass + id, container).addClass('current'); }); }; UiCoursesList.prototype = new UiList(); UiCoursesList.prototype.constructor = UiCoursesList; UiCoursesList.prototype.itemDomElement = function(course) { var cls = 'lang ' + this.itemClass + ' ' + (this.client.currentUser.currentCourseId === course.id ? 'current ' : '') + this.itemClass + course.id; var res = $('<div class="' + cls + '" key="' + course.name + '"></div>'); applyLang(null, res); var self = this; res.click(function(){ self.client.setCourse(course.id); }); return res; }; //====== UiExercisesList ======================================================= function UiExercisesList(list, container, itemClass) { UiList.apply(this, arguments); }; UiExercisesList.prototype = new UiList(); UiExercisesList.prototype.constructor = UiExercisesList; UiExercisesList.prototype.itemDomElement = function(exercise) { var cls = this.itemClass + ' ' + this.itemClass + exercise.id; var res = $('<div class="' + cls + '"><h3 class="lang" key="' + exercise.name + '"></h3>'+ '<p class="lang" key="' + exercise.name + '-desc"></p>' + '<div class="exercise-controls"><div class="select" level="' + exercise.level + '">&rarr;</div></div>'+ '</div>'); applyLang(null, res); return res; }; //====== UiPremadeUserList ===================================================== function UiPremadeUserList(list, container, itemClass, currentPremade) { UiUserList.apply(this, arguments); this.currentPremade = currentPremade; }; UiPremadeUserList.prototype = new UiUserList(); UiPremadeUserList.prototype.constructor = UiPremadeUserList; UiPremadeUserList.prototype.itemDomElement = function(user) { var text = user.nick; if (this.currentPremade.type == 'teamvsteam') { text = user.nick + (user.clan == 1 ? ' (внизу)' : ' (вверху)'); } return $('<div class="' + this.itemClass + ' ' + (window.bcClient.currentUser.id == user.id ? 'current ' : '') + this.itemClass + user.id + '"></div>').text(text); }; //====== UiPremadeList ========================================================= function UiPremadeList(list, container, itemClass) { UiList.apply(this, arguments); }; UiPremadeList.prototype = new UiList(); UiPremadeList.prototype.constructor = UiPremadeList; UiPremadeList.prototype.onAdd = function(premade) { if (premade.type != 'createbot') { this.container.append(this.itemDomElement(premade)); } }; UiPremadeList.prototype.itemDomElement = function(premade) { var res = $('<div class="' + this.itemClass + ' ' + (premade.locked ? 'locked ' : '') + this.itemClass + premade.id + '"><span class="name"/><span class="stat"/></div>'); var stat = ' (' + premade.userCount + '/' + (premade.type == 'classic' ? 2 : 4) + ')'; $('.name', res).text(premade.name); $('.stat', res).text(stat); return res; }; //====== UiMessageList ========================================================= function UiMessageList(list, container, itemClass) { UiList.apply(this, arguments); }; UiMessageList.prototype = new UiList(); UiMessageList.prototype.constructor = UiMessageList; UiMessageList.prototype.itemDomElement = function(message) { var date = new Date(message.time); var time = date.getHours() + ':' + (date.getMinutes() < 10 ? 0 : '') + date.getMinutes(); var res = $('<div class="' + this.itemClass + ' ' + this.itemClass + message.id + '"><span class="time">' + time + '</span> <span class="nick"></span> <span class="text"></span></div>'); $('.nick', res).text('<' + message.nick + '>'); $('.text', res).text(message.text); return res; }; UiMessageList.prototype.onAdd = function(item) { this.container.append(this.itemDomElement(item)); var wrapper1 = this.container.parent().get(0); var wrapper2 = this.container.parent().parent(); if ((wrapper1.scrollHeight - wrapper1.scrollTop) < (wrapper2.height() + 100)) { wrapper1.scrollTop = wrapper1.scrollHeight; } }; //====== UiTankStack =========================================================== function UiTankStack(list, container, itemClass) { UiList.apply(this, arguments); }; UiTankStack.prototype = new UiList(); UiTankStack.prototype.constructor = UiTankStack; UiTankStack.prototype.itemDomElement = function(item) { return $('<div class="' + this.itemClass + ' ' + this.itemClass + item.id + '"><img src="img/bot.png"></div>'); };
JavaScript
//====== WidgetLevelSelector =================================================== function WidgetLevelSelector(context, client) { client.currentPremade.on('change', function() { // "this" is client.currentPremade var levelSelect = $('select', context); levelSelect.empty(); for (var i = 1; i <= Premade.types[this.type].levels; i++) { levelSelect.append($('<option value="' + i + '">' + i + '</option>')); } levelSelect.val(this.level); }); }; //====== UserPoint ============================================================= function UserPoint(premadeUsers) { premadeUsers.on('add', this.onChange.bind(this)); premadeUsers.on('change', this.onChange.bind(this)); premadeUsers.on('remove', this.onRemove.bind(this)); }; UserPoint.prototype.onChange = function(user) { // todo hack var pos = user.positionId + (user.clan == 2 ? 2 /*first clan capacity*/ : 0); $('.player' + pos + '-stats') .text(user.lives + ':' + user.points); }; UserPoint.prototype.onRemove = function(user) { // todo hack var pos = user.positionId + (user.clan == 2 ? 2 /*first clan capacity*/ : 0); $('.player' + pos + '-stats').text(''); }; //====== WidgetCreateGame ====================================================== function WidgetCreateGame(context, client) { $('#create-form', context).submit(function(){ var name = $('input[name=name]', this).val(); var gameType = $('input[name=type]', this).val(); if (name) { client.join(name, gameType); } return false; }); $('.game-modes li', context).click(function(){ $('#create-form input[name=type]').val(this.id); $('.game-modes li').removeClass('current'); $(this).addClass('current'); }); }; //====== WidgetLoginForm ======================================================= function WidgetLoginForm(context, client) { var toPage = 'setStatePublic'; $('#game-login', context).submit(function(){ client.login($('input[name=nick]', this).val()); return false; }); $('#tutor-login', context).submit(function(){ toPage = 'setStateExercises'; client.login($('input[name=nick]', this).val()); return false; }); client.socket.on('logged', function(){ window.uiManager[toPage](); }); }; //====== WidgetLangSelector ==================================================== function WidgetLangSelector() { $('.lang-select li').click(function(){ applyLang($(this).attr('lang')); }); };
JavaScript
function WidgetNotifier(client) { client.socket.on('user-message', function(data) { alert(data.message); }); client.socket.on('nickNotAllowed', function(){ alert('Ник занят. Выберите другой.'); }); client.socket.on('doNotFlood', function() { alert('Слишком много сообщений за минуту.'); }); };
JavaScript
function WidgetCreateBot(context, client) { this.context = context; context.tabs({ show: function(event, ui) { if (ui.index == 1) { // hack to force codeMirror to show code window.codeMirror.setValue(window.codeMirror.getValue()); window.codeMirror.focus(); } } }); }; WidgetCreateBot.prototype.reset = function() { if (window.codeMirror === null) { window.codeMirror = CodeMirror(document.getElementById('editor'), { lineNumbers: true, mode: "pascal", theme: "night" }); } window.codeMirror.setValue("Program Program1;\n" + "begin\n" + " \n" + "end."); this.context.tabs('select', 0); };
JavaScript
function WidgetExercises(context, client) { this.courses = new UiCoursesList(client.courses, $('.courses', context), 'course', client); this.exercises = new UiExercisesList(client.exercises, $('.exercise-list', context), 'exercise'); $('.exercise .select', context).live('click', function(){ var name = 'createbot-' + client.currentUser.id; client.join(name, 'createbot'); client.startGame(parseInt($(this).attr('level'))); return false; }); };
JavaScript
function WidgetPublicChat(context, client) { this.context = context; this.client = client; this.users = new UiUserList( client.users, $('.user-list', context), 'user'); this.messages = new UiMessageList( client.messages, $('.messages', context), 'message'); this.init(); }; WidgetPublicChat.prototype.init = function() { var self = this; $('.user', this.context).live('click', function(){ // "this" is a div.user var nick = $(this).text(); var input = $('.message-form :text', self.context); input.val(nick + ': ' + input.val()); input.focus(); }); $('form.message-form', this.context).submit(function(){ // "this" is a form var text = $(':text', this).val(); if (text) self.client.say(text); $(':text', this).val('').focus(); return false; }); }; function WidgetPremadeChat(context, client) { this.context = context; this.client = client; this.premadeUsers = new UiPremadeUserList( client.premadeUsers, $('.user-list', context), 'user', client.currentPremade); this.premadeMessages = new UiMessageList( client.premadeMessages, $('.messages', context), 'message'); this.init(); }; WidgetPremadeChat.prototype.init = WidgetPublicChat.prototype.init;
JavaScript
function FieldView(context, client) { this.field = client.field; this.context = context; this.c2d = $('#field', context).get(0).getContext('2d'); this.c2d.font ="bold 25px Arial"; this.step = 1; this.animateIntervalId = null; var self = this; this.field.on('remove', function(object){ if (object instanceof Bullet) { var anim = new BulletHitAnimation(self.step, object.finalX, object.finalY); anim.id = object.id; self.field.add(anim); } if (object instanceof Tank) { // todo hit myself without splash :( var anim = new TankHitAnimation(self.step, object.x, object.y); anim.id = object.id; self.field.add(anim); } }); client.socket.on('gameover', function(event) { clearInterval(self.animateIntervalId); if (event.winnerClan == client.currentUser.clan) { self.message('Победа!'); } else { self.message('Вы проиграли'); } }); client.socket.on('disconnect', function() { clearInterval(self.animateIntervalId); }); client.socket.on('unjoined', function(){ clearInterval(self.animateIntervalId); }); client.socket.on('started', function(){ clearInterval(self.animateIntervalId); if (window.location.hash != '#test') { self.animateIntervalId = setInterval(self.animateStep.bind(self), 50); } }); }; FieldView.prototype._animateStepItem = function(item) { item.animateStep && item.animateStep(this.step); }; FieldView.prototype.animateStep = function() { this.field.objects.traversal(FieldView.prototype._animateStepItem, this); this.step++; this.draw(); }; FieldView.prototype.drawItem = function(current) { if (current.z == this.z) { for (var i in current.img) { this.c2d.drawImage(window.images[current.img[i]], current.x - current.hw, current.y - current.hh); } } }; FieldView.prototype.draw = function() { this.c2d.fillStyle = '#041012'; this.c2d.fillRect(0, 0, this.field.width, this.field.height); if (this.context.hasClass('create-bot')) { this.c2d.strokeStyle = '#000'; this.c2d.lineWidth = 1; for (var i = 1 ; i < 26 ; i++) { this.c2d.beginPath(); this.c2d.moveTo(0, 16 * i + 0.5); this.c2d.lineTo(416, 16 * i + 0.5); this.c2d.closePath(); this.c2d.stroke(); } for (var i = 1 ; i < 26 ; i++) { this.c2d.beginPath(); this.c2d.moveTo(16 * i + 0.5, 0); this.c2d.lineTo(16 * i + 0.5, 416); this.c2d.closePath(); this.c2d.stroke(); } } for (this.z = 0 ; this.z <= 2 ; this.z++) { // this.z hack? this.field.objects.traversal(this.drawItem, this); } }; FieldView.prototype.message = function(message) { this.c2d.fillStyle = '#fff'; this.c2d.fillText(message, 100, 200); this.c2d.strokeStyle = '#000'; this.c2d.strokeText(message, 100, 200); };
JavaScript
function WidgetHelp(context, client) { client.socket.on('started', function(event){ var langfile = '/src/edu/' + event.courseName + '/ex' + event.exerciseId; $('.lang', context).attr('langfile', langfile); $('.content', context).attr('onlang', 'WidgetHelp.onLang'); applyLang(null, context); }); }; WidgetHelp.onLang = function(each) { $('.code', each).each(function(){ CodeMirror.runMode($(this).addClass('cm-s-night').text(), "pascal", this); }); };
JavaScript
function WidgetGame(context, client) { this.controller = new TankController(client); this.tankStack = new UiTankStack( client.tankStack, $('#bot-stack', context), 'bot'); this.userPoints = new UserPoint(client.premadeUsers); this.fieldView = new FieldView(context, client); this.gameControls = new UiGameControls(context, client); };
JavaScript
function WidgetConsole(context, client) { client.on('compile-error', function(ex){ context.text(context.text() + ex.message + '\n'); }); client.on('write', function(data){ context.text(context.text() + data); }); }
JavaScript
function UiManager(client) { this.client = client; this.loginForm = new WidgetLoginForm($('#login'), client); this.publicArea = new WidgetPublic($('#public'), client); this.createGame = new WidgetCreateGame($('#create'), client); this.premade = new WidgetPremade($('#premade'), client); this.game = new WidgetGame($('#game'), client); this.createBot = new WidgetCreateBot($('#bot-editor'), client); this.exercises = new WidgetExercises($('#exercises'), client); this.help = new WidgetHelp($('#tabs-help'), client); this.notifier = new WidgetNotifier(client); this.console = new WidgetConsole($('#console'), client); var self = this; client.onConnect(this.setStateLogin.bind(this)); client.onConnectFail(this.setStateConnectionFail.bind(this)); client.socket.on('joined', function(){ if (client.currentPremade.type == 'createbot') { self.setStateCreateBot(); } else { self.setStatePremade(); } }); client.socket.on('unjoined', function(){ if ($('#premade').css('display') == 'block') { self.setStatePublic(); } else { self.setStateExercises(); } }); client.socket.on('disconnect', this.setStateDiconnected.bind(this)); }; UiManager.prototype.setStateLogin = function() { $('.ui-block').hide(); $('#login').show(); }; UiManager.prototype.setStateConnectionFail = function() { $('.ui-block').hide(); $('#connecting-fail').hide(); }; UiManager.prototype.setStateDiconnected = function() { $('.ui-block').hide(); $('#disconnect').show(); }; UiManager.prototype.setStatePublic = function() { this._slideTo($('#public').add('#create')); }; UiManager.prototype.setStateExercises = function() { this._slideTo($('#exercises')); }; UiManager.prototype.setStatePremade = function() { $('#game').removeClass('create-bot'); this._slideTo($('#premade').add('#game')); }; UiManager.prototype.setStateCreateBot = function() { this.createBot.reset(); $('#game').addClass('create-bot'); this._slideTo($('#bot-editor').add('#game')); }; UiManager.prototype._slideTo = function(toShow, callback) { $('.ui-block').hide(); toShow.show(); callback && callback(); setTimeout(function(){ // chrome doesn't fire resize event after a scrollbar has appeared $(window).resize(); }, 100); };
JavaScript
//interface: var self = this; var store = {}; this.botCodeInterval = setInterval(function() { var tank = { getX : function() { return self.field.get(self.user.tankId).x; }, getY : function() { return self.field.get(self.user.tankId).y; }, startMove : self.startMove.bind(self), stopMove : self.stopMove.bind(self), fire : self.fire.bind(self) }; var field = { intersect: function(x, y, hw, hh, types) { var res = []; switch (true) { case types === undefined: var tmp = self.field.intersect.call(self.field, {}, x, y, hw, hh); for (var i in tmp) { res.push(tmp[i]); } break; case Array.isArray(types): var tmp = self.field.intersect.call(self.field, {}, x, y, hw, hh); for (var i in tmp) { for (var t in types) { if (tmp[i] instanceof types[t]) { res.push(tmp[i]); break; } } } break; case types instanceof Function: var tmp = self.field.intersect.call(self.field, {}, x, y, hw, hh); for (var i in tmp) { if (tmp[i] instanceof types) { res.push(tmp[i]); } } break; } return res; } }; eval(self.botSource); }, 50);
JavaScript
var util = require('util'); var vm = require('vm'); var fs = require("fs"); var sandbox = { }; fs.readFile('untrusted.js', 'utf8', function(err, file) { if(!err) { // try { vm.runInNewContext(file, sandbox); // } catch (ex) { // console.log(ex, ex.message); // } console.log(sandbox); } });
JavaScript
qwe();
JavaScript
var n = 0; var id = 0; /** * this is also object manager, so all coordinate operations should be done here * Ideally object should not know about x and y * * public interface: * add(item) * remove(item) * move(item, newX, newY) * intersects(item) */ function Area(x, y, hw, hh, leaf) { this.x = x; this.y = y; this.hw = hw; this.hh = hh; this.leaf = leaf; // is this object (not area) // are childs leafs (true) or tree's nodes (false) // uses only if this.leaf is false this.leafs = true; this.childs = []; // childs indexes are 'id', so this.child.length don't work fine // uses only if this.leafs is true this.count = 0; }; Area.prototype.isContainer = function() { return this.leaf; }; Area.prototype.isTerminalArea = function() { return this.leafs; }; Area.prototype._brakeIn = function() { var childs = this.childs; this.childs = []; if (this.hw > this.hh) { this.childs[0] = new Area(this.x-this.hw/2, this.y, this.hw/2, this.hh, false); this.childs[1] = new Area(this.x+this.hw/2, this.y, this.hw/2, this.hh, false); } else { this.childs[0] = new Area(this.x, this.y-this.hh/2, this.hw, this.hh/2, false); this.childs[1] = new Area(this.x, this.y+this.hh/2, this.hw, this.hh/2, false); } this.leafs = false; for (var i in childs) { this.childs[0].add(childs[i]); this.childs[1].add(childs[i]); } }; Area.prototype._intersect = function(item1, item2) { if (item2 === undefined) { item2 = this; } n++; return (Math.abs(item2.x - item1.x) < (item2.hw + item1.hw)) && (Math.abs(item2.y - item1.y) < (item2.hh + item1.hh)); }; Area.prototype.add = function(item) { if (this._intersect(item)) { if (this.leafs) { /*16 - half size of maximum size object (most used maximum size?)*/ if (Math.max(this.hw, this.hh)>16 && this.count >= 2) { this._brakeIn(); } } if (this.leafs) { if (this.id === undefined) { this.id = id++; } this.childs[item.id] = item; this.count++; } else { this.childs[0].add(item); this.childs[1].add(item); } } }; Area.prototype._remove = function(item) { if (this.childs[item.id]) { delete this.childs[item.id]; this.count--; } }; Area.prototype.remove = function(item, from) { if (from === undefined) { from = this.intersects(item, true); } for (var i in from) { if (from[i].isTerminalArea()) { from[i]._remove(item); } else { from[i].remove(item, from[i].childs); } } }; Area.prototype.move = function(item, newX, newY) { // var intersects = this.intersects(item, true); }; Area.prototype.intersects = function(item, withTerminalAreas, res) { if (res === undefined) { res = []; } if (this._intersect(item)) { if (this.leafs) { for (var i in this.childs) { var each = this.childs[i]; if (this._intersect(item, each)) { res[each.id] = each; } } if (withTerminalAreas) { res[this.id] = this; } } else { for (var i in this.childs) { this.childs[i].intersects(item, withTerminalAreas, res); } } } return res; }; Area.prototype.toShortString = function() { return '<' + this.x + ':' + this.y + ':' + this.hw + ':' + this.hh + '>'; }; Area.prototype.toString = function() { var res; if (this.leafs) { res = '[' + this.toShortString() + '\n'; for (var i in this.childs) { res += ' (' + this.childs[i].toShortString() + ')'; } res += '\n]\n'; } else { res = '[' + this.toShortString() + '\n'; for (var i in this.childs) { res += ' ' + this.childs[i].toString().split('\n').join('\n ').trimRight() + '\n'; } res += ']\n'; } return res; }; Area.prototype.terrain = function(map) { this.add(new Area( - 20, this.height / 2, 20, this.height / 2, true)); this.add(new Area(this.width + 20, this.height / 2, 20, this.height / 2, true)); this.add(new Area(this.width / 2, - 20, this.width / 2, 20, true)); this.add(new Area(this.width / 2, this.height + 20, this.width / 2, 20, true)); this.add(new Area(this.width / 2, this.height - 16, 16, 16, true)); for (var y = 0 ; y < 26 ; y++) { for (var x = 0 ; x < 26 ; x++) { switch (map[y][x]) { case 1: this.add(new Area(x*16+ 4, y*16+ 4, 4, 4, true)); this.add(new Area(x*16+12, y*16+ 4, 4, 4, true)); this.add(new Area(x*16+ 4, y*16+12, 4, 4, true)); this.add(new Area(x*16+12, y*16+12, 4, 4, true)); break; case 2: this.add(new Area(x*16+8, y*16+8, 8, 8, true)); break; case 3: this.add(new Area(x*16+8, y*16+8, 8, 8, true)); break; } } } }; var area = new Area(13*32/2, 13*32/2, 13*32/2, 13*32/2, false); var map = require('../src/battle-city/maps/level1.js'); area.terrain(map.map); n = 0; var qwe = area.intersects(new Area(140, //Math.round(Math.random()*13*32), 140, //Math.round(Math.random()*13*32), 16, 16, true), true); console.log(qwe); console.log(n); //var i; // //area.add(new Area(10, 10, 5, 5, true)); //area.add(i = new Area(10, 10, 5, 5, true)); //area.add(new Area(10, 10, 5, 5, true)); //area.remove(i); // //console.log(area.toString());
JavaScript
$(window).resize(function(){ $('#body').height($(this).height() - $('#mainmenu').height() - 1); $('.chat-log').height($('#body').height() - 70); $('.user-list').add('.premades').height($('#body').height() - 18 * 3); $('#tabs-help').add('#tabs-editor').height($('#bot-editor').height() - $('#bot-editor .ui-tabs-nav').height() - 1); var cellMargin = 18; // line-height var columns = 12; for (var i = 1 ; i <= columns ; i++) { var cellWidth = ($('#body').width() - (columns + 1) * cellMargin) / columns; $('.cell-' + i).width(cellWidth * i + (i - 1) * cellMargin); $('.cell-' + i + 'w').width(cellWidth * i + (i - 1) * cellMargin); } if (window.location.hash == '#grid') { showGrid(cellMargin, columns); } }); function showGrid(cellMargin, columns) { $('.line').remove(); var cellWidth = ($('#body').width() - (columns + 1) * cellMargin) / columns; for (var i = 0 ; i <= columns ; i++) { if (i < columns) { var div = $('<div class="line"></div>'); div.css('position', 'fixed'); div.css('top', '0'); div.css('left', (i * cellWidth + (i + 1) * cellMargin - 0.5) + 'px'); div.css('width', '1px'); div.css('height', '100%'); div.css('opacity', 0.4); $('body').append(div); } if (i > 0) { var div = $('<div class="line"></div>'); div.css('position', 'fixed'); div.css('top', '0'); div.css('left', (i * cellWidth + i * cellMargin - 0.5) + 'px'); div.css('width', '1px'); div.css('height', '100%'); div.css('opacity', 0.4); $('body').append(div); } if (i < columns) { for (var j = 1 ; j < 5 ; j++) { var div = $('<div class="line"></div>'); div.css('position', 'fixed'); div.css('top', '0'); div.css('left', (i * cellWidth + (i + 1 + j) * cellMargin - 0.5) + 'px'); div.css('width', '1px'); div.css('height', '100%'); div.css('opacity', 0.1); $('body').append(div); } } } for (var i = 1 ; i <= 30 ; i++) { var div = $('<div class="line"></div>'); div.css('position', 'absolute'); div.css('left', '0'); div.css('top', (i * cellMargin) + 'px'); div.css('height', '1px'); div.css('width', '100%'); div.css('opacity', 0.2); $('body').append(div); } }
JavaScript
// Copyright Joyent, Inc. and other Node contributors. // // 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. var isArray = Array.isArray; function EventEmitter() { } // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. var defaultMaxListeners = 10; EventEmitter.prototype.setMaxListeners = function(n) { if (!this._events) this._events = {}; this._maxListeners = n; }; EventEmitter.prototype.emit = function() { var type = arguments[0]; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events || !this._events.error || (isArray(this._events.error) && !this._events.error.length)) { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } } if (!this._events) return false; var handler = this._events[type]; if (!handler) return false; if (typeof handler == 'function') { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } return true; } else if (isArray(handler)) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].apply(this, args); } return true; } else { return false; } }; // EventEmitter is defined in src/node_events.cc // EventEmitter.prototype.emit() is also defined there. EventEmitter.prototype.addListener = function(type, listener) { if ('function' !== typeof listener) { throw new Error('addListener only takes instances of Function'); } if (!this._events) this._events = {}; // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else if (isArray(this._events[type])) { // If we've already got an array, just append. this._events[type].push(listener); // Check for listener leak if (!this._events[type].warned) { var m; if (this._maxListeners !== undefined) { m = this._maxListeners; } else { m = defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } } else { // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if ('function' !== typeof listener) { throw new Error('.once only takes instances of Function'); } var self = this; function g() { self.removeListener(type, g); listener.apply(this, arguments); }; g.listener = listener; self.on(type, g); return this; }; EventEmitter.prototype.removeListener = function(type, listener) { if ('function' !== typeof listener) { throw new Error('removeListener only takes instances of Function'); } // does not use listeners(), so no side effect of creating _events[type] if (!this._events || !this._events[type]) return this; var list = this._events[type]; if (isArray(list)) { var position = -1; for (var i = 0, length = list.length; i < length; i++) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; list.splice(position, 1); if (list.length == 0) delete this._events[type]; } else if (list === listener || (list.listener && list.listener === listener)) { delete this._events[type]; } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { this._events = {}; return this; } // does not use listeners(), so no side effect of creating _events[type] if (type && this._events && this._events[type]) this._events[type] = null; return this; }; EventEmitter.prototype.listeners = function(type) { if (!this._events) this._events = {}; if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; };
JavaScript
CodeMirror.defineMode("pascal", function(config) { function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = words("and array begin case const div do downto else end file for forward integer " + "boolean char function goto if in label mod nil not of or packed procedure " + "program record repeat set string then to type until var while with"); var blockKeywords = words("case do else for if switch while struct then of"); var atoms = {"null": true}; var isOperatorChar = /[+\-*&%=<>!?|\/]/; var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (ch == "#" && state.startOfLine) { stream.skipToEnd(); return "meta"; } if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (ch == "(" && stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (/[\[\]{}\(\),;\:\.]/.test(ch)) { curPunc = ch; return null; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (ch == "/") { if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\$_]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; return "keyword"; } if (atoms.propertyIsEnumerable(cur)) return "atom"; return "word"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !escaped) state.tokenize = null; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == ")" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { return state.context = new Context(state.indented, col, type, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" ) state.indented = state.context.indented; return state.context = state.context.prev; } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false), indented: 0, startOfLine: true }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) return null; curPunc = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == ctx.type) popContext(state); else if ( ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) pushContext(state, stream.column(), "statement"); state.startOfLine = false; return style; }, electricChars: "{}" }; }); CodeMirror.defineMIME("text/x-pascal", "pascal");
JavaScript
// CodeMirror v2.18 // All functions that need access to the editor's state live inside // the CodeMirror function. Below that, at the bottom of the file, // some utilities are defined. // CodeMirror is the only global var we claim var CodeMirror = (function() { // This is the function that produces an editor instance. It's // closure is used to store the editor state. function CodeMirror(place, givenOptions) { // Determine effective options based on given values and defaults. var options = {}, defaults = CodeMirror.defaults; for (var opt in defaults) if (defaults.hasOwnProperty(opt)) options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt]; var targetDocument = options["document"]; // The element in which the editor lives. var wrapper = targetDocument.createElement("div"); wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : ""); // This mess creates the base DOM structure for the editor. wrapper.innerHTML = '<div style="overflow: hidden; position: relative; width: 1px; height: 0px;">' + // Wraps and hides input textarea '<textarea style="position: absolute; width: 1;" wrap="off" ' + 'autocorrect="off" autocapitalize="off"></textarea></div>' + '<div class="CodeMirror-scroll cm-s-' + options.theme + '">' + '<div style="position: relative">' + // Set to the height of the text, causes scrolling '<div style="position: relative">' + // Moved around its parent to cover visible view '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' + // Provides positioning relative to (visible) text origin '<div class="CodeMirror-lines"><div style="position: relative">' + '<div style="position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden"></div>' + '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor '<div></div>' + // This DIV contains the actual code '</div></div></div></div></div>'; if (place.appendChild) place.appendChild(wrapper); else place(wrapper); // I've never seen more elegant code in my life. var inputDiv = wrapper.firstChild, input = inputDiv.firstChild, scroller = wrapper.lastChild, code = scroller.firstChild, mover = code.firstChild, gutter = mover.firstChild, gutterText = gutter.firstChild, lineSpace = gutter.nextSibling.firstChild, measure = lineSpace.firstChild, cursor = measure.nextSibling, lineDiv = cursor.nextSibling; if (!webkit) lineSpace.draggable = true; if (options.tabindex != null) input.tabindex = options.tabindex; if (!options.gutter && !options.lineNumbers) gutter.style.display = "none"; // Check for problem with IE innerHTML not working when we have a // P (or similar) parent node. try { stringWidth("x"); } catch (e) { if (e.message.match(/unknown runtime/i)) e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)"); throw e; } // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval. var poll = new Delayed(), highlight = new Delayed(), blinker; // mode holds a mode API object. doc is the tree of Line objects, // work an array of lines that should be parsed, and history the // undo history (instance of History constructor). var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused; loadMode(); // The selection. These are always maintained to point at valid // positions. Inverted is used to remember that the user is // selecting bottom-to-top. var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false}; // Selection-related flags. shiftSelecting obviously tracks // whether the user is holding shift. var shiftSelecting, lastClick, lastDoubleClick, draggingText, overwrite = false; // Variables used by startOperation/endOperation to track what // happened during the operation. var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone, gutterDirty; // Current visible range (may be bigger than the view window). var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0; // bracketHighlighted is used to remember that a backet has been // marked. var bracketHighlighted; // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. var maxLine = "", maxWidth, tabText = computeTabText(); // Initialize the content. operation(function(){setValue(options.value || ""); updateInput = false;})(); var history = new History(); // Register our event handlers. connect(scroller, "mousedown", operation(onMouseDown)); connect(scroller, "dblclick", operation(onDoubleClick)); connect(lineSpace, "dragstart", onDragStart); connect(lineSpace, "selectstart", e_preventDefault); // Gecko browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for Gecko. if (!gecko) connect(scroller, "contextmenu", onContextMenu); connect(scroller, "scroll", function() { updateDisplay([]); if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px"; if (options.onScroll) options.onScroll(instance); }); connect(window, "resize", function() {updateDisplay(true);}); connect(input, "keyup", operation(onKeyUp)); connect(input, "input", fastPoll); connect(input, "keydown", operation(onKeyDown)); connect(input, "keypress", operation(onKeyPress)); connect(input, "focus", onFocus); connect(input, "blur", onBlur); connect(scroller, "dragenter", e_stop); connect(scroller, "dragover", e_stop); connect(scroller, "drop", operation(onDrop)); connect(scroller, "paste", function(){focusInput(); fastPoll();}); connect(input, "paste", fastPoll); connect(input, "cut", operation(function(){replaceSelection("");})); // IE throws unspecified error in certain cases, when // trying to access activeElement before onload var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { } if (hasFocus) setTimeout(onFocus, 20); else onBlur(); function isLine(l) {return l >= 0 && l < doc.size;} // The instance object that we'll return. Mostly calls out to // local functions in the CodeMirror function. Some do some extra // range checking and/or clipping. operation is used to wrap the // call so that changes it makes are tracked, and the display is // updated afterwards. var instance = wrapper.CodeMirror = { getValue: getValue, setValue: operation(setValue), getSelection: getSelection, replaceSelection: operation(replaceSelection), focus: function(){focusInput(); onFocus(); fastPoll();}, setOption: function(option, value) { var oldVal = options[option]; options[option] = value; if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme") operation(gutterChanged)(); if (option == "mode" || option == "indentUnit") loadMode(); else if (option == "readOnly" && value) {onBlur(); input.blur();} else if (option == "theme") scroller.className = scroller.className.replace(/cm-s-\w+/, "cm-s-" + value); else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)(); else if (option == "tabSize") operation(tabsChanged)(); }, getOption: function(option) {return options[option];}, undo: operation(undo), redo: operation(redo), indentLine: operation(function(n, dir) { if (isLine(n)) indentLine(n, dir == null ? "smart" : dir ? "add" : "subtract"); }), indentSelection: operation(indentSelected), historySize: function() {return {undo: history.done.length, redo: history.undone.length};}, clearHistory: function() {history = new History();}, matchBrackets: operation(function(){matchBrackets(true);}), getTokenAt: operation(function(pos) { pos = clipPos(pos); return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), pos.ch); }), getStateAfter: function(line) { line = clipLine(line == null ? doc.size - 1: line); return getStateBefore(line + 1); }, cursorCoords: function(start){ if (start == null) start = sel.inverted; return pageCoords(start ? sel.from : sel.to); }, charCoords: function(pos){return pageCoords(clipPos(pos));}, coordsChar: function(coords) { var off = eltOffset(lineSpace); return coordsChar(coords.x - off.left, coords.y - off.top); }, markText: operation(markText), setBookmark: setBookmark, setMarker: operation(addGutterMarker), clearMarker: operation(removeGutterMarker), setLineClass: operation(setLineClass), hideLine: operation(function(h) {return setLineHidden(h, true);}), showLine: operation(function(h) {return setLineHidden(h, false);}), lineInfo: lineInfo, addWidget: function(pos, node, scroll, vert, horiz) { pos = localCoords(clipPos(pos)); var top = pos.yBot, left = pos.x; node.style.position = "absolute"; code.appendChild(node); if (vert == "over") top = pos.y; else if (vert == "near") { var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()), hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft(); if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight) top = pos.y - node.offsetHeight; if (left + node.offsetWidth > hspace) left = hspace - node.offsetWidth; } node.style.top = (top + paddingTop()) + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = code.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") left = 0; else if (horiz == "middle") left = (code.clientWidth - node.offsetWidth) / 2; node.style.left = (left + paddingLeft()) + "px"; } if (scroll) scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight); }, lineCount: function() {return doc.size;}, clipPos: clipPos, getCursor: function(start) { if (start == null) start = sel.inverted; return copyPos(start ? sel.from : sel.to); }, somethingSelected: function() {return !posEq(sel.from, sel.to);}, setCursor: operation(function(line, ch, user) { if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user); else setCursor(line, ch, user); }), setSelection: operation(function(from, to, user) { (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from)); }), getLine: function(line) {if (isLine(line)) return getLine(line).text;}, setLine: operation(function(line, text) { if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length}); }), removeLine: operation(function(line) { if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0})); }), replaceRange: operation(replaceRange), getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));}, execCommand: function(cmd) {return commands[cmd](instance);}, // Stuff used by commands, probably not much use to outside code. moveH: operation(moveH), deleteH: operation(deleteH), moveV: operation(moveV), toggleOverwrite: function() {overwrite = !overwrite;}, coordsFromIndex: function(off) { var lineNo = 0, ch; doc.iter(0, doc.size, function(line) { var sz = line.text.length + 1; if (sz > off) { ch = off; return true; } off -= sz; ++lineNo; }); return clipPos({line: lineNo, ch: ch}); }, operation: function(f){return operation(f)();}, refresh: function(){updateDisplay(true);}, getInputField: function(){return input;}, getWrapperElement: function(){return wrapper;}, getScrollerElement: function(){return scroller;}, getGutterElement: function(){return gutter;} }; function getLine(n) { return getLineAt(doc, n); } function updateLineHeight(line, height) { gutterDirty = true; var diff = height - line.height; for (var n = line; n; n = n.parent) n.height += diff; } function setValue(code) { var top = {line: 0, ch: 0}; updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length}, splitLines(code), top, top); updateInput = true; } function getValue(code) { var text = []; doc.iter(0, doc.size, function(line) { text.push(line.text); }); return text.join("\n"); } function onMouseDown(e) { setShift(e.shiftKey); // Check whether this is a click in a widget for (var n = e_target(e); n != wrapper; n = n.parentNode) if (n.parentNode == code && n != mover) return; // See if this is a click in the gutter for (var n = e_target(e); n != wrapper; n = n.parentNode) if (n.parentNode == gutterText) { if (options.onGutterClick) options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e); return e_preventDefault(e); } var start = posFromMouse(e); switch (e_button(e)) { case 3: if (gecko && !mac) onContextMenu(e); return; case 2: if (start) setCursor(start.line, start.ch, true); return; } // For button 1, if it was clicked inside the editor // (posFromMouse returning non-null), we have to adjust the // selection. if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;} if (!focused) onFocus(); var now = +new Date; if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { e_preventDefault(e); setTimeout(focusInput, 20); return selectLine(start.line); } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { lastDoubleClick = {time: now, pos: start}; e_preventDefault(e); return selectWordAt(start); } else { lastClick = {time: now, pos: start}; } var last = start, going; if (dragAndDrop && !posEq(sel.from, sel.to) && !posLess(start, sel.from) && !posLess(sel.to, start)) { // Let the drag handler handle this. if (webkit) lineSpace.draggable = true; var up = connect(targetDocument, "mouseup", operation(function(e2) { if (webkit) lineSpace.draggable = false; draggingText = false; up(); if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { e_preventDefault(e2); setCursor(start.line, start.ch, true); focusInput(); } }), true); draggingText = true; return; } e_preventDefault(e); setCursor(start.line, start.ch, true); function extend(e) { var cur = posFromMouse(e, true); if (cur && !posEq(cur, last)) { if (!focused) onFocus(); last = cur; setSelectionUser(start, cur); updateInput = false; var visible = visibleLines(); if (cur.line >= visible.to || cur.line < visible.from) going = setTimeout(operation(function(){extend(e);}), 150); } } var move = connect(targetDocument, "mousemove", operation(function(e) { clearTimeout(going); e_preventDefault(e); extend(e); }), true); var up = connect(targetDocument, "mouseup", operation(function(e) { clearTimeout(going); var cur = posFromMouse(e); if (cur) setSelectionUser(start, cur); e_preventDefault(e); focusInput(); updateInput = true; move(); up(); }), true); } function onDoubleClick(e) { for (var n = e_target(e); n != wrapper; n = n.parentNode) if (n.parentNode == gutterText) return e_preventDefault(e); var start = posFromMouse(e); if (!start) return; lastDoubleClick = {time: +new Date, pos: start}; e_preventDefault(e); selectWordAt(start); } function onDrop(e) { e.preventDefault(); var pos = posFromMouse(e, true), files = e.dataTransfer.files; if (!pos || options.readOnly) return; if (files && files.length && window.FileReader && window.File) { function loadFile(file, i) { var reader = new FileReader; reader.onload = function() { text[i] = reader.result; if (++read == n) { pos = clipPos(pos); operation(function() { var end = replaceRange(text.join(""), pos, pos); setSelectionUser(pos, end); })(); } }; reader.readAsText(file); } var n = files.length, text = Array(n), read = 0; for (var i = 0; i < n; ++i) loadFile(files[i], i); } else { try { var text = e.dataTransfer.getData("Text"); if (text) { var end = replaceRange(text, pos, pos); var curFrom = sel.from, curTo = sel.to; setSelectionUser(pos, end); if (draggingText) replaceRange("", curFrom, curTo); focusInput(); } } catch(e){} } } function onDragStart(e) { var txt = getSelection(); // This will reset escapeElement htmlEscape(txt); e.dataTransfer.setDragImage(escapeElement, 0, 0); e.dataTransfer.setData("Text", txt); } function handleKeyBinding(e) { if (e.altGraphKey) return false; var bound = lookupKey(e, options.extraKeys, options.keyMap); var next = keyMap[options.keyMap].auto; if (next) options.keyMap = next; if (!bound) return false; if (typeof bound != "string") bound(instance); else if (commands.propertyIsEnumerable(bound)) commands[bound](instance); else if (!next) return false; e_preventDefault(e); return true; } var lastStoppedKey = null; function onKeyDown(e) { if (!focused) onFocus(); var code = e.keyCode; // IE does strange things with escape. if (ie && code == 27) { e.returnValue = false; } setShift(code == 16 || e.shiftKey); // First give onKeyEvent option a chance to handle this. if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; var handled = handleKeyBinding(e); if (window.opera) { lastStoppedKey = handled ? e.keyCode : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && (mac ? e.metaKey : e.ctrlKey) && e.keyCode == 88) replaceSelection(""); } } function onKeyPress(e) { if (window.opera && e.keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; if (window.opera && !e.which && handleKeyBinding(e)) return; if (options.electricChars && mode.electricChars) { var ch = String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode); if (mode.electricChars.indexOf(ch) > -1) setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 50); } fastPoll(); } function onKeyUp(e) { if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; if (e.keyCode == 16) shiftSelecting = null; } function onFocus() { if (options.readOnly) return; if (!focused) { if (options.onFocus) options.onFocus(instance); focused = true; if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1) wrapper.className += " CodeMirror-focused"; if (!leaveInputAlone) resetInput(true); } slowPoll(); restartBlink(); } function onBlur() { if (focused) { if (options.onBlur) options.onBlur(instance); focused = false; wrapper.className = wrapper.className.replace(" CodeMirror-focused", ""); } clearInterval(blinker); setTimeout(function() {if (!focused) shiftSelecting = null;}, 150); } // Replace the range from from to to by the strings in newText. // Afterwards, set the selection to selFrom, selTo. function updateLines(from, to, newText, selFrom, selTo) { if (history) { var old = []; doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); }); history.addChange(from.line, newText.length, old); while (history.done.length > options.undoDepth) history.done.shift(); } updateLinesNoUndo(from, to, newText, selFrom, selTo); } function unredoHelper(from, to) { var change = from.pop(); if (change) { var replaced = [], end = change.start + change.added; doc.iter(change.start, end, function(line) { replaced.push(line.text); }); to.push({start: change.start, added: change.old.length, old: replaced}); var pos = clipPos({line: change.start + change.old.length - 1, ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])}); updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos); updateInput = true; } } function undo() {unredoHelper(history.done, history.undone);} function redo() {unredoHelper(history.undone, history.done);} function updateLinesNoUndo(from, to, newText, selFrom, selTo) { var recomputeMaxLength = false, maxLineLength = maxLine.length; if (!options.lineWrapping) doc.iter(from.line, to.line, function(line) { if (line.text.length == maxLineLength) {recomputeMaxLength = true; return true;} }); var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line); // First adjust the line structure, taking some care to leave highlighting intact. if (firstLine == lastLine) { if (newText.length == 1) firstLine.replace(from.ch, to.ch, newText[0]); else { lastLine = firstLine.split(to.ch, newText[newText.length-1]); firstLine.replace(from.ch, null, newText[0]); firstLine.fixMarkEnds(lastLine); var added = []; for (var i = 1, e = newText.length - 1; i < e; ++i) added.push(Line.inheritMarks(newText[i], firstLine)); added.push(lastLine); doc.insert(from.line + 1, added); } } else if (newText.length == 1) { firstLine.replace(from.ch, null, newText[0]); lastLine.replace(null, to.ch, ""); firstLine.append(lastLine); doc.remove(from.line + 1, nlines); } else { var added = []; firstLine.replace(from.ch, null, newText[0]); lastLine.replace(null, to.ch, newText[newText.length-1]); firstLine.fixMarkEnds(lastLine); for (var i = 1, e = newText.length - 1; i < e; ++i) added.push(Line.inheritMarks(newText[i], firstLine)); if (nlines > 1) doc.remove(from.line + 1, nlines - 1); doc.insert(from.line + 1, added); } if (options.lineWrapping) { var perLine = scroller.clientWidth / charWidth() - 3; doc.iter(from.line, from.line + newText.length, function(line) { if (line.hidden) return; var guess = Math.ceil(line.text.length / perLine) || 1; if (guess != line.height) updateLineHeight(line, guess); }); } else { doc.iter(from.line, i + newText.length, function(line) { var l = line.text; if (l.length > maxLineLength) { maxLine = l; maxLineLength = l.length; maxWidth = null; recomputeMaxLength = false; } }); if (recomputeMaxLength) { maxLineLength = 0; maxLine = ""; maxWidth = null; doc.iter(0, doc.size, function(line) { var l = line.text; if (l.length > maxLineLength) { maxLineLength = l.length; maxLine = l; } }); } } // Add these lines to the work array, so that they will be // highlighted. Adjust work lines if lines were added/removed. var newWork = [], lendiff = newText.length - nlines - 1; for (var i = 0, l = work.length; i < l; ++i) { var task = work[i]; if (task < from.line) newWork.push(task); else if (task > to.line) newWork.push(task + lendiff); } var hlEnd = from.line + Math.min(newText.length, 500); highlightLines(from.line, hlEnd); newWork.push(hlEnd); work = newWork; startWorker(100); // Remember that these lines changed, for updating the display changes.push({from: from.line, to: to.line + 1, diff: lendiff}); var changeObj = {from: from, to: to, text: newText}; if (textChanged) { for (var cur = textChanged; cur.next; cur = cur.next) {} cur.next = changeObj; } else textChanged = changeObj; // Update the selection function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;} setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line)); // Make sure the scroll-size div has the correct height. code.style.height = (doc.height * textHeight() + 2 * paddingTop()) + "px"; } function replaceRange(code, from, to) { from = clipPos(from); if (!to) to = from; else to = clipPos(to); code = splitLines(code); function adjustPos(pos) { if (posLess(pos, from)) return pos; if (!posLess(to, pos)) return end; var line = pos.line + code.length - (to.line - from.line) - 1; var ch = pos.ch; if (pos.line == to.line) ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0)); return {line: line, ch: ch}; } var end; replaceRange1(code, from, to, function(end1) { end = end1; return {from: adjustPos(sel.from), to: adjustPos(sel.to)}; }); return end; } function replaceSelection(code, collapse) { replaceRange1(splitLines(code), sel.from, sel.to, function(end) { if (collapse == "end") return {from: end, to: end}; else if (collapse == "start") return {from: sel.from, to: sel.from}; else return {from: sel.from, to: end}; }); } function replaceRange1(code, from, to, computeSel) { var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length; var newSel = computeSel({line: from.line + code.length - 1, ch: endch}); updateLines(from, to, code, newSel.from, newSel.to); } function getRange(from, to) { var l1 = from.line, l2 = to.line; if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch); var code = [getLine(l1).text.slice(from.ch)]; doc.iter(l1 + 1, l2, function(line) { code.push(line.text); }); code.push(getLine(l2).text.slice(0, to.ch)); return code.join("\n"); } function getSelection() { return getRange(sel.from, sel.to); } var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll function slowPoll() { if (pollingFast) return; poll.set(options.pollInterval, function() { startOperation(); readInput(); if (focused) slowPoll(); endOperation(); }); } function fastPoll() { var missed = false; pollingFast = true; function p() { startOperation(); var changed = readInput(); if (!changed && !missed) {missed = true; poll.set(60, p);} else {pollingFast = false; slowPoll();} endOperation(); } poll.set(20, p); } // Previnput is a hack to work with IME. If we reset the textarea // on every change, that breaks IME. So we look for changes // compared to the previous content instead. (Modern browsers have // events that indicate IME taking place, but these are not widely // supported or compatible enough yet to rely on.) var prevInput = ""; function readInput() { if (leaveInputAlone || !focused || hasSelection(input)) return false; var text = input.value; if (text == prevInput) return false; shiftSelecting = null; var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput[same] == text[same]) ++same; if (same < prevInput.length) sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)}; else if (overwrite && posEq(sel.from, sel.to)) sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))}; replaceSelection(text.slice(same), "end"); prevInput = text; return true; } function resetInput(user) { if (!posEq(sel.from, sel.to)) { prevInput = ""; input.value = getSelection(); input.select(); } else if (user) prevInput = input.value = ""; } function focusInput() { if (!options.readOnly) input.focus(); } function scrollEditorIntoView() { if (!cursor.getBoundingClientRect) return; var rect = cursor.getBoundingClientRect(); var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); if (rect.top < 0 || rect.bottom > winH) cursor.scrollIntoView(); } function scrollCursorIntoView() { var cursor = localCoords(sel.inverted ? sel.from : sel.to); var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x; return scrollIntoView(x, cursor.y, x, cursor.yBot); } function scrollIntoView(x1, y1, x2, y2) { var pl = paddingLeft(), pt = paddingTop(), lh = textHeight(); y1 += pt; y2 += pt; x1 += pl; x2 += pl; var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true; if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;} else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;} var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft; var gutterw = options.fixedGutter ? gutter.clientWidth : 0; if (x1 < screenleft + gutterw) { if (x1 < 50) x1 = 0; scroller.scrollLeft = Math.max(0, x1 - 10 - gutterw); scrolled = true; } else if (x2 > screenw + screenleft - 3) { scroller.scrollLeft = x2 + 10 - screenw; scrolled = true; if (x2 > code.clientWidth) result = false; } if (scrolled && options.onScroll) options.onScroll(instance); return result; } function visibleLines() { var lh = textHeight(), top = scroller.scrollTop - paddingTop(); var from_height = Math.max(0, Math.floor(top / lh)); var to_height = Math.ceil((top + scroller.clientHeight) / lh); return {from: lineAtHeight(doc, from_height), to: lineAtHeight(doc, to_height)}; } // Uses a set of changes plus the current scroll position to // determine which DOM updates have to be made, and makes the // updates. function updateDisplay(changes) { if (!scroller.clientWidth) { showingFrom = showingTo = displayOffset = 0; return; } // Compute the new visible window var visible = visibleLines(); // Bail out if the visible area is already rendered and nothing changed. if (changes !== true && changes.length == 0 && visible.from >= showingFrom && visible.to <= showingTo) return; var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100); if (showingFrom < from && from - showingFrom < 20) from = showingFrom; if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo); // Create a range of theoretically intact lines, and punch holes // in that using the change info. var intact = changes === true ? [] : computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes); // Clip off the parts that won't be visible var intactLines = 0; for (var i = 0; i < intact.length; ++i) { var range = intact[i]; if (range.from < from) {range.domStart += (from - range.from); range.from = from;} if (range.to > to) range.to = to; if (range.from >= range.to) intact.splice(i--, 1); else intactLines += range.to - range.from; } if (intactLines == to - from) return; intact.sort(function(a, b) {return a.domStart - b.domStart;}); var th = textHeight(), gutterDisplay = gutter.style.display; lineDiv.style.display = gutter.style.display = "none"; patchDisplay(from, to, intact); lineDiv.style.display = ""; // Position the mover div to align with the lines it's supposed // to be showing (which will cover the visible display) var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th; // This is just a bogus formula that detects when the editor is // resized or the font size changes. if (different) lastSizeC = scroller.clientHeight + th; showingFrom = from; showingTo = to; displayOffset = heightAtLine(doc, from); mover.style.top = (displayOffset * th) + "px"; code.style.height = (doc.height * th + 2 * paddingTop()) + "px"; // Since this is all rather error prone, it is honoured with the // only assertion in the whole file. if (lineDiv.childNodes.length != showingTo - showingFrom) throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) + " nodes=" + lineDiv.childNodes.length); if (options.lineWrapping) { maxWidth = scroller.clientWidth; var curNode = lineDiv.firstChild; doc.iter(showingFrom, showingTo, function(line) { if (!line.hidden) { var height = Math.round(curNode.offsetHeight / th) || 1; if (line.height != height) {updateLineHeight(line, height); gutterDirty = true;} } curNode = curNode.nextSibling; }); } else { if (maxWidth == null) maxWidth = stringWidth(maxLine); if (maxWidth > scroller.clientWidth) { lineSpace.style.width = maxWidth + "px"; // Needed to prevent odd wrapping/hiding of widgets placed in here. code.style.width = ""; code.style.width = scroller.scrollWidth + "px"; } else { lineSpace.style.width = code.style.width = ""; } } gutter.style.display = gutterDisplay; if (different || gutterDirty) updateGutter(); updateCursor(); } function computeIntact(intact, changes) { for (var i = 0, l = changes.length || 0; i < l; ++i) { var change = changes[i], intact2 = [], diff = change.diff || 0; for (var j = 0, l2 = intact.length; j < l2; ++j) { var range = intact[j]; if (change.to <= range.from && change.diff) intact2.push({from: range.from + diff, to: range.to + diff, domStart: range.domStart}); else if (change.to <= range.from || change.from >= range.to) intact2.push(range); else { if (change.from > range.from) intact2.push({from: range.from, to: change.from, domStart: range.domStart}); if (change.to < range.to) intact2.push({from: change.to + diff, to: range.to + diff, domStart: range.domStart + (change.to - range.from)}); } } intact = intact2; } return intact; } function patchDisplay(from, to, intact) { // The first pass removes the DOM nodes that aren't intact. if (!intact.length) lineDiv.innerHTML = ""; else { function killNode(node) { var tmp = node.nextSibling; node.parentNode.removeChild(node); return tmp; } var domPos = 0, curNode = lineDiv.firstChild, n; for (var i = 0; i < intact.length; ++i) { var cur = intact[i]; while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;} for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;} } while (curNode) curNode = killNode(curNode); } // This pass fills in the lines that actually changed. var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from; var sfrom = sel.from.line, sto = sel.to.line, inSel = sfrom < from && sto >= from; var scratch = targetDocument.createElement("div"), newElt; doc.iter(from, to, function(line) { var ch1 = null, ch2 = null; if (inSel) { ch1 = 0; if (sto == j) {inSel = false; ch2 = sel.to.ch;} } else if (sfrom == j) { if (sto == j) {ch1 = sel.from.ch; ch2 = sel.to.ch;} else {inSel = true; ch1 = sel.from.ch;} } if (nextIntact && nextIntact.to == j) nextIntact = intact.shift(); if (!nextIntact || nextIntact.from > j) { if (line.hidden) scratch.innerHTML = "<pre></pre>"; else scratch.innerHTML = line.getHTML(ch1, ch2, true, tabText); lineDiv.insertBefore(scratch.firstChild, curNode); } else { curNode = curNode.nextSibling; } ++j; }); } function updateGutter() { if (!options.gutter && !options.lineNumbers) return; var hText = mover.offsetHeight, hEditor = scroller.clientHeight; gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px"; var html = [], i = showingFrom; doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) { if (line.hidden) { html.push("<pre></pre>"); } else { var marker = line.gutterMarker; var text = options.lineNumbers ? i + options.firstLineNumber : null; if (marker && marker.text) text = marker.text.replace("%N%", text != null ? text : ""); else if (text == null) text = "\u00a0"; html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text); for (var j = 1; j < line.height; ++j) html.push("<br>&nbsp;"); html.push("</pre>"); } ++i; }); gutter.style.display = "none"; gutterText.innerHTML = html.join(""); var minwidth = String(doc.size).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = ""; while (val.length + pad.length < minwidth) pad += "\u00a0"; if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild); gutter.style.display = ""; lineSpace.style.marginLeft = gutter.offsetWidth + "px"; gutterDirty = false; } function updateCursor() { var head = sel.inverted ? sel.from : sel.to, lh = textHeight(); var pos = localCoords(head, true); var globalY = pos.y + displayOffset * textHeight(); inputDiv.style.top = Math.max(Math.min(globalY, scroller.offsetHeight), 0) + "px"; inputDiv.style.left = pos.x + "px"; if (posEq(sel.from, sel.to)) { cursor.style.top = pos.y + "px"; cursor.style.left = (options.lineWrapping ? Math.min(pos.x, lineSpace.offsetWidth) : pos.x) + "px"; cursor.style.display = ""; } else cursor.style.display = "none"; } function setShift(val) { if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from); else shiftSelecting = null; } function setSelectionUser(from, to) { var sh = shiftSelecting && clipPos(shiftSelecting); if (sh) { if (posLess(sh, from)) from = sh; else if (posLess(to, sh)) to = sh; } setSelection(from, to); userSelChange = true; } // Update the selection. Last two args are only used by // updateLines, since they have to be expressed in the line // numbers before the update. function setSelection(from, to, oldFrom, oldTo) { goalColumn = null; if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;} if (posEq(sel.from, from) && posEq(sel.to, to)) return; if (posLess(to, from)) {var tmp = to; to = from; from = tmp;} // Skip over hidden lines. if (from.line != oldFrom) from = skipHidden(from, oldFrom, sel.from.ch); if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch); if (posEq(from, to)) sel.inverted = false; else if (posEq(from, sel.to)) sel.inverted = false; else if (posEq(to, sel.from)) sel.inverted = true; // Some ugly logic used to only mark the lines that actually did // see a change in selection as changed, rather than the whole // selected range. if (posEq(from, to)) { if (!posEq(sel.from, sel.to)) changes.push({from: oldFrom, to: oldTo + 1}); } else if (posEq(sel.from, sel.to)) { changes.push({from: from.line, to: to.line + 1}); } else { if (!posEq(from, sel.from)) { if (from.line < oldFrom) changes.push({from: from.line, to: Math.min(to.line, oldFrom) + 1}); else changes.push({from: oldFrom, to: Math.min(oldTo, from.line) + 1}); } if (!posEq(to, sel.to)) { if (to.line < oldTo) changes.push({from: Math.max(oldFrom, from.line), to: oldTo + 1}); else changes.push({from: Math.max(from.line, oldTo), to: to.line + 1}); } } sel.from = from; sel.to = to; selectionChanged = true; } function skipHidden(pos, oldLine, oldCh) { function getNonHidden(dir) { var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1; while (lNo != end) { var line = getLine(lNo); if (!line.hidden) { var ch = pos.ch; if (ch > oldCh || ch > line.text.length) ch = line.text.length; return {line: lNo, ch: ch}; } lNo += dir; } } var line = getLine(pos.line); if (!line.hidden) return pos; if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1); else return getNonHidden(-1) || getNonHidden(1); } function setCursor(line, ch, user) { var pos = clipPos({line: line, ch: ch || 0}); (user ? setSelectionUser : setSelection)(pos, pos); } function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));} function clipPos(pos) { if (pos.line < 0) return {line: 0, ch: 0}; if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length}; var ch = pos.ch, linelen = getLine(pos.line).text.length; if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; else if (ch < 0) return {line: pos.line, ch: 0}; else return pos; } function findPosH(dir, unit) { var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch; var lineObj = getLine(line); function findNextLine() { for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) { var lo = getLine(l); if (!lo.hidden) { line = l; lineObj = lo; return true; } } } function moveOnce() { if (ch == (dir < 0 ? 0 : lineObj.text.length)) { if (findNextLine()) ch = dir < 0 ? lineObj.text.length : 0; else return false; } else ch += dir; return true; } if (unit == "char") moveOnce(); else if (unit == "word") { var sawWord = false; for (;;) { if (dir < 0) if (!moveOnce()) break; if (/\w/.test(lineObj.text.charAt(ch))) sawWord = true; else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} if (dir > 0) if (!moveOnce()) break; } } return {line: line, ch: ch}; } function moveH(dir, unit) { var pos = dir < 0 ? sel.from : sel.to; if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit); setCursor(pos.line, pos.ch, true); } function deleteH(dir, unit) { if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to); else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to); else replaceRange("", sel.from, findPosH(dir, unit)); userSelChange = true; } var goalColumn = null; function moveV(dir, unit) { var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true); if (goalColumn != null) pos.x = goalColumn; if (unit == "page") dist = scroller.clientHeight; else if (unit == "line") dist = textHeight(); var target = coordsChar(pos.x, pos.y + dist * dir + 2); setCursor(target.line, target.ch, true); goalColumn = pos.x; } function selectWordAt(pos) { var line = getLine(pos.line).text; var start = pos.ch, end = pos.ch; while (start > 0 && /\w/.test(line.charAt(start - 1))) --start; while (end < line.length && /\w/.test(line.charAt(end))) ++end; setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end}); } function selectLine(line) { setSelectionUser({line: line, ch: 0}, {line: line, ch: getLine(line).text.length}); } function indentSelected(mode) { if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode); var e = sel.to.line - (sel.to.ch ? 0 : 1); for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode); } function indentLine(n, how) { if (!how) how = "add"; if (how == "smart") { if (!mode.indent) how = "prev"; else var state = getStateBefore(n); } var line = getLine(n), curSpace = line.indentation(options.tabSize), curSpaceString = line.text.match(/^\s*/)[0], indentation; if (how == "prev") { if (n) indentation = getLine(n-1).indentation(options.tabSize); else indentation = 0; } else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length)); else if (how == "add") indentation = curSpace + options.indentUnit; else if (how == "subtract") indentation = curSpace - options.indentUnit; indentation = Math.max(0, indentation); var diff = indentation - curSpace; if (!diff) { if (sel.from.line != n && sel.to.line != n) return; var indentString = curSpaceString; } else { var indentString = "", pos = 0; if (options.indentWithTabs) for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";} while (pos < indentation) {++pos; indentString += " ";} } replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}); } function loadMode() { mode = CodeMirror.getMode(options, options.mode); doc.iter(0, doc.size, function(line) { line.stateAfter = null; }); work = [0]; startWorker(); } function gutterChanged() { var visible = options.gutter || options.lineNumbers; gutter.style.display = visible ? "" : "none"; if (visible) gutterDirty = true; else lineDiv.parentNode.style.marginLeft = 0; } function wrappingChanged(from, to) { if (options.lineWrapping) { wrapper.className += " CodeMirror-wrap"; var perLine = scroller.clientWidth / charWidth() - 3; doc.iter(0, doc.size, function(line) { if (line.hidden) return; var guess = Math.ceil(line.text.length / perLine) || 1; if (guess != 1) updateLineHeight(line, guess); }); lineSpace.style.width = code.style.width = ""; } else { wrapper.className = wrapper.className.replace(" CodeMirror-wrap", ""); maxWidth = null; maxLine = ""; doc.iter(0, doc.size, function(line) { if (line.height != 1 && !line.hidden) updateLineHeight(line, 1); if (line.text.length > maxLine.length) maxLine = line.text; }); } changes.push({from: 0, to: doc.size}); } function computeTabText() { for (var str = '<span class="cm-tab">', i = 0; i < options.tabSize; ++i) str += " "; return str + "</span>"; } function tabsChanged() { tabText = computeTabText(); updateDisplay(true); } function TextMarker() { this.set = []; } TextMarker.prototype.clear = operation(function() { var min = Infinity, max = -Infinity; for (var i = 0, e = this.set.length; i < e; ++i) { var line = this.set[i], mk = line.marked; if (!mk || !line.parent) continue; var lineN = lineNo(line); min = Math.min(min, lineN); max = Math.max(max, lineN); for (var j = 0; j < mk.length; ++j) if (mk[j].set == this.set) mk.splice(j--, 1); } if (min != Infinity) changes.push({from: min, to: max + 1}); }); TextMarker.prototype.find = function() { var from, to; for (var i = 0, e = this.set.length; i < e; ++i) { var line = this.set[i], mk = line.marked; for (var j = 0; j < mk.length; ++j) { var mark = mk[j]; if (mark.set == this.set) { if (mark.from != null || mark.to != null) { var found = lineNo(line); if (found != null) { if (mark.from != null) from = {line: found, ch: mark.from}; if (mark.to != null) to = {line: found, ch: mark.to}; } } } } } return {from: from, to: to}; }; function markText(from, to, className) { from = clipPos(from); to = clipPos(to); var tm = new TextMarker(); function add(line, from, to, className) { getLine(line).addMark(new MarkedText(from, to, className, tm.set)); } if (from.line == to.line) add(from.line, from.ch, to.ch, className); else { add(from.line, from.ch, null, className); for (var i = from.line + 1, e = to.line; i < e; ++i) add(i, null, null, className); add(to.line, null, to.ch, className); } changes.push({from: from.line, to: to.line + 1}); return tm; } function setBookmark(pos) { pos = clipPos(pos); var bm = new Bookmark(pos.ch); getLine(pos.line).addMark(bm); return bm; } function addGutterMarker(line, text, className) { if (typeof line == "number") line = getLine(clipLine(line)); line.gutterMarker = {text: text, style: className}; gutterDirty = true; return line; } function removeGutterMarker(line) { if (typeof line == "number") line = getLine(clipLine(line)); line.gutterMarker = null; gutterDirty = true; } function changeLine(handle, op) { var no = handle, line = handle; if (typeof handle == "number") line = getLine(clipLine(handle)); else no = lineNo(handle); if (no == null) return null; if (op(line, no)) changes.push({from: no, to: no + 1}); return line; } function setLineClass(handle, className) { return changeLine(handle, function(line) { if (line.className != className) { line.className = className; return true; } }); } function setLineHidden(handle, hidden) { return changeLine(handle, function(line, no) { if (line.hidden != hidden) { line.hidden = hidden; updateLineHeight(line, hidden ? 0 : 1); if (hidden && (sel.from.line == no || sel.to.line == no)) setSelection(skipHidden(sel.from, sel.from.line, sel.from.ch), skipHidden(sel.to, sel.to.line, sel.to.ch)); return (gutterDirty = true); } }); } function lineInfo(line) { if (typeof line == "number") { if (!isLine(line)) return null; var n = line; line = getLine(line); if (!line) return null; } else { var n = lineNo(line); if (n == null) return null; } var marker = line.gutterMarker; return {line: n, handle: line, text: line.text, markerText: marker && marker.text, markerClass: marker && marker.style, lineClass: line.className}; } function stringWidth(str) { measure.innerHTML = "<pre><span>x</span></pre>"; measure.firstChild.firstChild.firstChild.nodeValue = str; return measure.firstChild.firstChild.offsetWidth || 10; } // These are used to go from pixel positions to character // positions, taking varying character widths into account. function charFromX(line, x) { if (x <= 0) return 0; var lineObj = getLine(line), text = lineObj.text; function getX(len) { measure.innerHTML = "<pre><span>" + lineObj.getHTML(null, null, false, tabText, len) + "</span></pre>"; return measure.firstChild.firstChild.offsetWidth; } var from = 0, fromX = 0, to = text.length, toX; // Guess a suitable upper bound for our search. var estimated = Math.min(to, Math.ceil(x / charWidth())); for (;;) { var estX = getX(estimated); if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); else {toX = estX; to = estimated; break;} } if (x > toX) return to; // Try to guess a suitable lower bound as well. estimated = Math.floor(to * 0.8); estX = getX(estimated); if (estX < x) {from = estimated; fromX = estX;} // Do a binary search between these bounds. for (;;) { if (to - from <= 1) return (toX - x > x - fromX) ? from : to; var middle = Math.ceil((from + to) / 2), middleX = getX(middle); if (middleX > x) {to = middle; toX = middleX;} else {from = middle; fromX = middleX;} } } var tempId = Math.floor(Math.random() * 0xffffff).toString(16); function measureLine(line, ch) { var extra = ""; // Include extra text at the end to make sure the measured line is wrapped in the right way. if (options.lineWrapping) { var end = line.text.indexOf(" ", ch + 2); extra = line.text.slice(ch + 1, end < 0 ? line.text.length : end + (ie ? 5 : 0)); } measure.innerHTML = "<pre>" + line.getHTML(null, null, false, tabText, ch) + '<span id="CodeMirror-temp-' + tempId + '">' + (line.text.charAt(ch) || " ") + "</span>" + extra + "</pre>"; var elt = document.getElementById("CodeMirror-temp-" + tempId); var top = elt.offsetTop, left = elt.offsetLeft; // Older IEs report zero offsets for spans directly after a wrap if (ie && ch && top == 0 && left == 0) { var backup = document.createElement("span"); backup.innerHTML = "x"; elt.parentNode.insertBefore(backup, elt.nextSibling); top = backup.offsetTop; } return {top: top, left: left}; } function localCoords(pos, inLineWrap) { var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0)); if (pos.ch == 0) x = 0; else { var sp = measureLine(getLine(pos.line), pos.ch); x = sp.left; if (options.lineWrapping) y += Math.max(0, sp.top); } return {x: x, y: y, yBot: y + lh}; } // Coords must be lineSpace-local function coordsChar(x, y) { if (y < 0) y = 0; var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th); var lineNo = lineAtHeight(doc, heightPos); if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length}; var lineObj = getLine(lineNo), text = lineObj.text; var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0; if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0}; function getX(len) { var sp = measureLine(lineObj, len); if (tw) { var off = Math.round(sp.top / th); return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth); } return sp.left; } var from = 0, fromX = 0, to = text.length, toX; // Guess a suitable upper bound for our search. var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw)); for (;;) { var estX = getX(estimated); if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); else {toX = estX; to = estimated; break;} } if (x > toX) return {line: lineNo, ch: to}; // Try to guess a suitable lower bound as well. estimated = Math.floor(to * 0.8); estX = getX(estimated); if (estX < x) {from = estimated; fromX = estX;} // Do a binary search between these bounds. for (;;) { if (to - from <= 1) return {line: lineNo, ch: (toX - x > x - fromX) ? from : to}; var middle = Math.ceil((from + to) / 2), middleX = getX(middle); if (middleX > x) {to = middle; toX = middleX;} else {from = middle; fromX = middleX;} } } function pageCoords(pos) { var local = localCoords(pos, true), off = eltOffset(lineSpace); return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot}; } var cachedHeight, cachedFor; function textHeight() { var offsetHeight = lineDiv.offsetHeight; if (offsetHeight == cachedFor) return cachedHeight; cachedFor = offsetHeight; measure.innerHTML = "<pre>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x</pre>"; return (cachedHeight = measure.firstChild.offsetHeight / 10 || 1); } var cachedWidth, cachedFor = 0; function charWidth() { if (scroller.clientWidth == cachedFor) return cachedWidth; cachedFor = scroller.clientWidth; return (cachedWidth = stringWidth("x")); } function paddingTop() {return lineSpace.offsetTop;} function paddingLeft() {return lineSpace.offsetLeft;} function posFromMouse(e, liberal) { var offW = eltOffset(scroller, true), x, y; // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX; y = e.clientY; } catch (e) { return null; } // This is a mess of a heuristic to try and determine whether a // scroll-bar was clicked or not, and to return null if one was // (and !liberal). if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight)) return null; var offL = eltOffset(lineSpace, true); return coordsChar(x - offL.left, y - offL.top); } function onContextMenu(e) { var pos = posFromMouse(e); if (!pos || window.opera) return; // Opera is difficult. if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) operation(setCursor)(pos.line, pos.ch); var oldCSS = input.style.cssText; inputDiv.style.position = "absolute"; input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " + "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; leaveInputAlone = true; var val = input.value = getSelection(); focusInput(); input.select(); function rehide() { var newVal = splitLines(input.value).join("\n"); if (newVal != val) operation(replaceSelection)(newVal, "end"); inputDiv.style.position = "relative"; input.style.cssText = oldCSS; leaveInputAlone = false; resetInput(true); slowPoll(); } if (gecko) { e_stop(e); var mouseup = connect(window, "mouseup", function() { mouseup(); setTimeout(rehide, 20); }, true); } else { setTimeout(rehide, 50); } } // Cursor-blinking function restartBlink() { clearInterval(blinker); var on = true; cursor.style.visibility = ""; blinker = setInterval(function() { cursor.style.visibility = (on = !on) ? "" : "hidden"; }, 650); } var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; function matchBrackets(autoclear) { var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1; var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; if (!match) return; var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles; for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2) if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;} var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; function scan(line, from, to) { if (!line.text) return; var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur; for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) { var text = st[i]; if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;} for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) { if (pos >= from && pos < to && re.test(cur = text.charAt(j))) { var match = matching[cur]; if (match.charAt(1) == ">" == forward) stack.push(cur); else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; else if (!stack.length) return {pos: pos, match: true}; } } } } for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) { var line = getLine(i), first = i == head.line; var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length); if (found) break; } if (!found) found = {pos: null, match: false}; var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style), two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style); var clear = operation(function(){one.clear(); two && two.clear();}); if (autoclear) setTimeout(clear, 800); else bracketHighlighted = clear; } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(n) { var minindent, minline; for (var search = n, lim = n - 40; search > lim; --search) { if (search == 0) return 0; var line = getLine(search-1); if (line.stateAfter) return search; var indented = line.indentation(options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline; } function getStateBefore(n) { var start = findStartLine(n), state = start && getLine(start-1).stateAfter; if (!state) state = startState(mode); else state = copyState(mode, state); doc.iter(start, n, function(line) { line.highlight(mode, state, options.tabSize); line.stateAfter = copyState(mode, state); }); if (start < n) changes.push({from: start, to: n}); if (n < doc.size && !getLine(n).stateAfter) work.push(n); return state; } function highlightLines(start, end) { var state = getStateBefore(start); doc.iter(start, end, function(line) { line.highlight(mode, state, options.tabSize); line.stateAfter = copyState(mode, state); }); } function highlightWorker() { var end = +new Date + options.workTime; var foundWork = work.length; while (work.length) { if (!getLine(showingFrom).stateAfter) var task = showingFrom; else var task = work.pop(); if (task >= doc.size) continue; var start = findStartLine(task), state = start && getLine(start-1).stateAfter; if (state) state = copyState(mode, state); else state = startState(mode); var unchanged = 0, compare = mode.compareStates, realChange = false, i = start, bail = false; doc.iter(i, doc.size, function(line) { var hadState = line.stateAfter; if (+new Date > end) { work.push(i); startWorker(options.workDelay); if (realChange) changes.push({from: task, to: i + 1}); return (bail = true); } var changed = line.highlight(mode, state, options.tabSize); if (changed) realChange = true; line.stateAfter = copyState(mode, state); if (compare) { if (hadState && compare(hadState, state)) return true; } else { if (changed !== false || !hadState) unchanged = 0; else if (++unchanged > 3) return true; } ++i; }); if (bail) return; if (realChange) changes.push({from: task, to: i + 1}); } if (foundWork && options.onHighlightComplete) options.onHighlightComplete(instance); } function startWorker(time) { if (!work.length) return; highlight.set(time, operation(highlightWorker)); } // Operations are used to wrap changes in such a way that each // change won't have to update the cursor and display (which would // be awkward, slow, and error-prone), but instead updates are // batched and then all combined and executed at once. function startOperation() { updateInput = userSelChange = textChanged = null; changes = []; selectionChanged = false; } function endOperation() { var reScroll = false; if (selectionChanged) reScroll = !scrollCursorIntoView(); if (changes.length) updateDisplay(changes); else { if (selectionChanged) updateCursor(); if (gutterDirty) updateGutter(); } if (reScroll) scrollCursorIntoView(); if (selectionChanged) {scrollEditorIntoView(); restartBlink();} if (focused && !leaveInputAlone && (updateInput === true || (updateInput !== false && selectionChanged))) resetInput(userSelChange); if (selectionChanged && options.matchBrackets) setTimeout(operation(function() { if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;} if (posEq(sel.from, sel.to)) matchBrackets(false); }), 20); var tc = textChanged; // textChanged can be reset by cursoractivity callback if (selectionChanged && options.onCursorActivity) options.onCursorActivity(instance); if (tc && options.onChange && instance) options.onChange(instance, tc); } var nestedOperation = 0; function operation(f) { return function() { if (!nestedOperation++) startOperation(); try {var result = f.apply(this, arguments);} finally {if (!--nestedOperation) endOperation();} return result; }; } for (var ext in extensions) if (extensions.propertyIsEnumerable(ext) && !instance.propertyIsEnumerable(ext)) instance[ext] = extensions[ext]; return instance; } // (end of function CodeMirror) // The default configuration options. CodeMirror.defaults = { value: "", mode: null, theme: "default", indentUnit: 2, indentWithTabs: false, tabSize: 4, keyMap: "default", extraKeys: null, electricChars: true, onKeyEvent: null, lineWrapping: false, lineNumbers: false, gutter: false, fixedGutter: false, firstLineNumber: 1, readOnly: false, onChange: null, onCursorActivity: null, onGutterClick: null, onHighlightComplete: null, onFocus: null, onBlur: null, onScroll: null, matchBrackets: false, workTime: 100, workDelay: 200, pollInterval: 100, undoDepth: 40, tabindex: null, document: window.document }; var mac = /Mac/.test(navigator.platform); var win = /Win/.test(navigator.platform); // Known modes, by name and by MIME var modes = {}, mimeModes = {}; CodeMirror.defineMode = function(name, mode) { if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; modes[name] = mode; }; CodeMirror.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; CodeMirror.getMode = function(options, spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) spec = mimeModes[spec]; if (typeof spec == "string") var mname = spec, config = {}; else if (spec != null) var mname = spec.name, config = spec; var mfactory = modes[mname]; if (!mfactory) { if (window.console) console.warn("No mode " + mname + " found, falling back to plain text."); return CodeMirror.getMode(options, "text/plain"); } return mfactory(options, config || {}); }; CodeMirror.listModes = function() { var list = []; for (var m in modes) if (modes.propertyIsEnumerable(m)) list.push(m); return list; }; CodeMirror.listMIMEs = function() { var list = []; for (var m in mimeModes) if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]}); return list; }; var extensions = CodeMirror.extensions = {}; CodeMirror.defineExtension = function(name, func) { extensions[name] = func; }; var commands = CodeMirror.commands = { selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});}, killLine: function(cm) { var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0}); else cm.replaceRange("", from, sel ? to : {line: from.line}); }, deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});}, undo: function(cm) {cm.undo();}, redo: function(cm) {cm.redo();}, goDocStart: function(cm) {cm.setCursor(0, 0, true);}, goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);}, goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);}, goLineStartSmart: function(cm) { var cur = cm.getCursor(); var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/)); cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true); }, goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);}, goLineUp: function(cm) {cm.moveV(-1, "line");}, goLineDown: function(cm) {cm.moveV(1, "line");}, goPageUp: function(cm) {cm.moveV(-1, "page");}, goPageDown: function(cm) {cm.moveV(1, "page");}, goCharLeft: function(cm) {cm.moveH(-1, "char");}, goCharRight: function(cm) {cm.moveH(1, "char");}, goWordLeft: function(cm) {cm.moveH(-1, "word");}, goWordRight: function(cm) {cm.moveH(1, "word");}, delCharLeft: function(cm) {cm.deleteH(-1, "char");}, delCharRight: function(cm) {cm.deleteH(1, "char");}, delWordLeft: function(cm) {cm.deleteH(-1, "word");}, delWordRight: function(cm) {cm.deleteH(1, "word");}, indentAuto: function(cm) {cm.indentSelection("smart");}, indentMore: function(cm) {cm.indentSelection("add");}, indentLess: function(cm) {cm.indentSelection("subtract");}, insertTab: function(cm) {cm.replaceSelection("\t", "end");}, transposeChars: function(cm) { var cur = cm.getCursor(), line = cm.getLine(cur.line); if (cur.ch > 0 && cur.ch < line.length - 1) cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1}); }, newlineAndIndent: function(cm) { cm.replaceSelection("\n", "end"); cm.indentLine(cm.getCursor().line); }, toggleOverwrite: function(cm) {cm.toggleOverwrite();} }; var keyMap = CodeMirror.keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "indentMore", "Shift-Tab": "indentLess", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" }; // Note that the save and find-related commands aren't defined by // default. Unknown commands are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Ctrl-R": "replace", "Shift-Ctrl-R": "replaceAll", fallthrough: "basic" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft", "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordRight", "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", fallthrough: ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft", "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" }; function lookupKey(event, extraMap, map) { var name = keyNames[event.keyCode]; if (name == null) return null; if (event.altKey) name = "Alt-" + name; if (event.ctrlKey) name = "Ctrl-" + name; if (event.metaKey) name = "Cmd-" + name; function lookup(name, map, ft) { var found = map[name]; if (found != null) return found; if (ft == null) ft = map.fallthrough; if (ft == null) return map.catchall; if (typeof ft == "string") return lookup(name, keyMap[ft]); for (var i = 0, e = ft.length; i < e; ++i) { found = lookup(name, keyMap[ft[i]]); if (found != null) return found; } return null; } function lookup0(name) { return extraMap ? lookup(name, extraMap, map) : lookup(name, keyMap[map]); } if (event.shiftKey) { var found = lookup0("Shift-" + name); if (found != null) return found; } return lookup0(name); } CodeMirror.fromTextArea = function(textarea, options) { if (!options) options = {}; options.value = textarea.value; if (!options.tabindex && textarea.tabindex) options.tabindex = textarea.tabindex; function save() {textarea.value = instance.getValue();} if (textarea.form) { // Deplorable hack to make the submit method do the right thing. var rmSubmit = connect(textarea.form, "submit", save, true); if (typeof textarea.form.submit == "function") { var realSubmit = textarea.form.submit; function wrappedSubmit() { save(); textarea.form.submit = realSubmit; textarea.form.submit(); textarea.form.submit = wrappedSubmit; } textarea.form.submit = wrappedSubmit; } } textarea.style.display = "none"; var instance = CodeMirror(function(node) { textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); instance.save = save; instance.toTextArea = function() { save(); textarea.parentNode.removeChild(instance.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { rmSubmit(); if (typeof textarea.form.submit == "function") textarea.form.submit = realSubmit; } }; return instance; }; // Utility functions for working with state. Exported because modes // sometimes need to do this. function copyState(mode, state) { if (state === true) return state; if (mode.copyState) return mode.copyState(state); var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) val = val.concat([]); nstate[n] = val; } return nstate; } CodeMirror.copyState = copyState; function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; } CodeMirror.startState = startState; // The character stream used by a mode's parser. function StringStream(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; } StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == 0;}, peek: function() {return this.string.charAt(this.pos);}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, column: function() {return countColumn(this.string, this.start, this.tabSize);}, indentation: function() {return countColumn(this.string, null, this.tabSize);}, match: function(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { if (consume !== false) this.pos += pattern.length; return true; } } else { var match = this.string.slice(this.pos).match(pattern); if (match && consume !== false) this.pos += match[0].length; return match; } }, current: function(){return this.string.slice(this.start, this.pos);} }; CodeMirror.StringStream = StringStream; function MarkedText(from, to, className, set) { this.from = from; this.to = to; this.style = className; this.set = set; } MarkedText.prototype = { attach: function(line) { this.set.push(line); }, detach: function(line) { var ix = indexOf(this.set, line); if (ix > -1) this.set.splice(ix, 1); }, split: function(pos, lenBefore) { if (this.to <= pos && this.to != null) return null; var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore; var to = this.to == null ? null : this.to - pos + lenBefore; return new MarkedText(from, to, this.style, this.set); }, dup: function() { return new MarkedText(null, null, this.style, this.set); }, clipTo: function(fromOpen, from, toOpen, to, diff) { if (this.from != null && this.from >= from) this.from = Math.max(to, this.from) + diff; if (this.to != null && this.to > from) this.to = to < this.to ? this.to + diff : from; if (fromOpen && to > this.from && (to < this.to || this.to == null)) this.from = null; if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null)) this.to = null; }, isDead: function() { return this.from != null && this.to != null && this.from >= this.to; }, sameSet: function(x) { return this.set == x.set; } }; function Bookmark(pos) { this.from = pos; this.to = pos; this.line = null; } Bookmark.prototype = { attach: function(line) { this.line = line; }, detach: function(line) { if (this.line == line) this.line = null; }, split: function(pos, lenBefore) { if (pos < this.from) { this.from = this.to = (this.from - pos) + lenBefore; return this; } }, isDead: function() { return this.from > this.to; }, clipTo: function(fromOpen, from, toOpen, to, diff) { if ((fromOpen || from < this.from) && (toOpen || to > this.to)) { this.from = 0; this.to = -1; } else if (this.from > from) { this.from = this.to = Math.max(to, this.from) + diff; } }, sameSet: function(x) { return false; }, find: function() { if (!this.line || !this.line.parent) return null; return {line: lineNo(this.line), ch: this.from}; }, clear: function() { if (this.line) { var found = indexOf(this.line.marked, this); if (found != -1) this.line.marked.splice(found, 1); this.line = null; } } }; // Line objects. These hold state related to a line, including // highlighting info (the styles array). function Line(text, styles) { this.styles = styles || [text, null]; this.text = text; this.height = 1; this.marked = this.gutterMarker = this.className = null; this.stateAfter = this.parent = this.hidden = null; } Line.inheritMarks = function(text, orig) { var ln = new Line(text), mk = orig.marked; if (mk) { for (var i = 0; i < mk.length; ++i) { if (mk[i].to == null && mk[i].style) { var newmk = ln.marked || (ln.marked = []), mark = mk[i]; var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln); } } } return ln; }; Line.prototype = { // Replace a piece of a line, keeping the styles around it intact. replace: function(from, to_, text) { // Reset line class if the whole text was replaced. if (!from && (to_ == null || to_ == this.text.length)) this.className = this.gutterMarker = null; var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_; copyStyles(0, from, this.styles, st); if (text) st.push(text, null); copyStyles(to, this.text.length, this.styles, st); this.styles = st; this.text = this.text.slice(0, from) + text + this.text.slice(to); this.stateAfter = null; if (mk) { var diff = text.length - (to - from); for (var i = 0, mark = mk[i]; i < mk.length; ++i) { mark.clipTo(from == null, from || 0, to_ == null, to, diff); if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);} } } }, // Split a part off a line, keeping styles and markers intact. split: function(pos, textBefore) { var st = [textBefore, null], mk = this.marked; copyStyles(pos, this.text.length, this.styles, st); var taken = new Line(textBefore + this.text.slice(pos), st); if (mk) { for (var i = 0; i < mk.length; ++i) { var mark = mk[i]; var newmark = mark.split(pos, textBefore.length); if (newmark) { if (!taken.marked) taken.marked = []; taken.marked.push(newmark); newmark.attach(taken); } } } return taken; }, append: function(line) { var mylen = this.text.length, mk = line.marked, mymk = this.marked; this.text += line.text; copyStyles(0, line.text.length, line.styles, this.styles); if (mymk) { for (var i = 0; i < mymk.length; ++i) if (mymk[i].to == null) mymk[i].to = mylen; } if (mk && mk.length) { if (!mymk) this.marked = mymk = []; outer: for (var i = 0; i < mk.length; ++i) { var mark = mk[i]; if (!mark.from) { for (var j = 0; j < mymk.length; ++j) { var mymark = mymk[j]; if (mymark.to == mylen && mymark.sameSet(mark)) { mymark.to = mark.to == null ? null : mark.to + mylen; if (mymark.isDead()) { mymark.detach(this); mk.splice(i--, 1); } continue outer; } } } mymk.push(mark); mark.attach(this); mark.from += mylen; if (mark.to != null) mark.to += mylen; } } }, fixMarkEnds: function(other) { var mk = this.marked, omk = other.marked; if (!mk) return; for (var i = 0; i < mk.length; ++i) { var mark = mk[i], close = mark.to == null; if (close && omk) { for (var j = 0; j < omk.length; ++j) if (omk[j].sameSet(mark)) {close = false; break;} } if (close) mark.to = this.text.length; } }, addMark: function(mark) { mark.attach(this); if (this.marked == null) this.marked = []; this.marked.push(mark); this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);}); }, // Run the given mode's parser over a line, update the styles // array, which contains alternating fragments of text and CSS // classes. highlight: function(mode, state, tabSize) { var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0; var changed = false, curWord = st[0], prevWord; if (this.text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { var style = mode.token(stream, state); var substr = this.text.slice(stream.start, stream.pos); stream.start = stream.pos; if (pos && st[pos-1] == style) st[pos-2] += substr; else if (substr) { if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true; st[pos++] = substr; st[pos++] = style; prevWord = curWord; curWord = st[pos]; } // Give up when line is ridiculously long if (stream.pos > 5000) { st[pos++] = this.text.slice(stream.pos); st[pos++] = null; break; } } if (st.length != pos) {st.length = pos; changed = true;} if (pos && st[pos-2] != prevWord) changed = true; // Short lines with simple highlights return null, and are // counted as changed by the driver because they are likely to // highlight the same way in various contexts. return changed || (st.length < 5 && this.text.length < 10 ? null : false); }, // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(mode, state, ch) { var txt = this.text, stream = new StringStream(txt); while (stream.pos < ch && !stream.eol()) { stream.start = stream.pos; var style = mode.token(stream, state); } return {start: stream.start, end: stream.pos, string: stream.current(), className: style || null, state: state}; }, indentation: function(tabSize) {return countColumn(this.text, null, tabSize);}, // Produces an HTML fragment for the line, taking selection, // marking, and highlighting into account. getHTML: function(sfrom, sto, includePre, tabText, endAt) { var html = [], first = true; if (includePre) html.push(this.className ? '<pre class="' + this.className + '">': "<pre>"); function span(text, style) { if (!text) return; // Work around a bug where, in some compat modes, IE ignores leading spaces if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1); first = false; if (style) html.push('<span class="', style, '">', htmlEscape(text).replace(/\t/g, tabText), "</span>"); else html.push(htmlEscape(text).replace(/\t/g, tabText)); } var st = this.styles, allText = this.text, marked = this.marked; if (sfrom == sto) sfrom = null; var len = allText.length; if (endAt != null) len = Math.min(endAt, len); if (!allText && endAt == null) span(" ", sfrom != null && sto == null ? "CodeMirror-selected" : null); else if (!marked && sfrom == null) for (var i = 0, ch = 0; ch < len; i+=2) { var str = st[i], style = st[i+1], l = str.length; if (ch + l > len) str = str.slice(0, len - ch); ch += l; span(str, style && "cm-" + style); } else { var pos = 0, i = 0, text = "", style, sg = 0; var markpos = -1, mark = null; function nextMark() { if (marked) { markpos += 1; mark = (markpos < marked.length) ? marked[markpos] : null; } } nextMark(); while (pos < len) { var upto = len; var extraStyle = ""; if (sfrom != null) { if (sfrom > pos) upto = sfrom; else if (sto == null || sto > pos) { extraStyle = " CodeMirror-selected"; if (sto != null) upto = Math.min(upto, sto); } } while (mark && mark.to != null && mark.to <= pos) nextMark(); if (mark) { if (mark.from > pos) upto = Math.min(upto, mark.from); else { extraStyle += " " + mark.style; if (mark.to != null) upto = Math.min(upto, mark.to); } } for (;;) { var end = pos + text.length; var appliedStyle = style; if (extraStyle) appliedStyle = style ? style + extraStyle : extraStyle; span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle); if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} pos = end; text = st[i++]; style = "cm-" + st[i++]; } } if (sfrom != null && sto == null) span(" ", "CodeMirror-selected"); } if (includePre) html.push("</pre>"); return html.join(""); }, cleanUp: function() { this.parent = null; if (this.marked) for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this); } }; // Utility used by replace and split above function copyStyles(from, to, source, dest) { for (var i = 0, pos = 0, state = 0; pos < to; i+=2) { var part = source[i], end = pos + part.length; if (state == 0) { if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]); if (end >= from) state = 1; } else if (state == 1) { if (end > to) dest.push(part.slice(0, to - pos), source[i+1]); else dest.push(part, source[i+1]); } pos = end; } } // Data structure that holds the sequence of lines. function LeafChunk(lines) { this.lines = lines; this.parent = null; for (var i = 0, e = lines.length, height = 0; i < e; ++i) { lines[i].parent = this; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length; }, remove: function(at, n) { for (var i = at, e = at + n; i < e; ++i) { var line = this.lines[i]; line.cleanUp(); this.height -= line.height; } this.lines.splice(at, n); }, collapse: function(lines) { lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); }, insertHeight: function(at, lines, height) { this.height += height; this.lines.splice.apply(this.lines, [at, 0].concat(lines)); for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; }, iterN: function(at, n, op) { for (var e = at + n; at < e; ++at) if (op(this.lines[at])) return true; } }; function BranchChunk(children) { this.children = children; var size = 0, height = 0; for (var i = 0, e = children.length; i < e; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size; }, remove: function(at, n) { this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.remove(at, rm); this.height -= oldHeight - child.height; if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) break; at = 0; } else at -= sz; } if (this.size - n < 25) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; } }, collapse: function(lines) { for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); }, insert: function(at, lines) { var height = 0; for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; this.insertHeight(at, lines, height); }, insertHeight: function(at, lines, height) { this.size += lines.length; this.height += height; for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertHeight(at, lines, height); if (child.lines && child.lines.length > 50) { while (child.lines.length > 50) { var spilled = child.lines.splice(child.lines.length - 25, 25); var newleaf = new LeafChunk(spilled); child.height -= newleaf.height; this.children.splice(i + 1, 0, newleaf); newleaf.parent = this; } this.maybeSpill(); } break; } at -= sz; } }, maybeSpill: function() { if (this.children.length <= 10) return; var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10); me.parent.maybeSpill(); }, iter: function(from, to, op) { this.iterN(from, to - from, op); }, iterN: function(at, n, op) { for (var i = 0, e = this.children.length; i < e; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) return true; if ((n -= used) == 0) break; at = 0; } else at -= sz; } } }; function getLineAt(chunk, n) { while (!chunk.lines) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break; } n -= sz; } } return chunk.lines[n]; } function lineNo(line) { if (line.parent == null) return null; var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0, e = chunk.children.length; ; ++i) { if (chunk.children[i] == cur) break; no += chunk.children[i].chunkSize(); } } return no; } function lineAtHeight(chunk, h) { var n = 0; outer: do { for (var i = 0, e = chunk.children.length; i < e; ++i) { var child = chunk.children[i], ch = child.height; if (h < ch) { chunk = child; continue outer; } h -= ch; n += child.chunkSize(); } return n; } while (!chunk.lines); for (var i = 0, e = chunk.lines.length; i < e; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) break; h -= lh; } return n + i; } function heightAtLine(chunk, n) { var h = 0; outer: do { for (var i = 0, e = chunk.children.length; i < e; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; continue outer; } n -= sz; h += child.height; } return h; } while (!chunk.lines); for (var i = 0; i < n; ++i) h += chunk.lines[i].height; return h; } // The history object 'chunks' changes that are made close together // and at almost the same time into bigger undoable units. function History() { this.time = 0; this.done = []; this.undone = []; } History.prototype = { addChange: function(start, added, old) { this.undone.length = 0; var time = +new Date, last = this.done[this.done.length - 1]; if (time - this.time > 400 || !last || last.start > start + added || last.start + last.added < start - last.added + last.old.length) this.done.push({start: start, added: added, old: old}); else { var oldoff = 0; if (start < last.start) { for (var i = last.start - start - 1; i >= 0; --i) last.old.unshift(old[i]); last.added += last.start - start; last.start = start; } else if (last.start < start) { oldoff = start - last.start; added += oldoff; } for (var i = last.added - oldoff, e = old.length; i < e; ++i) last.old.push(old[i]); if (last.added < added) last.added = added; } this.time = time; } }; function stopMethod() {e_stop(this);} // Ensure an event has a stop method. function addStop(event) { if (!event.stop) event.stop = stopMethod; return event; } function e_preventDefault(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } function e_stopPropagation(e) { if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; } function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} CodeMirror.e_stop = e_stop; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; function e_target(e) {return e.target || e.srcElement;} function e_button(e) { if (e.which) return e.which; else if (e.button & 1) return 1; else if (e.button & 2) return 3; else if (e.button & 4) return 2; } // Event handler registration. If disconnect is true, it'll return a // function that unregisters the handler. function connect(node, type, handler, disconnect) { if (typeof node.addEventListener == "function") { node.addEventListener(type, handler, false); if (disconnect) return function() {node.removeEventListener(type, handler, false);}; } else { var wrapHandler = function(event) {handler(event || window.event);}; node.attachEvent("on" + type, wrapHandler); if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);}; } } CodeMirror.connect = connect; function Delayed() {this.id = null;} Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; // Detect drag-and-drop var dragAndDrop = function() { // IE8 has ondragstart and ondrop properties, but doesn't seem to // actually support ondragstart the way it's supposed to work. if (/MSIE [1-8]\b/.test(navigator.userAgent)) return false; var div = document.createElement('div'); return "draggable" in div; }(); var gecko = /gecko\/\d{7}/i.test(navigator.userAgent); var ie = /MSIE \d/.test(navigator.userAgent); var webkit = /WebKit\//.test(navigator.userAgent); var lineSep = "\n"; // Feature-detect whether newlines in textareas are converted to \r\n (function () { var te = document.createElement("textarea"); te.value = "foo\nbar"; if (te.value.indexOf("\r") > -1) lineSep = "\r\n"; }()); // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. function countColumn(string, end, tabSize) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) end = string.length; } for (var i = 0, n = 0; i < end; ++i) { if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); else ++n; } return n; } function computedStyle(elt) { if (elt.currentStyle) return elt.currentStyle; return window.getComputedStyle(elt, null); } // Find the position of an element by following the offsetParent chain. // If screen==true, it returns screen (rather than page) coordinates. function eltOffset(node, screen) { var bod = node.ownerDocument.body; var x = 0, y = 0, skipBody = false; for (var n = node; n; n = n.offsetParent) { var ol = n.offsetLeft, ot = n.offsetTop; // Firefox reports weird inverted offsets when the body has a border. if (n == bod) { x += Math.abs(ol); y += Math.abs(ot); } else { x += ol, y += ot; } if (screen && computedStyle(n).position == "fixed") skipBody = true; } var e = screen && !skipBody ? null : bod; for (var n = node.parentNode; n != e; n = n.parentNode) if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;} return {left: x, top: y}; } // Use the faster and saner getBoundingClientRect method when possible. if (document.documentElement.getBoundingClientRect != null) eltOffset = function(node, screen) { // Take the parts of bounding client rect that we are interested in so we are able to edit if need be, // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page) try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; } catch(e) { box = {top: 0, left: 0}; } if (!screen) { // Get the toplevel scroll, working around browser differences. if (window.pageYOffset == null) { var t = document.documentElement || document.body.parentNode; if (t.scrollTop == null) t = document.body; box.top += t.scrollTop; box.left += t.scrollLeft; } else { box.top += window.pageYOffset; box.left += window.pageXOffset; } } return box; }; // Get a node's text content. function eltText(node) { return node.textContent || node.innerText || node.nodeValue || ""; } // Operations on {line, ch} objects. function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} function copyPos(x) {return {line: x.line, ch: x.ch};} var escapeElement = document.createElement("pre"); function htmlEscape(str) { escapeElement.textContent = str; return escapeElement.innerHTML; } // Recent (late 2011) Opera betas insert bogus newlines at the start // of the textContent, so we strip those. if (htmlEscape("a") == "\na") htmlEscape = function(str) { escapeElement.textContent = str; return escapeElement.innerHTML.slice(1); }; // Some IEs don't preserve tabs through innerHTML else if (htmlEscape("\t") != "\t") htmlEscape = function(str) { escapeElement.innerHTML = ""; escapeElement.appendChild(document.createTextNode(str)); return escapeElement.innerHTML; }; CodeMirror.htmlEscape = htmlEscape; // Used to position the cursor after an undo/redo by finding the // last edited character. function editEnd(from, to) { if (!to) return from ? from.length : 0; if (!from) return to.length; for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j) if (from.charAt(i) != to.charAt(j)) break; return j + 1; } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { var pos = 0, nl, result = []; while ((nl = string.indexOf("\n", pos)) > -1) { result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl)); pos = nl + 1; } result.push(string.slice(pos)); return result; } : function(string){return string.split(/\r?\n/);}; CodeMirror.splitLines = splitLines; var hasSelection = window.getSelection ? function(te) { try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } } : function(te) { try {var range = te.ownerDocument.selection.createRange();} catch(e) {} if (!range || range.parentElement() != te) return false; return range.compareEndPoints("StartToEnd", range) != 0; }; CodeMirror.defineMode("null", function() { return {token: function(stream) {stream.skipToEnd();}}; }); CodeMirror.defineMIME("text/plain", "null"); var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 91: "Win", 92: "Win", 93: "Select", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; CodeMirror.keyNames = keyNames; (function() { // Number keys for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); // Alphabetic keys for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); // Function keys for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; })(); return CodeMirror; })();
JavaScript
CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var jsonMode = parserConfig.json; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; return { "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom }; }(); var isOperatorChar = /[+\-*&%=<>!?|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function nextUntilUnescaped(stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next == end && !escaped) return false; escaped = !escaped && next == "\\"; } return escaped; } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function jsTokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") return chain(stream, state, jsTokenString(ch)); else if (/[\[\]{}\(\),;\:\.]/.test(ch)) return ret(ch); else if (ch == "0" && stream.eat(/x/i)) { stream.eatWhile(/[\da-f]/i); return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { return chain(stream, state, jsTokenComment); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (state.reAllowed) { nextUntilUnescaped(stream, "/"); stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla return ret("regexp", "string"); } else { stream.eatWhile(isOperatorChar); return ret("operator", null, stream.current()); } } else if (ch == "#") { stream.skipToEnd(); return ret("error", "error"); } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return ret("operator", null, stream.current()); } else { stream.eatWhile(/[\w\$_]/); var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; return known ? ret(known.type, known.style, word) : ret("variable", "variable", word); } } function jsTokenString(quote) { return function(stream, state) { if (!nextUntilUnescaped(stream, quote)) state.tokenize = jsTokenBase; return ret("string", "string"); }; } function jsTokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = jsTokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function register(varname) { var state = cx.state; if (state.context) { cx.marked = "def"; for (var v = state.localVars; v; v = v.next) if (v.name == varname) return; state.localVars = {name: varname, next: state.localVars}; } } // Combinators var defaultVars = {name: "this", next: {name: "arguments"}}; function pushcontext() { if (!cx.state.context) cx.state.localVars = defaultVars; cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; } function popcontext() { cx.state.localVars = cx.state.context.vars; cx.state.context = cx.state.context.prev; } function pushlex(type, info) { var result = function() { var state = cx.state; state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { return function expecting(type) { if (type == wanted) return cont(); else if (wanted == ";") return pass(); else return cont(arguments.callee); }; } function statement(type) { if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "{") return cont(pushlex("}"), block, poplex); if (type == ";") return cont(); if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); if (type == "variable") return cont(pushlex("stat"), maybelabel); if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); return pass(pushlex("stat"), expression, expect(";"), poplex); } function expression(type) { if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator); if (type == "function") return cont(functiondef); if (type == "keyword c") return cont(maybeexpression); if (type == "(") return cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator); if (type == "operator") return cont(expression); if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeoperator(type, value) { if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator); if (type == "operator") return cont(expression); if (type == ";") return; if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); if (type == ".") return cont(property, maybeoperator); if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperator, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type) { if (type == "variable") cx.marked = "property"; if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression); } function commasep(what, end) { function proceed(type) { if (type == ",") return cont(what, proceed); if (type == end) return cont(); return cont(expect(end)); } return function commaSeparated(type) { if (type == end) return cont(); else return pass(what, proceed); }; } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function vardef1(type, value) { if (type == "variable"){register(value); return cont(vardef2);} return cont(); } function vardef2(type, value) { if (value == "=") return cont(expression, vardef2); if (type == ",") return cont(vardef1); } function forspec1(type) { if (type == "var") return cont(vardef1, forspec2); if (type == ";") return pass(forspec2); if (type == "variable") return cont(formaybein); return pass(forspec2); } function formaybein(type, value) { if (value == "in") return cont(expression); return cont(maybeoperator, forspec2); } function forspec2(type, value) { if (type == ";") return cont(forspec3); if (value == "in") return cont(expression); return cont(expression, expect(";"), forspec3); } function forspec3(type) { if (type != ")") cont(expression); } function functiondef(type, value) { if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); } function funarg(type, value) { if (type == "variable") {register(value); return cont();} } // Interface return { startState: function(basecolumn) { return { tokenize: jsTokenBase, reAllowed: true, cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: null, context: null, indented: 0 }; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.reAllowed = type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/); return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize != jsTokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + 4; else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricChars: ":{}" }; }); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
JavaScript
CodeMirror.runMode = function(string, modespec, callback) { var mode = CodeMirror.getMode({indentUnit: 2}, modespec); var isNode = callback.nodeType == 1; if (isNode) { var node = callback, accum = []; callback = function(string, style) { if (string == "\n") accum.push("<br>"); else if (style) accum.push("<span class=\"cm-" + CodeMirror.htmlEscape(style) + "\">" + CodeMirror.htmlEscape(string) + "</span>"); else accum.push(CodeMirror.htmlEscape(string)); } } var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode); for (var i = 0, e = lines.length; i < e; ++i) { if (i) callback("\n"); var stream = new CodeMirror.StringStream(lines[i]); while (!stream.eol()) { var style = mode.token(stream, state); callback(stream.current(), style, i, stream.start); stream.start = stream.pos; } } if (isNode) node.innerHTML = accum.join(""); };
JavaScript
// Copyright 2012 Google Inc. /** * @name Store Locator for Google Maps API V3 * @version 0.1 * @author Chris Broadfoot (Google) * @fileoverview * This library makes it easy to create a fully-featured Store Locator for * your business's website. */ /** * @license * * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Namespace for Store Locator. * @constructor */ var storeLocator = function() {}; window['storeLocator'] = storeLocator; /** * Convert from degrees to radians. * @private * @param {number} degrees the number in degrees. * @return {number} the number in radians. */ storeLocator.toRad_ = function(degrees) { return degrees * Math.PI / 180; };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Allows developers to specify a static set of stores to be used in the * storelocator. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A DataFeed with a static set of stores. Provides sorting of stores by * proximity and feature filtering (store must have <em>all</em> features from * the filter). * @example <pre> * var dataFeed = new storeLocator.StaticDataFeed(); * jQuery.getJSON('stores.json', function(json) { * var stores = parseStores(json); * dataFeed.setStores(stores); * }); * new storeLocator.View(map, dataFeed); * </pre> * @implements {storeLocator.DataFeed} * @constructor * @implements storeLocator_StaticDataFeed */ storeLocator.StaticDataFeed = function() { /** * The static list of stores. * @private * @type {Array.<storeLocator.Store>} */ this.stores_ = []; }; storeLocator['StaticDataFeed'] = storeLocator.StaticDataFeed; /** * This will contain a callback to be called if getStores was called before * setStores (i.e. if the map is waiting for data from the data source). * @private * @type {Function} */ storeLocator.StaticDataFeed.prototype.firstCallback_; /** * Set the stores for this data feed. * @param {!Array.<!storeLocator.Store>} stores the stores for this data feed. */ storeLocator.StaticDataFeed.prototype.setStores = function(stores) { this.stores_ = stores; if (this.firstCallback_) { this.firstCallback_(); } else { delete this.firstCallback_; } }; /** * @inheritDoc */ storeLocator.StaticDataFeed.prototype.getStores = function(bounds, features, callback) { // Prevent race condition - if getStores is called before stores are loaded. if (!this.stores_.length) { var that = this; this.firstCallback_ = function() { that.getStores(bounds, features, callback); }; return; } // Filter stores for features. var stores = []; for (var i = 0, store; store = this.stores_[i]; i++) { if (store.hasAllFeatures(features)) { stores.push(store); } } this.sortByDistance_(bounds.getCenter(), stores); callback(stores); }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ storeLocator.StaticDataFeed.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Feature model class for Store Locator library. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Representation of a feature of a store. (e.g. 24 hours, BYO, etc). * @example <pre> * var feature = new storeLocator.Feature('24hour', 'Open 24 Hours'); * </pre> * @param {string} id unique identifier for this feature. * @param {string} name display name of this feature. * @constructor * @implements storeLocator_Feature */ storeLocator.Feature = function(id, name) { this.id_ = id; this.name_ = name; }; storeLocator['Feature'] = storeLocator.Feature; /** * Gets this Feature's ID. * @return {string} this feature's ID. */ storeLocator.Feature.prototype.getId = function() { return this.id_; }; /** * Gets this Feature's display name. * @return {string} this feature's display name. */ storeLocator.Feature.prototype.getDisplayName = function() { return this.name_; }; storeLocator.Feature.prototype.toString = function() { return this.getDisplayName(); };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * An info panel, which complements the map view of the Store Locator. * Provides a list of stores, location search, feature filter, and directions. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * An info panel, to complement the map view. * Provides a list of stores, location search, feature filter, and directions. * @example <pre> * var container = document.getElementById('panel'); * var panel = new storeLocator.Panel(container, { * view: view, * locationSearchLabel: 'Location:' * }); * google.maps.event.addListener(panel, 'geocode', function(result) { * geocodeMarker.setPosition(result.geometry.location); * }); * </pre> * @extends {google.maps.MVCObject} * @param {!Node} el the element to contain this panel. * @param {storeLocator.PanelOptions} opt_options * @constructor * @implements storeLocator_Panel */ storeLocator.Panel = function(el, opt_options) { this.el_ = $(el); this.el_.addClass('storelocator-panel'); this.settings_ = $.extend({ 'locationSearch': true, 'locationSearchLabel': 'Where are you?', 'featureFilter': true, 'directions': true, 'view': null }, opt_options); this.directionsRenderer_ = new google.maps.DirectionsRenderer({ draggable: true }); this.directionsService_ = new google.maps.DirectionsService; this.init_(); }; storeLocator['Panel'] = storeLocator.Panel; storeLocator.Panel.prototype = new google.maps.MVCObject; /** * Initialise the info panel * @private */ storeLocator.Panel.prototype.init_ = function() { var that = this; this.itemCache_ = {}; if (this.settings_['view']) { this.set('view', this.settings_['view']); } this.filter_ = $('<form class="storelocator-filter"/>'); this.el_.append(this.filter_); if (this.settings_['locationSearch']) { this.locationSearch_ = $('<div class="location-search"><h4>' + this.settings_['locationSearchLabel'] + '</h4><input></div>'); this.filter_.append(this.locationSearch_); if (typeof google.maps.places != 'undefined') { this.initAutocomplete_(); } else { this.filter_.submit(function() { var search = $('input', that.locationSearch_).val(); that.searchPosition(/** @type {string} */(search)); }); } this.filter_.submit(function() { return false; }); google.maps.event.addListener(this, 'geocode', function(place) { if (!place.geometry) { that.searchPosition(place.name); return; } this.directionsFrom_ = place.geometry.location; if (that.directionsVisible_) { that.renderDirections_(); } var sl = that.get('view'); sl.highlight(null); var map = sl.getMap(); if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(13); } sl.refreshView(); that.listenForStoresUpdate_(); }); } if (this.settings_['featureFilter']) { // TODO(cbro): update this on view_changed this.featureFilter_ = $('<div class="feature-filter"/>'); var allFeatures = this.get('view').getFeatures().asList(); for (var i = 0, ii = allFeatures.length; i < ii; i++) { var feature = allFeatures[i]; var checkbox = $('<input type="checkbox"/>'); checkbox.data('feature', feature); $('<label/>').append(checkbox).append(feature.getDisplayName()) .appendTo(this.featureFilter_); } this.filter_.append(this.featureFilter_); this.featureFilter_.find('input').change(function() { var feature = $(this).data('feature'); that.toggleFeatureFilter_(/** @type {storeLocator.Feature} */(feature)); that.get('view').refreshView(); }); } this.storeList_ = $('<ul class="store-list"/>'); this.el_.append(this.storeList_); if (this.settings_['directions']) { this.directionsPanel_ = $('<div class="directions-panel"><form>' + '<input class="directions-to"/>' + '<input type="submit" value="Find directions"/>' + '<a href="#" class="close-directions">Close</a>' + '</form><div class="rendered-directions"></div></div>'); this.directionsPanel_.find('.directions-to').attr('readonly', 'readonly'); this.directionsPanel_.hide(); this.directionsVisible_ = false; this.directionsPanel_.find('form').submit(function() { that.renderDirections_(); return false; }); this.directionsPanel_.find('.close-directions').click(function() { that.hideDirections(); }); this.el_.append(this.directionsPanel_); } }; /** * Toggles a particular feature on/off in the feature filter. * @param {storeLocator.Feature} feature The feature to toggle. * @private */ storeLocator.Panel.prototype.toggleFeatureFilter_ = function(feature) { var featureFilter = this.get('featureFilter'); featureFilter.toggle(feature); this.set('featureFilter', featureFilter); }; /** * Global Geocoder instance, for convenience. * @type {google.maps.Geocoder} * @private */ storeLocator.geocoder_ = new google.maps.Geocoder; /** * Triggers an update for the store list in the Panel. Will wait for stores * to load asynchronously from the data source. * @private */ storeLocator.Panel.prototype.listenForStoresUpdate_ = function() { var that = this; var view = /** @type storeLocator.View */(this.get('view')); if (this.storesChangedListener_) { google.maps.event.removeListener(this.storesChangedListener_); } this.storesChangedListener_ = google.maps.event.addListenerOnce(view, 'stores_changed', function() { that.set('stores', view.get('stores')); }); }; /** * Search and pan to the specified address. * @param {string} searchText the address to pan to. */ storeLocator.Panel.prototype.searchPosition = function(searchText) { var that = this; var request = { address: searchText, bounds: this.get('view').getMap().getBounds() }; storeLocator.geocoder_.geocode(request, function(result, status) { if (status != google.maps.GeocoderStatus.OK) { //TODO(cbro): proper error handling return; } google.maps.event.trigger(that, 'geocode', result[0]); }); }; /** * Sets the associated View. * @param {storeLocator.View} view the view to set. */ storeLocator.Panel.prototype.setView = function(view) { this.set('view', view); }; /** * view_changed handler. * Sets up additional bindings between the info panel and the map view. */ storeLocator.Panel.prototype.view_changed = function() { var sl = /** @type {google.maps.MVCObject} */ (this.get('view')); this.bindTo('selectedStore', sl); var that = this; if (this.geolocationListener_) { google.maps.event.removeListener(this.geolocationListener_); } if (this.zoomListener_) { google.maps.event.removeListener(this.zoomListener_); } if (this.idleListener_) { google.maps.event.removeListener(this.idleListener_); } var center = sl.getMap().getCenter(); var updateList = function() { sl.clearMarkers(); that.listenForStoresUpdate_(); }; //TODO(cbro): somehow get the geolocated position and populate the 'from' box. this.geolocationListener_ = google.maps.event.addListener(sl, 'load', updateList); this.zoomListener_ = google.maps.event.addListener(sl.getMap(), 'zoom_changed', updateList); this.idleListener_ = google.maps.event.addListener(sl.getMap(), 'idle', function() { return that.idle_(sl.getMap()); }); updateList(); this.bindTo('featureFilter', sl); if (this.autoComplete_) { this.autoComplete_.bindTo('bounds', sl.getMap()); } }; /** * Adds autocomplete to the input box. * @private */ storeLocator.Panel.prototype.initAutocomplete_ = function() { var that = this; var input = $('input', this.locationSearch_)[0]; this.autoComplete_ = new google.maps.places.Autocomplete(input); if (this.get('view')) { this.autoComplete_.bindTo('bounds', this.get('view').getMap()); } google.maps.event.addListener(this.autoComplete_, 'place_changed', function() { google.maps.event.trigger(that, 'geocode', this.getPlace()); }); }; /** * Called on the view's map idle event. Refreshes the store list if the * user has navigated far away enough. * @param {google.maps.Map} map the current view's map. * @private */ storeLocator.Panel.prototype.idle_ = function(map) { if (!this.center_) { this.center_ = map.getCenter(); } else if (!map.getBounds().contains(this.center_)) { this.center_ = map.getCenter(); this.listenForStoresUpdate_(); } }; /** * @const * @type {string} * @private */ storeLocator.Panel.NO_STORES_HTML_ = '<li class="no-stores">There are no' + ' stores in this area.</li>'; /** * @const * @type {string} * @private */ storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">There are' + ' no stores in this area. However, stores closest to you are' + ' listed below.</li>'; /** * Handler for stores_changed. Updates the list of stores. * @this storeLocator.Panel */ storeLocator.Panel.prototype.stores_changed = function() { if (!this.get('stores')) { return; } var view = this.get('view'); var bounds = view && view.getMap().getBounds(); var that = this; var stores = this.get('stores'); var selectedStore = this.get('selectedStore'); this.storeList_.empty(); if (!stores.length) { this.storeList_.append(storeLocator.Panel.NO_STORES_HTML_); } else if (bounds && !bounds.contains(stores[0].getLocation())) { this.storeList_.append(storeLocator.Panel.NO_STORES_IN_VIEW_HTML_); } var clickHandler = function() { view.highlight(this['store'], true); }; // TODO(cbro): change 10 to a setting/option for (var i = 0, ii = Math.min(10, stores.length); i < ii; i++) { var storeLi = stores[i].getInfoPanelItem(); storeLi['store'] = stores[i]; if (selectedStore && stores[i].getId() == selectedStore.getId()) { $(storeLi).addClass('highlighted'); } if (!storeLi.clickHandler_) { storeLi.clickHandler_ = google.maps.event.addDomListener( storeLi, 'click', clickHandler); } that.storeList_.append(storeLi); } }; /** * Handler for selectedStore_changed. Highlights the selected store in the * store list. * @this storeLocator.Panel */ storeLocator.Panel.prototype.selectedStore_changed = function() { $('.highlighted', this.storeList_).removeClass('highlighted'); var that = this; var store = this.get('selectedStore'); if (!store) { return; } this.directionsTo_ = store; this.storeList_.find('#store-' + store.getId()).addClass('highlighted'); if (this.settings_['directions']) { this.directionsPanel_.find('.directions-to') .val(store.getDetails().title); } var node = that.get('view').getInfoWindow().getContent(); var directionsLink = $('<a/>') .text('Directions') .attr('href', '#') .addClass('action') .addClass('directions'); // TODO(cbro): Make these two permanent fixtures in InfoWindow. // Move out of Panel. var zoomLink = $('<a/>') .text('Zoom here') .attr('href', '#') .addClass('action') .addClass('zoomhere'); var streetViewLink = $('<a/>') .text('Street view') .attr('href', '#') .addClass('action') .addClass('streetview'); directionsLink.click(function() { that.showDirections(); return false; }); zoomLink.click(function() { that.get('view').getMap().setOptions({ center: store.getLocation(), zoom: 16 }); }); streetViewLink.click(function() { var streetView = that.get('view').getMap().getStreetView(); streetView.setPosition(store.getLocation()); streetView.setVisible(true); }); $(node).append(directionsLink).append(zoomLink).append(streetViewLink); }; /** * Hides the directions panel. */ storeLocator.Panel.prototype.hideDirections = function() { this.directionsVisible_ = false; this.directionsPanel_.fadeOut(); this.featureFilter_.fadeIn(); this.storeList_.fadeIn(); this.directionsRenderer_.setMap(null); }; /** * Shows directions to the selected store. */ storeLocator.Panel.prototype.showDirections = function() { var store = this.get('selectedStore'); this.featureFilter_.fadeOut(); this.storeList_.fadeOut(); this.directionsPanel_.find('.directions-to').val(store.getDetails().title); this.directionsPanel_.fadeIn(); this.renderDirections_(); this.directionsVisible_ = true; }; /** * Renders directions from the location in the input box, to the store that is * pre-filled in the 'to' box. * @private */ storeLocator.Panel.prototype.renderDirections_ = function() { var that = this; if (!this.directionsFrom_ || !this.directionsTo_) { return; } var rendered = this.directionsPanel_.find('.rendered-directions').empty(); this.directionsService_.route({ origin: this.directionsFrom_, destination: this.directionsTo_.getLocation(), travelMode: google.maps['DirectionsTravelMode'].DRIVING //TODO(cbro): region biasing, waypoints, travelmode }, function(result, status) { if (status != google.maps.DirectionsStatus.OK) { // TODO(cbro): better error handling return; } var renderer = that.directionsRenderer_; renderer.setPanel(rendered[0]); renderer.setMap(that.get('view').getMap()); renderer.setDirections(result); }); }; /** * featureFilter_changed event handler. */ storeLocator.Panel.prototype.featureFilter_changed = function() { this.listenForStoresUpdate_(); }; /** * Fired when searchPosition has been called. This happens when the user has * searched for a location from the location search box and/or autocomplete. * @name storeLocator.Panel#event:geocode * @param {google.maps.PlaceResult|google.maps.GeocoderResult} result * @event */ /** * Fired when the <code>Panel</code>'s <code>view</code> property changes. * @name storeLocator.Panel#event:view_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>featureFilter</code> property * changes. * @name storeLocator.Panel#event:featureFilter_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>stores</code> property changes. * @name storeLocator.Panel#event:stores_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>selectedStore</code> property * changes. * @name storeLocator.Panel#event:selectedStore_changed * @event */ /** * @example see storeLocator.Panel * @interface */ storeLocator.PanelOptions = function() {}; /** * Whether to show the location search box. Default is true. * @type boolean */ storeLocator.prototype.locationSearch; /** * The label to show above the location search box. Default is "Where are you * now?". * @type string */ storeLocator.PanelOptions.prototype.locationSearchLabel; /** * Whether to show the feature filter picker. Default is true. * @type boolean */ storeLocator.PanelOptions.prototype.featureFilter; /** * Whether to provide directions. Deafult is true. * @type boolean */ storeLocator.PanelOptions.prototype.directions; /** * The store locator model to bind to. * @type storeLocator.View */ storeLocator.PanelOptions.prototype.view;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * This library makes it easy to create a fully-featured Store Locator for * your business's website. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Data feed that returns stores based on a given bounds and a set of features. * @example <pre> * // always returns the same stores * function SimpleStaticFeed(stores) { * this.stores = stores; * } * SimpleStaticFeed.prototype.getStores = function(bounds, features, callback) { * callback(this.stores); * }; * new storeLocator.View(map, new SimpleStaticFeed()); * </pre> * @interface */ storeLocator.DataFeed = function() {}; storeLocator['DataFeed'] = storeLocator.DataFeed; /** * Fetch stores, based on bounds to search within, and features to filter on. * @param {google.maps.LatLngBounds} bounds the bounds to search within. * @param {storeLocator.FeatureSet} features the features to filter on. * @param {function(Array.<!storeLocator.Store>)} callback the callback * function. */ storeLocator.DataFeed.prototype.getStores = function(bounds, features, callback) {}; /** * The main store locator object. * @example <pre> * new storeLocator.View(map, dataFeed); * </pre> * <pre> * var features = new storeLocator.FeatureSet(feature1, feature2, feature3); * new storeLocator.View(map, dataFeed, { * markerIcon: 'icon.png', * features: features, * geolocation: false * }); * </pre> * <pre> * // refresh stores every 10 seconds, regardless of interaction on the map. * var view = new storeLocator.View(map, dataFeed, { * updateOnPan: false * }); * setTimeout(function() { * view.refreshView(); * }, 10000); * </pre> * <pre> * // custom MarkerOptions, by overriding the createMarker method. * view.createMarker = function(store) { * return new google.maps.Marker({ * position: store.getLocation(), * icon: store.getDetails().icon, * title: store.getDetails().title * }); * }; * </pre> * @extends {google.maps.MVCObject} * @param {google.maps.Map} map the map to operate upon. * @param {storeLocator.DataFeed} data the data feed to fetch stores from. * @param {storeLocator.ViewOptions} opt_options * @constructor * @implements storeLocator_View */ storeLocator.View = function(map, data, opt_options) { this.map_ = map; this.data_ = data; this.settings_ = $.extend({ 'updateOnPan': true, 'geolocation': true, 'features': new storeLocator.FeatureSet }, opt_options); this.init_(); google.maps.event.trigger(this, 'load'); this.set('featureFilter', new storeLocator.FeatureSet); }; storeLocator['View'] = storeLocator.View; storeLocator.View.prototype = new google.maps.MVCObject; /** * Attempt to perform geolocation and pan to the given location * @private */ storeLocator.View.prototype.geolocate_ = function() { var that = this; if (window.navigator && navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(pos) { var loc = new google.maps.LatLng( pos.coords.latitude, pos.coords.longitude); that.getMap().setCenter(loc); that.getMap().setZoom(11); google.maps.event.trigger(that, 'load'); }, undefined, /** @type GeolocationPositionOptions */({ maximumAge: 60 * 1000, timeout: 10 * 1000 })); } }; /** * Initialise the View object * @private */ storeLocator.View.prototype.init_ = function() { if (this.settings_['geolocation']) { this.geolocate_(); } this.markerCache_ = {}; this.infoWindow_ = new google.maps.InfoWindow; var that = this; var map = this.getMap(); this.set('updateOnPan', this.settings_['updateOnPan']); google.maps.event.addListener(this.infoWindow_, 'closeclick', function() { that.highlight(null); }); google.maps.event.addListener(map, 'click', function() { that.highlight(null); that.infoWindow_.close(); }); }; /** * Adds/remove hooks as appropriate. */ storeLocator.View.prototype.updateOnPan_changed = function() { if (this.updateOnPanListener_) { google.maps.event.removeListener(this.updateOnPanListener_); } if (this.get('updateOnPan') && this.getMap()) { var that = this; var map = this.getMap(); this.updateOnPanListener_ = google.maps.event.addListener(map, 'idle', function() { that.refreshView(); }); } }; /** * Add a store to the map. * @param {storeLocator.Store} store the store to add. */ storeLocator.View.prototype.addStoreToMap = function(store) { var marker = this.getMarker(store); store.setMarker(marker); var that = this; marker.clickListener_ = google.maps.event.addListener(marker, 'click', function() { that.highlight(store, false); }); if (marker.getMap() != this.getMap()) { marker.setMap(this.getMap()); } }; /** * Create a marker for a store. * @param {storeLocator.Store} store the store to produce a marker for. * @this storeLocator.View * @return {google.maps.Marker} a new marker. * @export */ storeLocator.View.prototype.createMarker = function(store) { var markerOptions = { position: store.getLocation() }; var opt_icon = this.settings_['markerIcon']; if (opt_icon) { markerOptions.icon = opt_icon; } return new google.maps.Marker(markerOptions); }; /** * Get a marker for a store. By default, this caches the value from * createMarker(store) * @param {storeLocator.Store} store the store to get the marker from. * @return {google.maps.Marker} the marker. */ storeLocator.View.prototype.getMarker = function(store) { var cache = this.markerCache_; var key = store.getId(); if (!cache[key]) { cache[key] = this['createMarker'](store); } return cache[key]; }; /** * Get a InfoWindow for a particular store. * @param {storeLocator.Store} store the store. * @return {google.maps.InfoWindow} the store's InfoWindow. */ storeLocator.View.prototype.getInfoWindow = function(store) { if (!store) { return this.infoWindow_; } var div = $(store.getInfoWindowContent()); this.infoWindow_.setContent(div[0]); return this.infoWindow_; }; /** * Gets all possible features for this View. * @return {storeLocator.FeatureSet} All possible features. */ storeLocator.View.prototype.getFeatures = function() { return this.settings_['features']; }; /** * Gets a feature by its id. Convenience method. * @param {string} id the feature's id. * @return {storeLocator.Feature|undefined} The feature, if the id is valid. * undefined if not. */ storeLocator.View.prototype.getFeatureById = function(id) { if (!this.featureById_) { this.featureById_ = {}; for (var i = 0, feature; feature = this.settings_['features'][i]; i++) { this.featureById_[feature.getId()] = feature; } } return this.featureById_[id]; }; /** * featureFilter_changed event handler. */ storeLocator.View.prototype.featureFilter_changed = function() { google.maps.event.trigger(this, 'featureFilter_changed', this.get('featureFilter')); if (this.get('stores')) { this.clearMarkers(); } }; /** * Clears the visible markers on the map. */ storeLocator.View.prototype.clearMarkers = function() { for (var marker in this.markerCache_) { this.markerCache_[marker].setMap(null); var listener = this.markerCache_[marker].clickListener_; if (listener) { google.maps.event.removeListener(listener); } } }; /** * Refresh the map's view. This will fetch new data based on the map's bounds. */ storeLocator.View.prototype.refreshView = function() { var that = this; this.data_.getStores(this.getMap().getBounds(), /** @type {storeLocator.FeatureSet} */ (this.get('featureFilter')), function(stores) { var oldStores = that.get('stores'); if (oldStores) { for (var i = 0, ii = oldStores.length; i < ii; i++) { google.maps.event.removeListener( oldStores[i].getMarker().clickListener_); } } that.set('stores', stores); }); }; /** * stores_changed event handler. * This will display all new stores on the map. * @this storeLocator.View */ storeLocator.View.prototype.stores_changed = function() { var stores = this.get('stores'); for (var i = 0, store; store = stores[i]; i++) { this.addStoreToMap(store); } }; /** * Gets the view's Map. * @return {google.maps.Map} the view's Map. */ storeLocator.View.prototype.getMap = function() { return this.map_; }; /** * Select a particular store. * @param {storeLocator.Store} store the store to highlight. * @param {boolean=} opt_pan if panning to the store on the map is desired. */ storeLocator.View.prototype.highlight = function(store, opt_pan) { var infoWindow = this.getInfoWindow(store); if (store) { var infoWindow = this.getInfoWindow(store); if (store.getMarker()) { infoWindow.open(this.getMap(), store.getMarker()); } else { infoWindow.setPosition(store.getLocation()); infoWindow.open(this.getMap()); } if (opt_pan) { this.getMap().panTo(store.getLocation()); } if (this.getMap().getStreetView().getVisible()) { this.getMap().getStreetView().setPosition(store.getLocation()); } } else { infoWindow.close(); } this.set('selectedStore', store); }; /** * Re-triggers the selectedStore_changed event with the store as a parameter. * @this storeLocator.View */ storeLocator.View.prototype.selectedStore_changed = function() { google.maps.event.trigger(this, 'selectedStore_changed', this.get('selectedStore')); }; /** * Fired when the <code>View</code> is loaded. This happens once immediately, * then once more if geolocation is successful. * @name storeLocator.View#event:load * @event */ /** * Fired when the <code>View</code>'s <code>featureFilter</code> property * changes. * @name storeLocator.View#event:featureFilter_changed * @event */ /** * Fired when the <code>View</code>'s <code>updateOnPan</code> property changes. * @name storeLocator.View#event:updateOnPan_changed * @event */ /** * Fired when the <code>View</code>'s <code>stores</code> property changes. * @name storeLocator.View#event:stores_changed * @event */ /** * Fired when the <code>View</code>'s <code>selectedStore</code> property * changes. This happens after <code>highlight()</code> is called. * @name storeLocator.View#event:selectedStore_changed * @param {storeLocator.Store} store * @event */ /** * @example see storeLocator.View * @interface */ storeLocator.ViewOptions = function() {}; /** * Whether the map should update stores in the visible area when the visible * area changes. <code>refreshView()</code> will need to be called * programatically. Defaults to true. * @type boolean */ storeLocator.ViewOptions.prototype.updateOnPan; /** * Whether the store locator should attempt to determine the user's location * for the initial view. Defaults to true. * @type boolean */ storeLocator.ViewOptions.prototype.geolocation; /** * All available store features. Defaults to empty FeatureSet. * @type storeLocator.FeatureSet */ storeLocator.ViewOptions.prototype.features; /** * The icon to use for markers representing stores. * @type string|google.maps.MarkerImage */ storeLocator.ViewOptions.prototype.markerIcon;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Store model class for Store Locator library. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Represents a store. * @example <pre> * var latLng = new google.maps.LatLng(40.7585, -73.9861); * var store = new storeLocator.Store('times_square', latLng, null); * </pre> * <pre> * var features = new storeLocator.FeatureSet( * view.getFeatureById('24hour'), * view.getFeatureById('express'), * view.getFeatureById('wheelchair_access')); * * var store = new storeLocator.Store('times_square', latLng, features, { * title: 'Times Square', * address: '1 Times Square&lt;br>Manhattan, NY 10036' * }); * </pre> * <pre> * store.distanceTo(map.getCenter()); * * // override default info window * store.getInfoWindowContent = function() { * var details = this.getDetails(); * return '&lt;h1>' + details.title + '&lt;h1>' + details.address; * }; * </pre> * @param {string} id globally unique id of the store - should be suitable to * use as a HTML id. * @param {!google.maps.LatLng} location location of the store. * @param {storeLocator.FeatureSet} features the features of this store. * @param {Object.<string, *>=} props any additional properties. * <p> Recommended fields are: * 'title', 'address', 'phone', 'misc', 'web'. </p> * @constructor * @implements storeLocator_Store */ storeLocator.Store = function(id, location, features, props) { this.id_ = id; this.location_ = location; this.features_ = features || storeLocator.FeatureSet.NONE; this.props_ = props || {}; }; storeLocator['Store'] = storeLocator.Store; /** * Sets this store's Marker. * @param {google.maps.Marker} marker the marker to set on this store. */ storeLocator.Store.prototype.setMarker = function(marker) { this.marker_ = marker; google.maps.event.trigger(this, 'marker_changed', marker); }; /** * Gets this store's Marker * @return {google.maps.Marker} the store's marker. */ storeLocator.Store.prototype.getMarker = function() { return this.marker_; }; /** * Gets this store's ID. * @return {string} this store's ID. */ storeLocator.Store.prototype.getId = function() { return this.id_; }; /** * Gets this store's location. * @return {google.maps.LatLng} this store's location. */ storeLocator.Store.prototype.getLocation = function() { return this.location_; }; /** * Gets this store's features. * @return {storeLocator.FeatureSet} this store's features. */ storeLocator.Store.prototype.getFeatures = function() { return this.features_; }; /** * Checks whether this store has a particular feature. * @param {!storeLocator.Feature} feature the feature to check for. * @return {boolean} true if the store has the feature, false otherwise. */ storeLocator.Store.prototype.hasFeature = function(feature) { return this.features_.contains(feature); }; /** * Checks whether this store has all the given features. * @param {storeLocator.FeatureSet} features the features to check for. * @return {boolean} true if the store has all features, false otherwise. */ storeLocator.Store.prototype.hasAllFeatures = function(features) { if (!features) { return true; } var featureList = features.asList(); for (var i = 0, ii = featureList.length; i < ii; i++) { if (!this.hasFeature(featureList[i])) { return false; } } return true; }; /** * Gets additional details about this store. * @return {Object} additional properties of this store. */ storeLocator.Store.prototype.getDetails = function() { return this.props_; }; /** * Generates HTML for additional details about this store. * @private * @param {Array.<string>} fields the optional fields of this store to output. * @return {string} html version of additional fields of this store. */ storeLocator.Store.prototype.generateFieldsHTML_ = function(fields) { var html = []; for (var i = 0, ii = fields.length; i < ii; i++) { var prop = fields[i]; if (this.props_[prop]) { html.push('<div class="'); html.push(prop); html.push('">'); html.push(this.props_[prop]); html.push('</div>'); } } return html.join(''); }; /** * Generates a HTML list of this store's features. * @private * @return {string} html list of this store's features. */ storeLocator.Store.prototype.generateFeaturesHTML_ = function() { var html = []; html.push('<ul class="features">'); var featureList = this.features_.asList(); for (var i = 0, feature; feature = featureList[i]; i++) { html.push('<li>'); html.push(feature.getDisplayName()); html.push('</li>'); } html.push('</ul>'); return html.join(''); }; /** * Gets the HTML content for this Store, suitable for use in an InfoWindow. * @return {string} a HTML version of this store. */ storeLocator.Store.prototype.getInfoWindowContent = function() { if (!this.content_) { // TODO(cbro): make this a setting? var fields = ['title', 'address', 'phone', 'misc', 'web']; var html = ['<div class="store">']; html.push(this.generateFieldsHTML_(fields)); html.push(this.generateFeaturesHTML_()); html.push('</div>'); this.content_ = html.join(''); } return this.content_; }; /** * Gets the HTML content for this Store, suitable for use in suitable for use * in the sidebar info panel. * @this storeLocator.Store * @return {string} a HTML version of this store. */ storeLocator.Store.prototype.getInfoPanelContent = function() { return this.getInfoWindowContent(); }; /** * Keep a cache of InfoPanel items (DOM Node), keyed by the store ID. * @private * @type {Object} */ storeLocator.Store.infoPanelCache_ = {}; /** * Gets a HTML element suitable for use in the InfoPanel. * @return {Node} a HTML element. */ storeLocator.Store.prototype.getInfoPanelItem = function() { var cache = storeLocator.Store.infoPanelCache_; var store = this; var key = store.getId(); if (!cache[key]) { var content = store.getInfoPanelContent(); cache[key] = $('<li class="store" id="store-' + store.getId() + '">' + content + '</li>')[0]; } return cache[key]; }; /** * Gets the distance between this Store and a certain location. * @param {google.maps.LatLng} point the point to calculate distance to/from. * @return {number} the distance from this store to a given point. * @license * Latitude/longitude spherical geodesy formulae & scripts * (c) Chris Veness 2002-2010 * www.movable-type.co.uk/scripts/latlong.html */ storeLocator.Store.prototype.distanceTo = function(point) { var R = 6371; // mean radius of earth var location = this.getLocation(); var lat1 = storeLocator.toRad_(location.lat()); var lon1 = storeLocator.toRad_(location.lng()); var lat2 = storeLocator.toRad_(point.lat()); var lon2 = storeLocator.toRad_(point.lng()); var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; }; /** * Fired when the <code>Store</code>'s <code>marker</code> property changes. * @name storeLocator.Store#event:marker_changed * @param {google.maps.Marker} marker * @event */
JavaScript
// Copyright 2013 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Provides access to store data through Google Maps Engine. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A DataFeed where stores are provided by Google Maps Engine. * <p> * Note: the table that contains the stores needs to be publicly accessible. * @example <pre> * var dataFeed = new storeLocator.GMEDataFeed({ * tableId: '12421761926155747447-06672618218968397709', * apiKey: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', * propertiesModifier: function(props) { * return { * id: transformId(props.store_id), * title: props.store_title * }; * } * }); * new storeLocator.View(map, dataFeed); * </pre> * @implements storeLocator.DataFeed * @param {!storeLocator.GMEDataFeedOptions} opts the table ID, API key and * a transformation function for feature/store properties. * @constructor * @implements storeLocator_GMEDataFeed */ storeLocator.GMEDataFeed = function(opts) { this.tableId_ = opts['tableId']; this.apiKey_ = opts['apiKey']; if (opts['propertiesModifier']) { this.propertiesModifier_ = opts['propertiesModifier']; } }; storeLocator['GMEDataFeed'] = storeLocator.GMEDataFeed; storeLocator.GMEDataFeed.prototype.getStores = function(bounds, features, callback) { // TODO: use features. var that = this; var center = bounds.getCenter(); var where = '(ST_INTERSECTS(geometry, ' + this.boundsToWkt_(bounds) + ')' + ' OR ST_DISTANCE(geometry, ' + this.latLngToWkt_(center) + ') < 20000)'; var url = 'https://www.googleapis.com/mapsengine/v1/tables/' + this.tableId_ + '/features?callback=?'; $.getJSON(url, { 'key': this.apiKey_, 'where': where, 'version': 'published', 'maxResults': 300 }, function(resp) { var stores = that.parse_(resp); that.sortByDistance_(center, stores); callback(stores); }); }; /** * @private * @param {!google.maps.LatLng} point * @return {string} */ storeLocator.GMEDataFeed.prototype.latLngToWkt_ = function(point) { return 'ST_POINT(' + point.lng() + ', ' + point.lat() + ')'; }; /** * @private * @param {!google.maps.LatLngBounds} bounds * @return {string} */ storeLocator.GMEDataFeed.prototype.boundsToWkt_ = function(bounds) { var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); return [ "ST_GEOMFROMTEXT('POLYGON ((", sw.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', sw.lat(), "))')" ].join(''); }; /** * @private * @param {*} data GeoJSON feature set. * @return {!Array.<!storeLocator.Store>} */ storeLocator.GMEDataFeed.prototype.parse_ = function(data) { if (data['error']) { window.alert(data['error']['message']); return []; } var features = data['features']; if (!features) { return []; } var stores = []; for (var i = 0, row; row = features[i]; i++) { var coordinates = row['geometry']['coordinates']; var position = new google.maps.LatLng(coordinates[1], coordinates[0]); var props = this.propertiesModifier_(row['properties']); var store = new storeLocator.Store(props['id'], position, null, props); stores.push(store); } return stores; }; /** * Default properties modifier. Just returns the same properties passed into * it. Useful if the columns in the GME table are already appropriate. * @private * @param {Object} props * @return {Object} an Object to be passed into the "props" argument in the * Store constructor. */ storeLocator.GMEDataFeed.prototype.propertiesModifier_ = function(props) { return props; }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ storeLocator.GMEDataFeed.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); }; /** * @example see storeLocator.GMEDataFeed * @interface */ storeLocator.GMEDataFeedOptions = function() {}; /** * The table's asset ID. * @type string */ storeLocator.GMEDataFeedOptions.prototype.tableId; /** * The API key to use for all requests. * @type string */ storeLocator.GMEDataFeedOptions.prototype.apiKey; /** * A transformation function. The first argument is the feature's properties. * Return an object useful for the <code>"props"</code> argument in the * storeLocator.Store constructor. The default properties modifier * function passes the feature straight through. * <p> * Note: storeLocator.GMEDataFeed expects an <code>"id"</code> property. * @type ?(function(Object): Object) */ storeLocator.GMEDataFeedOptions.prototype.propertiesModifier;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * FeatureSet class for Store Locator library. A mutable, ordered set of * storeLocator.Features. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A mutable, ordered set of <code>storeLocator.Feature</code>s. * @example <pre> * var feature1 = new storeLocator.Feature('1', 'Feature One'); * var feature2 = new storeLocator.Feature('2', 'Feature Two'); * var feature3 = new storeLocator.Feature('3', 'Feature Three'); * * var featureSet = new storeLocator.FeatureSet(feature1, feature2, feature3); * </pre> * @param {...storeLocator.Feature} var_args the initial features to add to * the set. * @constructor * @implements storeLocator_FeatureSet */ storeLocator.FeatureSet = function(var_args) { /** * Stores references to the actual Feature. * @private * @type {!Array.<storeLocator.Feature>} */ this.array_ = []; /** * Maps from a Feature's id to its array index. * @private * @type {Object.<string, number>} */ this.hash_ = {}; for (var i = 0, feature; feature = arguments[i]; i++) { this.add(feature); } }; storeLocator['FeatureSet'] = storeLocator.FeatureSet; /** * Adds the given feature to the set, if it doesn't exist in the set already. * Else, removes the feature from the set. * @param {!storeLocator.Feature} feature the feature to toggle. */ storeLocator.FeatureSet.prototype.toggle = function(feature) { if (this.contains(feature)) { this.remove(feature); } else { this.add(feature); } }; /** * Check if a feature exists within this set. * @param {!storeLocator.Feature} feature the feature. * @return {boolean} true if the set contains the given feature. */ storeLocator.FeatureSet.prototype.contains = function(feature) { return feature.getId() in this.hash_; }; /** * Gets a Feature object from the set, by the feature id. * @param {string} featureId the feature's id. * @return {storeLocator.Feature} the feature, if the set contains it. */ storeLocator.FeatureSet.prototype.getById = function(featureId) { if (featureId in this.hash_) { return this.array_[this.hash_[featureId]]; } return null; }; /** * Adds a feature to the set. * @param {storeLocator.Feature} feature the feature to add. */ storeLocator.FeatureSet.prototype.add = function(feature) { if (!feature) { return; } this.array_.push(feature); this.hash_[feature.getId()] = this.array_.length - 1; }; /** * Removes a feature from the set, if it already exists in the set. If it does * not already exist in the set, this function is a no op. * @param {!storeLocator.Feature} feature the feature to remove. */ storeLocator.FeatureSet.prototype.remove = function(feature) { if (!this.contains(feature)) { return; } this.array_[this.hash_[feature.getId()]] = null; delete this.hash_[feature.getId()]; }; /** * Get the contents of this set as an Array. * @return {Array.<!storeLocator.Feature>} the features in the set, in the order * they were inserted. */ storeLocator.FeatureSet.prototype.asList = function() { var filtered = []; for (var i = 0, ii = this.array_.length; i < ii; i++) { var elem = this.array_[i]; if (elem !== null) { filtered.push(elem); } } return filtered; }; /** * Empty feature set. * @type storeLocator.FeatureSet * @const */ storeLocator.FeatureSet.NONE = new storeLocator.FeatureSet;
JavaScript
/** @interface */ function storeLocator_Feature() {}; storeLocator_Feature.prototype.getId = function(var_args) {}; storeLocator_Feature.prototype.getDisplayName = function(var_args) {}; /** @interface */ function storeLocator_FeatureSet() {}; storeLocator_FeatureSet.prototype.toggle = function(var_args) {}; storeLocator_FeatureSet.prototype.contains = function(var_args) {}; storeLocator_FeatureSet.prototype.getById = function(var_args) {}; storeLocator_FeatureSet.prototype.add = function(var_args) {}; storeLocator_FeatureSet.prototype.remove = function(var_args) {}; storeLocator_FeatureSet.prototype.asList = function(var_args) {}; /** @interface */ function storeLocator_GMEDataFeed() {}; /** @interface */ function storeLocator_Panel() {}; storeLocator_Panel.prototype.searchPosition = function(var_args) {}; storeLocator_Panel.prototype.setView = function(var_args) {}; storeLocator_Panel.prototype.view_changed = function(var_args) {}; storeLocator_Panel.prototype.stores_changed = function(var_args) {}; storeLocator_Panel.prototype.selectedStore_changed = function(var_args) {}; storeLocator_Panel.prototype.hideDirections = function(var_args) {}; storeLocator_Panel.prototype.showDirections = function(var_args) {}; storeLocator_Panel.prototype.featureFilter_changed = function(var_args) {}; /** @interface */ function storeLocator_StaticDataFeed() {}; storeLocator_StaticDataFeed.prototype.setStores = function(var_args) {}; storeLocator_StaticDataFeed.prototype.getStores = function(var_args) {}; /** @interface */ function storeLocator_Store() {}; storeLocator_Store.prototype.setMarker = function(var_args) {}; storeLocator_Store.prototype.getMarker = function(var_args) {}; storeLocator_Store.prototype.getId = function(var_args) {}; storeLocator_Store.prototype.getLocation = function(var_args) {}; storeLocator_Store.prototype.getFeatures = function(var_args) {}; storeLocator_Store.prototype.hasFeature = function(var_args) {}; storeLocator_Store.prototype.hasAllFeatures = function(var_args) {}; storeLocator_Store.prototype.getDetails = function(var_args) {}; storeLocator_Store.prototype.getInfoWindowContent = function(var_args) {}; storeLocator_Store.prototype.getInfoPanelContent = function(var_args) {}; storeLocator_Store.prototype.getInfoPanelItem = function(var_args) {}; storeLocator_Store.prototype.distanceTo = function(var_args) {}; /** @interface */ function storeLocator_View() {}; storeLocator_View.prototype.updateOnPan_changed = function(var_args) {}; storeLocator_View.prototype.addStoreToMap = function(var_args) {}; storeLocator_View.prototype.createMarker = function(var_args) {}; storeLocator_View.prototype.getMarker = function(var_args) {}; storeLocator_View.prototype.getInfoWindow = function(var_args) {}; storeLocator_View.prototype.getFeatures = function(var_args) {}; storeLocator_View.prototype.getFeatureById = function(var_args) {}; storeLocator_View.prototype.featureFilter_changed = function(var_args) {}; storeLocator_View.prototype.clearMarkers = function(var_args) {}; storeLocator_View.prototype.refreshView = function(var_args) {}; storeLocator_View.prototype.stores_changed = function(var_args) {}; storeLocator_View.prototype.getMap = function(var_args) {}; storeLocator_View.prototype.highlight = function(var_args) {}; storeLocator_View.prototype.selectedStore_changed = function(var_args) {};
JavaScript
// A simple demo showing how to grab places using the Maps API Places Library. // Useful extensions may include using "name" filtering or "keyword" search. google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new PlacesDataSource(map); var view = new storeLocator.View(map, data); var markerSize = new google.maps.Size(24, 24); view.createMarker = function(store) { return new google.maps.Marker({ position: store.getLocation(), icon: new google.maps.MarkerImage(store.getDetails().icon, null, null, null, markerSize) }); }; new storeLocator.Panel(panelDiv, { view: view }); }); /** * Creates a new PlacesDataSource. * @param {google.maps.Map} map * @constructor */ function PlacesDataSource(map) { this.service_ = new google.maps.places.PlacesService(map); } /** * @inheritDoc */ PlacesDataSource.prototype.getStores = function(bounds, features, callback) { this.service_.search({ bounds: bounds }, function(results, status) { var stores = []; for (var i = 0, result; result = results[i]; i++) { var latLng = result.geometry.location; var store = new storeLocator.Store(result.id, latLng, null, { title: result.name, address: result.types.join(', '), icon: result.icon }); stores.push(store); } callback(stores); }); };
JavaScript
google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new storeLocator.GMEDataFeed({ tableId: '12421761926155747447-06672618218968397709', apiKey: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', propertiesModifier: function(props) { var shop = join([props.Shp_num_an, props.Shp_centre], ', '); var locality = join([props.Locality, props.Postcode], ', '); return { id: props.uuid, title: props.Fcilty_nam, address: join([shop, props.Street_add, locality], '<br>'), hours: props.Hrs_of_bus }; } }); var view = new storeLocator.View(map, data, { geolocation: false }); new storeLocator.Panel(panelDiv, { view: view }); }); /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ function join(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }
JavaScript
/** * @implements storeLocator.DataFeed * @constructor */ function MedicareDataSource() { } MedicareDataSource.prototype.getStores = function(bounds, features, callback) { var that = this; var center = bounds.getCenter(); var audioFeature = this.FEATURES_.getById('Audio-YES'); var wheelchairFeature = this.FEATURES_.getById('Wheelchair-YES'); var where = '(ST_INTERSECTS(geometry, ' + this.boundsToWkt_(bounds) + ')' + ' OR ST_DISTANCE(geometry, ' + this.latLngToWkt_(center) + ') < 20000)'; if (features.contains(audioFeature)) { where += " AND Audio='YES'"; } if (features.contains(wheelchairFeature)) { where += " AND Wheelchair='YES'"; } var tableId = '12421761926155747447-06672618218968397709'; var url = 'https://www.googleapis.com/mapsengine/v1/tables/' + tableId + '/features?callback=?'; $.getJSON(url, { key: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', where: where, version: 'published', maxResults: 300 }, function(resp) { var stores = that.parse_(resp); that.sortByDistance_(center, stores); callback(stores); }); }; MedicareDataSource.prototype.latLngToWkt_ = function(point) { return 'ST_POINT(' + point.lng() + ', ' + point.lat() + ')'; }; MedicareDataSource.prototype.boundsToWkt_ = function(bounds) { var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); return [ "ST_GEOMFROMTEXT('POLYGON ((", sw.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', sw.lat(), "))')" ].join(''); }; MedicareDataSource.prototype.parse_ = function(data) { var stores = []; for (var i = 0, row; row = data.features[i]; i++) { var props = row.properties; var features = new storeLocator.FeatureSet; features.add(this.FEATURES_.getById('Wheelchair-' + props.Wheelchair)); features.add(this.FEATURES_.getById('Audio-' + props.Audio)); var position = new google.maps.LatLng(row.geometry.coordinates[1], row.geometry.coordinates[0]); var shop = this.join_([props.Shp_num_an, props.Shp_centre], ', '); var locality = this.join_([props.Locality, props.Postcode], ', '); var store = new storeLocator.Store(props.uuid, position, features, { title: props.Fcilty_nam, address: this.join_([shop, props.Street_add, locality], '<br>'), hours: props.Hrs_of_bus }); stores.push(store); } return stores; }; /** * @const * @type {!storeLocator.FeatureSet} * @private */ MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet( new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'), new storeLocator.Feature('Audio-YES', 'Audio') ); /** * @return {!storeLocator.FeatureSet} */ MedicareDataSource.prototype.getFeatures = function() { return this.FEATURES_; }; /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ MedicareDataSource.prototype.join_ = function(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ MedicareDataSource.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); };
JavaScript
google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new MedicareDataSource; var view = new storeLocator.View(map, data, { geolocation: false, features: data.getFeatures() }); new storeLocator.Panel(panelDiv, { view: view }); });
JavaScript
/** * @extends storeLocator.StaticDataFeed * @constructor */ function MedicareDataSource() { $.extend(this, new storeLocator.StaticDataFeed); var that = this; $.get('medicare.csv', function(data) { that.setStores(that.parse_(data)); }); } /** * @const * @type {!storeLocator.FeatureSet} * @private */ MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet( new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'), new storeLocator.Feature('Audio-YES', 'Audio') ); /** * @return {!storeLocator.FeatureSet} */ MedicareDataSource.prototype.getFeatures = function() { return this.FEATURES_; }; /** * @private * @param {string} csv * @return {!Array.<!storeLocator.Store>} */ MedicareDataSource.prototype.parse_ = function(csv) { var stores = []; var rows = csv.split('\n'); var headings = this.parseRow_(rows[0]); for (var i = 1, row; row = rows[i]; i++) { row = this.toObject_(headings, this.parseRow_(row)); var features = new storeLocator.FeatureSet; features.add(this.FEATURES_.getById('Wheelchair-' + row.Wheelchair)); features.add(this.FEATURES_.getById('Audio-' + row.Audio)); var position = new google.maps.LatLng(row.Ycoord, row.Xcoord); var shop = this.join_([row.Shp_num_an, row.Shp_centre], ', '); var locality = this.join_([row.Locality, row.Postcode], ', '); var store = new storeLocator.Store(row.uuid, position, features, { title: row.Fcilty_nam, address: this.join_([shop, row.Street_add, locality], '<br>'), hours: row.Hrs_of_bus }); stores.push(store); } return stores; }; /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ MedicareDataSource.prototype.join_ = function(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }; /** * Very rudimentary CSV parsing - we know how this particular CSV is formatted. * IMPORTANT: Don't use this for general CSV parsing! * @private * @param {string} row * @return {Array.<string>} */ MedicareDataSource.prototype.parseRow_ = function(row) { // Strip leading quote. if (row.charAt(0) == '"') { row = row.substring(1); } // Strip trailing quote. There seems to be a character between the last quote // and the line ending, hence 2 instead of 1. if (row.charAt(row.length - 2) == '"') { row = row.substring(0, row.length - 2); } row = row.split('","'); return row; }; /** * Creates an object mapping headings to row elements. * @private * @param {Array.<string>} headings * @param {Array.<string>} row * @return {Object} */ MedicareDataSource.prototype.toObject_ = function(headings, row) { var result = {}; for (var i = 0, ii = row.length; i < ii; i++) { result[headings[i]] = row[i]; } return result; };
JavaScript
// Store locator with customisations // - custom marker // - custom info window (using Info Bubble) // - custom info window content (+ store hours) var ICON = new google.maps.MarkerImage('medicare.png', null, null, new google.maps.Point(14, 13)); var SHADOW = new google.maps.MarkerImage('medicare-shadow.png', null, null, new google.maps.Point(14, 13)); google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new MedicareDataSource; var view = new storeLocator.View(map, data, { geolocation: false, features: data.getFeatures() }); view.createMarker = function(store) { var markerOptions = { position: store.getLocation(), icon: ICON, shadow: SHADOW, title: store.getDetails().title }; return new google.maps.Marker(markerOptions); } var infoBubble = new InfoBubble; view.getInfoWindow = function(store) { if (!store) { return infoBubble; } var details = store.getDetails(); var html = ['<div class="store"><div class="title">', details.title, '</div><div class="address">', details.address, '</div>', '<div class="hours misc">', details.hours, '</div></div>'].join(''); infoBubble.setContent($(html)[0]); return infoBubble; }; new storeLocator.Panel(panelDiv, { view: view }); });
JavaScript
(function($) { $.fn.spasticNav = function(options) { options = $.extend({ overlap : 5, speed : 500, reset : 1500, color : '#0b2b61', easing : 'easeOutExpo' }, options); return this.each(function() { var nav = $(this), currentPageItem = $('#selected', nav), blob, reset; $('<li id="blob"></li>').css({ width : currentPageItem.outerWidth(), height : currentPageItem.outerHeight() + options.overlap, left : currentPageItem.position().left, top : currentPageItem.position().top - options.overlap / 2, backgroundColor : options.color }).appendTo(this); blob = $('#blob', nav); $('li:not(#blob)', nav).hover(function() { // mouse over clearTimeout(reset); blob.animate( { left : $(this).position().left, width : $(this).width() }, { duration : options.speed, easing : options.easing, queue : false } ); }, function() { // mouse out reset = setTimeout(function() { blob.animate({ width : currentPageItem.outerWidth(), left : currentPageItem.position().left }, options.speed) }, options.reset); }); }); // end each }; })(jQuery);
JavaScript
/* * jCarousel - Riding carousels with jQuery * http://sorgalla.com/jcarousel/ * * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Built on top of the jQuery library * http://jquery.com * * Inspired by the "Carousel Component" by Bill Scott * http://billwscott.com/carousel/ */ (function(g){var q={vertical:!1,rtl:!1,start:1,offset:1,size:null,scroll:3,visible:null,animation:"normal",easing:"swing",auto:0,wrap:null,initCallback:null,setupCallback:null,reloadCallback:null,itemLoadCallback:null,itemFirstInCallback:null,itemFirstOutCallback:null,itemLastInCallback:null,itemLastOutCallback:null,itemVisibleInCallback:null,itemVisibleOutCallback:null,animationStepCallback:null,buttonNextHTML:"<div></div>",buttonPrevHTML:"<div></div>",buttonNextEvent:"click",buttonPrevEvent:"click", buttonNextCallback:null,buttonPrevCallback:null,itemFallbackDimension:null},m=!1;g(window).bind("load.jcarousel",function(){m=!0});g.jcarousel=function(a,c){this.options=g.extend({},q,c||{});this.autoStopped=this.locked=!1;this.buttonPrevState=this.buttonNextState=this.buttonPrev=this.buttonNext=this.list=this.clip=this.container=null;if(!c||c.rtl===void 0)this.options.rtl=(g(a).attr("dir")||g("html").attr("dir")||"").toLowerCase()=="rtl";this.wh=!this.options.vertical?"width":"height";this.lt=!this.options.vertical? this.options.rtl?"right":"left":"top";for(var b="",d=a.className.split(" "),f=0;f<d.length;f++)if(d[f].indexOf("jcarousel-skin")!=-1){g(a).removeClass(d[f]);b=d[f];break}a.nodeName.toUpperCase()=="UL"||a.nodeName.toUpperCase()=="OL"?(this.list=g(a),this.clip=this.list.parents(".jcarousel-clip"),this.container=this.list.parents(".jcarousel-container")):(this.container=g(a),this.list=this.container.find("ul,ol").eq(0),this.clip=this.container.find(".jcarousel-clip"));if(this.clip.size()===0)this.clip= this.list.wrap("<div></div>").parent();if(this.container.size()===0)this.container=this.clip.wrap("<div></div>").parent();b!==""&&this.container.parent()[0].className.indexOf("jcarousel-skin")==-1&&this.container.wrap('<div class=" '+b+'"></div>');this.buttonPrev=g(".jcarousel-prev",this.container);if(this.buttonPrev.size()===0&&this.options.buttonPrevHTML!==null)this.buttonPrev=g(this.options.buttonPrevHTML).appendTo(this.container);this.buttonPrev.addClass(this.className("jcarousel-prev"));this.buttonNext= g(".jcarousel-next",this.container);if(this.buttonNext.size()===0&&this.options.buttonNextHTML!==null)this.buttonNext=g(this.options.buttonNextHTML).appendTo(this.container);this.buttonNext.addClass(this.className("jcarousel-next"));this.clip.addClass(this.className("jcarousel-clip")).css({position:"relative"});this.list.addClass(this.className("jcarousel-list")).css({overflow:"hidden",position:"relative",top:0,margin:0,padding:0}).css(this.options.rtl?"right":"left",0);this.container.addClass(this.className("jcarousel-container")).css({position:"relative"}); !this.options.vertical&&this.options.rtl&&this.container.addClass("jcarousel-direction-rtl").attr("dir","rtl");var j=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible):null,b=this.list.children("li"),e=this;if(b.size()>0){var h=0,i=this.options.offset;b.each(function(){e.format(this,i++);h+=e.dimension(this,j)});this.list.css(this.wh,h+100+"px");if(!c||c.size===void 0)this.options.size=b.size()}this.container.css("display","block");this.buttonNext.css("display","block");this.buttonPrev.css("display", "block");this.funcNext=function(){e.next()};this.funcPrev=function(){e.prev()};this.funcResize=function(){e.resizeTimer&&clearTimeout(e.resizeTimer);e.resizeTimer=setTimeout(function(){e.reload()},100)};this.options.initCallback!==null&&this.options.initCallback(this,"init");!m&&g.browser.safari?(this.buttons(!1,!1),g(window).bind("load.jcarousel",function(){e.setup()})):this.setup()};var f=g.jcarousel;f.fn=f.prototype={jcarousel:"0.2.8"};f.fn.extend=f.extend=g.extend;f.fn.extend({setup:function(){this.prevLast= this.prevFirst=this.last=this.first=null;this.animating=!1;this.tail=this.resizeTimer=this.timer=null;this.inTail=!1;if(!this.locked){this.list.css(this.lt,this.pos(this.options.offset)+"px");var a=this.pos(this.options.start,!0);this.prevFirst=this.prevLast=null;this.animate(a,!1);g(window).unbind("resize.jcarousel",this.funcResize).bind("resize.jcarousel",this.funcResize);this.options.setupCallback!==null&&this.options.setupCallback(this)}},reset:function(){this.list.empty();this.list.css(this.lt, "0px");this.list.css(this.wh,"10px");this.options.initCallback!==null&&this.options.initCallback(this,"reset");this.setup()},reload:function(){this.tail!==null&&this.inTail&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+this.tail);this.tail=null;this.inTail=!1;this.options.reloadCallback!==null&&this.options.reloadCallback(this);if(this.options.visible!==null){var a=this,c=Math.ceil(this.clipping()/this.options.visible),b=0,d=0;this.list.children("li").each(function(f){b+=a.dimension(this, c);f+1<a.first&&(d=b)});this.list.css(this.wh,b+"px");this.list.css(this.lt,-d+"px")}this.scroll(this.first,!1)},lock:function(){this.locked=!0;this.buttons()},unlock:function(){this.locked=!1;this.buttons()},size:function(a){if(a!==void 0)this.options.size=a,this.locked||this.buttons();return this.options.size},has:function(a,c){if(c===void 0||!c)c=a;if(this.options.size!==null&&c>this.options.size)c=this.options.size;for(var b=a;b<=c;b++){var d=this.get(b);if(!d.length||d.hasClass("jcarousel-item-placeholder"))return!1}return!0}, get:function(a){return g(">.jcarousel-item-"+a,this.list)},add:function(a,c){var b=this.get(a),d=0,p=g(c);if(b.length===0)for(var j,e=f.intval(a),b=this.create(a);;){if(j=this.get(--e),e<=0||j.length){e<=0?this.list.prepend(b):j.after(b);break}}else d=this.dimension(b);p.get(0).nodeName.toUpperCase()=="LI"?(b.replaceWith(p),b=p):b.empty().append(c);this.format(b.removeClass(this.className("jcarousel-item-placeholder")),a);p=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible): null;d=this.dimension(b,p)-d;a>0&&a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))-d+"px");this.list.css(this.wh,f.intval(this.list.css(this.wh))+d+"px");return b},remove:function(a){var c=this.get(a);if(c.length&&!(a>=this.first&&a<=this.last)){var b=this.dimension(c);a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+b+"px");c.remove();this.list.css(this.wh,f.intval(this.list.css(this.wh))-b+"px")}},next:function(){this.tail!==null&&!this.inTail?this.scrollTail(!1): this.scroll((this.options.wrap=="both"||this.options.wrap=="last")&&this.options.size!==null&&this.last==this.options.size?1:this.first+this.options.scroll)},prev:function(){this.tail!==null&&this.inTail?this.scrollTail(!0):this.scroll((this.options.wrap=="both"||this.options.wrap=="first")&&this.options.size!==null&&this.first==1?this.options.size:this.first-this.options.scroll)},scrollTail:function(a){if(!this.locked&&!this.animating&&this.tail){this.pauseAuto();var c=f.intval(this.list.css(this.lt)), c=!a?c-this.tail:c+this.tail;this.inTail=!a;this.prevFirst=this.first;this.prevLast=this.last;this.animate(c)}},scroll:function(a,c){!this.locked&&!this.animating&&(this.pauseAuto(),this.animate(this.pos(a),c))},pos:function(a,c){var b=f.intval(this.list.css(this.lt));if(this.locked||this.animating)return b;this.options.wrap!="circular"&&(a=a<1?1:this.options.size&&a>this.options.size?this.options.size:a);for(var d=this.first>a,g=this.options.wrap!="circular"&&this.first<=1?1:this.first,j=d?this.get(g): this.get(this.last),e=d?g:g-1,h=null,i=0,k=!1,l=0;d?--e>=a:++e<a;){h=this.get(e);k=!h.length;if(h.length===0&&(h=this.create(e).addClass(this.className("jcarousel-item-placeholder")),j[d?"before":"after"](h),this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size)))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)));j=h;l=this.dimension(h);k&&(i+=l);if(this.first!==null&&(this.options.wrap=="circular"||e>=1&&(this.options.size===null||e<= this.options.size)))b=d?b+l:b-l}for(var g=this.clipping(),m=[],o=0,n=0,j=this.get(a-1),e=a;++o;){h=this.get(e);k=!h.length;if(h.length===0){h=this.create(e).addClass(this.className("jcarousel-item-placeholder"));if(j.length===0)this.list.prepend(h);else j[d?"before":"after"](h);if(this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)))}j=h;l=this.dimension(h);if(l===0)throw Error("jCarousel: No width/height set for items. This will cause an infinite loop. Aborting..."); this.options.wrap!="circular"&&this.options.size!==null&&e>this.options.size?m.push(h):k&&(i+=l);n+=l;if(n>=g)break;e++}for(h=0;h<m.length;h++)m[h].remove();i>0&&(this.list.css(this.wh,this.dimension(this.list)+i+"px"),d&&(b-=i,this.list.css(this.lt,f.intval(this.list.css(this.lt))-i+"px")));i=a+o-1;if(this.options.wrap!="circular"&&this.options.size&&i>this.options.size)i=this.options.size;if(e>i){o=0;e=i;for(n=0;++o;){h=this.get(e--);if(!h.length)break;n+=this.dimension(h);if(n>=g)break}}e=i-o+ 1;this.options.wrap!="circular"&&e<1&&(e=1);if(this.inTail&&d)b+=this.tail,this.inTail=!1;this.tail=null;if(this.options.wrap!="circular"&&i==this.options.size&&i-o+1>=1&&(d=f.intval(this.get(i).css(!this.options.vertical?"marginRight":"marginBottom")),n-d>g))this.tail=n-g-d;if(c&&a===this.options.size&&this.tail)b-=this.tail,this.inTail=!0;for(;a-- >e;)b+=this.dimension(this.get(a));this.prevFirst=this.first;this.prevLast=this.last;this.first=e;this.last=i;return b},animate:function(a,c){if(!this.locked&& !this.animating){this.animating=!0;var b=this,d=function(){b.animating=!1;a===0&&b.list.css(b.lt,0);!b.autoStopped&&(b.options.wrap=="circular"||b.options.wrap=="both"||b.options.wrap=="last"||b.options.size===null||b.last<b.options.size||b.last==b.options.size&&b.tail!==null&&!b.inTail)&&b.startAuto();b.buttons();b.notify("onAfterAnimation");if(b.options.wrap=="circular"&&b.options.size!==null)for(var c=b.prevFirst;c<=b.prevLast;c++)c!==null&&!(c>=b.first&&c<=b.last)&&(c<1||c>b.options.size)&&b.remove(c)}; this.notify("onBeforeAnimation");if(!this.options.animation||c===!1)this.list.css(this.lt,a+"px"),d();else{var f=!this.options.vertical?this.options.rtl?{right:a}:{left:a}:{top:a},d={duration:this.options.animation,easing:this.options.easing,complete:d};if(g.isFunction(this.options.animationStepCallback))d.step=this.options.animationStepCallback;this.list.animate(f,d)}}},startAuto:function(a){if(a!==void 0)this.options.auto=a;if(this.options.auto===0)return this.stopAuto();if(this.timer===null){this.autoStopped= !1;var c=this;this.timer=window.setTimeout(function(){c.next()},this.options.auto*1E3)}},stopAuto:function(){this.pauseAuto();this.autoStopped=!0},pauseAuto:function(){if(this.timer!==null)window.clearTimeout(this.timer),this.timer=null},buttons:function(a,c){if(a==null&&(a=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="first"||this.options.size===null||this.last<this.options.size),!this.locked&&(!this.options.wrap||this.options.wrap=="first")&&this.options.size!==null&& this.last>=this.options.size))a=this.tail!==null&&!this.inTail;if(c==null&&(c=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="last"||this.first>1),!this.locked&&(!this.options.wrap||this.options.wrap=="last")&&this.options.size!==null&&this.first==1))c=this.tail!==null&&this.inTail;var b=this;this.buttonNext.size()>0?(this.buttonNext.unbind(this.options.buttonNextEvent+".jcarousel",this.funcNext),a&&this.buttonNext.bind(this.options.buttonNextEvent+".jcarousel",this.funcNext), this.buttonNext[a?"removeClass":"addClass"](this.className("jcarousel-next-disabled")).attr("disabled",a?!1:!0),this.options.buttonNextCallback!==null&&this.buttonNext.data("jcarouselstate")!=a&&this.buttonNext.each(function(){b.options.buttonNextCallback(b,this,a)}).data("jcarouselstate",a)):this.options.buttonNextCallback!==null&&this.buttonNextState!=a&&this.options.buttonNextCallback(b,null,a);this.buttonPrev.size()>0?(this.buttonPrev.unbind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev), c&&this.buttonPrev.bind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev),this.buttonPrev[c?"removeClass":"addClass"](this.className("jcarousel-prev-disabled")).attr("disabled",c?!1:!0),this.options.buttonPrevCallback!==null&&this.buttonPrev.data("jcarouselstate")!=c&&this.buttonPrev.each(function(){b.options.buttonPrevCallback(b,this,c)}).data("jcarouselstate",c)):this.options.buttonPrevCallback!==null&&this.buttonPrevState!=c&&this.options.buttonPrevCallback(b,null,c);this.buttonNextState= a;this.buttonPrevState=c},notify:function(a){var c=this.prevFirst===null?"init":this.prevFirst<this.first?"next":"prev";this.callback("itemLoadCallback",a,c);this.prevFirst!==this.first&&(this.callback("itemFirstInCallback",a,c,this.first),this.callback("itemFirstOutCallback",a,c,this.prevFirst));this.prevLast!==this.last&&(this.callback("itemLastInCallback",a,c,this.last),this.callback("itemLastOutCallback",a,c,this.prevLast));this.callback("itemVisibleInCallback",a,c,this.first,this.last,this.prevFirst, this.prevLast);this.callback("itemVisibleOutCallback",a,c,this.prevFirst,this.prevLast,this.first,this.last)},callback:function(a,c,b,d,f,j,e){if(!(this.options[a]==null||typeof this.options[a]!="object"&&c!="onAfterAnimation")){var h=typeof this.options[a]=="object"?this.options[a][c]:this.options[a];if(g.isFunction(h)){var i=this;if(d===void 0)h(i,b,c);else if(f===void 0)this.get(d).each(function(){h(i,this,d,b,c)});else for(var a=function(a){i.get(a).each(function(){h(i,this,a,b,c)})},k=d;k<=f;k++)k!== null&&!(k>=j&&k<=e)&&a(k)}}},create:function(a){return this.format("<li></li>",a)},format:function(a,c){for(var a=g(a),b=a.get(0).className.split(" "),d=0;d<b.length;d++)b[d].indexOf("jcarousel-")!=-1&&a.removeClass(b[d]);a.addClass(this.className("jcarousel-item")).addClass(this.className("jcarousel-item-"+c)).css({"float":this.options.rtl?"right":"left","list-style":"none"}).attr("jcarouselindex",c);return a},className:function(a){return a+" "+a+(!this.options.vertical?"-horizontal":"-vertical")}, dimension:function(a,c){var b=g(a);if(c==null)return!this.options.vertical?b.outerWidth(!0)||f.intval(this.options.itemFallbackDimension):b.outerHeight(!0)||f.intval(this.options.itemFallbackDimension);else{var d=!this.options.vertical?c-f.intval(b.css("marginLeft"))-f.intval(b.css("marginRight")):c-f.intval(b.css("marginTop"))-f.intval(b.css("marginBottom"));g(b).css(this.wh,d+"px");return this.dimension(b)}},clipping:function(){return!this.options.vertical?this.clip[0].offsetWidth-f.intval(this.clip.css("borderLeftWidth"))- f.intval(this.clip.css("borderRightWidth")):this.clip[0].offsetHeight-f.intval(this.clip.css("borderTopWidth"))-f.intval(this.clip.css("borderBottomWidth"))},index:function(a,c){if(c==null)c=this.options.size;return Math.round(((a-1)/c-Math.floor((a-1)/c))*c)+1}});f.extend({defaults:function(a){return g.extend(q,a||{})},intval:function(a){a=parseInt(a,10);return isNaN(a)?0:a},windowLoaded:function(){m=!0}});g.fn.jcarousel=function(a){if(typeof a=="string"){var c=g(this).data("jcarousel"),b=Array.prototype.slice.call(arguments, 1);return c[a].apply(c,b)}else return this.each(function(){var b=g(this).data("jcarousel");b?(a&&g.extend(b.options,a),b.reload()):g(this).data("jcarousel",new f(this,a))})}})(jQuery); /* 5/31/2011 PikaChoose Jquery plugin for photo galleries Copyright (C) 2011 Jeremy Fry This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function($) { /** * Creates a slideshow for all matched elements. * * @example $("#pikame").PikaChoose(); * @input needed <ul id="pikame"><li><img src="first.jpg"><span>Caption</span></li><li><img src="second.jpg"><span>Caption</span></li></ul> * * @method PikaChoose * @return $ * @param o {Hash|String} A set of key/value pairs to set as configuration properties or a method name to call on a formerly created instance. */ var defaults = { autoPlay: true, speed: 5000, text: { play: "", stop: "", previous: "Previous", next: "Next" }, transition:[1], showCaption: true, IESafe: false, showTooltips: false, carousel: false, carouselVertical: false, animationFinished: null, buildFinished: null, bindFinished: null, startOn: 0, thumbOpacity: 0.4, hoverPause: false }; $.fn.PikaChoose = function(o) { return this.each(function() { $(this).data('pikachoose', new $pc(this, o)); }); }; /** * The PikaChoose object. * * @constructor * @class pikachoose * @param e {HTMLElement} The element to create the carousel for. * @param o {Object} A set of key/value pairs to set as configuration properties. * @cat Plugins/PikaChoose */ $.PikaChoose = function(e, o) { this.options = $.extend({}, defaults, o || {}); this.list = null; this.image = null; this.anchor = null; this.caption = null; this.imgNav = null; this.imgPlay = null; this.imgPrev = null; this.imgNext = null; this.textNext = null; this.textPrev = null; this.previous = null; this.next = null; this.aniWrap = null; this.aniDiv = null; this.aniImg = null; this.thumbs = null; this.transition = null; this.active = null; this.tooltip = null; this.animating = false; this.stillOut = null; this.counter = null; this.timeOut = null; if(typeof(this.options.data) != "undefined"){ //user passed a data source e = $("<ul></ul>").appendTo(e); $.each(this.options.data,function(){ if(typeof(this.link) != "undefined"){ var tmp = $("<li><a href='"+this.link+"'><img></a></li>").appendTo(e); if(typeof(this.title) != "undefined"){ tmp.find('a').attr('title',this.title); } }else{ var tmp = $("<li><img></li>").appendTo(e); } if(typeof(this.caption) != "undefined"){ tmp.append("<span>"+this.caption+"</span>"); } if(typeof(this.thumbnail) != "undefined"){ tmp.find('img').attr('ref',this.image); tmp.find('img').attr('src',this.thumbnail); }else{ tmp.find('img').attr('src',this.image); } }); } if(e.nodeName == 'UL' || e.nodeName == 'OL' || e instanceof jQuery) { this.list = $(e); this.build(); this.bindEvents(); }else{ return; } var y = 0; var x = 0; for(var t = 0; t<25;t++){ var a = '<div col="'+y+'" row="'+x+'"></div>'; this.aniDiv.append(a); y++; if(y == 5){ x++; y=0; } } };//end PikaChoose function(e, o) var $pc = $.PikaChoose; $pc.fn = $pc.prototype = { pikachoose: '4.3.1' }; $.fn.pikachoose = $.fn.PikaChoose; $pc.fn.extend = $pc.extend = $.extend; $pc.fn.extend({ /** * Builds the gallery structure. * * @method build * @return undefined */ build: function() { this.step = 0; //transition step count //create the structure for pikachoose //this.wrap = $("<div class='pika-stage'></div>").insertBefore(this.list); this.image = $("<img>").appendTo(this.wrap); this.imgNav = $("<div class='pika-imgnav'></div>").insertAfter(this.image); this.imgPlay = $("<a></a>").appendTo(this.imgNav); this.counter = $("<span class='pika-counter'></span>").appendTo(this.imgNav); if(this.options.autoPlay){ this.imgPlay.addClass('pause'); }else{ this.imgPlay.addClass('play'); } this.imgPrev = $("<a class='previous'></a>").insertAfter(this.imgPlay); this.imgNext = $("<a class='next'></a>").insertAfter(this.imgPrev); this.caption = $("<div class='caption'></div>").insertAfter(this.imgNav).hide(); this.tooltip = $("<div class='pika-tooltip'></div>").insertAfter(this.list).hide(); this.aniWrap = $("<div class='pika-aniwrap'></div>").insertAfter(this.caption); this.aniImg = $("<img>").appendTo(this.aniWrap).hide(); this.aniDiv = $("<div class='pika-ani'></div>").appendTo(this.aniWrap); this.textNav = $("<div class='pika-textnav'></div>").insertAfter(this.aniWrap); this.textPrev = $("<a class='previous'>"+this.options.text.previous+"</a>").appendTo(this.textNav); this.textNext = $("<a class='next'>"+this.options.text.next+"</a>").appendTo(this.textNav); this.list.addClass('pika-thumbs'); this.list.children('li').wrapInner("<div class='clip' />"); this.thumbs = this.list.find('img'); this.active = this.thumbs.eq(this.options.startOn); //fill in info for first image this.finishAnimating({'source':this.active.attr('ref') || this.active.attr('src'),'caption':this.active.parents('li:first').find('span:first').html(), 'clickThrough':this.active.parent().attr('href') || "", 'clickThroughTitle':this.active.parent().attr('title') || ""}); //process all the thumbnails var self = this; this.thumbs.each(function(){ self.createThumb($(this),self); }); if(this.options.carousel){ this.list.jcarousel({vertical:this.options.carouselVertical, initCallback: function(carousel){ jQuery(carousel.list).find('img').click(function() { var clicked = parseInt(jQuery(this).parents('.jcarousel-item').attr('jcarouselindex')); var last = (jQuery(this).parents('ul').find('li:last').index() == clicked-1) ? true : false; if(!last){ clicked = (clicked-2<=0) ? 0 : clicked-2; } clicked++; carousel.scroll(clicked); }); }}); } if(typeof(this.options.buildFinished) == 'function'){ this.options.buildFinished(this); } }, //end setup /** * proccesses thumbnails * * @method createThumb * @return undefined */ createThumb: function(ele) { var self = ele; var that = this; self.hide(); //store all the data with the image $.data(ele[0],'clickThrough',self.parent('a').attr('href') || ""); $.data(ele[0],'clickThroughTitle',self.parent('a').attr('title') || ""); if(self.parent('a').length > 0){ self.unwrap(); } $.data(ele[0],'caption',self.next('span').html() || ""); self.next('span').remove(); $.data(ele[0],'source',self.attr('ref') || self.attr('src')); //gets each items index to iterate through them. Thanks to Tushar for the fix. $.data(ele[0],'order',self.closest('ul').find('li').index(self.parents('li'))); //pass data so it can enter the load scope var data = $.data(ele[0]); $('<img />').bind('load',{data:data},function(){ if(typeof(that.options.buildThumbStart) == 'function'){ that.options.buildThumbStart(that); } //in this scope self refers to the image var img = $(this); var w = this.width; var h = this.height; if(w===0){w = img.attr("width");} if(h===0){h = img.attr("height");} //grab a ratio for image to user defined settings var rw = parseInt(self.parents('.clip').css('width').slice(0,-2))/w; var rh = parseInt(self.parents('.clip').css('height').slice(0,-2))/h; //determine which has the smallest ratio (thus needing //to be the side we use to scale so our whole thumb is filled) var ratio; if(rw<rh){ //we'll use ratio later to scale and not distort ratio = rh; var left = ((w*ratio- parseInt(self.parents('.clip').css('width').slice(0,-2)))/2)*-1; left = Math.round(left); self.css({left:left}); }else{ ratio = rw; self.css({top:0}); } //use those ratios to calculate scale var width = Math.round(w*ratio); var height = Math.round(h*ratio); self.css("position","relative"); var imgcss={ width: width+"px", height: height+"px" }; self.css(imgcss); self.hover( function(e){ clearTimeout(that.stillOut); $(this).stop(true,true).fadeTo(250,1); if(!that.options.showTooltips){ return; } that.tooltip.show().stop(true,true).html(data.caption).animate({top:$(this).parent().position().top, left:$(this).parent().position().left, opacity: 1.0},'fast'); }, function(e){ if(!$(this).hasClass("active")){$(this).stop(true,true).fadeTo(250,that.options.thumbOpacity); that.stillOut = setTimeout(that.hideTooltip,700); }} ); if(data.order == that.options.startOn){ self.fadeTo(250,1); self.addClass('active'); self.parents('li').eq(0).addClass('active'); }else{ self.fadeTo(250,that.options.thumbOpacity); } if(typeof(that.options.buildThumbFinish) == 'function'){ that.options.buildThumbFinish(that); } }).attr('src',self.attr('src')); },//end createThumb /** * proccesses thumbnails * * @method bindEvents * @return undefined */ bindEvents: function() { this.thumbs.bind('click',{self:this},this.imgClick); this.imgNext.bind('click',{self:this},this.nextClick); this.textNext.bind('click',{self:this},this.nextClick); this.imgPrev.bind('click',{self:this},this.prevClick); this.textPrev.bind('click',{self:this},this.prevClick); this.imgPlay.bind('click',{self:this},this.playClick); this.wrap.bind('mouseenter',{self:this},function(e){ e.data.self.imgNav.stop(true,true).fadeIn('slow'); if(e.data.self.options.hoverPause == true){ clearTimeout(e.data.self.timeOut); } }); this.wrap.bind('mouseleave',{self:this},function(e){ e.data.self.imgNav.stop(true,true).fadeOut('slow'); if(e.data.self.options.autoPlay == true && e.data.self.options.hoverPause){ e.data.self.timeOut = setTimeout((function(self){ return function(){ self.nextClick(); }; })(e.data.self), e.data.self.options.speed); } }); this.tooltip.bind('mouseenter',{self:this},function(e){ clearTimeout(e.data.self.stillOut); }); this.tooltip.bind('mouseleave',{self:this},function(e){ e.data.self.stillOut = setTimeout(e.data.self.hideTooltip,700); }); if(typeof(this.options.bindsFinished) == 'function'){ this.options.bindsFinished(this); } },//end bind event /** * hides tooltip * * @method hideTooltip * @return undefined */ hideTooltip: function (e){ $(".pika-tooltip").animate({opacity:0.01}); }, /** * handles gallery after aclick occurs. and sets active classes * * @method imgClick * @return undefined */ imgClick: function(e,x) { var self = e.data.self; var data = $.data(this); if(self.animating){return;} if(typeof(x) == 'undefined' || x.how != "auto"){ //arrive here if natural click if(self.options.autoPlay){ self.imgPlay.trigger('click'); } }else{ if(self.options.autoPlay == false){ return false; } } self.caption.fadeOut('slow'); self.animating = true; self.active.fadeTo(300,self.options.thumbOpacity).removeClass('active'); self.active.parents('.active').eq(0).removeClass('active'); self.active = $(this); self.active.addClass('active').fadeTo(200,1); self.active.parents('li').eq(0).addClass('active'); $('<img />').bind('load', {self:self,data:data}, function(){ //in this scope self referes to the PikaChoose object self.aniDiv.css({height:self.image.height(),width:self.image.width()}).fadeIn('fast'); self.aniDiv.children('div').css({'width':'20%','height':'20%','float':'left'}); //decide our transition var n = 0; if(self.options.transition[0] == -1){ //random n = Math.floor(Math.random()*7)+1; }else{ n = self.options.transition[self.step]; self.step++; if(self.step >= self.options.transition.length){self.step=0;} } if(self.options.IESafe && $.browser.msie){ n = 1; } self.doAnimation(n,data); }).attr('src',$.data(this).source);//end image preload },//end bindEvents doAnimation: function(n,data){ var self = this; //self in this scope refers to PikaChoose object. Needed for callbacks on animations self.image.stop(true,false); self.caption.stop().fadeOut(); var aWidth = self.aniDiv.children('div').eq(0).width(); var aHeight = self.aniDiv.children('div').eq(0).height(); var img = new Image(); $(img).attr('src',data.source); if(img.height != self.image.height() || img.width != self.image.width()){ //Your images are not the same height? Well you get limited on transitions if(n != 0 && n != 1 && n != 7){ n = 1; } } self.aniDiv.css({height:img.height,width:img.width}); self.aniDiv.children().each(function(){ //position myself absolutely var div = $(this); var xOffset = Math.floor(div.parent().width()/5)*div.attr('col'); var yOffset = Math.floor(div.parent().height()/5)*div.attr('row'); div.css({ 'background':'url('+data.source+') -'+xOffset+'px -'+yOffset+'px', 'width':'0px', 'height':'0px', 'position':'absolute', 'top':yOffset+'px', 'left':xOffset+'px', 'float':'none' }); });//end ani_divs.children.each self.aniDiv.hide(); self.aniImg.hide(); switch(n){ case 0: //fade out then in self.image.stop(true,true).fadeOut('slow',function(){ self.image.attr('src',data.source).fadeIn('slow',function(){ self.finishAnimating(data); }); }); break; case 1: //full frame fade self.aniDiv.hide(); self.aniImg.height(self.image.height()).hide().attr('src',data.source); $.when( self.image.fadeOut('slow'), self.aniImg.eq(0).fadeIn('slow')).done(function(){ self.finishAnimating(data); }); break; case 2: self.aniDiv.show().children().hide().each(function(index){ //animate out as blocks var delay = index*30; $(this).css({opacity: 0.1}).show().delay(delay).animate({opacity: 1,"width":aWidth,"height":aHeight},200,'linear',function(){ if(self.aniDiv.find("div").index(this) == 24){ self.finishAnimating(data); } }); }); break; case 3: self.aniDiv.show().children("div:lt(5)").hide().each(function(index){ var delay = $(this).attr('col')*100; $(this).css({opacity:0.1,"width":aWidth}).show().delay(delay).animate({opacity:1,"height":self.image.height()},700,'linear',function(){ if(self.aniDiv.find(" div").index(this) == 4){ self.finishAnimating(data); } }); }); break; case 4: self.aniDiv.show().children().hide().each(function(index){ if(index>4){ return; } var delay = $(this).attr('col')*10; aHeight = self.gapper($(this), aHeight); $(this).css({opacity:0.1,"height":"100%"}).show().animate({opacity:1,"width":aWidth},500,'linear',function(){ if(self.aniDiv.find(" div").index(this) == 4){ self.finishAnimating(data); } }); }); break; case 5: self.aniDiv.show().children().show().each(function(index){ var delay = index*Math.floor(Math.random()*5)*7; aHeight = self.gapper($(this), aHeight); if($(".animation div").index(this) == 24){ delay = 600; } $(this).css({"height":aHeight,"width":aWidth,"opacity":.01}).delay(delay).animate({"opacity":1},600,function(){ if(self.aniDiv.find(" div").index(this) == 24){ self.finishAnimating(data); } }); }); break; case 6: //full frame slide self.aniDiv.height(self.image.height()).hide().css({'background':'url('+data.source+') top left no-repeat'}); self.aniDiv.children('div').hide(); self.aniDiv.css({width:0}).show().animate({width:self.image.width()},'slow',function(){ self.finishAnimating(data); self.aniDiv.css({'background':'transparent'}); }); break; case 7: //side in slide self.wrap.css({overflow:'hidden'}); self.aniImg.height(self.image.height()).hide().attr('src',data.source); self.aniDiv.hide(); self.image.css({position:'relative'}).animate({left:"-"+self.wrap.outerWidth()+"px"}); self.aniImg.show(); self.aniWrap.css({left:self.wrap.outerWidth()}).show().animate({left:"0px"},'slow',function(){ self.finishAnimating(data); }); break; } },//end doAnimation finishAnimating: function(data){ this.animating = false; this.image.attr('src',data.source); this.image.css({left:"0"}); this.image.show(); var self = this; $('<img />').bind('load',function(){ self.aniImg.hide(); self.aniDiv.hide(); }).attr('src',data.source); var cur = this.list.find('img').index(this.active); cur++; var total = this.list.find('img').length; this.counter.html(cur+"/"+total); if(data.clickThrough != ""){ if(this.anchor == null){ this.anchor = this.image.wrap("<a>").parent(); } this.anchor.attr('href',data.clickThrough); this.anchor.attr('title',data.clickThroughTitle); }else{ if(this.image.parent('a').length > 0){ this.image.unwrap(); } this.anchor = null; } if(this.options.showCaption && data.caption != "" && data.caption != null){ this.caption.html(data.caption).fadeTo('slow',1); } if(this.options.autoPlay == true){ var self = this; this.timeOut = setTimeout((function(self){ return function(){ self.nextClick(); }; })(this), this.options.speed, this.timeOut); } if(typeof(this.options.animationFinished) == 'function'){ this.options.animationFinished(this); } },//end finishedAnimating gapper: function(ele, aHeight){ if(ele.attr('row') == 9 && ele.attr('col') == 0){ //last row, check the gap and fix it! var gap = ani_divs.height()-(aHeight*9); return gap; } return aHeight; }, nextClick : function(e){ var how = "natural"; try{ var self = e.data.self; if(typeof(e.data.self.options.next) == 'function'){ e.data.self.options.next(this); } }catch(err){ var self = this; how = "auto"; } var next = self.active.parents('li:first').next().find('img'); if(next.length == 0){next = self.list.find('img').eq(0);}; next.trigger('click',{how:how}); }, prevClick : function(e){ if(typeof(e.data.self.options.previous) == 'function'){ e.data.self.options.previous(this); } var self = e.data.self; var prev = self.active.parents('li:first').prev().find('img'); if(prev.length == 0){prev = self.list.find('img:last');}; prev.trigger('click'); }, playClick: function(e){ var self = e.data.self; self.options.autoPlay = !self.options.autoPlay; self.imgPlay.toggleClass('play').toggleClass('pause'); if(self.options.autoPlay){ self.nextClick(); } } }); //end extend })(jQuery);
JavaScript
$(function() { $( "#dialog:ui-dialog" ).dialog( "destroy" ); $( "#login-form" ).dialog({ autoOpen: false, height: 300, width: 350, modal: true, buttons: { }, close: function() { allFields.val( "" ).removeClass( "ui-state-error" ); } }); $( "#login" ) .click(function() { $( "#login-form" ).dialog( "open" ); }); $( "#login-form" ).dialog({ height: 220, width: 200 }); });
JavaScript
/** * @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again. * * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder * Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/dfa8ce454af789605d8d971f2d61c57d * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/dfa8ce454af789605d8d971f2d61c57d * Straight download link to the latest version of CKEditor (Optimized) with the same setup as before. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moonocolor', preset: 'full', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'basicstyles' : 1, 'bidi' : 1, 'blockquote' : 1, 'clipboard' : 1, 'colorbutton' : 1, 'colordialog' : 1, 'contextmenu' : 1, 'dialogadvtab' : 1, 'div' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'find' : 1, 'flash' : 1, 'floatingspace' : 1, 'font' : 1, 'format' : 1, 'forms' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'iframe' : 1, 'image' : 1, 'indentblock' : 1, 'indentlist' : 1, 'justify' : 1, 'language' : 1, 'link' : 1, 'list' : 1, 'liststyle' : 1, 'magicline' : 1, 'maximize' : 1, 'newpage' : 1, 'pagebreak' : 1, 'pastefromword' : 1, 'pastetext' : 1, 'preview' : 1, 'print' : 1, 'removeformat' : 1, 'resize' : 1, 'save' : 1, 'scayt' : 1, 'selectall' : 1, 'showblocks' : 1, 'showborders' : 1, 'smiley' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'templates' : 1, 'toolbar' : 1, 'undo' : 1, 'wsc' : 1, 'wysiwygarea' : 1 }, languages : { 'en' : 1 } };
JavaScript
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */
JavaScript
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; };
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'myDialog', function( editor ) { return { title: 'My Dialog', minWidth: 400, minHeight: 200, contents: [ { id: 'tab1', label: 'First Tab', title: 'First Tab', elements: [ { id: 'input1', type: 'text', label: 'Text Field' }, { id: 'select1', type: 'select', label: 'Select Field', items: [ [ 'option1', 'value1' ], [ 'option2', 'value2' ] ] } ] }, { id: 'tab2', label: 'Second Tab', title: 'Second Tab', elements: [ { id: 'button1', type: 'button', label: 'Button Field' } ] } ] }; } );
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ // Tool scripts for the sample pages. // This file can be ignored and is not required to make use of CKEditor. ( function() { CKEDITOR.on( 'instanceReady', function( ev ) { // Check for sample compliance. var editor = ev.editor, meta = CKEDITOR.document.$.getElementsByName( 'ckeditor-sample-required-plugins' ), requires = meta.length ? CKEDITOR.dom.element.get( meta[ 0 ] ).getAttribute( 'content' ).split( ',' ) : [], missing = [], i; if ( requires.length ) { for ( i = 0; i < requires.length; i++ ) { if ( !editor.plugins[ requires[ i ] ] ) missing.push( '<code>' + requires[ i ] + '</code>' ); } if ( missing.length ) { var warn = CKEDITOR.dom.element.createFromHtml( '<div class="warning">' + '<span>To fully experience this demo, the ' + missing.join( ', ' ) + ' plugin' + ( missing.length > 1 ? 's are' : ' is' ) + ' required.</span>' + '</div>' ); warn.insertBefore( editor.container ); } } // Set icons. var doc = new CKEDITOR.dom.document( document ), icons = doc.find( '.button_icon' ); for ( i = 0; i < icons.count(); i++ ) { var icon = icons.getItem( i ), name = icon.getAttribute( 'data-icon' ), style = CKEDITOR.skin.getIconStyle( name, ( CKEDITOR.lang.dir == 'rtl' ) ); icon.addClass( 'cke_button_icon' ); icon.addClass( 'cke_button__' + name + '_icon' ); icon.setAttribute( 'style', style ); icon.setStyle( 'float', 'none' ); } } ); } )();
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin, which shows a combo // in the editor toolbar, containing all styles. Other plugins instead, like // the div plugin, use a subset of the styles on their feature. // // If you don't have plugins that depend on this file, you can simply ignore it. // Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. CKEDITOR.stylesSet.add( 'default', [ /* Block Styles */ // These styles are already available in the "Format" combo ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline Styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles combo, removing them from the toolbar. // (This requires the "stylescombo" plugin) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker', element: 'span', attributes: { 'class': 'marker' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object Styles */ { name: 'Styled image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } } ] );
JavaScript
 /** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time at http://ckeditor.com/builder to build CKEditor again. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moono', preset: 'standard', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'about' : 1, 'a11yhelp' : 1, 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'resize' : 1, 'toolbar' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'htmlwriter' : 1, 'horizontalrule' : 1, 'wysiwygarea' : 1, 'image' : 1, 'indent' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastetext' : 1, 'pastefromword' : 1, 'removeformat' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'scayt' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'undo' : 1, 'wsc' : 1, 'dialog' : 1, 'dialogui' : 1, 'menu' : 1, 'floatpanel' : 1, 'panel' : 1, 'button' : 1, 'popup' : 1, 'richcombo' : 1, 'listblock' : 1, 'fakeobjects' : 1, 'menubutton' : 1 }, languages : { 'af' : 1, 'ar' : 1, 'eu' : 1, 'bn' : 1, 'bs' : 1, 'bg' : 1, 'ca' : 1, 'zh-cn' : 1, 'zh' : 1, 'hr' : 1, 'cs' : 1, 'da' : 1, 'nl' : 1, 'en' : 1, 'en-au' : 1, 'en-ca' : 1, 'en-gb' : 1, 'eo' : 1, 'et' : 1, 'fo' : 1, 'fi' : 1, 'fr' : 1, 'fr-ca' : 1, 'gl' : 1, 'ka' : 1, 'de' : 1, 'el' : 1, 'gu' : 1, 'he' : 1, 'hi' : 1, 'hu' : 1, 'is' : 1, 'it' : 1, 'ja' : 1, 'km' : 1, 'ko' : 1, 'ku' : 1, 'lv' : 1, 'lt' : 1, 'mk' : 1, 'ms' : 1, 'mn' : 1, 'no' : 1, 'nb' : 1, 'fa' : 1, 'pl' : 1, 'pt-br' : 1, 'pt' : 1, 'ro' : 1, 'ru' : 1, 'sr' : 1, 'sr-latn' : 1, 'sk' : 1, 'sl' : 1, 'es' : 1, 'sv' : 1, 'th' : 1, 'tr' : 1, 'ug' : 1, 'uk' : 1, 'vi' : 1, 'cy' : 1, } };
JavaScript
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
/** * @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. // For the complete reference: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. config.toolbarGroups = [ { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'links' }, { name: 'insert' }, { name: 'forms' }, { name: 'tools' }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'others' }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ] }, { name: 'styles' }, { name: 'colors' }, { name: 'about' } ]; // Remove some buttons, provided by the standard plugins, which we don't // need to have in the Standard(s) toolbar. config.removeButtons = 'Underline,Subscript,Superscript'; };
JavaScript
/** * Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'myDialog', function( editor ) { return { title: 'My Dialog', minWidth: 400, minHeight: 200, contents: [ { id: 'tab1', label: 'First Tab', title: 'First Tab', elements: [ { id: 'input1', type: 'text', label: 'Text Field' }, { id: 'select1', type: 'select', label: 'Select Field', items: [ [ 'option1', 'value1' ], [ 'option2', 'value2' ] ] } ] }, { id: 'tab2', label: 'Second Tab', title: 'Second Tab', elements: [ { id: 'button1', type: 'button', label: 'Button Field' } ] } ] }; });
JavaScript
/** * Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin, which shows a combo // in the editor toolbar, containing all styles. Other plugins instead, like // the div plugin, use a subset of the styles on their feature. // // If you don't have plugins that depend on this file, you can simply ignore it. // Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. CKEDITOR.stylesSet.add( 'default', [ /* Block Styles */ // These styles are already available in the "Format" combo ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline Styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles combo, removing them from the toolbar. // (This requires the "stylescombo" plugin) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } }, { name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object Styles */ { name: 'Styled image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } } ]);
JavaScript
/** * @license wysihtml5 v0.3.0 * https://github.com/xing/wysihtml5 * * Author: Christopher Blum (https://github.com/tiff) * * Copyright (C) 2012 XING AG * Licensed under the MIT license (MIT) * */ var wysihtml5 = { version: "0.3.0", // namespaces commands: {}, dom: {}, quirks: {}, toolbar: {}, lang: {}, selection: {}, views: {}, INVISIBLE_SPACE: "\uFEFF", EMPTY_FUNCTION: function() {}, ELEMENT_NODE: 1, TEXT_NODE: 3, BACKSPACE_KEY: 8, ENTER_KEY: 13, ESCAPE_KEY: 27, SPACE_KEY: 32, DELETE_KEY: 46 };/** * @license Rangy, a cross-browser JavaScript range and selection library * http://code.google.com/p/rangy/ * * Copyright 2011, Tim Down * Licensed under the MIT license. * Version: 1.2.2 * Build date: 13 November 2011 */ window['rangy'] = (function() { var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined"; var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer", "START_TO_START", "START_TO_END", "END_TO_START", "END_TO_END"]; var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore", "setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents", "extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"]; var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"]; // Subset of TextRange's full set of methods that we're interested in var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "getBookmark", "moveToBookmark", "moveToElementText", "parentElement", "pasteHTML", "select", "setEndPoint", "getBoundingClientRect"]; /*----------------------------------------------------------------------------------------------------------------*/ // Trio of functions taken from Peter Michaux's article: // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(o, p) { var t = typeof o[p]; return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown"; } function isHostObject(o, p) { return !!(typeof o[p] == OBJECT && o[p]); } function isHostProperty(o, p) { return typeof o[p] != UNDEFINED; } // Creates a convenience function to save verbose repeated calls to tests functions function createMultiplePropertyTest(testFunc) { return function(o, props) { var i = props.length; while (i--) { if (!testFunc(o, props[i])) { return false; } } return true; }; } // Next trio of functions are a convenience to save verbose repeated calls to previous two functions var areHostMethods = createMultiplePropertyTest(isHostMethod); var areHostObjects = createMultiplePropertyTest(isHostObject); var areHostProperties = createMultiplePropertyTest(isHostProperty); function isTextRange(range) { return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties); } var api = { version: "1.2.2", initialized: false, supported: true, util: { isHostMethod: isHostMethod, isHostObject: isHostObject, isHostProperty: isHostProperty, areHostMethods: areHostMethods, areHostObjects: areHostObjects, areHostProperties: areHostProperties, isTextRange: isTextRange }, features: {}, modules: {}, config: { alertOnWarn: false, preferTextRange: false } }; function fail(reason) { window.alert("Rangy not supported in your browser. Reason: " + reason); api.initialized = true; api.supported = false; } api.fail = fail; function warn(msg) { var warningMessage = "Rangy warning: " + msg; if (api.config.alertOnWarn) { window.alert(warningMessage); } else if (typeof window.console != UNDEFINED && typeof window.console.log != UNDEFINED) { window.console.log(warningMessage); } } api.warn = warn; if ({}.hasOwnProperty) { api.util.extend = function(o, props) { for (var i in props) { if (props.hasOwnProperty(i)) { o[i] = props[i]; } } }; } else { fail("hasOwnProperty not supported"); } var initListeners = []; var moduleInitializers = []; // Initialization function init() { if (api.initialized) { return; } var testRange; var implementsDomRange = false, implementsTextRange = false; // First, perform basic feature tests if (isHostMethod(document, "createRange")) { testRange = document.createRange(); if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) { implementsDomRange = true; } testRange.detach(); } var body = isHostObject(document, "body") ? document.body : document.getElementsByTagName("body")[0]; if (body && isHostMethod(body, "createTextRange")) { testRange = body.createTextRange(); if (isTextRange(testRange)) { implementsTextRange = true; } } if (!implementsDomRange && !implementsTextRange) { fail("Neither Range nor TextRange are implemented"); } api.initialized = true; api.features = { implementsDomRange: implementsDomRange, implementsTextRange: implementsTextRange }; // Initialize modules and call init listeners var allListeners = moduleInitializers.concat(initListeners); for (var i = 0, len = allListeners.length; i < len; ++i) { try { allListeners[i](api); } catch (ex) { if (isHostObject(window, "console") && isHostMethod(window.console, "log")) { window.console.log("Init listener threw an exception. Continuing.", ex); } } } } // Allow external scripts to initialize this library in case it's loaded after the document has loaded api.init = init; // Execute listener immediately if already initialized api.addInitListener = function(listener) { if (api.initialized) { listener(api); } else { initListeners.push(listener); } }; var createMissingNativeApiListeners = []; api.addCreateMissingNativeApiListener = function(listener) { createMissingNativeApiListeners.push(listener); }; function createMissingNativeApi(win) { win = win || window; init(); // Notify listeners for (var i = 0, len = createMissingNativeApiListeners.length; i < len; ++i) { createMissingNativeApiListeners[i](win); } } api.createMissingNativeApi = createMissingNativeApi; /** * @constructor */ function Module(name) { this.name = name; this.initialized = false; this.supported = false; } Module.prototype.fail = function(reason) { this.initialized = true; this.supported = false; throw new Error("Module '" + this.name + "' failed to load: " + reason); }; Module.prototype.warn = function(msg) { api.warn("Module " + this.name + ": " + msg); }; Module.prototype.createError = function(msg) { return new Error("Error in Rangy " + this.name + " module: " + msg); }; api.createModule = function(name, initFunc) { var module = new Module(name); api.modules[name] = module; moduleInitializers.push(function(api) { initFunc(api, module); module.initialized = true; module.supported = true; }); }; api.requireModules = function(modules) { for (var i = 0, len = modules.length, module, moduleName; i < len; ++i) { moduleName = modules[i]; module = api.modules[moduleName]; if (!module || !(module instanceof Module)) { throw new Error("Module '" + moduleName + "' not found"); } if (!module.supported) { throw new Error("Module '" + moduleName + "' not supported"); } } }; /*----------------------------------------------------------------------------------------------------------------*/ // Wait for document to load before running tests var docReady = false; var loadHandler = function(e) { if (!docReady) { docReady = true; if (!api.initialized) { init(); } } }; // Test whether we have window and document objects that we will need if (typeof window == UNDEFINED) { fail("No window found"); return; } if (typeof document == UNDEFINED) { fail("No document found"); return; } if (isHostMethod(document, "addEventListener")) { document.addEventListener("DOMContentLoaded", loadHandler, false); } // Add a fallback in case the DOMContentLoaded event isn't supported if (isHostMethod(window, "addEventListener")) { window.addEventListener("load", loadHandler, false); } else if (isHostMethod(window, "attachEvent")) { window.attachEvent("onload", loadHandler); } else { fail("Window does not have required addEventListener or attachEvent method"); } return api; })(); rangy.createModule("DomUtil", function(api, module) { var UNDEF = "undefined"; var util = api.util; // Perform feature tests if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) { module.fail("document missing a Node creation method"); } if (!util.isHostMethod(document, "getElementsByTagName")) { module.fail("document missing getElementsByTagName method"); } var el = document.createElement("div"); if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) { module.fail("Incomplete Element implementation"); } // innerHTML is required for Range's createContextualFragment method if (!util.isHostProperty(el, "innerHTML")) { module.fail("Element is missing innerHTML property"); } var textNode = document.createTextNode("test"); if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) || !util.areHostProperties(textNode, ["data"]))) { module.fail("Incomplete Text Node implementation"); } /*----------------------------------------------------------------------------------------------------------------*/ // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that // contains just the document as a single element and the value searched for is the document. var arrayContains = /*Array.prototype.indexOf ? function(arr, val) { return arr.indexOf(val) > -1; }:*/ function(arr, val) { var i = arr.length; while (i--) { if (arr[i] === val) { return true; } } return false; }; // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI function isHtmlNamespace(node) { var ns; return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml"); } function parentElement(node) { var parent = node.parentNode; return (parent.nodeType == 1) ? parent : null; } function getNodeIndex(node) { var i = 0; while( (node = node.previousSibling) ) { i++; } return i; } function getNodeLength(node) { var childNodes; return isCharacterDataNode(node) ? node.length : ((childNodes = node.childNodes) ? childNodes.length : 0); } function getCommonAncestor(node1, node2) { var ancestors = [], n; for (n = node1; n; n = n.parentNode) { ancestors.push(n); } for (n = node2; n; n = n.parentNode) { if (arrayContains(ancestors, n)) { return n; } } return null; } function isAncestorOf(ancestor, descendant, selfIsAncestor) { var n = selfIsAncestor ? descendant : descendant.parentNode; while (n) { if (n === ancestor) { return true; } else { n = n.parentNode; } } return false; } function getClosestAncestorIn(node, ancestor, selfIsAncestor) { var p, n = selfIsAncestor ? node : node.parentNode; while (n) { p = n.parentNode; if (p === ancestor) { return n; } n = p; } return null; } function isCharacterDataNode(node) { var t = node.nodeType; return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment } function insertAfter(node, precedingNode) { var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode; if (nextNode) { parent.insertBefore(node, nextNode); } else { parent.appendChild(node); } return node; } // Note that we cannot use splitText() because it is bugridden in IE 9. function splitDataNode(node, index) { var newNode = node.cloneNode(false); newNode.deleteData(0, index); node.deleteData(index, node.length - index); insertAfter(newNode, node); return newNode; } function getDocument(node) { if (node.nodeType == 9) { return node; } else if (typeof node.ownerDocument != UNDEF) { return node.ownerDocument; } else if (typeof node.document != UNDEF) { return node.document; } else if (node.parentNode) { return getDocument(node.parentNode); } else { throw new Error("getDocument: no document found for node"); } } function getWindow(node) { var doc = getDocument(node); if (typeof doc.defaultView != UNDEF) { return doc.defaultView; } else if (typeof doc.parentWindow != UNDEF) { return doc.parentWindow; } else { throw new Error("Cannot get a window object for node"); } } function getIframeDocument(iframeEl) { if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument; } else if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow.document; } else { throw new Error("getIframeWindow: No Document object found for iframe element"); } } function getIframeWindow(iframeEl) { if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow; } else if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument.defaultView; } else { throw new Error("getIframeWindow: No Window object found for iframe element"); } } function getBody(doc) { return util.isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0]; } function getRootContainer(node) { var parent; while ( (parent = node.parentNode) ) { node = parent; } return node; } function comparePoints(nodeA, offsetA, nodeB, offsetB) { // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing var nodeC, root, childA, childB, n; if (nodeA == nodeB) { // Case 1: nodes are the same return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) { // Case 2: node C (container B or an ancestor) is a child node of A return offsetA <= getNodeIndex(nodeC) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) { // Case 3: node C (container A or an ancestor) is a child node of B return getNodeIndex(nodeC) < offsetB ? -1 : 1; } else { // Case 4: containers are siblings or descendants of siblings root = getCommonAncestor(nodeA, nodeB); childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true); childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true); if (childA === childB) { // This shouldn't be possible throw new Error("comparePoints got to case 4 and childA and childB are the same!"); } else { n = root.firstChild; while (n) { if (n === childA) { return -1; } else if (n === childB) { return 1; } n = n.nextSibling; } throw new Error("Should not be here!"); } } } function fragmentFromNodeChildren(node) { var fragment = getDocument(node).createDocumentFragment(), child; while ( (child = node.firstChild) ) { fragment.appendChild(child); } return fragment; } function inspectNode(node) { if (!node) { return "[No node]"; } if (isCharacterDataNode(node)) { return '"' + node.data + '"'; } else if (node.nodeType == 1) { var idAttr = node.id ? ' id="' + node.id + '"' : ""; return "<" + node.nodeName + idAttr + ">[" + node.childNodes.length + "]"; } else { return node.nodeName; } } /** * @constructor */ function NodeIterator(root) { this.root = root; this._next = root; } NodeIterator.prototype = { _current: null, hasNext: function() { return !!this._next; }, next: function() { var n = this._current = this._next; var child, next; if (this._current) { child = n.firstChild; if (child) { this._next = child; } else { next = null; while ((n !== this.root) && !(next = n.nextSibling)) { n = n.parentNode; } this._next = next; } } return this._current; }, detach: function() { this._current = this._next = this.root = null; } }; function createIterator(root) { return new NodeIterator(root); } /** * @constructor */ function DomPosition(node, offset) { this.node = node; this.offset = offset; } DomPosition.prototype = { equals: function(pos) { return this.node === pos.node & this.offset == pos.offset; }, inspect: function() { return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]"; } }; /** * @constructor */ function DOMException(codeName) { this.code = this[codeName]; this.codeName = codeName; this.message = "DOMException: " + this.codeName; } DOMException.prototype = { INDEX_SIZE_ERR: 1, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INVALID_STATE_ERR: 11 }; DOMException.prototype.toString = function() { return this.message; }; api.dom = { arrayContains: arrayContains, isHtmlNamespace: isHtmlNamespace, parentElement: parentElement, getNodeIndex: getNodeIndex, getNodeLength: getNodeLength, getCommonAncestor: getCommonAncestor, isAncestorOf: isAncestorOf, getClosestAncestorIn: getClosestAncestorIn, isCharacterDataNode: isCharacterDataNode, insertAfter: insertAfter, splitDataNode: splitDataNode, getDocument: getDocument, getWindow: getWindow, getIframeWindow: getIframeWindow, getIframeDocument: getIframeDocument, getBody: getBody, getRootContainer: getRootContainer, comparePoints: comparePoints, inspectNode: inspectNode, fragmentFromNodeChildren: fragmentFromNodeChildren, createIterator: createIterator, DomPosition: DomPosition }; api.DOMException = DOMException; });rangy.createModule("DomRange", function(api, module) { api.requireModules( ["DomUtil"] ); var dom = api.dom; var DomPosition = dom.DomPosition; var DOMException = api.DOMException; /*----------------------------------------------------------------------------------------------------------------*/ // Utility functions function isNonTextPartiallySelected(node, range) { return (node.nodeType != 3) && (dom.isAncestorOf(node, range.startContainer, true) || dom.isAncestorOf(node, range.endContainer, true)); } function getRangeDocument(range) { return dom.getDocument(range.startContainer); } function dispatchEvent(range, type, args) { var listeners = range._listeners[type]; if (listeners) { for (var i = 0, len = listeners.length; i < len; ++i) { listeners[i].call(range, {target: range, args: args}); } } } function getBoundaryBeforeNode(node) { return new DomPosition(node.parentNode, dom.getNodeIndex(node)); } function getBoundaryAfterNode(node) { return new DomPosition(node.parentNode, dom.getNodeIndex(node) + 1); } function insertNodeAtPosition(node, n, o) { var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node; if (dom.isCharacterDataNode(n)) { if (o == n.length) { dom.insertAfter(node, n); } else { n.parentNode.insertBefore(node, o == 0 ? n : dom.splitDataNode(n, o)); } } else if (o >= n.childNodes.length) { n.appendChild(node); } else { n.insertBefore(node, n.childNodes[o]); } return firstNodeInserted; } function cloneSubtree(iterator) { var partiallySelected; for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { partiallySelected = iterator.isPartiallySelectedSubtree(); node = node.cloneNode(!partiallySelected); if (partiallySelected) { subIterator = iterator.getSubtreeIterator(); node.appendChild(cloneSubtree(subIterator)); subIterator.detach(true); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function iterateSubtree(rangeIterator, func, iteratorState) { var it, n; iteratorState = iteratorState || { stop: false }; for (var node, subRangeIterator; node = rangeIterator.next(); ) { //log.debug("iterateSubtree, partially selected: " + rangeIterator.isPartiallySelectedSubtree(), nodeToString(node)); if (rangeIterator.isPartiallySelectedSubtree()) { // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of the // node selected by the Range. if (func(node) === false) { iteratorState.stop = true; return; } else { subRangeIterator = rangeIterator.getSubtreeIterator(); iterateSubtree(subRangeIterator, func, iteratorState); subRangeIterator.detach(true); if (iteratorState.stop) { return; } } } else { // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its // descendant it = dom.createIterator(node); while ( (n = it.next()) ) { if (func(n) === false) { iteratorState.stop = true; return; } } } } } function deleteSubtree(iterator) { var subIterator; while (iterator.next()) { if (iterator.isPartiallySelectedSubtree()) { subIterator = iterator.getSubtreeIterator(); deleteSubtree(subIterator); subIterator.detach(true); } else { iterator.remove(); } } } function extractSubtree(iterator) { for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { if (iterator.isPartiallySelectedSubtree()) { node = node.cloneNode(false); subIterator = iterator.getSubtreeIterator(); node.appendChild(extractSubtree(subIterator)); subIterator.detach(true); } else { iterator.remove(); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function getNodesInRange(range, nodeTypes, filter) { //log.info("getNodesInRange, " + nodeTypes.join(",")); var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex; var filterExists = !!filter; if (filterNodeTypes) { regex = new RegExp("^(" + nodeTypes.join("|") + ")$"); } var nodes = []; iterateSubtree(new RangeIterator(range, false), function(node) { if ((!filterNodeTypes || regex.test(node.nodeType)) && (!filterExists || filter(node))) { nodes.push(node); } }); return nodes; } function inspect(range) { var name = (typeof range.getName == "undefined") ? "Range" : range.getName(); return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " + dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]"; } /*----------------------------------------------------------------------------------------------------------------*/ // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange) /** * @constructor */ function RangeIterator(range, clonePartiallySelectedTextNodes) { this.range = range; this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes; if (!range.collapsed) { this.sc = range.startContainer; this.so = range.startOffset; this.ec = range.endContainer; this.eo = range.endOffset; var root = range.commonAncestorContainer; if (this.sc === this.ec && dom.isCharacterDataNode(this.sc)) { this.isSingleCharacterDataNode = true; this._first = this._last = this._next = this.sc; } else { this._first = this._next = (this.sc === root && !dom.isCharacterDataNode(this.sc)) ? this.sc.childNodes[this.so] : dom.getClosestAncestorIn(this.sc, root, true); this._last = (this.ec === root && !dom.isCharacterDataNode(this.ec)) ? this.ec.childNodes[this.eo - 1] : dom.getClosestAncestorIn(this.ec, root, true); } } } RangeIterator.prototype = { _current: null, _next: null, _first: null, _last: null, isSingleCharacterDataNode: false, reset: function() { this._current = null; this._next = this._first; }, hasNext: function() { return !!this._next; }, next: function() { // Move to next node var current = this._current = this._next; if (current) { this._next = (current !== this._last) ? current.nextSibling : null; // Check for partially selected text nodes if (dom.isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) { if (current === this.ec) { (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo); } if (this._current === this.sc) { (current = current.cloneNode(true)).deleteData(0, this.so); } } } return current; }, remove: function() { var current = this._current, start, end; if (dom.isCharacterDataNode(current) && (current === this.sc || current === this.ec)) { start = (current === this.sc) ? this.so : 0; end = (current === this.ec) ? this.eo : current.length; if (start != end) { current.deleteData(start, end - start); } } else { if (current.parentNode) { current.parentNode.removeChild(current); } else { } } }, // Checks if the current node is partially selected isPartiallySelectedSubtree: function() { var current = this._current; return isNonTextPartiallySelected(current, this.range); }, getSubtreeIterator: function() { var subRange; if (this.isSingleCharacterDataNode) { subRange = this.range.cloneRange(); subRange.collapse(); } else { subRange = new Range(getRangeDocument(this.range)); var current = this._current; var startContainer = current, startOffset = 0, endContainer = current, endOffset = dom.getNodeLength(current); if (dom.isAncestorOf(current, this.sc, true)) { startContainer = this.sc; startOffset = this.so; } if (dom.isAncestorOf(current, this.ec, true)) { endContainer = this.ec; endOffset = this.eo; } updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset); } return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes); }, detach: function(detachRange) { if (detachRange) { this.range.detach(); } this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null; } }; /*----------------------------------------------------------------------------------------------------------------*/ // Exceptions /** * @constructor */ function RangeException(codeName) { this.code = this[codeName]; this.codeName = codeName; this.message = "RangeException: " + this.codeName; } RangeException.prototype = { BAD_BOUNDARYPOINTS_ERR: 1, INVALID_NODE_TYPE_ERR: 2 }; RangeException.prototype.toString = function() { return this.message; }; /*----------------------------------------------------------------------------------------------------------------*/ /** * Currently iterates through all nodes in the range on creation until I think of a decent way to do it * TODO: Look into making this a proper iterator, not requiring preloading everything first * @constructor */ function RangeNodeIterator(range, nodeTypes, filter) { this.nodes = getNodesInRange(range, nodeTypes, filter); this._next = this.nodes[0]; this._position = 0; } RangeNodeIterator.prototype = { _current: null, hasNext: function() { return !!this._next; }, next: function() { this._current = this._next; this._next = this.nodes[ ++this._position ]; return this._current; }, detach: function() { this._current = this._next = this.nodes = null; } }; var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10]; var rootContainerNodeTypes = [2, 9, 11]; var readonlyNodeTypes = [5, 6, 10, 12]; var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11]; var surroundNodeTypes = [1, 3, 4, 5, 7, 8]; function createAncestorFinder(nodeTypes) { return function(node, selfIsAncestor) { var t, n = selfIsAncestor ? node : node.parentNode; while (n) { t = n.nodeType; if (dom.arrayContains(nodeTypes, t)) { return n; } n = n.parentNode; } return null; }; } var getRootContainer = dom.getRootContainer; var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] ); var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes); var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] ); function assertNoDocTypeNotationEntityAncestor(node, allowSelf) { if (getDocTypeNotationEntityAncestor(node, allowSelf)) { throw new RangeException("INVALID_NODE_TYPE_ERR"); } } function assertNotDetached(range) { if (!range.startContainer) { throw new DOMException("INVALID_STATE_ERR"); } } function assertValidNodeType(node, invalidTypes) { if (!dom.arrayContains(invalidTypes, node.nodeType)) { throw new RangeException("INVALID_NODE_TYPE_ERR"); } } function assertValidOffset(node, offset) { if (offset < 0 || offset > (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length)) { throw new DOMException("INDEX_SIZE_ERR"); } } function assertSameDocumentOrFragment(node1, node2) { if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } function assertNodeNotReadOnly(node) { if (getReadonlyAncestor(node, true)) { throw new DOMException("NO_MODIFICATION_ALLOWED_ERR"); } } function assertNode(node, codeName) { if (!node) { throw new DOMException(codeName); } } function isOrphan(node) { return !dom.arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true); } function isValidOffset(node, offset) { return offset <= (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length); } function assertRangeValid(range) { assertNotDetached(range); if (isOrphan(range.startContainer) || isOrphan(range.endContainer) || !isValidOffset(range.startContainer, range.startOffset) || !isValidOffset(range.endContainer, range.endOffset)) { throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")"); } } /*----------------------------------------------------------------------------------------------------------------*/ // Test the browser's innerHTML support to decide how to implement createContextualFragment var styleEl = document.createElement("style"); var htmlParsingConforms = false; try { styleEl.innerHTML = "<b>x</b>"; htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node } catch (e) { // IE 6 and 7 throw } api.features.htmlParsingConforms = htmlParsingConforms; var createContextualFragment = htmlParsingConforms ? // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See // discussion and base code for this implementation at issue 67. // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface // Thanks to Aleks Williams. function(fragmentStr) { // "Let node the context object's start's node." var node = this.startContainer; var doc = dom.getDocument(node); // "If the context object's start's node is null, raise an INVALID_STATE_ERR // exception and abort these steps." if (!node) { throw new DOMException("INVALID_STATE_ERR"); } // "Let element be as follows, depending on node's interface:" // Document, Document Fragment: null var el = null; // "Element: node" if (node.nodeType == 1) { el = node; // "Text, Comment: node's parentElement" } else if (dom.isCharacterDataNode(node)) { el = dom.parentElement(node); } // "If either element is null or element's ownerDocument is an HTML document // and element's local name is "html" and element's namespace is the HTML // namespace" if (el === null || ( el.nodeName == "HTML" && dom.isHtmlNamespace(dom.getDocument(el).documentElement) && dom.isHtmlNamespace(el) )) { // "let element be a new Element with "body" as its local name and the HTML // namespace as its namespace."" el = doc.createElement("body"); } else { el = el.cloneNode(false); } // "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm." // "If the node's document is an XML document: Invoke the XML fragment parsing algorithm." // "In either case, the algorithm must be invoked with fragment as the input // and element as the context element." el.innerHTML = fragmentStr; // "If this raises an exception, then abort these steps. Otherwise, let new // children be the nodes returned." // "Let fragment be a new DocumentFragment." // "Append all new children to fragment." // "Return fragment." return dom.fragmentFromNodeChildren(el); } : // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that // previous versions of Rangy used (with the exception of using a body element rather than a div) function(fragmentStr) { assertNotDetached(this); var doc = getRangeDocument(this); var el = doc.createElement("body"); el.innerHTML = fragmentStr; return dom.fragmentFromNodeChildren(el); }; /*----------------------------------------------------------------------------------------------------------------*/ var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer"]; var s2s = 0, s2e = 1, e2e = 2, e2s = 3; var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3; function RangePrototype() {} RangePrototype.prototype = { attachListener: function(type, listener) { this._listeners[type].push(listener); }, compareBoundaryPoints: function(how, range) { assertRangeValid(this); assertSameDocumentOrFragment(this.startContainer, range.startContainer); var nodeA, offsetA, nodeB, offsetB; var prefixA = (how == e2s || how == s2s) ? "start" : "end"; var prefixB = (how == s2e || how == s2s) ? "start" : "end"; nodeA = this[prefixA + "Container"]; offsetA = this[prefixA + "Offset"]; nodeB = range[prefixB + "Container"]; offsetB = range[prefixB + "Offset"]; return dom.comparePoints(nodeA, offsetA, nodeB, offsetB); }, insertNode: function(node) { assertRangeValid(this); assertValidNodeType(node, insertableNodeTypes); assertNodeNotReadOnly(this.startContainer); if (dom.isAncestorOf(node, this.startContainer, true)) { throw new DOMException("HIERARCHY_REQUEST_ERR"); } // No check for whether the container of the start of the Range is of a type that does not allow // children of the type of node: the browser's DOM implementation should do this for us when we attempt // to add the node var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset); this.setStartBefore(firstNodeInserted); }, cloneContents: function() { assertRangeValid(this); var clone, frag; if (this.collapsed) { return getRangeDocument(this).createDocumentFragment(); } else { if (this.startContainer === this.endContainer && dom.isCharacterDataNode(this.startContainer)) { clone = this.startContainer.cloneNode(true); clone.data = clone.data.slice(this.startOffset, this.endOffset); frag = getRangeDocument(this).createDocumentFragment(); frag.appendChild(clone); return frag; } else { var iterator = new RangeIterator(this, true); clone = cloneSubtree(iterator); iterator.detach(); } return clone; } }, canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, surroundContents: function(node) { assertValidNodeType(node, surroundNodeTypes); if (!this.canSurroundContents()) { throw new RangeException("BAD_BOUNDARYPOINTS_ERR"); } // Extract the contents var content = this.extractContents(); // Clear the children of the node if (node.hasChildNodes()) { while (node.lastChild) { node.removeChild(node.lastChild); } } // Insert the new node and add the extracted contents insertNodeAtPosition(node, this.startContainer, this.startOffset); node.appendChild(content); this.selectNode(node); }, cloneRange: function() { assertRangeValid(this); var range = new Range(getRangeDocument(this)); var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = this[prop]; } return range; }, toString: function() { assertRangeValid(this); var sc = this.startContainer; if (sc === this.endContainer && dom.isCharacterDataNode(sc)) { return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : ""; } else { var textBits = [], iterator = new RangeIterator(this, true); iterateSubtree(iterator, function(node) { // Accept only text or CDATA nodes, not comments if (node.nodeType == 3 || node.nodeType == 4) { textBits.push(node.data); } }); iterator.detach(); return textBits.join(""); } }, // The methods below are all non-standard. The following batch were introduced by Mozilla but have since // been removed from Mozilla. compareNode: function(node) { assertRangeValid(this); var parent = node.parentNode; var nodeIndex = dom.getNodeIndex(node); if (!parent) { throw new DOMException("NOT_FOUND_ERR"); } var startComparison = this.comparePoint(parent, nodeIndex), endComparison = this.comparePoint(parent, nodeIndex + 1); if (startComparison < 0) { // Node starts before return (endComparison > 0) ? n_b_a : n_b; } else { return (endComparison > 0) ? n_a : n_i; } }, comparePoint: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); if (dom.comparePoints(node, offset, this.startContainer, this.startOffset) < 0) { return -1; } else if (dom.comparePoints(node, offset, this.endContainer, this.endOffset) > 0) { return 1; } return 0; }, createContextualFragment: createContextualFragment, toHtml: function() { assertRangeValid(this); var container = getRangeDocument(this).createElement("div"); container.appendChild(this.cloneContents()); return container.innerHTML; }, // touchingIsIntersecting determines whether this method considers a node that borders a range intersects // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default) intersectsNode: function(node, touchingIsIntersecting) { assertRangeValid(this); assertNode(node, "NOT_FOUND_ERR"); if (dom.getDocument(node) !== getRangeDocument(this)) { return false; } var parent = node.parentNode, offset = dom.getNodeIndex(node); assertNode(parent, "NOT_FOUND_ERR"); var startComparison = dom.comparePoints(parent, offset, this.endContainer, this.endOffset), endComparison = dom.comparePoints(parent, offset + 1, this.startContainer, this.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; }, isPointInRange: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); return (dom.comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) && (dom.comparePoints(node, offset, this.endContainer, this.endOffset) <= 0); }, // The methods below are non-standard and invented by me. // Sharing a boundary start-to-end or end-to-start does not count as intersection. intersectsRange: function(range, touchingIsIntersecting) { assertRangeValid(this); if (getRangeDocument(range) != getRangeDocument(this)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.endContainer, range.endOffset), endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.startContainer, range.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; }, intersection: function(range) { if (this.intersectsRange(range)) { var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset), endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset); var intersectionRange = this.cloneRange(); if (startComparison == -1) { intersectionRange.setStart(range.startContainer, range.startOffset); } if (endComparison == 1) { intersectionRange.setEnd(range.endContainer, range.endOffset); } return intersectionRange; } return null; }, union: function(range) { if (this.intersectsRange(range, true)) { var unionRange = this.cloneRange(); if (dom.comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) { unionRange.setStart(range.startContainer, range.startOffset); } if (dom.comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) { unionRange.setEnd(range.endContainer, range.endOffset); } return unionRange; } else { throw new RangeException("Ranges do not intersect"); } }, containsNode: function(node, allowPartial) { if (allowPartial) { return this.intersectsNode(node, false); } else { return this.compareNode(node) == n_i; } }, containsNodeContents: function(node) { return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, dom.getNodeLength(node)) <= 0; }, containsRange: function(range) { return this.intersection(range).equals(range); }, containsNodeText: function(node) { var nodeRange = this.cloneRange(); nodeRange.selectNode(node); var textNodes = nodeRange.getNodes([3]); if (textNodes.length > 0) { nodeRange.setStart(textNodes[0], 0); var lastTextNode = textNodes.pop(); nodeRange.setEnd(lastTextNode, lastTextNode.length); var contains = this.containsRange(nodeRange); nodeRange.detach(); return contains; } else { return this.containsNodeContents(node); } }, createNodeIterator: function(nodeTypes, filter) { assertRangeValid(this); return new RangeNodeIterator(this, nodeTypes, filter); }, getNodes: function(nodeTypes, filter) { assertRangeValid(this); return getNodesInRange(this, nodeTypes, filter); }, getDocument: function() { return getRangeDocument(this); }, collapseBefore: function(node) { assertNotDetached(this); this.setEndBefore(node); this.collapse(false); }, collapseAfter: function(node) { assertNotDetached(this); this.setStartAfter(node); this.collapse(true); }, getName: function() { return "DomRange"; }, equals: function(range) { return Range.rangesEqual(this, range); }, inspect: function() { return inspect(this); } }; function copyComparisonConstantsToObject(obj) { obj.START_TO_START = s2s; obj.START_TO_END = s2e; obj.END_TO_END = e2e; obj.END_TO_START = e2s; obj.NODE_BEFORE = n_b; obj.NODE_AFTER = n_a; obj.NODE_BEFORE_AND_AFTER = n_b_a; obj.NODE_INSIDE = n_i; } function copyComparisonConstants(constructor) { copyComparisonConstantsToObject(constructor); copyComparisonConstantsToObject(constructor.prototype); } function createRangeContentRemover(remover, boundaryUpdater) { return function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer; var iterator = new RangeIterator(this, true); // Work out where to position the range after content removal var node, boundary; if (sc !== root) { node = dom.getClosestAncestorIn(sc, root, true); boundary = getBoundaryAfterNode(node); sc = boundary.node; so = boundary.offset; } // Check none of the range is read-only iterateSubtree(iterator, assertNodeNotReadOnly); iterator.reset(); // Remove the content var returnValue = remover(iterator); iterator.detach(); // Move to the new position boundaryUpdater(this, sc, so, sc, so); return returnValue; }; } function createPrototypeRange(constructor, boundaryUpdater, detacher) { function createBeforeAfterNodeSetter(isBefore, isStart) { return function(node) { assertNotDetached(this); assertValidNodeType(node, beforeAfterNodeTypes); assertValidNodeType(getRootContainer(node), rootContainerNodeTypes); var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node); (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset); }; } function setRangeStart(range, node, offset) { var ec = range.endContainer, eo = range.endOffset; if (node !== range.startContainer || offset !== range.startOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(ec) || dom.comparePoints(node, offset, ec, eo) == 1) { ec = node; eo = offset; } boundaryUpdater(range, node, offset, ec, eo); } } function setRangeEnd(range, node, offset) { var sc = range.startContainer, so = range.startOffset; if (node !== range.endContainer || offset !== range.endOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(sc) || dom.comparePoints(node, offset, sc, so) == -1) { sc = node; so = offset; } boundaryUpdater(range, sc, so, node, offset); } } function setRangeStartAndEnd(range, node, offset) { if (node !== range.startContainer || offset !== range.startOffset || node !== range.endContainer || offset !== range.endOffset) { boundaryUpdater(range, node, offset, node, offset); } } constructor.prototype = new RangePrototype(); api.util.extend(constructor.prototype, { setStart: function(node, offset) { assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeStart(this, node, offset); }, setEnd: function(node, offset) { assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeEnd(this, node, offset); }, setStartBefore: createBeforeAfterNodeSetter(true, true), setStartAfter: createBeforeAfterNodeSetter(false, true), setEndBefore: createBeforeAfterNodeSetter(true, false), setEndAfter: createBeforeAfterNodeSetter(false, false), collapse: function(isStart) { assertRangeValid(this); if (isStart) { boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset); } else { boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset); } }, selectNodeContents: function(node) { // This doesn't seem well specified: the spec talks only about selecting the node's contents, which // could be taken to mean only its children. However, browsers implement this the same as selectNode for // text nodes, so I shall do likewise assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, true); boundaryUpdater(this, node, 0, node, dom.getNodeLength(node)); }, selectNode: function(node) { assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, false); assertValidNodeType(node, beforeAfterNodeTypes); var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node); boundaryUpdater(this, start.node, start.offset, end.node, end.offset); }, extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater), deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater), canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, detach: function() { detacher(this); }, splitBoundaries: function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset; var startEndSame = (sc === ec); if (dom.isCharacterDataNode(ec) && eo > 0 && eo < ec.length) { dom.splitDataNode(ec, eo); } if (dom.isCharacterDataNode(sc) && so > 0 && so < sc.length) { sc = dom.splitDataNode(sc, so); if (startEndSame) { eo -= so; ec = sc; } else if (ec == sc.parentNode && eo >= dom.getNodeIndex(sc)) { eo++; } so = 0; } boundaryUpdater(this, sc, so, ec, eo); }, normalizeBoundaries: function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset; var mergeForward = function(node) { var sibling = node.nextSibling; if (sibling && sibling.nodeType == node.nodeType) { ec = node; eo = node.length; node.appendData(sibling.data); sibling.parentNode.removeChild(sibling); } }; var mergeBackward = function(node) { var sibling = node.previousSibling; if (sibling && sibling.nodeType == node.nodeType) { sc = node; var nodeLength = node.length; so = sibling.length; node.insertData(0, sibling.data); sibling.parentNode.removeChild(sibling); if (sc == ec) { eo += so; ec = sc; } else if (ec == node.parentNode) { var nodeIndex = dom.getNodeIndex(node); if (eo == nodeIndex) { ec = node; eo = nodeLength; } else if (eo > nodeIndex) { eo--; } } } }; var normalizeStart = true; if (dom.isCharacterDataNode(ec)) { if (ec.length == eo) { mergeForward(ec); } } else { if (eo > 0) { var endNode = ec.childNodes[eo - 1]; if (endNode && dom.isCharacterDataNode(endNode)) { mergeForward(endNode); } } normalizeStart = !this.collapsed; } if (normalizeStart) { if (dom.isCharacterDataNode(sc)) { if (so == 0) { mergeBackward(sc); } } else { if (so < sc.childNodes.length) { var startNode = sc.childNodes[so]; if (startNode && dom.isCharacterDataNode(startNode)) { mergeBackward(startNode); } } } } else { sc = ec; so = eo; } boundaryUpdater(this, sc, so, ec, eo); }, collapseToPoint: function(node, offset) { assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeStartAndEnd(this, node, offset); } }); copyComparisonConstants(constructor); } /*----------------------------------------------------------------------------------------------------------------*/ // Updates commonAncestorContainer and collapsed after boundary change function updateCollapsedAndCommonAncestor(range) { range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); range.commonAncestorContainer = range.collapsed ? range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer); } function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) { var startMoved = (range.startContainer !== startContainer || range.startOffset !== startOffset); var endMoved = (range.endContainer !== endContainer || range.endOffset !== endOffset); range.startContainer = startContainer; range.startOffset = startOffset; range.endContainer = endContainer; range.endOffset = endOffset; updateCollapsedAndCommonAncestor(range); dispatchEvent(range, "boundarychange", {startMoved: startMoved, endMoved: endMoved}); } function detach(range) { assertNotDetached(range); range.startContainer = range.startOffset = range.endContainer = range.endOffset = null; range.collapsed = range.commonAncestorContainer = null; dispatchEvent(range, "detach", null); range._listeners = null; } /** * @constructor */ function Range(doc) { this.startContainer = doc; this.startOffset = 0; this.endContainer = doc; this.endOffset = 0; this._listeners = { boundarychange: [], detach: [] }; updateCollapsedAndCommonAncestor(this); } createPrototypeRange(Range, updateBoundaries, detach); api.rangePrototype = RangePrototype.prototype; Range.rangeProperties = rangeProperties; Range.RangeIterator = RangeIterator; Range.copyComparisonConstants = copyComparisonConstants; Range.createPrototypeRange = createPrototypeRange; Range.inspect = inspect; Range.getRangeDocument = getRangeDocument; Range.rangesEqual = function(r1, r2) { return r1.startContainer === r2.startContainer && r1.startOffset === r2.startOffset && r1.endContainer === r2.endContainer && r1.endOffset === r2.endOffset; }; api.DomRange = Range; api.RangeException = RangeException; });rangy.createModule("WrappedRange", function(api, module) { api.requireModules( ["DomUtil", "DomRange"] ); /** * @constructor */ var WrappedRange; var dom = api.dom; var DomPosition = dom.DomPosition; var DomRange = api.DomRange; /*----------------------------------------------------------------------------------------------------------------*/ /* This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement() method. For example, in the following (where pipes denote the selection boundaries): <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul> var range = document.selection.createRange(); alert(range.parentElement().id); // Should alert "ul" but alerts "b" This method returns the common ancestor node of the following: - the parentElement() of the textRange - the parentElement() of the textRange after calling collapse(true) - the parentElement() of the textRange after calling collapse(false) */ function getTextRangeContainerElement(textRange) { var parentEl = textRange.parentElement(); var range = textRange.duplicate(); range.collapse(true); var startEl = range.parentElement(); range = textRange.duplicate(); range.collapse(false); var endEl = range.parentElement(); var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl); return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer); } function textRangeIsCollapsed(textRange) { return textRange.compareEndPoints("StartToEnd", textRange) == 0; } // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started out as // an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) but has // grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange bugs, handling // for inputs and images, plus optimizations. function getTextRangeBoundaryPosition(textRange, wholeRangeContainerElement, isStart, isCollapsed) { var workingRange = textRange.duplicate(); workingRange.collapse(isStart); var containerElement = workingRange.parentElement(); // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so // check for that // TODO: Find out when. Workaround for wholeRangeContainerElement may break this if (!dom.isAncestorOf(wholeRangeContainerElement, containerElement, true)) { containerElement = wholeRangeContainerElement; } // Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx if (!containerElement.canHaveHTML) { return new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement)); } var workingNode = dom.getDocument(containerElement).createElement("span"); var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd"; var previousNode, nextNode, boundaryPosition, boundaryNode; // Move the working range through the container's children, starting at the end and working backwards, until the // working range reaches or goes past the boundary we're interested in do { containerElement.insertBefore(workingNode, workingNode.previousSibling); workingRange.moveToElementText(workingNode); } while ( (comparison = workingRange.compareEndPoints(workingComparisonType, textRange)) > 0 && workingNode.previousSibling); // We've now reached or gone past the boundary of the text range we're interested in // so have identified the node we want boundaryNode = workingNode.nextSibling; if (comparison == -1 && boundaryNode && dom.isCharacterDataNode(boundaryNode)) { // This is a character data node (text, comment, cdata). The working range is collapsed at the start of the // node containing the text range's boundary, so we move the end of the working range to the boundary point // and measure the length of its text to get the boundary's offset within the node. workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange); var offset; if (/[\r\n]/.test(boundaryNode.data)) { /* For the particular case of a boundary within a text node containing line breaks (within a <pre> element, for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts: - Each line break is represented as \r in the text node's data/nodeValue properties - Each line break is represented as \r\n in the TextRange's 'text' property - The 'text' property of the TextRange does not contain trailing line breaks To get round the problem presented by the final fact above, we can use the fact that TextRange's moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily the same as the number of characters it was instructed to move. The simplest approach is to use this to store the characters moved when moving both the start and end of the range to the start of the document body and subtracting the start offset from the end offset (the "move-negative-gazillion" method). However, this is extremely slow when the document is large and the range is near the end of it. Clearly doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same problem. Another approach that works is to use moveStart() to move the start boundary of the range up to the end boundary one character at a time and incrementing a counter with the value returned by the moveStart() call. However, the check for whether the start boundary has reached the end boundary is expensive, so this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of the range within the document). The method below is a hybrid of the two methods above. It uses the fact that a string containing the TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the text of the TextRange, so the start of the range is moved that length initially and then a character at a time to make up for any trailing line breaks not contained in the 'text' property. This has good performance in most situations compared to the previous two methods. */ var tempRange = workingRange.duplicate(); var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length; offset = tempRange.moveStart("character", rangeLength); while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) { offset++; tempRange.moveStart("character", 1); } } else { offset = workingRange.text.length; } boundaryPosition = new DomPosition(boundaryNode, offset); } else { // If the boundary immediately follows a character data node and this is the end boundary, we should favour // a position within that, and likewise for a start boundary preceding a character data node previousNode = (isCollapsed || !isStart) && workingNode.previousSibling; nextNode = (isCollapsed || isStart) && workingNode.nextSibling; if (nextNode && dom.isCharacterDataNode(nextNode)) { boundaryPosition = new DomPosition(nextNode, 0); } else if (previousNode && dom.isCharacterDataNode(previousNode)) { boundaryPosition = new DomPosition(previousNode, previousNode.length); } else { boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode)); } } // Clean up workingNode.parentNode.removeChild(workingNode); return boundaryPosition; } // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that node. // This function started out as an optimized version of code found in Tim Cameron Ryan's IERange // (http://code.google.com/p/ierange/) function createBoundaryTextRange(boundaryPosition, isStart) { var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset; var doc = dom.getDocument(boundaryPosition.node); var workingNode, childNodes, workingRange = doc.body.createTextRange(); var nodeIsDataNode = dom.isCharacterDataNode(boundaryPosition.node); if (nodeIsDataNode) { boundaryNode = boundaryPosition.node; boundaryParent = boundaryNode.parentNode; } else { childNodes = boundaryPosition.node.childNodes; boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null; boundaryParent = boundaryPosition.node; } // Position the range immediately before the node containing the boundary workingNode = doc.createElement("span"); // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within the // element rather than immediately before or after it, which is what we want workingNode.innerHTML = "&#feff;"; // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12 if (boundaryNode) { boundaryParent.insertBefore(workingNode, boundaryNode); } else { boundaryParent.appendChild(workingNode); } workingRange.moveToElementText(workingNode); workingRange.collapse(!isStart); // Clean up boundaryParent.removeChild(workingNode); // Move the working range to the text offset, if required if (nodeIsDataNode) { workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset); } return workingRange; } /*----------------------------------------------------------------------------------------------------------------*/ if (api.features.implementsDomRange && (!api.features.implementsTextRange || !api.config.preferTextRange)) { // This is a wrapper around the browser's native DOM Range. It has two aims: // - Provide workarounds for specific browser bugs // - provide convenient extensions, which are inherited from Rangy's DomRange (function() { var rangeProto; var rangeProperties = DomRange.rangeProperties; var canSetRangeStartAfterEnd; function updateRangeProperties(range) { var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = range.nativeRange[prop]; } } function updateNativeRange(range, startContainer, startOffset, endContainer,endOffset) { var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset); var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset); // Always set both boundaries for the benefit of IE9 (see issue 35) if (startMoved || endMoved) { range.setEnd(endContainer, endOffset); range.setStart(startContainer, startOffset); } } function detach(range) { range.nativeRange.detach(); range.detached = true; var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = null; } } var createBeforeAfterNodeSetter; WrappedRange = function(range) { if (!range) { throw new Error("Range must be specified"); } this.nativeRange = range; updateRangeProperties(this); }; DomRange.createPrototypeRange(WrappedRange, updateNativeRange, detach); rangeProto = WrappedRange.prototype; rangeProto.selectNode = function(node) { this.nativeRange.selectNode(node); updateRangeProperties(this); }; rangeProto.deleteContents = function() { this.nativeRange.deleteContents(); updateRangeProperties(this); }; rangeProto.extractContents = function() { var frag = this.nativeRange.extractContents(); updateRangeProperties(this); return frag; }; rangeProto.cloneContents = function() { return this.nativeRange.cloneContents(); }; // TODO: Until I can find a way to programmatically trigger the Firefox bug (apparently long-standing, still // present in 3.6.8) that throws "Index or size is negative or greater than the allowed amount" for // insertNode in some circumstances, all browsers will have to use the Rangy's own implementation of // insertNode, which works but is almost certainly slower than the native implementation. /* rangeProto.insertNode = function(node) { this.nativeRange.insertNode(node); updateRangeProperties(this); }; */ rangeProto.surroundContents = function(node) { this.nativeRange.surroundContents(node); updateRangeProperties(this); }; rangeProto.collapse = function(isStart) { this.nativeRange.collapse(isStart); updateRangeProperties(this); }; rangeProto.cloneRange = function() { return new WrappedRange(this.nativeRange.cloneRange()); }; rangeProto.refresh = function() { updateRangeProperties(this); }; rangeProto.toString = function() { return this.nativeRange.toString(); }; // Create test range and node for feature detection var testTextNode = document.createTextNode("test"); dom.getBody(document).appendChild(testTextNode); var range = document.createRange(); /*--------------------------------------------------------------------------------------------------------*/ // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and // correct for it range.setStart(testTextNode, 0); range.setEnd(testTextNode, 0); try { range.setStart(testTextNode, 1); canSetRangeStartAfterEnd = true; rangeProto.setStart = function(node, offset) { this.nativeRange.setStart(node, offset); updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { this.nativeRange.setEnd(node, offset); updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name) { return function(node) { this.nativeRange[name](node); updateRangeProperties(this); }; }; } catch(ex) { canSetRangeStartAfterEnd = false; rangeProto.setStart = function(node, offset) { try { this.nativeRange.setStart(node, offset); } catch (ex) { this.nativeRange.setEnd(node, offset); this.nativeRange.setStart(node, offset); } updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { try { this.nativeRange.setEnd(node, offset); } catch (ex) { this.nativeRange.setStart(node, offset); this.nativeRange.setEnd(node, offset); } updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name, oppositeName) { return function(node) { try { this.nativeRange[name](node); } catch (ex) { this.nativeRange[oppositeName](node); this.nativeRange[name](node); } updateRangeProperties(this); }; }; } rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore"); rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter"); rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore"); rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter"); /*--------------------------------------------------------------------------------------------------------*/ // Test for and correct Firefox 2 behaviour with selectNodeContents on text nodes: it collapses the range to // the 0th character of the text node range.selectNodeContents(testTextNode); if (range.startContainer == testTextNode && range.endContainer == testTextNode && range.startOffset == 0 && range.endOffset == testTextNode.length) { rangeProto.selectNodeContents = function(node) { this.nativeRange.selectNodeContents(node); updateRangeProperties(this); }; } else { rangeProto.selectNodeContents = function(node) { this.setStart(node, 0); this.setEnd(node, DomRange.getEndOffset(node)); }; } /*--------------------------------------------------------------------------------------------------------*/ // Test for WebKit bug that has the beahviour of compareBoundaryPoints round the wrong way for constants // START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738 range.selectNodeContents(testTextNode); range.setEnd(testTextNode, 3); var range2 = document.createRange(); range2.selectNodeContents(testTextNode); range2.setEnd(testTextNode, 4); range2.setStart(testTextNode, 2); if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 & range.compareBoundaryPoints(range.END_TO_START, range2) == 1) { // This is the wrong way round, so correct for it rangeProto.compareBoundaryPoints = function(type, range) { range = range.nativeRange || range; if (type == range.START_TO_END) { type = range.END_TO_START; } else if (type == range.END_TO_START) { type = range.START_TO_END; } return this.nativeRange.compareBoundaryPoints(type, range); }; } else { rangeProto.compareBoundaryPoints = function(type, range) { return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range); }; } /*--------------------------------------------------------------------------------------------------------*/ // Test for existence of createContextualFragment and delegate to it if it exists if (api.util.isHostMethod(range, "createContextualFragment")) { rangeProto.createContextualFragment = function(fragmentStr) { return this.nativeRange.createContextualFragment(fragmentStr); }; } /*--------------------------------------------------------------------------------------------------------*/ // Clean up dom.getBody(document).removeChild(testTextNode); range.detach(); range2.detach(); })(); api.createNativeRange = function(doc) { doc = doc || document; return doc.createRange(); }; } else if (api.features.implementsTextRange) { // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a // prototype WrappedRange = function(textRange) { this.textRange = textRange; this.refresh(); }; WrappedRange.prototype = new DomRange(document); WrappedRange.prototype.refresh = function() { var start, end; // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that. var rangeContainerElement = getTextRangeContainerElement(this.textRange); if (textRangeIsCollapsed(this.textRange)) { end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true); } else { start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false); end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false); } this.setStart(start.node, start.offset); this.setEnd(end.node, end.offset); }; DomRange.copyComparisonConstants(WrappedRange); // Add WrappedRange as the Range property of the global object to allow expression like Range.END_TO_END to work var globalObj = (function() { return this; })(); if (typeof globalObj.Range == "undefined") { globalObj.Range = WrappedRange; } api.createNativeRange = function(doc) { doc = doc || document; return doc.body.createTextRange(); }; } if (api.features.implementsTextRange) { WrappedRange.rangeToTextRange = function(range) { if (range.collapsed) { var tr = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); return tr; //return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); } else { var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false); var textRange = dom.getDocument(range.startContainer).body.createTextRange(); textRange.setEndPoint("StartToStart", startRange); textRange.setEndPoint("EndToEnd", endRange); return textRange; } }; } WrappedRange.prototype.getName = function() { return "WrappedRange"; }; api.WrappedRange = WrappedRange; api.createRange = function(doc) { doc = doc || document; return new WrappedRange(api.createNativeRange(doc)); }; api.createRangyRange = function(doc) { doc = doc || document; return new DomRange(doc); }; api.createIframeRange = function(iframeEl) { return api.createRange(dom.getIframeDocument(iframeEl)); }; api.createIframeRangyRange = function(iframeEl) { return api.createRangyRange(dom.getIframeDocument(iframeEl)); }; api.addCreateMissingNativeApiListener(function(win) { var doc = win.document; if (typeof doc.createRange == "undefined") { doc.createRange = function() { return api.createRange(this); }; } doc = win = null; }); });rangy.createModule("WrappedSelection", function(api, module) { // This will create a selection object wrapper that follows the Selection object found in the WHATWG draft DOM Range // spec (http://html5.org/specs/dom-range.html) api.requireModules( ["DomUtil", "DomRange", "WrappedRange"] ); api.config.checkSelectionRanges = true; var BOOLEAN = "boolean", windowPropertyName = "_rangySelection", dom = api.dom, util = api.util, DomRange = api.DomRange, WrappedRange = api.WrappedRange, DOMException = api.DOMException, DomPosition = dom.DomPosition, getSelection, selectionIsCollapsed, CONTROL = "Control"; function getWinSelection(winParam) { return (winParam || window).getSelection(); } function getDocSelection(winParam) { return (winParam || window).document.selection; } // Test for the Range/TextRange and Selection features required // Test for ability to retrieve selection var implementsWinGetSelection = api.util.isHostMethod(window, "getSelection"), implementsDocSelection = api.util.isHostObject(document, "selection"); var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange); if (useDocumentSelection) { getSelection = getDocSelection; api.isSelectionValid = function(winParam) { var doc = (winParam || window).document, nativeSel = doc.selection; // Check whether the selection TextRange is actually contained within the correct document return (nativeSel.type != "None" || dom.getDocument(nativeSel.createRange().parentElement()) == doc); }; } else if (implementsWinGetSelection) { getSelection = getWinSelection; api.isSelectionValid = function() { return true; }; } else { module.fail("Neither document.selection or window.getSelection() detected."); } api.getNativeSelection = getSelection; var testSelection = getSelection(); var testRange = api.createNativeRange(document); var body = dom.getBody(document); // Obtaining a range from a selection var selectionHasAnchorAndFocus = util.areHostObjects(testSelection, ["anchorNode", "focusNode"] && util.areHostProperties(testSelection, ["anchorOffset", "focusOffset"])); api.features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus; // Test for existence of native selection extend() method var selectionHasExtend = util.isHostMethod(testSelection, "extend"); api.features.selectionHasExtend = selectionHasExtend; // Test if rangeCount exists var selectionHasRangeCount = (typeof testSelection.rangeCount == "number"); api.features.selectionHasRangeCount = selectionHasRangeCount; var selectionSupportsMultipleRanges = false; var collapsedNonEditableSelectionsSupported = true; if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) && typeof testSelection.rangeCount == "number" && api.features.implementsDomRange) { (function() { var iframe = document.createElement("iframe"); body.appendChild(iframe); var iframeDoc = dom.getIframeDocument(iframe); iframeDoc.open(); iframeDoc.write("<html><head></head><body>12</body></html>"); iframeDoc.close(); var sel = dom.getIframeWindow(iframe).getSelection(); var docEl = iframeDoc.documentElement; var iframeBody = docEl.lastChild, textNode = iframeBody.firstChild; // Test whether the native selection will allow a collapsed selection within a non-editable element var r1 = iframeDoc.createRange(); r1.setStart(textNode, 1); r1.collapse(true); sel.addRange(r1); collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1); sel.removeAllRanges(); // Test whether the native selection is capable of supporting multiple ranges var r2 = r1.cloneRange(); r1.setStart(textNode, 0); r2.setEnd(textNode, 2); sel.addRange(r1); sel.addRange(r2); selectionSupportsMultipleRanges = (sel.rangeCount == 2); // Clean up r1.detach(); r2.detach(); body.removeChild(iframe); })(); } api.features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges; api.features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported; // ControlRanges var implementsControlRange = false, testControlRange; if (body && util.isHostMethod(body, "createControlRange")) { testControlRange = body.createControlRange(); if (util.areHostProperties(testControlRange, ["item", "add"])) { implementsControlRange = true; } } api.features.implementsControlRange = implementsControlRange; // Selection collapsedness if (selectionHasAnchorAndFocus) { selectionIsCollapsed = function(sel) { return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset; }; } else { selectionIsCollapsed = function(sel) { return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false; }; } function updateAnchorAndFocusFromRange(sel, range, backwards) { var anchorPrefix = backwards ? "end" : "start", focusPrefix = backwards ? "start" : "end"; sel.anchorNode = range[anchorPrefix + "Container"]; sel.anchorOffset = range[anchorPrefix + "Offset"]; sel.focusNode = range[focusPrefix + "Container"]; sel.focusOffset = range[focusPrefix + "Offset"]; } function updateAnchorAndFocusFromNativeSelection(sel) { var nativeSel = sel.nativeSelection; sel.anchorNode = nativeSel.anchorNode; sel.anchorOffset = nativeSel.anchorOffset; sel.focusNode = nativeSel.focusNode; sel.focusOffset = nativeSel.focusOffset; } function updateEmptySelection(sel) { sel.anchorNode = sel.focusNode = null; sel.anchorOffset = sel.focusOffset = 0; sel.rangeCount = 0; sel.isCollapsed = true; sel._ranges.length = 0; } function getNativeRange(range) { var nativeRange; if (range instanceof DomRange) { nativeRange = range._selectionNativeRange; if (!nativeRange) { nativeRange = api.createNativeRange(dom.getDocument(range.startContainer)); nativeRange.setEnd(range.endContainer, range.endOffset); nativeRange.setStart(range.startContainer, range.startOffset); range._selectionNativeRange = nativeRange; range.attachListener("detach", function() { this._selectionNativeRange = null; }); } } else if (range instanceof WrappedRange) { nativeRange = range.nativeRange; } else if (api.features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) { nativeRange = range; } return nativeRange; } function rangeContainsSingleElement(rangeNodes) { if (!rangeNodes.length || rangeNodes[0].nodeType != 1) { return false; } for (var i = 1, len = rangeNodes.length; i < len; ++i) { if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) { return false; } } return true; } function getSingleElementFromRange(range) { var nodes = range.getNodes(); if (!rangeContainsSingleElement(nodes)) { throw new Error("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element"); } return nodes[0]; } function isTextRange(range) { return !!range && typeof range.text != "undefined"; } function updateFromTextRange(sel, range) { // Create a Range from the selected TextRange var wrappedRange = new WrappedRange(range); sel._ranges = [wrappedRange]; updateAnchorAndFocusFromRange(sel, wrappedRange, false); sel.rangeCount = 1; sel.isCollapsed = wrappedRange.collapsed; } function updateControlSelection(sel) { // Update the wrapped selection based on what's now in the native selection sel._ranges.length = 0; if (sel.docSelection.type == "None") { updateEmptySelection(sel); } else { var controlRange = sel.docSelection.createRange(); if (isTextRange(controlRange)) { // This case (where the selection type is "Control" and calling createRange() on the selection returns // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected // ControlRange have been removed from the ControlRange and removed from the document. updateFromTextRange(sel, controlRange); } else { sel.rangeCount = controlRange.length; var range, doc = dom.getDocument(controlRange.item(0)); for (var i = 0; i < sel.rangeCount; ++i) { range = api.createRange(doc); range.selectNode(controlRange.item(i)); sel._ranges.push(range); } sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed; updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false); } } } function addRangeToControlSelection(sel, range) { var controlRange = sel.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange plus the element // contained by the supplied range var doc = dom.getDocument(controlRange.item(0)); var newControlRange = dom.getBody(doc).createControlRange(); for (var i = 0, len = controlRange.length; i < len; ++i) { newControlRange.add(controlRange.item(i)); } try { newControlRange.add(rangeElement); } catch (ex) { throw new Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)"); } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } var getSelectionRangeAt; if (util.isHostMethod(testSelection, "getRangeAt")) { getSelectionRangeAt = function(sel, index) { try { return sel.getRangeAt(index); } catch(ex) { return null; } }; } else if (selectionHasAnchorAndFocus) { getSelectionRangeAt = function(sel) { var doc = dom.getDocument(sel.anchorNode); var range = api.createRange(doc); range.setStart(sel.anchorNode, sel.anchorOffset); range.setEnd(sel.focusNode, sel.focusOffset); // Handle the case when the selection was selected backwards (from the end to the start in the // document) if (range.collapsed !== this.isCollapsed) { range.setStart(sel.focusNode, sel.focusOffset); range.setEnd(sel.anchorNode, sel.anchorOffset); } return range; }; } /** * @constructor */ function WrappedSelection(selection, docSelection, win) { this.nativeSelection = selection; this.docSelection = docSelection; this._ranges = []; this.win = win; this.refresh(); } api.getSelection = function(win) { win = win || window; var sel = win[windowPropertyName]; var nativeSel = getSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null; if (sel) { sel.nativeSelection = nativeSel; sel.docSelection = docSel; sel.refresh(win); } else { sel = new WrappedSelection(nativeSel, docSel, win); win[windowPropertyName] = sel; } return sel; }; api.getIframeSelection = function(iframeEl) { return api.getSelection(dom.getIframeWindow(iframeEl)); }; var selProto = WrappedSelection.prototype; function createControlSelection(sel, ranges) { // Ensure that the selection becomes of type "Control" var doc = dom.getDocument(ranges[0].startContainer); var controlRange = dom.getBody(doc).createControlRange(); for (var i = 0, el; i < rangeCount; ++i) { el = getSingleElementFromRange(ranges[i]); try { controlRange.add(el); } catch (ex) { throw new Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)"); } } controlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } // Selecting a range if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) { selProto.removeAllRanges = function() { this.nativeSelection.removeAllRanges(); updateEmptySelection(this); }; var addRangeBackwards = function(sel, range) { var doc = DomRange.getRangeDocument(range); var endRange = api.createRange(doc); endRange.collapseToPoint(range.endContainer, range.endOffset); sel.nativeSelection.addRange(getNativeRange(endRange)); sel.nativeSelection.extend(range.startContainer, range.startOffset); sel.refresh(); }; if (selectionHasRangeCount) { selProto.addRange = function(range, backwards) { if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { if (backwards && selectionHasExtend) { addRangeBackwards(this, range); } else { var previousRangeCount; if (selectionSupportsMultipleRanges) { previousRangeCount = this.rangeCount; } else { this.removeAllRanges(); previousRangeCount = 0; } this.nativeSelection.addRange(getNativeRange(range)); // Check whether adding the range was successful this.rangeCount = this.nativeSelection.rangeCount; if (this.rangeCount == previousRangeCount + 1) { // The range was added successfully // Check whether the range that we added to the selection is reflected in the last range extracted from // the selection if (api.config.checkSelectionRanges) { var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1); if (nativeRange && !DomRange.rangesEqual(nativeRange, range)) { // Happens in WebKit with, for example, a selection placed at the start of a text node range = new WrappedRange(nativeRange); } } this._ranges[this.rangeCount - 1] = range; updateAnchorAndFocusFromRange(this, range, selectionIsBackwards(this.nativeSelection)); this.isCollapsed = selectionIsCollapsed(this); } else { // The range was not added successfully. The simplest thing is to refresh this.refresh(); } } } }; } else { selProto.addRange = function(range, backwards) { if (backwards && selectionHasExtend) { addRangeBackwards(this, range); } else { this.nativeSelection.addRange(getNativeRange(range)); this.refresh(); } }; } selProto.setRanges = function(ranges) { if (implementsControlRange && ranges.length > 1) { createControlSelection(this, ranges); } else { this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { this.addRange(ranges[i]); } } }; } else if (util.isHostMethod(testSelection, "empty") && util.isHostMethod(testRange, "select") && implementsControlRange && useDocumentSelection) { selProto.removeAllRanges = function() { // Added try/catch as fix for issue #21 try { this.docSelection.empty(); // Check for empty() not working (issue #24) if (this.docSelection.type != "None") { // Work around failure to empty a control selection by instead selecting a TextRange and then // calling empty() var doc; if (this.anchorNode) { doc = dom.getDocument(this.anchorNode); } else if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); if (controlRange.length) { doc = dom.getDocument(controlRange.item(0)).body.createTextRange(); } } if (doc) { var textRange = doc.body.createTextRange(); textRange.select(); this.docSelection.empty(); } } } catch(ex) {} updateEmptySelection(this); }; selProto.addRange = function(range) { if (this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { WrappedRange.rangeToTextRange(range).select(); this._ranges[0] = range; this.rangeCount = 1; this.isCollapsed = this._ranges[0].collapsed; updateAnchorAndFocusFromRange(this, range, false); } }; selProto.setRanges = function(ranges) { this.removeAllRanges(); var rangeCount = ranges.length; if (rangeCount > 1) { createControlSelection(this, ranges); } else if (rangeCount) { this.addRange(ranges[0]); } }; } else { module.fail("No means of selecting a Range or TextRange was found"); return false; } selProto.getRangeAt = function(index) { if (index < 0 || index >= this.rangeCount) { throw new DOMException("INDEX_SIZE_ERR"); } else { return this._ranges[index]; } }; var refreshSelection; if (useDocumentSelection) { refreshSelection = function(sel) { var range; if (api.isSelectionValid(sel.win)) { range = sel.docSelection.createRange(); } else { range = dom.getBody(sel.win.document).createTextRange(); range.collapse(true); } if (sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else if (isTextRange(range)) { updateFromTextRange(sel, range); } else { updateEmptySelection(sel); } }; } else if (util.isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == "number") { refreshSelection = function(sel) { if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else { sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount; if (sel.rangeCount) { for (var i = 0, len = sel.rangeCount; i < len; ++i) { sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i)); } updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackwards(sel.nativeSelection)); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } } }; } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && api.features.implementsDomRange) { refreshSelection = function(sel) { var range, nativeSel = sel.nativeSelection; if (nativeSel.anchorNode) { range = getSelectionRangeAt(nativeSel, 0); sel._ranges = [range]; sel.rangeCount = 1; updateAnchorAndFocusFromNativeSelection(sel); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } }; } else { module.fail("No means of obtaining a Range or TextRange from the user's selection was found"); return false; } selProto.refresh = function(checkForChanges) { var oldRanges = checkForChanges ? this._ranges.slice(0) : null; refreshSelection(this); if (checkForChanges) { var i = oldRanges.length; if (i != this._ranges.length) { return false; } while (i--) { if (!DomRange.rangesEqual(oldRanges[i], this._ranges[i])) { return false; } } return true; } }; // Removal of a single range var removeRangeManually = function(sel, range) { var ranges = sel.getAllRanges(), removed = false; sel.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { if (removed || range !== ranges[i]) { sel.addRange(ranges[i]); } else { // According to the draft WHATWG Range spec, the same range may be added to the selection multiple // times. removeRange should only remove the first instance, so the following ensures only the first // instance is removed removed = true; } } if (!sel.rangeCount) { updateEmptySelection(sel); } }; if (implementsControlRange) { selProto.removeRange = function(range) { if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange minus the // element contained by the supplied range var doc = dom.getDocument(controlRange.item(0)); var newControlRange = dom.getBody(doc).createControlRange(); var el, removed = false; for (var i = 0, len = controlRange.length; i < len; ++i) { el = controlRange.item(i); if (el !== rangeElement || removed) { newControlRange.add(controlRange.item(i)); } else { removed = true; } } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(this); } else { removeRangeManually(this, range); } }; } else { selProto.removeRange = function(range) { removeRangeManually(this, range); }; } // Detecting if a selection is backwards var selectionIsBackwards; if (!useDocumentSelection && selectionHasAnchorAndFocus && api.features.implementsDomRange) { selectionIsBackwards = function(sel) { var backwards = false; if (sel.anchorNode) { backwards = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1); } return backwards; }; selProto.isBackwards = function() { return selectionIsBackwards(this); }; } else { selectionIsBackwards = selProto.isBackwards = function() { return false; }; } // Selection text // This is conformant to the new WHATWG DOM Range draft spec but differs from WebKit and Mozilla's implementation selProto.toString = function() { var rangeTexts = []; for (var i = 0, len = this.rangeCount; i < len; ++i) { rangeTexts[i] = "" + this._ranges[i]; } return rangeTexts.join(""); }; function assertNodeInSameDocument(sel, node) { if (sel.anchorNode && (dom.getDocument(sel.anchorNode) !== dom.getDocument(node))) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } // No current browsers conform fully to the HTML 5 draft spec for this method, so Rangy's own method is always used selProto.collapse = function(node, offset) { assertNodeInSameDocument(this, node); var range = api.createRange(dom.getDocument(node)); range.collapseToPoint(node, offset); this.removeAllRanges(); this.addRange(range); this.isCollapsed = true; }; selProto.collapseToStart = function() { if (this.rangeCount) { var range = this._ranges[0]; this.collapse(range.startContainer, range.startOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; selProto.collapseToEnd = function() { if (this.rangeCount) { var range = this._ranges[this.rangeCount - 1]; this.collapse(range.endContainer, range.endOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; // The HTML 5 spec is very specific on how selectAllChildren should be implemented so the native implementation is // never used by Rangy. selProto.selectAllChildren = function(node) { assertNodeInSameDocument(this, node); var range = api.createRange(dom.getDocument(node)); range.selectNodeContents(node); this.removeAllRanges(); this.addRange(range); }; selProto.deleteFromDocument = function() { // Sepcial behaviour required for Control selections if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var element; while (controlRange.length) { element = controlRange.item(0); controlRange.remove(element); element.parentNode.removeChild(element); } this.refresh(); } else if (this.rangeCount) { var ranges = this.getAllRanges(); this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { ranges[i].deleteContents(); } // The HTML5 spec says nothing about what the selection should contain after calling deleteContents on each // range. Firefox moves the selection to where the final selected range was, so we emulate that this.addRange(ranges[len - 1]); } }; // The following are non-standard extensions selProto.getAllRanges = function() { return this._ranges.slice(0); }; selProto.setSingleRange = function(range) { this.setRanges( [range] ); }; selProto.containsNode = function(node, allowPartial) { for (var i = 0, len = this._ranges.length; i < len; ++i) { if (this._ranges[i].containsNode(node, allowPartial)) { return true; } } return false; }; selProto.toHtml = function() { var html = ""; if (this.rangeCount) { var container = DomRange.getRangeDocument(this._ranges[0]).createElement("div"); for (var i = 0, len = this._ranges.length; i < len; ++i) { container.appendChild(this._ranges[i].cloneContents()); } html = container.innerHTML; } return html; }; function inspect(sel) { var rangeInspects = []; var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset); var focus = new DomPosition(sel.focusNode, sel.focusOffset); var name = (typeof sel.getName == "function") ? sel.getName() : "Selection"; if (typeof sel.rangeCount != "undefined") { for (var i = 0, len = sel.rangeCount; i < len; ++i) { rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i)); } } return "[" + name + "(Ranges: " + rangeInspects.join(", ") + ")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]"; } selProto.getName = function() { return "WrappedSelection"; }; selProto.inspect = function() { return inspect(this); }; selProto.detach = function() { this.win[windowPropertyName] = null; this.win = this.anchorNode = this.focusNode = null; }; WrappedSelection.inspect = inspect; api.Selection = WrappedSelection; api.selectionPrototype = selProto; api.addCreateMissingNativeApiListener(function(win) { if (typeof win.getSelection == "undefined") { win.getSelection = function() { return api.getSelection(this); }; } win = null; }); }); /* Base.js, version 1.1a Copyright 2006-2010, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ var Base = function() { // dummy }; Base.extend = function(_instance, _static) { // subclass var extend = Base.prototype.extend; // build the prototype Base._prototyping = true; var proto = new this; extend.call(proto, _instance); proto.base = function() { // call this method from any other method to invoke that method's ancestor }; delete Base._prototyping; // create the wrapper for the constructor function //var constructor = proto.constructor.valueOf(); //-dean var constructor = proto.constructor; var klass = proto.constructor = function() { if (!Base._prototyping) { if (this._constructing || this.constructor == klass) { // instantiation this._constructing = true; constructor.apply(this, arguments); delete this._constructing; } else if (arguments[0] != null) { // casting return (arguments[0].extend || extend).call(arguments[0], proto); } } }; // build the class interface klass.ancestor = this; klass.extend = this.extend; klass.forEach = this.forEach; klass.implement = this.implement; klass.prototype = proto; klass.toString = this.toString; klass.valueOf = function(type) { //return (type == "object") ? klass : constructor; //-dean return (type == "object") ? klass : constructor.valueOf(); }; extend.call(klass, _static); // class initialisation if (typeof klass.init == "function") klass.init(); return klass; }; Base.prototype = { extend: function(source, value) { if (arguments.length > 1) { // extending with a name/value pair var ancestor = this[source]; if (ancestor && (typeof value == "function") && // overriding a method? // the valueOf() comparison is to avoid circular references (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) && /\bbase\b/.test(value)) { // get the underlying method var method = value.valueOf(); // override value = function() { var previous = this.base || Base.prototype.base; this.base = ancestor; var returnValue = method.apply(this, arguments); this.base = previous; return returnValue; }; // point to the underlying method value.valueOf = function(type) { return (type == "object") ? value : method; }; value.toString = Base.toString; } this[source] = value; } else if (source) { // extending with an object literal var extend = Base.prototype.extend; // if this object has a customised extend method then use it if (!Base._prototyping && typeof this != "function") { extend = this.extend || extend; } var proto = {toSource: null}; // do the "toString" and other methods manually var hidden = ["constructor", "toString", "valueOf"]; // if we are prototyping then include the constructor var i = Base._prototyping ? 0 : 1; while (key = hidden[i++]) { if (source[key] != proto[key]) { extend.call(this, key, source[key]); } } // copy each of the source object's properties to this object for (var key in source) { if (!proto[key]) extend.call(this, key, source[key]); } } return this; } }; // initialise Base = Base.extend({ constructor: function() { this.extend(arguments[0]); } }, { ancestor: Object, version: "1.1", forEach: function(object, block, context) { for (var key in object) { if (this.prototype[key] === undefined) { block.call(context, object[key], key, object); } } }, implement: function() { for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] == "function") { // if it's a function, call it arguments[i](this.prototype); } else { // add the interface using the extend method this.prototype.extend(arguments[i]); } } return this; }, toString: function() { return String(this.valueOf()); } });/** * Detect browser support for specific features */ wysihtml5.browser = (function() { var userAgent = navigator.userAgent, testElement = document.createElement("div"), // Browser sniffing is unfortunately needed since some behaviors are impossible to feature detect isIE = userAgent.indexOf("MSIE") !== -1 && userAgent.indexOf("Opera") === -1, isGecko = userAgent.indexOf("Gecko") !== -1 && userAgent.indexOf("KHTML") === -1, isWebKit = userAgent.indexOf("AppleWebKit/") !== -1, isChrome = userAgent.indexOf("Chrome/") !== -1, isOpera = userAgent.indexOf("Opera/") !== -1; function iosVersion(userAgent) { return ((/ipad|iphone|ipod/.test(userAgent) && userAgent.match(/ os (\d+).+? like mac os x/)) || [, 0])[1]; } return { // Static variable needed, publicly accessible, to be able override it in unit tests USER_AGENT: userAgent, /** * Exclude browsers that are not capable of displaying and handling * contentEditable as desired: * - iPhone, iPad (tested iOS 4.2.2) and Android (tested 2.2) refuse to make contentEditables focusable * - IE < 8 create invalid markup and crash randomly from time to time * * @return {Boolean} */ supported: function() { var userAgent = this.USER_AGENT.toLowerCase(), // Essential for making html elements editable hasContentEditableSupport = "contentEditable" in testElement, // Following methods are needed in order to interact with the contentEditable area hasEditingApiSupport = document.execCommand && document.queryCommandSupported && document.queryCommandState, // document selector apis are only supported by IE 8+, Safari 4+, Chrome and Firefox 3.5+ hasQuerySelectorSupport = document.querySelector && document.querySelectorAll, // contentEditable is unusable in mobile browsers (tested iOS 4.2.2, Android 2.2, Opera Mobile, WebOS 3.05) isIncompatibleMobileBrowser = (this.isIos() && iosVersion(userAgent) < 5) || userAgent.indexOf("opera mobi") !== -1 || userAgent.indexOf("hpwos/") !== -1; return hasContentEditableSupport && hasEditingApiSupport && hasQuerySelectorSupport && !isIncompatibleMobileBrowser; }, isTouchDevice: function() { return this.supportsEvent("touchmove"); }, isIos: function() { var userAgent = this.USER_AGENT.toLowerCase(); return userAgent.indexOf("webkit") !== -1 && userAgent.indexOf("mobile") !== -1; }, /** * Whether the browser supports sandboxed iframes * Currently only IE 6+ offers such feature <iframe security="restricted"> * * http://msdn.microsoft.com/en-us/library/ms534622(v=vs.85).aspx * http://blogs.msdn.com/b/ie/archive/2008/01/18/using-frames-more-securely.aspx * * HTML5 sandboxed iframes are still buggy and their DOM is not reachable from the outside (except when using postMessage) */ supportsSandboxedIframes: function() { return isIE; }, /** * IE6+7 throw a mixed content warning when the src of an iframe * is empty/unset or about:blank * window.querySelector is implemented as of IE8 */ throwsMixedContentWarningWhenIframeSrcIsEmpty: function() { return !("querySelector" in document); }, /** * Whether the caret is correctly displayed in contentEditable elements * Firefox sometimes shows a huge caret in the beginning after focusing */ displaysCaretInEmptyContentEditableCorrectly: function() { return !isGecko; }, /** * Opera and IE are the only browsers who offer the css value * in the original unit, thx to the currentStyle object * All other browsers provide the computed style in px via window.getComputedStyle */ hasCurrentStyleProperty: function() { return "currentStyle" in testElement; }, /** * Whether the browser inserts a <br> when pressing enter in a contentEditable element */ insertsLineBreaksOnReturn: function() { return isGecko; }, supportsPlaceholderAttributeOn: function(element) { return "placeholder" in element; }, supportsEvent: function(eventName) { return "on" + eventName in testElement || (function() { testElement.setAttribute("on" + eventName, "return;"); return typeof(testElement["on" + eventName]) === "function"; })(); }, /** * Opera doesn't correctly fire focus/blur events when clicking in- and outside of iframe */ supportsEventsInIframeCorrectly: function() { return !isOpera; }, /** * Chrome & Safari only fire the ondrop/ondragend/... events when the ondragover event is cancelled * with event.preventDefault * Firefox 3.6 fires those events anyway, but the mozilla doc says that the dragover/dragenter event needs * to be cancelled */ firesOnDropOnlyWhenOnDragOverIsCancelled: function() { return isWebKit || isGecko; }, /** * Whether the browser supports the event.dataTransfer property in a proper way */ supportsDataTransfer: function() { try { // Firefox doesn't support dataTransfer in a safe way, it doesn't strip script code in the html payload (like Chrome does) return isWebKit && (window.Clipboard || window.DataTransfer).prototype.getData; } catch(e) { return false; } }, /** * Everything below IE9 doesn't know how to treat HTML5 tags * * @param {Object} context The document object on which to check HTML5 support * * @example * wysihtml5.browser.supportsHTML5Tags(document); */ supportsHTML5Tags: function(context) { var element = context.createElement("div"), html5 = "<article>foo</article>"; element.innerHTML = html5; return element.innerHTML.toLowerCase() === html5; }, /** * Checks whether a document supports a certain queryCommand * In particular, Opera needs a reference to a document that has a contentEditable in it's dom tree * in oder to report correct results * * @param {Object} doc Document object on which to check for a query command * @param {String} command The query command to check for * @return {Boolean} * * @example * wysihtml5.browser.supportsCommand(document, "bold"); */ supportsCommand: (function() { // Following commands are supported but contain bugs in some browsers var buggyCommands = { // formatBlock fails with some tags (eg. <blockquote>) "formatBlock": isIE, // When inserting unordered or ordered lists in Firefox, Chrome or Safari, the current selection or line gets // converted into a list (<ul><li>...</li></ul>, <ol><li>...</li></ol>) // IE and Opera act a bit different here as they convert the entire content of the current block element into a list "insertUnorderedList": isIE || isOpera || isWebKit, "insertOrderedList": isIE || isOpera || isWebKit }; // Firefox throws errors for queryCommandSupported, so we have to build up our own object of supported commands var supported = { "insertHTML": isGecko }; return function(doc, command) { var isBuggy = buggyCommands[command]; if (!isBuggy) { // Firefox throws errors when invoking queryCommandSupported or queryCommandEnabled try { return doc.queryCommandSupported(command); } catch(e1) {} try { return doc.queryCommandEnabled(command); } catch(e2) { return !!supported[command]; } } return false; }; })(), /** * IE: URLs starting with: * www., http://, https://, ftp://, gopher://, mailto:, new:, snews:, telnet:, wasis:, file://, * nntp://, newsrc:, ldap://, ldaps://, outlook:, mic:// and url: * will automatically be auto-linked when either the user inserts them via copy&paste or presses the * space bar when the caret is directly after such an url. * This behavior cannot easily be avoided in IE < 9 since the logic is hardcoded in the mshtml.dll * (related blog post on msdn * http://blogs.msdn.com/b/ieinternals/archive/2009/09/17/prevent-automatic-hyperlinking-in-contenteditable-html.aspx). */ doesAutoLinkingInContentEditable: function() { return isIE; }, /** * As stated above, IE auto links urls typed into contentEditable elements * Since IE9 it's possible to prevent this behavior */ canDisableAutoLinking: function() { return this.supportsCommand(document, "AutoUrlDetect"); }, /** * IE leaves an empty paragraph in the contentEditable element after clearing it * Chrome/Safari sometimes an empty <div> */ clearsContentEditableCorrectly: function() { return isGecko || isOpera || isWebKit; }, /** * IE gives wrong results for getAttribute */ supportsGetAttributeCorrectly: function() { var td = document.createElement("td"); return td.getAttribute("rowspan") != "1"; }, /** * When clicking on images in IE, Opera and Firefox, they are selected, which makes it easy to interact with them. * Chrome and Safari both don't support this */ canSelectImagesInContentEditable: function() { return isGecko || isIE || isOpera; }, /** * When the caret is in an empty list (<ul><li>|</li></ul>) which is the first child in an contentEditable container * pressing backspace doesn't remove the entire list as done in other browsers */ clearsListsInContentEditableCorrectly: function() { return isGecko || isIE || isWebKit; }, /** * All browsers except Safari and Chrome automatically scroll the range/caret position into view */ autoScrollsToCaret: function() { return !isWebKit; }, /** * Check whether the browser automatically closes tags that don't need to be opened */ autoClosesUnclosedTags: function() { var clonedTestElement = testElement.cloneNode(false), returnValue, innerHTML; clonedTestElement.innerHTML = "<p><div></div>"; innerHTML = clonedTestElement.innerHTML.toLowerCase(); returnValue = innerHTML === "<p></p><div></div>" || innerHTML === "<p><div></div></p>"; // Cache result by overwriting current function this.autoClosesUnclosedTags = function() { return returnValue; }; return returnValue; }, /** * Whether the browser supports the native document.getElementsByClassName which returns live NodeLists */ supportsNativeGetElementsByClassName: function() { return String(document.getElementsByClassName).indexOf("[native code]") !== -1; }, /** * As of now (19.04.2011) only supported by Firefox 4 and Chrome * See https://developer.mozilla.org/en/DOM/Selection/modify */ supportsSelectionModify: function() { return "getSelection" in window && "modify" in window.getSelection(); }, /** * Whether the browser supports the classList object for fast className manipulation * See https://developer.mozilla.org/en/DOM/element.classList */ supportsClassList: function() { return "classList" in testElement; }, /** * Opera needs a white space after a <br> in order to position the caret correctly */ needsSpaceAfterLineBreak: function() { return isOpera; }, /** * Whether the browser supports the speech api on the given element * See http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ * * @example * var input = document.createElement("input"); * if (wysihtml5.browser.supportsSpeechApiOn(input)) { * // ... * } */ supportsSpeechApiOn: function(input) { var chromeVersion = userAgent.match(/Chrome\/(\d+)/) || [, 0]; return chromeVersion[1] >= 11 && ("onwebkitspeechchange" in input || "speech" in input); }, /** * IE9 crashes when setting a getter via Object.defineProperty on XMLHttpRequest or XDomainRequest * See https://connect.microsoft.com/ie/feedback/details/650112 * or try the POC http://tifftiff.de/ie9_crash/ */ crashesWhenDefineProperty: function(property) { return isIE && (property === "XMLHttpRequest" || property === "XDomainRequest"); }, /** * IE is the only browser who fires the "focus" event not immediately when .focus() is called on an element */ doesAsyncFocus: function() { return isIE; }, /** * In IE it's impssible for the user and for the selection library to set the caret after an <img> when it's the lastChild in the document */ hasProblemsSettingCaretAfterImg: function() { return isIE; }, hasUndoInContextMenu: function() { return isGecko || isChrome || isOpera; } }; })();wysihtml5.lang.array = function(arr) { return { /** * Check whether a given object exists in an array * * @example * wysihtml5.lang.array([1, 2]).contains(1); * // => true */ contains: function(needle) { if (arr.indexOf) { return arr.indexOf(needle) !== -1; } else { for (var i=0, length=arr.length; i<length; i++) { if (arr[i] === needle) { return true; } } return false; } }, /** * Substract one array from another * * @example * wysihtml5.lang.array([1, 2, 3, 4]).without([3, 4]); * // => [1, 2] */ without: function(arrayToSubstract) { arrayToSubstract = wysihtml5.lang.array(arrayToSubstract); var newArr = [], i = 0, length = arr.length; for (; i<length; i++) { if (!arrayToSubstract.contains(arr[i])) { newArr.push(arr[i]); } } return newArr; }, /** * Return a clean native array * * Following will convert a Live NodeList to a proper Array * @example * var childNodes = wysihtml5.lang.array(document.body.childNodes).get(); */ get: function() { var i = 0, length = arr.length, newArray = []; for (; i<length; i++) { newArray.push(arr[i]); } return newArray; } }; };wysihtml5.lang.Dispatcher = Base.extend( /** @scope wysihtml5.lang.Dialog.prototype */ { observe: function(eventName, handler) { this.events = this.events || {}; this.events[eventName] = this.events[eventName] || []; this.events[eventName].push(handler); return this; }, on: function() { return this.observe.apply(this, wysihtml5.lang.array(arguments).get()); }, fire: function(eventName, payload) { this.events = this.events || {}; var handlers = this.events[eventName] || [], i = 0; for (; i<handlers.length; i++) { handlers[i].call(this, payload); } return this; }, stopObserving: function(eventName, handler) { this.events = this.events || {}; var i = 0, handlers, newHandlers; if (eventName) { handlers = this.events[eventName] || [], newHandlers = []; for (; i<handlers.length; i++) { if (handlers[i] !== handler && handler) { newHandlers.push(handlers[i]); } } this.events[eventName] = newHandlers; } else { // Clean up all events this.events = {}; } return this; } });wysihtml5.lang.object = function(obj) { return { /** * @example * wysihtml5.lang.object({ foo: 1, bar: 1 }).merge({ bar: 2, baz: 3 }).get(); * // => { foo: 1, bar: 2, baz: 3 } */ merge: function(otherObj) { for (var i in otherObj) { obj[i] = otherObj[i]; } return this; }, get: function() { return obj; }, /** * @example * wysihtml5.lang.object({ foo: 1 }).clone(); * // => { foo: 1 } */ clone: function() { var newObj = {}, i; for (i in obj) { newObj[i] = obj[i]; } return newObj; }, /** * @example * wysihtml5.lang.object([]).isArray(); * // => true */ isArray: function() { return Object.prototype.toString.call(obj) === "[object Array]"; } }; };(function() { var WHITE_SPACE_START = /^\s+/, WHITE_SPACE_END = /\s+$/; wysihtml5.lang.string = function(str) { str = String(str); return { /** * @example * wysihtml5.lang.string(" foo ").trim(); * // => "foo" */ trim: function() { return str.replace(WHITE_SPACE_START, "").replace(WHITE_SPACE_END, ""); }, /** * @example * wysihtml5.lang.string("Hello #{name}").interpolate({ name: "Christopher" }); * // => "Hello Christopher" */ interpolate: function(vars) { for (var i in vars) { str = this.replace("#{" + i + "}").by(vars[i]); } return str; }, /** * @example * wysihtml5.lang.string("Hello Tom").replace("Tom").with("Hans"); * // => "Hello Hans" */ replace: function(search) { return { by: function(replace) { return str.split(search).join(replace); } } } }; }; })();/** * Find urls in descendant text nodes of an element and auto-links them * Inspired by http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ * * @param {Element} element Container element in which to search for urls * * @example * <div id="text-container">Please click here: www.google.com</div> * <script>wysihtml5.dom.autoLink(document.getElementById("text-container"));</script> */ (function(wysihtml5) { var /** * Don't auto-link urls that are contained in the following elements: */ IGNORE_URLS_IN = wysihtml5.lang.array(["CODE", "PRE", "A", "SCRIPT", "HEAD", "TITLE", "STYLE"]), /** * revision 1: * /(\S+\.{1}[^\s\,\.\!]+)/g * * revision 2: * /(\b(((https?|ftp):\/\/)|(www\.))[-A-Z0-9+&@#\/%?=~_|!:,.;\[\]]*[-A-Z0-9+&@#\/%=~_|])/gim * * put this in the beginning if you don't wan't to match within a word * (^|[\>\(\{\[\s\>]) */ URL_REG_EXP = /((https?:\/\/|www\.)[^\s<]{3,})/gi, TRAILING_CHAR_REG_EXP = /([^\w\/\-](,?))$/i, MAX_DISPLAY_LENGTH = 100, BRACKETS = { ")": "(", "]": "[", "}": "{" }; function autoLink(element) { if (_hasParentThatShouldBeIgnored(element)) { return element; } if (element === element.ownerDocument.documentElement) { element = element.ownerDocument.body; } return _parseNode(element); } /** * This is basically a rebuild of * the rails auto_link_urls text helper */ function _convertUrlsToLinks(str) { return str.replace(URL_REG_EXP, function(match, url) { var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "", opening = BRACKETS[punctuation]; url = url.replace(TRAILING_CHAR_REG_EXP, ""); if (url.split(opening).length > url.split(punctuation).length) { url = url + punctuation; punctuation = ""; } var realUrl = url, displayUrl = url; if (url.length > MAX_DISPLAY_LENGTH) { displayUrl = displayUrl.substr(0, MAX_DISPLAY_LENGTH) + "..."; } // Add http prefix if necessary if (realUrl.substr(0, 4) === "www.") { realUrl = "http://" + realUrl; } return '<a href="' + realUrl + '">' + displayUrl + '</a>' + punctuation; }); } /** * Creates or (if already cached) returns a temp element * for the given document object */ function _getTempElement(context) { var tempElement = context._wysihtml5_tempElement; if (!tempElement) { tempElement = context._wysihtml5_tempElement = context.createElement("div"); } return tempElement; } /** * Replaces the original text nodes with the newly auto-linked dom tree */ function _wrapMatchesInNode(textNode) { var parentNode = textNode.parentNode, tempElement = _getTempElement(parentNode.ownerDocument); // We need to insert an empty/temporary <span /> to fix IE quirks // Elsewise IE would strip white space in the beginning tempElement.innerHTML = "<span></span>" + _convertUrlsToLinks(textNode.data); tempElement.removeChild(tempElement.firstChild); while (tempElement.firstChild) { // inserts tempElement.firstChild before textNode parentNode.insertBefore(tempElement.firstChild, textNode); } parentNode.removeChild(textNode); } function _hasParentThatShouldBeIgnored(node) { var nodeName; while (node.parentNode) { node = node.parentNode; nodeName = node.nodeName; if (IGNORE_URLS_IN.contains(nodeName)) { return true; } else if (nodeName === "body") { return false; } } return false; } function _parseNode(element) { if (IGNORE_URLS_IN.contains(element.nodeName)) { return; } if (element.nodeType === wysihtml5.TEXT_NODE && element.data.match(URL_REG_EXP)) { _wrapMatchesInNode(element); return; } var childNodes = wysihtml5.lang.array(element.childNodes).get(), childNodesLength = childNodes.length, i = 0; for (; i<childNodesLength; i++) { _parseNode(childNodes[i]); } return element; } wysihtml5.dom.autoLink = autoLink; // Reveal url reg exp to the outside wysihtml5.dom.autoLink.URL_REG_EXP = URL_REG_EXP; })(wysihtml5);(function(wysihtml5) { var supportsClassList = wysihtml5.browser.supportsClassList(), api = wysihtml5.dom; api.addClass = function(element, className) { if (supportsClassList) { return element.classList.add(className); } if (api.hasClass(element, className)) { return; } element.className += " " + className; }; api.removeClass = function(element, className) { if (supportsClassList) { return element.classList.remove(className); } element.className = element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " "); }; api.hasClass = function(element, className) { if (supportsClassList) { return element.classList.contains(className); } var elementClassName = element.className; return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); }; })(wysihtml5); wysihtml5.dom.contains = (function() { var documentElement = document.documentElement; if (documentElement.contains) { return function(container, element) { if (element.nodeType !== wysihtml5.ELEMENT_NODE) { element = element.parentNode; } return container !== element && container.contains(element); }; } else if (documentElement.compareDocumentPosition) { return function(container, element) { // https://developer.mozilla.org/en/DOM/Node.compareDocumentPosition return !!(container.compareDocumentPosition(element) & 16); }; } })();/** * Converts an HTML fragment/element into a unordered/ordered list * * @param {Element} element The element which should be turned into a list * @param {String} listType The list type in which to convert the tree (either "ul" or "ol") * @return {Element} The created list * * @example * <!-- Assume the following dom: --> * <span id="pseudo-list"> * eminem<br> * dr. dre * <div>50 Cent</div> * </span> * * <script> * wysihtml5.dom.convertToList(document.getElementById("pseudo-list"), "ul"); * </script> * * <!-- Will result in: --> * <ul> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> */ wysihtml5.dom.convertToList = (function() { function _createListItem(doc, list) { var listItem = doc.createElement("li"); list.appendChild(listItem); return listItem; } function _createList(doc, type) { return doc.createElement(type); } function convertToList(element, listType) { if (element.nodeName === "UL" || element.nodeName === "OL" || element.nodeName === "MENU") { // Already a list return element; } var doc = element.ownerDocument, list = _createList(doc, listType), lineBreaks = element.querySelectorAll("br"), lineBreaksLength = lineBreaks.length, childNodes, childNodesLength, childNode, lineBreak, parentNode, isBlockElement, isLineBreak, currentListItem, i; // First find <br> at the end of inline elements and move them behind them for (i=0; i<lineBreaksLength; i++) { lineBreak = lineBreaks[i]; while ((parentNode = lineBreak.parentNode) && parentNode !== element && parentNode.lastChild === lineBreak) { if (wysihtml5.dom.getStyle("display").from(parentNode) === "block") { parentNode.removeChild(lineBreak); break; } wysihtml5.dom.insert(lineBreak).after(lineBreak.parentNode); } } childNodes = wysihtml5.lang.array(element.childNodes).get(); childNodesLength = childNodes.length; for (i=0; i<childNodesLength; i++) { currentListItem = currentListItem || _createListItem(doc, list); childNode = childNodes[i]; isBlockElement = wysihtml5.dom.getStyle("display").from(childNode) === "block"; isLineBreak = childNode.nodeName === "BR"; if (isBlockElement) { // Append blockElement to current <li> if empty, otherwise create a new one currentListItem = currentListItem.firstChild ? _createListItem(doc, list) : currentListItem; currentListItem.appendChild(childNode); currentListItem = null; continue; } if (isLineBreak) { // Only create a new list item in the next iteration when the current one has already content currentListItem = currentListItem.firstChild ? null : currentListItem; continue; } currentListItem.appendChild(childNode); } element.parentNode.replaceChild(list, element); return list; } return convertToList; })();/** * Copy a set of attributes from one element to another * * @param {Array} attributesToCopy List of attributes which should be copied * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to * copy the attributes from., this again returns an object which provides a method named "to" which can be invoked * with the element where to copy the attributes to (see example) * * @example * var textarea = document.querySelector("textarea"), * div = document.querySelector("div[contenteditable=true]"), * anotherDiv = document.querySelector("div.preview"); * wysihtml5.dom.copyAttributes(["spellcheck", "value", "placeholder"]).from(textarea).to(div).andTo(anotherDiv); * */ wysihtml5.dom.copyAttributes = function(attributesToCopy) { return { from: function(elementToCopyFrom) { return { to: function(elementToCopyTo) { var attribute, i = 0, length = attributesToCopy.length; for (; i<length; i++) { attribute = attributesToCopy[i]; if (typeof(elementToCopyFrom[attribute]) !== "undefined" && elementToCopyFrom[attribute] !== "") { elementToCopyTo[attribute] = elementToCopyFrom[attribute]; } } return { andTo: arguments.callee }; } }; } }; };/** * Copy a set of styles from one element to another * Please note that this only works properly across browsers when the element from which to copy the styles * is in the dom * * Interesting article on how to copy styles * * @param {Array} stylesToCopy List of styles which should be copied * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to * copy the styles from., this again returns an object which provides a method named "to" which can be invoked * with the element where to copy the styles to (see example) * * @example * var textarea = document.querySelector("textarea"), * div = document.querySelector("div[contenteditable=true]"), * anotherDiv = document.querySelector("div.preview"); * wysihtml5.dom.copyStyles(["overflow-y", "width", "height"]).from(textarea).to(div).andTo(anotherDiv); * */ (function(dom) { /** * Mozilla, WebKit and Opera recalculate the computed width when box-sizing: boder-box; is set * So if an element has "width: 200px; -moz-box-sizing: border-box; border: 1px;" then * its computed css width will be 198px */ var BOX_SIZING_PROPERTIES = ["-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing"]; var shouldIgnoreBoxSizingBorderBox = function(element) { if (hasBoxSizingBorderBox(element)) { return parseInt(dom.getStyle("width").from(element), 10) < element.offsetWidth; } return false; }; var hasBoxSizingBorderBox = function(element) { var i = 0, length = BOX_SIZING_PROPERTIES.length; for (; i<length; i++) { if (dom.getStyle(BOX_SIZING_PROPERTIES[i]).from(element) === "border-box") { return BOX_SIZING_PROPERTIES[i]; } } }; dom.copyStyles = function(stylesToCopy) { return { from: function(element) { if (shouldIgnoreBoxSizingBorderBox(element)) { stylesToCopy = wysihtml5.lang.array(stylesToCopy).without(BOX_SIZING_PROPERTIES); } var cssText = "", length = stylesToCopy.length, i = 0, property; for (; i<length; i++) { property = stylesToCopy[i]; cssText += property + ":" + dom.getStyle(property).from(element) + ";"; } return { to: function(element) { dom.setStyles(cssText).on(element); return { andTo: arguments.callee }; } }; } }; }; })(wysihtml5.dom);/** * Event Delegation * * @example * wysihtml5.dom.delegate(document.body, "a", "click", function() { * // foo * }); */ (function(wysihtml5) { wysihtml5.dom.delegate = function(container, selector, eventName, handler) { return wysihtml5.dom.observe(container, eventName, function(event) { var target = event.target, match = wysihtml5.lang.array(container.querySelectorAll(selector)); while (target && target !== container) { if (match.contains(target)) { handler.call(target, event); break; } target = target.parentNode; } }); }; })(wysihtml5);/** * Returns the given html wrapped in a div element * * Fixing IE's inability to treat unknown elements (HTML5 section, article, ...) correctly * when inserted via innerHTML * * @param {String} html The html which should be wrapped in a dom element * @param {Obejct} [context] Document object of the context the html belongs to * * @example * wysihtml5.dom.getAsDom("<article>foo</article>"); */ wysihtml5.dom.getAsDom = (function() { var _innerHTMLShiv = function(html, context) { var tempElement = context.createElement("div"); tempElement.style.display = "none"; context.body.appendChild(tempElement); // IE throws an exception when trying to insert <frameset></frameset> via innerHTML try { tempElement.innerHTML = html; } catch(e) {} context.body.removeChild(tempElement); return tempElement; }; /** * Make sure IE supports HTML5 tags, which is accomplished by simply creating one instance of each element */ var _ensureHTML5Compatibility = function(context) { if (context._wysihtml5_supportsHTML5Tags) { return; } for (var i=0, length=HTML5_ELEMENTS.length; i<length; i++) { context.createElement(HTML5_ELEMENTS[i]); } context._wysihtml5_supportsHTML5Tags = true; }; /** * List of html5 tags * taken from http://simon.html5.org/html5-elements */ var HTML5_ELEMENTS = [ "abbr", "article", "aside", "audio", "bdi", "canvas", "command", "datalist", "details", "figcaption", "figure", "footer", "header", "hgroup", "keygen", "mark", "meter", "nav", "output", "progress", "rp", "rt", "ruby", "svg", "section", "source", "summary", "time", "track", "video", "wbr" ]; return function(html, context) { context = context || document; var tempElement; if (typeof(html) === "object" && html.nodeType) { tempElement = context.createElement("div"); tempElement.appendChild(html); } else if (wysihtml5.browser.supportsHTML5Tags(context)) { tempElement = context.createElement("div"); tempElement.innerHTML = html; } else { _ensureHTML5Compatibility(context); tempElement = _innerHTMLShiv(html, context); } return tempElement; }; })();/** * Walks the dom tree from the given node up until it finds a match * Designed for optimal performance. * * @param {Element} node The from which to check the parent nodes * @param {Object} matchingSet Object to match against (possible properties: nodeName, className, classRegExp) * @param {Number} [levels] How many parents should the function check up from the current node (defaults to 50) * @return {null|Element} Returns the first element that matched the desiredNodeName(s) * @example * var listElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: ["MENU", "UL", "OL"] }); * // ... or ... * var unorderedListElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: "UL" }); * // ... or ... * var coloredElement = wysihtml5.dom.getParentElement(myTextNode, { nodeName: "SPAN", className: "wysiwyg-color-red", classRegExp: /wysiwyg-color-[a-z]/g }); */ wysihtml5.dom.getParentElement = (function() { function _isSameNodeName(nodeName, desiredNodeNames) { if (!desiredNodeNames || !desiredNodeNames.length) { return true; } if (typeof(desiredNodeNames) === "string") { return nodeName === desiredNodeNames; } else { return wysihtml5.lang.array(desiredNodeNames).contains(nodeName); } } function _isElement(node) { return node.nodeType === wysihtml5.ELEMENT_NODE; } function _hasClassName(element, className, classRegExp) { var classNames = (element.className || "").match(classRegExp) || []; if (!className) { return !!classNames.length; } return classNames[classNames.length - 1] === className; } function _getParentElementWithNodeName(node, nodeName, levels) { while (levels-- && node && node.nodeName !== "BODY") { if (_isSameNodeName(node.nodeName, nodeName)) { return node; } node = node.parentNode; } return null; } function _getParentElementWithNodeNameAndClassName(node, nodeName, className, classRegExp, levels) { while (levels-- && node && node.nodeName !== "BODY") { if (_isElement(node) && _isSameNodeName(node.nodeName, nodeName) && _hasClassName(node, className, classRegExp)) { return node; } node = node.parentNode; } return null; } return function(node, matchingSet, levels) { levels = levels || 50; // Go max 50 nodes upwards from current node if (matchingSet.className || matchingSet.classRegExp) { return _getParentElementWithNodeNameAndClassName( node, matchingSet.nodeName, matchingSet.className, matchingSet.classRegExp, levels ); } else { return _getParentElementWithNodeName( node, matchingSet.nodeName, levels ); } }; })(); /** * Get element's style for a specific css property * * @param {Element} element The element on which to retrieve the style * @param {String} property The CSS property to retrieve ("float", "display", "text-align", ...) * * @example * wysihtml5.dom.getStyle("display").from(document.body); * // => "block" */ wysihtml5.dom.getStyle = (function() { var stylePropertyMapping = { "float": ("styleFloat" in document.createElement("div").style) ? "styleFloat" : "cssFloat" }, REG_EXP_CAMELIZE = /\-[a-z]/g; function camelize(str) { return str.replace(REG_EXP_CAMELIZE, function(match) { return match.charAt(1).toUpperCase(); }); } return function(property) { return { from: function(element) { if (element.nodeType !== wysihtml5.ELEMENT_NODE) { return; } var doc = element.ownerDocument, camelizedProperty = stylePropertyMapping[property] || camelize(property), style = element.style, currentStyle = element.currentStyle, styleValue = style[camelizedProperty]; if (styleValue) { return styleValue; } // currentStyle is no standard and only supported by Opera and IE but it has one important advantage over the standard-compliant // window.getComputedStyle, since it returns css property values in their original unit: // If you set an elements width to "50%", window.getComputedStyle will give you it's current width in px while currentStyle // gives you the original "50%". // Opera supports both, currentStyle and window.getComputedStyle, that's why checking for currentStyle should have higher prio if (currentStyle) { try { return currentStyle[camelizedProperty]; } catch(e) { //ie will occasionally fail for unknown reasons. swallowing exception } } var win = doc.defaultView || doc.parentWindow, needsOverflowReset = (property === "height" || property === "width") && element.nodeName === "TEXTAREA", originalOverflow, returnValue; if (win.getComputedStyle) { // Chrome and Safari both calculate a wrong width and height for textareas when they have scroll bars // therfore we remove and restore the scrollbar and calculate the value in between if (needsOverflowReset) { originalOverflow = style.overflow; style.overflow = "hidden"; } returnValue = win.getComputedStyle(element, null).getPropertyValue(property); if (needsOverflowReset) { style.overflow = originalOverflow || ""; } return returnValue; } } }; }; })();/** * High performant way to check whether an element with a specific tag name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithTagName(document, "IMG"); */ wysihtml5.dom.hasElementWithTagName = (function() { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } return function(doc, tagName) { var key = _getDocumentIdentifier(doc) + ":" + tagName, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByTagName(tagName); } return cacheEntry.length > 0; }; })();/** * High performant way to check whether an element with a specific class name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithClassName(document, "foobar"); */ (function(wysihtml5) { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } wysihtml5.dom.hasElementWithClassName = function(doc, className) { // getElementsByClassName is not supported by IE<9 // but is sometimes mocked via library code (which then doesn't return live node lists) if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) { return !!doc.querySelector("." + className); } var key = _getDocumentIdentifier(doc) + ":" + className, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className); } return cacheEntry.length > 0; }; })(wysihtml5); wysihtml5.dom.insert = function(elementToInsert) { return { after: function(element) { element.parentNode.insertBefore(elementToInsert, element.nextSibling); }, before: function(element) { element.parentNode.insertBefore(elementToInsert, element); }, into: function(element) { element.appendChild(elementToInsert); } }; };wysihtml5.dom.insertCSS = function(rules) { rules = rules.join("\n"); return { into: function(doc) { var head = doc.head || doc.getElementsByTagName("head")[0], styleElement = doc.createElement("style"); styleElement.type = "text/css"; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = rules; } else { styleElement.appendChild(doc.createTextNode(rules)); } if (head) { head.appendChild(styleElement); } } }; };/** * Method to set dom events * * @example * wysihtml5.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... }); */ wysihtml5.dom.observe = function(element, eventNames, handler) { eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames; var handlerWrapper, eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else { handlerWrapper = function(event) { if (!("target" in event)) { event.target = event.srcElement; } event.preventDefault = event.preventDefault || function() { this.returnValue = false; }; event.stopPropagation = event.stopPropagation || function() { this.cancelBubble = true; }; handler.call(element, event); }; element.attachEvent("on" + eventName, handlerWrapper); } } return { stop: function() { var eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.removeEventListener) { element.removeEventListener(eventName, handler, false); } else { element.detachEvent("on" + eventName, handlerWrapper); } } } }; }; /** * HTML Sanitizer * Rewrites the HTML based on given rules * * @param {Element|String} elementOrHtml HTML String to be sanitized OR element whose content should be sanitized * @param {Object} [rules] List of rules for rewriting the HTML, if there's no rule for an element it will * be converted to a "span". Each rule is a key/value pair where key is the tag to convert, and value the * desired substitution. * @param {Object} context Document object in which to parse the html, needed to sandbox the parsing * * @return {Element|String} Depends on the elementOrHtml parameter. When html then the sanitized html as string elsewise the element. * * @example * var userHTML = '<div id="foo" onclick="alert(1);"><p><font color="red">foo</font><script>alert(1);</script></p></div>'; * wysihtml5.dom.parse(userHTML, { * tags { * p: "div", // Rename p tags to div tags * font: "span" // Rename font tags to span tags * div: true, // Keep them, also possible (same result when passing: "div" or true) * script: undefined // Remove script elements * } * }); * // => <div><div><span>foo bar</span></div></div> * * var userHTML = '<table><tbody><tr><td>I'm a table!</td></tr></tbody></table>'; * wysihtml5.dom.parse(userHTML); * // => '<span><span><span><span>I'm a table!</span></span></span></span>' * * var userHTML = '<div>foobar<br>foobar</div>'; * wysihtml5.dom.parse(userHTML, { * tags: { * div: undefined, * br: true * } * }); * // => '' * * var userHTML = '<div class="red">foo</div><div class="pink">bar</div>'; * wysihtml5.dom.parse(userHTML, { * classes: { * red: 1, * green: 1 * }, * tags: { * div: { * rename_tag: "p" * } * } * }); * // => '<p class="red">foo</p><p>bar</p>' */ wysihtml5.dom.parse = (function() { /** * It's not possible to use a XMLParser/DOMParser as HTML5 is not always well-formed XML * new DOMParser().parseFromString('<img src="foo.gif">') will cause a parseError since the * node isn't closed * * Therefore we've to use the browser's ordinary HTML parser invoked by setting innerHTML. */ var NODE_TYPE_MAPPING = { "1": _handleElement, "3": _handleText }, // Rename unknown tags to this DEFAULT_NODE_NAME = "span", WHITE_SPACE_REG_EXP = /\s+/, defaultRules = { tags: {}, classes: {} }, currentRules = {}; /** * Iterates over all childs of the element, recreates them, appends them into a document fragment * which later replaces the entire body content */ function parse(elementOrHtml, rules, context, cleanUp) { wysihtml5.lang.object(currentRules).merge(defaultRules).merge(rules).get(); context = context || elementOrHtml.ownerDocument || document; var fragment = context.createDocumentFragment(), isString = typeof(elementOrHtml) === "string", element, newNode, firstChild; if (isString) { element = wysihtml5.dom.getAsDom(elementOrHtml, context); } else { element = elementOrHtml; } while (element.firstChild) { firstChild = element.firstChild; element.removeChild(firstChild); newNode = _convert(firstChild, cleanUp); if (newNode) { fragment.appendChild(newNode); } } // Clear element contents element.innerHTML = ""; // Insert new DOM tree element.appendChild(fragment); return isString ? wysihtml5.quirks.getCorrectInnerHTML(element) : element; } function _convert(oldNode, cleanUp) { var oldNodeType = oldNode.nodeType, oldChilds = oldNode.childNodes, oldChildsLength = oldChilds.length, newNode, method = NODE_TYPE_MAPPING[oldNodeType], i = 0; newNode = method && method(oldNode); if (!newNode) { return null; } for (i=0; i<oldChildsLength; i++) { newChild = _convert(oldChilds[i], cleanUp); if (newChild) { newNode.appendChild(newChild); } } // Cleanup senseless <span> elements if (cleanUp && newNode.childNodes.length <= 1 && newNode.nodeName.toLowerCase() === DEFAULT_NODE_NAME && !newNode.attributes.length) { return newNode.firstChild; } return newNode; } function _handleElement(oldNode) { var rule, newNode, endTag, tagRules = currentRules.tags, nodeName = oldNode.nodeName.toLowerCase(), scopeName = oldNode.scopeName; /** * We already parsed that element * ignore it! (yes, this sometimes happens in IE8 when the html is invalid) */ if (oldNode._wysihtml5) { return null; } oldNode._wysihtml5 = 1; if (oldNode.className === "wysihtml5-temp") { return null; } /** * IE is the only browser who doesn't include the namespace in the * nodeName, that's why we have to prepend it by ourselves * scopeName is a proprietary IE feature * read more here http://msdn.microsoft.com/en-us/library/ms534388(v=vs.85).aspx */ if (scopeName && scopeName != "HTML") { nodeName = scopeName + ":" + nodeName; } /** * Repair node * IE is a bit bitchy when it comes to invalid nested markup which includes unclosed tags * A <p> doesn't need to be closed according HTML4-5 spec, we simply replace it with a <div> to preserve its content and layout */ if ("outerHTML" in oldNode) { if (!wysihtml5.browser.autoClosesUnclosedTags() && oldNode.nodeName === "P" && oldNode.outerHTML.slice(-4).toLowerCase() !== "</p>") { nodeName = "div"; } } if (nodeName in tagRules) { rule = tagRules[nodeName]; if (!rule || rule.remove) { return null; } rule = typeof(rule) === "string" ? { rename_tag: rule } : rule; } else if (oldNode.firstChild) { rule = { rename_tag: DEFAULT_NODE_NAME }; } else { // Remove empty unknown elements return null; } newNode = oldNode.ownerDocument.createElement(rule.rename_tag || nodeName); _handleAttributes(oldNode, newNode, rule); oldNode = null; return newNode; } function _handleAttributes(oldNode, newNode, rule) { var attributes = {}, // fresh new set of attributes to set on newNode setClass = rule.set_class, // classes to set addClass = rule.add_class, // add classes based on existing attributes setAttributes = rule.set_attributes, // attributes to set on the current node checkAttributes = rule.check_attributes, // check/convert values of attributes allowedClasses = currentRules.classes, i = 0, classes = [], newClasses = [], newUniqueClasses = [], oldClasses = [], classesLength, newClassesLength, currentClass, newClass, attributeName, newAttributeValue, method; if (setAttributes) { attributes = wysihtml5.lang.object(setAttributes).clone(); } if (checkAttributes) { for (attributeName in checkAttributes) { method = attributeCheckMethods[checkAttributes[attributeName]]; if (!method) { continue; } newAttributeValue = method(_getAttribute(oldNode, attributeName)); if (typeof(newAttributeValue) === "string") { attributes[attributeName] = newAttributeValue; } } } if (setClass) { classes.push(setClass); } if (addClass) { for (attributeName in addClass) { method = addClassMethods[addClass[attributeName]]; if (!method) { continue; } newClass = method(_getAttribute(oldNode, attributeName)); if (typeof(newClass) === "string") { classes.push(newClass); } } } // make sure that wysihtml5 temp class doesn't get stripped out allowedClasses["_wysihtml5-temp-placeholder"] = 1; // add old classes last oldClasses = oldNode.getAttribute("class"); if (oldClasses) { classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP)); } classesLength = classes.length; for (; i<classesLength; i++) { currentClass = classes[i]; if (allowedClasses[currentClass]) { newClasses.push(currentClass); } } // remove duplicate entries and preserve class specificity newClassesLength = newClasses.length; while (newClassesLength--) { currentClass = newClasses[newClassesLength]; if (!wysihtml5.lang.array(newUniqueClasses).contains(currentClass)) { newUniqueClasses.unshift(currentClass); } } if (newUniqueClasses.length) { attributes["class"] = newUniqueClasses.join(" "); } // set attributes on newNode for (attributeName in attributes) { // Setting attributes can cause a js error in IE under certain circumstances // eg. on a <img> under https when it's new attribute value is non-https // TODO: Investigate this further and check for smarter handling try { newNode.setAttribute(attributeName, attributes[attributeName]); } catch(e) {} } // IE8 sometimes loses the width/height attributes when those are set before the "src" // so we make sure to set them again if (attributes.src) { if (typeof(attributes.width) !== "undefined") { newNode.setAttribute("width", attributes.width); } if (typeof(attributes.height) !== "undefined") { newNode.setAttribute("height", attributes.height); } } } /** * IE gives wrong results for hasAttribute/getAttribute, for example: * var td = document.createElement("td"); * td.getAttribute("rowspan"); // => "1" in IE * * Therefore we have to check the element's outerHTML for the attribute */ var HAS_GET_ATTRIBUTE_BUG = !wysihtml5.browser.supportsGetAttributeCorrectly(); function _getAttribute(node, attributeName) { attributeName = attributeName.toLowerCase(); var nodeName = node.nodeName; if (nodeName == "IMG" && attributeName == "src" && _isLoadedImage(node) === true) { // Get 'src' attribute value via object property since this will always contain the // full absolute url (http://...) // this fixes a very annoying bug in firefox (ver 3.6 & 4) and IE 8 where images copied from the same host // will have relative paths, which the sanitizer strips out (see attributeCheckMethods.url) return node.src; } else if (HAS_GET_ATTRIBUTE_BUG && "outerHTML" in node) { // Don't trust getAttribute/hasAttribute in IE 6-8, instead check the element's outerHTML var outerHTML = node.outerHTML.toLowerCase(), // TODO: This might not work for attributes without value: <input disabled> hasAttribute = outerHTML.indexOf(" " + attributeName + "=") != -1; return hasAttribute ? node.getAttribute(attributeName) : null; } else{ return node.getAttribute(attributeName); } } /** * Check whether the given node is a proper loaded image * FIXME: Returns undefined when unknown (Chrome, Safari) */ function _isLoadedImage(node) { try { return node.complete && !node.mozMatchesSelector(":-moz-broken"); } catch(e) { if (node.complete && node.readyState === "complete") { return true; } } } function _handleText(oldNode) { return oldNode.ownerDocument.createTextNode(oldNode.data); } // ------------ attribute checks ------------ \\ var attributeCheckMethods = { url: (function() { var REG_EXP = /^https?:\/\//i; return function(attributeValue) { if (!attributeValue || !attributeValue.match(REG_EXP)) { return null; } return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); }); }; })(), alt: (function() { var REG_EXP = /[^ a-z0-9_\-]/gi; return function(attributeValue) { if (!attributeValue) { return ""; } return attributeValue.replace(REG_EXP, ""); }; })(), numbers: (function() { var REG_EXP = /\D/g; return function(attributeValue) { attributeValue = (attributeValue || "").replace(REG_EXP, ""); return attributeValue || null; }; })() }; // ------------ class converter (converts an html attribute to a class name) ------------ \\ var addClassMethods = { align_img: (function() { var mapping = { left: "wysiwyg-float-left", right: "wysiwyg-float-right" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), align_text: (function() { var mapping = { left: "wysiwyg-text-align-left", right: "wysiwyg-text-align-right", center: "wysiwyg-text-align-center", justify: "wysiwyg-text-align-justify" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), clear_br: (function() { var mapping = { left: "wysiwyg-clear-left", right: "wysiwyg-clear-right", both: "wysiwyg-clear-both", all: "wysiwyg-clear-both" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), size_font: (function() { var mapping = { "1": "wysiwyg-font-size-xx-small", "2": "wysiwyg-font-size-small", "3": "wysiwyg-font-size-medium", "4": "wysiwyg-font-size-large", "5": "wysiwyg-font-size-x-large", "6": "wysiwyg-font-size-xx-large", "7": "wysiwyg-font-size-xx-large", "-": "wysiwyg-font-size-smaller", "+": "wysiwyg-font-size-larger" }; return function(attributeValue) { return mapping[String(attributeValue).charAt(0)]; }; })() }; return parse; })();/** * Checks for empty text node childs and removes them * * @param {Element} node The element in which to cleanup * @example * wysihtml5.dom.removeEmptyTextNodes(element); */ wysihtml5.dom.removeEmptyTextNodes = function(node) { var childNode, childNodes = wysihtml5.lang.array(node.childNodes).get(), childNodesLength = childNodes.length, i = 0; for (; i<childNodesLength; i++) { childNode = childNodes[i]; if (childNode.nodeType === wysihtml5.TEXT_NODE && childNode.data === "") { childNode.parentNode.removeChild(childNode); } } }; /** * Renames an element (eg. a <div> to a <p>) and keeps its childs * * @param {Element} element The list element which should be renamed * @param {Element} newNodeName The desired tag name * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.renameElement(document.getElementById("list"), "ol"); * </script> * * <!-- Will result in: --> * <ol> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ol> */ wysihtml5.dom.renameElement = function(element, newNodeName) { var newElement = element.ownerDocument.createElement(newNodeName), firstChild; while (firstChild = element.firstChild) { newElement.appendChild(firstChild); } wysihtml5.dom.copyAttributes(["align", "className"]).from(element).to(newElement); element.parentNode.replaceChild(newElement, element); return newElement; };/** * Takes an element, removes it and replaces it with it's childs * * @param {Object} node The node which to replace with it's child nodes * @example * <div id="foo"> * <span>hello</span> * </div> * <script> * // Remove #foo and replace with it's children * wysihtml5.dom.replaceWithChildNodes(document.getElementById("foo")); * </script> */ wysihtml5.dom.replaceWithChildNodes = function(node) { if (!node.parentNode) { return; } if (!node.firstChild) { node.parentNode.removeChild(node); return; } var fragment = node.ownerDocument.createDocumentFragment(); while (node.firstChild) { fragment.appendChild(node.firstChild); } node.parentNode.replaceChild(fragment, node); node = fragment = null; }; /** * Unwraps an unordered/ordered list * * @param {Element} element The list element which should be unwrapped * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.resolveList(document.getElementById("list")); * </script> * * <!-- Will result in: --> * eminem<br> * dr. dre<br> * 50 Cent<br> */ (function(dom) { function _isBlockElement(node) { return dom.getStyle("display").from(node) === "block"; } function _isLineBreak(node) { return node.nodeName === "BR"; } function _appendLineBreak(element) { var lineBreak = element.ownerDocument.createElement("br"); element.appendChild(lineBreak); } function resolveList(list) { if (list.nodeName !== "MENU" && list.nodeName !== "UL" && list.nodeName !== "OL") { return; } var doc = list.ownerDocument, fragment = doc.createDocumentFragment(), previousSibling = list.previousElementSibling || list.previousSibling, firstChild, lastChild, isLastChild, shouldAppendLineBreak, listItem; if (previousSibling && !_isBlockElement(previousSibling)) { _appendLineBreak(fragment); } while (listItem = list.firstChild) { lastChild = listItem.lastChild; while (firstChild = listItem.firstChild) { isLastChild = firstChild === lastChild; // This needs to be done before appending it to the fragment, as it otherwise will loose style information shouldAppendLineBreak = isLastChild && !_isBlockElement(firstChild) && !_isLineBreak(firstChild); fragment.appendChild(firstChild); if (shouldAppendLineBreak) { _appendLineBreak(fragment); } } listItem.parentNode.removeChild(listItem); } list.parentNode.replaceChild(fragment, list); } dom.resolveList = resolveList; })(wysihtml5.dom);/** * Sandbox for executing javascript, parsing css styles and doing dom operations in a secure way * * Browser Compatibility: * - Secure in MSIE 6+, but only when the user hasn't made changes to his security level "restricted" * - Partially secure in other browsers (Firefox, Opera, Safari, Chrome, ...) * * Please note that this class can't benefit from the HTML5 sandbox attribute for the following reasons: * - sandboxing doesn't work correctly with inlined content (src="javascript:'<html>...</html>'") * - sandboxing of physical documents causes that the dom isn't accessible anymore from the outside (iframe.contentWindow, ...) * - setting the "allow-same-origin" flag would fix that, but then still javascript and dom events refuse to fire * - therefore the "allow-scripts" flag is needed, which then would deactivate any security, as the js executed inside the iframe * can do anything as if the sandbox attribute wasn't set * * @param {Function} [readyCallback] Method that gets invoked when the sandbox is ready * @param {Object} [config] Optional parameters * * @example * new wysihtml5.dom.Sandbox(function(sandbox) { * sandbox.getWindow().document.body.innerHTML = '<img src=foo.gif onerror="alert(document.cookie)">'; * }); */ (function(wysihtml5) { var /** * Default configuration */ doc = document, /** * Properties to unset/protect on the window object */ windowProperties = [ "parent", "top", "opener", "frameElement", "frames", "localStorage", "globalStorage", "sessionStorage", "indexedDB" ], /** * Properties on the window object which are set to an empty function */ windowProperties2 = [ "open", "close", "openDialog", "showModalDialog", "alert", "confirm", "prompt", "openDatabase", "postMessage", "XMLHttpRequest", "XDomainRequest" ], /** * Properties to unset/protect on the document object */ documentProperties = [ "referrer", "write", "open", "close" ]; wysihtml5.dom.Sandbox = Base.extend( /** @scope wysihtml5.dom.Sandbox.prototype */ { constructor: function(readyCallback, config) { this.callback = readyCallback || wysihtml5.EMPTY_FUNCTION; this.config = wysihtml5.lang.object({}).merge(config).get(); this.iframe = this._createIframe(); }, insertInto: function(element) { if (typeof(element) === "string") { element = doc.getElementById(element); } element.appendChild(this.iframe); }, getIframe: function() { return this.iframe; }, getWindow: function() { this._readyError(); }, getDocument: function() { this._readyError(); }, destroy: function() { var iframe = this.getIframe(); iframe.parentNode.removeChild(iframe); }, _readyError: function() { throw new Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet"); }, /** * Creates the sandbox iframe * * Some important notes: * - We can't use HTML5 sandbox for now: * setting it causes that the iframe's dom can't be accessed from the outside * Therefore we need to set the "allow-same-origin" flag which enables accessing the iframe's dom * But then there's another problem, DOM events (focus, blur, change, keypress, ...) aren't fired. * In order to make this happen we need to set the "allow-scripts" flag. * A combination of allow-scripts and allow-same-origin is almost the same as setting no sandbox attribute at all. * - Chrome & Safari, doesn't seem to support sandboxing correctly when the iframe's html is inlined (no physical document) * - IE needs to have the security="restricted" attribute set before the iframe is * inserted into the dom tree * - Believe it or not but in IE "security" in document.createElement("iframe") is false, even * though it supports it * - When an iframe has security="restricted", in IE eval() & execScript() don't work anymore * - IE doesn't fire the onload event when the content is inlined in the src attribute, therefore we rely * on the onreadystatechange event */ _createIframe: function() { var that = this, iframe = doc.createElement("iframe"); iframe.className = "wysihtml5-sandbox"; wysihtml5.dom.setAttributes({ "security": "restricted", "allowtransparency": "true", "frameborder": 0, "width": 0, "height": 0, "marginwidth": 0, "marginheight": 0 }).on(iframe); // Setting the src like this prevents ssl warnings in IE6 if (wysihtml5.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()) { iframe.src = "javascript:'<html></html>'"; } iframe.onload = function() { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); }; iframe.onreadystatechange = function() { if (/loaded|complete/.test(iframe.readyState)) { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); } }; return iframe; }, /** * Callback for when the iframe has finished loading */ _onLoadIframe: function(iframe) { // don't resume when the iframe got unloaded (eg. by removing it from the dom) if (!wysihtml5.dom.contains(doc.documentElement, iframe)) { return; } var that = this, iframeWindow = iframe.contentWindow, iframeDocument = iframe.contentWindow.document, charset = doc.characterSet || doc.charset || "utf-8", sandboxHtml = this._getHtml({ charset: charset, stylesheets: this.config.stylesheets }); // Create the basic dom tree including proper DOCTYPE and charset iframeDocument.open("text/html", "replace"); iframeDocument.write(sandboxHtml); iframeDocument.close(); this.getWindow = function() { return iframe.contentWindow; }; this.getDocument = function() { return iframe.contentWindow.document; }; // Catch js errors and pass them to the parent's onerror event // addEventListener("error") doesn't work properly in some browsers // TODO: apparently this doesn't work in IE9! iframeWindow.onerror = function(errorMessage, fileName, lineNumber) { throw new Error("wysihtml5.Sandbox: " + errorMessage, fileName, lineNumber); }; if (!wysihtml5.browser.supportsSandboxedIframes()) { // Unset a bunch of sensitive variables // Please note: This isn't hack safe! // It more or less just takes care of basic attacks and prevents accidental theft of sensitive information // IE is secure though, which is the most important thing, since IE is the only browser, who // takes over scripts & styles into contentEditable elements when copied from external websites // or applications (Microsoft Word, ...) var i, length; for (i=0, length=windowProperties.length; i<length; i++) { this._unset(iframeWindow, windowProperties[i]); } for (i=0, length=windowProperties2.length; i<length; i++) { this._unset(iframeWindow, windowProperties2[i], wysihtml5.EMPTY_FUNCTION); } for (i=0, length=documentProperties.length; i<length; i++) { this._unset(iframeDocument, documentProperties[i]); } // This doesn't work in Safari 5 // See http://stackoverflow.com/questions/992461/is-it-possible-to-override-document-cookie-in-webkit this._unset(iframeDocument, "cookie", "", true); } this.loaded = true; // Trigger the callback setTimeout(function() { that.callback(that); }, 0); }, _getHtml: function(templateVars) { var stylesheets = templateVars.stylesheets, html = "", i = 0, length; stylesheets = typeof(stylesheets) === "string" ? [stylesheets] : stylesheets; if (stylesheets) { length = stylesheets.length; for (; i<length; i++) { html += '<link rel="stylesheet" href="' + stylesheets[i] + '">'; } } templateVars.stylesheets = html; return wysihtml5.lang.string( '<!DOCTYPE html><html><head>' + '<meta charset="#{charset}">#{stylesheets}</head>' + '<body></body></html>' ).interpolate(templateVars); }, /** * Method to unset/override existing variables * @example * // Make cookie unreadable and unwritable * this._unset(document, "cookie", "", true); */ _unset: function(object, property, value, setter) { try { object[property] = value; } catch(e) {} try { object.__defineGetter__(property, function() { return value; }); } catch(e) {} if (setter) { try { object.__defineSetter__(property, function() {}); } catch(e) {} } if (!wysihtml5.browser.crashesWhenDefineProperty(property)) { try { var config = { get: function() { return value; } }; if (setter) { config.set = function() {}; } Object.defineProperty(object, property, config); } catch(e) {} } } }); })(wysihtml5); (function() { var mapping = { "className": "class" }; wysihtml5.dom.setAttributes = function(attributes) { return { on: function(element) { for (var i in attributes) { element.setAttribute(mapping[i] || i, attributes[i]); } } } }; })();wysihtml5.dom.setStyles = function(styles) { return { on: function(element) { var style = element.style; if (typeof(styles) === "string") { style.cssText += ";" + styles; return; } for (var i in styles) { if (i === "float") { style.cssFloat = styles[i]; style.styleFloat = styles[i]; } else { style[i] = styles[i]; } } } }; };/** * Simulate HTML5 placeholder attribute * * Needed since * - div[contentEditable] elements don't support it * - older browsers (such as IE8 and Firefox 3.6) don't support it at all * * @param {Object} parent Instance of main wysihtml5.Editor class * @param {Element} view Instance of wysihtml5.views.* class * @param {String} placeholderText * * @example * wysihtml.dom.simulatePlaceholder(this, composer, "Foobar"); */ (function(dom) { dom.simulatePlaceholder = function(editor, view, placeholderText) { var CLASS_NAME = "placeholder", unset = function() { if (view.hasPlaceholderSet()) { view.clear(); } dom.removeClass(view.element, CLASS_NAME); }, set = function() { if (view.isEmpty()) { view.setValue(placeholderText); dom.addClass(view.element, CLASS_NAME); } }; editor .observe("set_placeholder", set) .observe("unset_placeholder", unset) .observe("focus:composer", unset) .observe("paste:composer", unset) .observe("blur:composer", set); set(); }; })(wysihtml5.dom); (function(dom) { var documentElement = document.documentElement; if ("textContent" in documentElement) { dom.setTextContent = function(element, text) { element.textContent = text; }; dom.getTextContent = function(element) { return element.textContent; }; } else if ("innerText" in documentElement) { dom.setTextContent = function(element, text) { element.innerText = text; }; dom.getTextContent = function(element) { return element.innerText; }; } else { dom.setTextContent = function(element, text) { element.nodeValue = text; }; dom.getTextContent = function(element) { return element.nodeValue; }; } })(wysihtml5.dom); /** * Fix most common html formatting misbehaviors of browsers implementation when inserting * content via copy & paste contentEditable * * @author Christopher Blum */ wysihtml5.quirks.cleanPastedHTML = (function() { // TODO: We probably need more rules here var defaultRules = { // When pasting underlined links <a> into a contentEditable, IE thinks, it has to insert <u> to keep the styling "a u": wysihtml5.dom.replaceWithChildNodes }; function cleanPastedHTML(elementOrHtml, rules, context) { rules = rules || defaultRules; context = context || elementOrHtml.ownerDocument || document; var element, isString = typeof(elementOrHtml) === "string", method, matches, matchesLength, i, j = 0; if (isString) { element = wysihtml5.dom.getAsDom(elementOrHtml, context); } else { element = elementOrHtml; } for (i in rules) { matches = element.querySelectorAll(i); method = rules[i]; matchesLength = matches.length; for (; j<matchesLength; j++) { method(matches[j]); } } matches = elementOrHtml = rules = null; return isString ? element.innerHTML : element; } return cleanPastedHTML; })();/** * IE and Opera leave an empty paragraph in the contentEditable element after clearing it * * @param {Object} contentEditableElement The contentEditable element to observe for clearing events * @exaple * wysihtml5.quirks.ensureProperClearing(myContentEditableElement); */ (function(wysihtml5) { var dom = wysihtml5.dom; wysihtml5.quirks.ensureProperClearing = (function() { var clearIfNecessary = function(event) { var element = this; setTimeout(function() { var innerHTML = element.innerHTML.toLowerCase(); if (innerHTML == "<p>&nbsp;</p>" || innerHTML == "<p>&nbsp;</p><p>&nbsp;</p>") { element.innerHTML = ""; } }, 0); }; return function(composer) { dom.observe(composer.element, ["cut", "keydown"], clearIfNecessary); }; })(); /** * In Opera when the caret is in the first and only item of a list (<ul><li>|</li></ul>) and the list is the first child of the contentEditable element, it's impossible to delete the list by hitting backspace * * @param {Object} contentEditableElement The contentEditable element to observe for clearing events * @exaple * wysihtml5.quirks.ensureProperClearing(myContentEditableElement); */ wysihtml5.quirks.ensureProperClearingOfLists = (function() { var ELEMENTS_THAT_CONTAIN_LI = ["OL", "UL", "MENU"]; var clearIfNecessary = function(element, contentEditableElement) { if (!contentEditableElement.firstChild || !wysihtml5.lang.array(ELEMENTS_THAT_CONTAIN_LI).contains(contentEditableElement.firstChild.nodeName)) { return; } var list = dom.getParentElement(element, { nodeName: ELEMENTS_THAT_CONTAIN_LI }); if (!list) { return; } var listIsFirstChildOfContentEditable = list == contentEditableElement.firstChild; if (!listIsFirstChildOfContentEditable) { return; } var hasOnlyOneListItem = list.childNodes.length <= 1; if (!hasOnlyOneListItem) { return; } var onlyListItemIsEmpty = list.firstChild ? list.firstChild.innerHTML === "" : true; if (!onlyListItemIsEmpty) { return; } list.parentNode.removeChild(list); }; return function(composer) { dom.observe(composer.element, "keydown", function(event) { if (event.keyCode !== wysihtml5.BACKSPACE_KEY) { return; } var element = composer.selection.getSelectedNode(); clearIfNecessary(element, composer.element); }); }; })(); })(wysihtml5); // See https://bugzilla.mozilla.org/show_bug.cgi?id=664398 // // In Firefox this: // var d = document.createElement("div"); // d.innerHTML ='<a href="~"></a>'; // d.innerHTML; // will result in: // <a href="%7E"></a> // which is wrong (function(wysihtml5) { var TILDE_ESCAPED = "%7E"; wysihtml5.quirks.getCorrectInnerHTML = function(element) { var innerHTML = element.innerHTML; if (innerHTML.indexOf(TILDE_ESCAPED) === -1) { return innerHTML; } var elementsWithTilde = element.querySelectorAll("[href*='~'], [src*='~']"), url, urlToSearch, length, i; for (i=0, length=elementsWithTilde.length; i<length; i++) { url = elementsWithTilde[i].href || elementsWithTilde[i].src; urlToSearch = wysihtml5.lang.string(url).replace("~").by(TILDE_ESCAPED); innerHTML = wysihtml5.lang.string(innerHTML).replace(urlToSearch).by(url); } return innerHTML; }; })(wysihtml5);/** * Some browsers don't insert line breaks when hitting return in a contentEditable element * - Opera & IE insert new <p> on return * - Chrome & Safari insert new <div> on return * - Firefox inserts <br> on return (yippie!) * * @param {Element} element * * @example * wysihtml5.quirks.insertLineBreakOnReturn(element); */ (function(wysihtml5) { var dom = wysihtml5.dom, USE_NATIVE_LINE_BREAK_WHEN_CARET_INSIDE_TAGS = ["LI", "P", "H1", "H2", "H3", "H4", "H5", "H6"], LIST_TAGS = ["UL", "OL", "MENU"]; wysihtml5.quirks.insertLineBreakOnReturn = function(composer) { function unwrap(selectedNode) { var parentElement = dom.getParentElement(selectedNode, { nodeName: ["P", "DIV"] }, 2); if (!parentElement) { return; } var invisibleSpace = document.createTextNode(wysihtml5.INVISIBLE_SPACE); dom.insert(invisibleSpace).before(parentElement); dom.replaceWithChildNodes(parentElement); composer.selection.selectNode(invisibleSpace); } function keyDown(event) { var keyCode = event.keyCode; if (event.shiftKey || (keyCode !== wysihtml5.ENTER_KEY && keyCode !== wysihtml5.BACKSPACE_KEY)) { return; } var element = event.target, selectedNode = composer.selection.getSelectedNode(), blockElement = dom.getParentElement(selectedNode, { nodeName: USE_NATIVE_LINE_BREAK_WHEN_CARET_INSIDE_TAGS }, 4); if (blockElement) { // Some browsers create <p> elements after leaving a list // check after keydown of backspace and return whether a <p> got inserted and unwrap it if (blockElement.nodeName === "LI" && (keyCode === wysihtml5.ENTER_KEY || keyCode === wysihtml5.BACKSPACE_KEY)) { setTimeout(function() { var selectedNode = composer.selection.getSelectedNode(), list, div; if (!selectedNode) { return; } list = dom.getParentElement(selectedNode, { nodeName: LIST_TAGS }, 2); if (list) { return; } unwrap(selectedNode); }, 0); } else if (blockElement.nodeName.match(/H[1-6]/) && keyCode === wysihtml5.ENTER_KEY) { setTimeout(function() { unwrap(composer.selection.getSelectedNode()); }, 0); } return; } if (keyCode === wysihtml5.ENTER_KEY && !wysihtml5.browser.insertsLineBreaksOnReturn()) { composer.commands.exec("insertLineBreak"); event.preventDefault(); } } // keypress doesn't fire when you hit backspace dom.observe(composer.element.ownerDocument, "keydown", keyDown); }; })(wysihtml5);/** * Force rerendering of a given element * Needed to fix display misbehaviors of IE * * @param {Element} element The element object which needs to be rerendered * @example * wysihtml5.quirks.redraw(document.body); */ (function(wysihtml5) { var CLASS_NAME = "wysihtml5-quirks-redraw"; wysihtml5.quirks.redraw = function(element) { wysihtml5.dom.addClass(element, CLASS_NAME); wysihtml5.dom.removeClass(element, CLASS_NAME); // Following hack is needed for firefox to make sure that image resize handles are properly removed try { var doc = element.ownerDocument; doc.execCommand("italic", false, null); doc.execCommand("italic", false, null); } catch(e) {} }; })(wysihtml5);/** * Selection API * * @example * var selection = new wysihtml5.Selection(editor); */ (function(wysihtml5) { var dom = wysihtml5.dom; function _getCumulativeOffsetTop(element) { var top = 0; if (element.parentNode) { do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); } return top; } wysihtml5.Selection = Base.extend( /** @scope wysihtml5.Selection.prototype */ { constructor: function(editor) { // Make sure that our external range library is initialized window.rangy.init(); this.editor = editor; this.composer = editor.composer; this.doc = this.composer.doc; }, /** * Get the current selection as a bookmark to be able to later restore it * * @return {Object} An object that represents the current selection */ getBookmark: function() { var range = this.getRange(); return range && range.cloneRange(); }, /** * Restore a selection retrieved via wysihtml5.Selection.prototype.getBookmark * * @param {Object} bookmark An object that represents the current selection */ setBookmark: function(bookmark) { if (!bookmark) { return; } this.setSelection(bookmark); }, /** * Set the caret in front of the given node * * @param {Object} node The element or text node where to position the caret in front of * @example * selection.setBefore(myElement); */ setBefore: function(node) { var range = rangy.createRange(this.doc); range.setStartBefore(node); range.setEndBefore(node); return this.setSelection(range); }, /** * Set the caret after the given node * * @param {Object} node The element or text node where to position the caret in front of * @example * selection.setBefore(myElement); */ setAfter: function(node) { var range = rangy.createRange(this.doc); range.setStartAfter(node); range.setEndAfter(node); return this.setSelection(range); }, /** * Ability to select/mark nodes * * @param {Element} node The node/element to select * @example * selection.selectNode(document.getElementById("my-image")); */ selectNode: function(node) { var range = rangy.createRange(this.doc), isElement = node.nodeType === wysihtml5.ELEMENT_NODE, canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : (node.nodeName !== "IMG"), content = isElement ? node.innerHTML : node.data, isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE), displayStyle = dom.getStyle("display").from(node), isBlockElement = (displayStyle === "block" || displayStyle === "list-item"); if (isEmpty && isElement && canHaveHTML) { // Make sure that caret is visible in node by inserting a zero width no breaking space try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {} } if (canHaveHTML) { range.selectNodeContents(node); } else { range.selectNode(node); } if (canHaveHTML && isEmpty && isElement) { range.collapse(isBlockElement); } else if (canHaveHTML && isEmpty) { range.setStartAfter(node); range.setEndAfter(node); } this.setSelection(range); }, /** * Get the node which contains the selection * * @param {Boolean} [controlRange] (only IE) Whether it should return the selected ControlRange element when the selection type is a "ControlRange" * @return {Object} The node that contains the caret * @example * var nodeThatContainsCaret = selection.getSelectedNode(); */ getSelectedNode: function(controlRange) { var selection, range; if (controlRange && this.doc.selection && this.doc.selection.type === "Control") { range = this.doc.selection.createRange(); if (range && range.length) { return range.item(0); } } selection = this.getSelection(this.doc); if (selection.focusNode === selection.anchorNode) { return selection.focusNode; } else { range = this.getRange(this.doc); return range ? range.commonAncestorContainer : this.doc.body; } }, executeAndRestore: function(method, restoreScrollPosition) { var body = this.doc.body, oldScrollTop = restoreScrollPosition && body.scrollTop, oldScrollLeft = restoreScrollPosition && body.scrollLeft, className = "_wysihtml5-temp-placeholder", placeholderHTML = '<span class="' + className + '">' + wysihtml5.INVISIBLE_SPACE + '</span>', range = this.getRange(this.doc), newRange; // Nothing selected, execute and say goodbye if (!range) { method(body, body); return; } var node = range.createContextualFragment(placeholderHTML); range.insertNode(node); // Make sure that a potential error doesn't cause our placeholder element to be left as a placeholder try { method(range.startContainer, range.endContainer); } catch(e3) { setTimeout(function() { throw e3; }, 0); } caretPlaceholder = this.doc.querySelector("." + className); if (caretPlaceholder) { newRange = rangy.createRange(this.doc); newRange.selectNode(caretPlaceholder); newRange.deleteContents(); this.setSelection(newRange); } else { // fallback for when all hell breaks loose body.focus(); } if (restoreScrollPosition) { body.scrollTop = oldScrollTop; body.scrollLeft = oldScrollLeft; } // Remove it again, just to make sure that the placeholder is definitely out of the dom tree try { caretPlaceholder.parentNode.removeChild(caretPlaceholder); } catch(e4) {} }, /** * Different approach of preserving the selection (doesn't modify the dom) * Takes all text nodes in the selection and saves the selection position in the first and last one */ executeAndRestoreSimple: function(method) { var range = this.getRange(), body = this.doc.body, newRange, firstNode, lastNode, textNodes, rangeBackup; // Nothing selected, execute and say goodbye if (!range) { method(body, body); return; } textNodes = range.getNodes([3]); firstNode = textNodes[0] || range.startContainer; lastNode = textNodes[textNodes.length - 1] || range.endContainer; rangeBackup = { collapsed: range.collapsed, startContainer: firstNode, startOffset: firstNode === range.startContainer ? range.startOffset : 0, endContainer: lastNode, endOffset: lastNode === range.endContainer ? range.endOffset : lastNode.length }; try { method(range.startContainer, range.endContainer); } catch(e) { setTimeout(function() { throw e; }, 0); } newRange = rangy.createRange(this.doc); try { newRange.setStart(rangeBackup.startContainer, rangeBackup.startOffset); } catch(e1) {} try { newRange.setEnd(rangeBackup.endContainer, rangeBackup.endOffset); } catch(e2) {} try { this.setSelection(newRange); } catch(e3) {} }, /** * Insert html at the caret position and move the cursor after the inserted html * * @param {String} html HTML string to insert * @example * selection.insertHTML("<p>foobar</p>"); */ insertHTML: function(html) { var range = rangy.createRange(this.doc), node = range.createContextualFragment(html), lastChild = node.lastChild; this.insertNode(node); if (lastChild) { this.setAfter(lastChild); } }, /** * Insert a node at the caret position and move the cursor behind it * * @param {Object} node HTML string to insert * @example * selection.insertNode(document.createTextNode("foobar")); */ insertNode: function(node) { var range = this.getRange(); if (range) { range.insertNode(node); } }, /** * Wraps current selection with the given node * * @param {Object} node The node to surround the selected elements with */ surround: function(node) { var range = this.getRange(); if (!range) { return; } try { // This only works when the range boundaries are not overlapping other elements range.surroundContents(node); this.selectNode(node); } catch(e) { // fallback node.appendChild(range.extractContents()); range.insertNode(node); } }, /** * Scroll the current caret position into the view * FIXME: This is a bit hacky, there might be a smarter way of doing this * * @example * selection.scrollIntoView(); */ scrollIntoView: function() { var doc = this.doc, hasScrollBars = doc.documentElement.scrollHeight > doc.documentElement.offsetHeight, tempElement = doc._wysihtml5ScrollIntoViewElement = doc._wysihtml5ScrollIntoViewElement || (function() { var element = doc.createElement("span"); // The element needs content in order to be able to calculate it's position properly element.innerHTML = wysihtml5.INVISIBLE_SPACE; return element; })(), offsetTop; if (hasScrollBars) { this.insertNode(tempElement); offsetTop = _getCumulativeOffsetTop(tempElement); tempElement.parentNode.removeChild(tempElement); if (offsetTop > doc.body.scrollTop) { doc.body.scrollTop = offsetTop; } } }, /** * Select line where the caret is in */ selectLine: function() { if (wysihtml5.browser.supportsSelectionModify()) { this._selectLine_W3C(); } else if (this.doc.selection) { this._selectLine_MSIE(); } }, /** * See https://developer.mozilla.org/en/DOM/Selection/modify */ _selectLine_W3C: function() { var win = this.doc.defaultView, selection = win.getSelection(); selection.modify("extend", "left", "lineboundary"); selection.modify("extend", "right", "lineboundary"); }, _selectLine_MSIE: function() { var range = this.doc.selection.createRange(), rangeTop = range.boundingTop, rangeHeight = range.boundingHeight, scrollWidth = this.doc.body.scrollWidth, rangeBottom, rangeEnd, measureNode, i, j; if (!range.moveToPoint) { return; } if (rangeTop === 0) { // Don't know why, but when the selection ends at the end of a line // range.boundingTop is 0 measureNode = this.doc.createElement("span"); this.insertNode(measureNode); rangeTop = measureNode.offsetTop; measureNode.parentNode.removeChild(measureNode); } rangeTop += 1; for (i=-10; i<scrollWidth; i+=2) { try { range.moveToPoint(i, rangeTop); break; } catch(e1) {} } // Investigate the following in order to handle multi line selections // rangeBottom = rangeTop + (rangeHeight ? (rangeHeight - 1) : 0); rangeBottom = rangeTop; rangeEnd = this.doc.selection.createRange(); for (j=scrollWidth; j>=0; j--) { try { rangeEnd.moveToPoint(j, rangeBottom); break; } catch(e2) {} } range.setEndPoint("EndToEnd", rangeEnd); range.select(); }, getText: function() { var selection = this.getSelection(); return selection ? selection.toString() : ""; }, getNodes: function(nodeType, filter) { var range = this.getRange(); if (range) { return range.getNodes([nodeType], filter); } else { return []; } }, getRange: function() { var selection = this.getSelection(); return selection && selection.rangeCount && selection.getRangeAt(0); }, getSelection: function() { return rangy.getSelection(this.doc.defaultView || this.doc.parentWindow); }, setSelection: function(range) { var win = this.doc.defaultView || this.doc.parentWindow, selection = rangy.getSelection(win); return selection.setSingleRange(range); } }); })(wysihtml5); /** * Inspired by the rangy CSS Applier module written by Tim Down and licensed under the MIT license. * http://code.google.com/p/rangy/ * * changed in order to be able ... * - to use custom tags * - to detect and replace similar css classes via reg exp */ (function(wysihtml5, rangy) { var defaultTagName = "span"; var REG_EXP_WHITE_SPACE = /\s+/g; function hasClass(el, cssClass, regExp) { if (!el.className) { return false; } var matchingClassNames = el.className.match(regExp) || []; return matchingClassNames[matchingClassNames.length - 1] === cssClass; } function addClass(el, cssClass, regExp) { if (el.className) { removeClass(el, regExp); el.className += " " + cssClass; } else { el.className = cssClass; } } function removeClass(el, regExp) { if (el.className) { el.className = el.className.replace(regExp, ""); } } function hasSameClasses(el1, el2) { return el1.className.replace(REG_EXP_WHITE_SPACE, " ") == el2.className.replace(REG_EXP_WHITE_SPACE, " "); } function replaceWithOwnChildren(el) { var parent = el.parentNode; while (el.firstChild) { parent.insertBefore(el.firstChild, el); } parent.removeChild(el); } function elementsHaveSameNonClassAttributes(el1, el2) { if (el1.attributes.length != el2.attributes.length) { return false; } for (var i = 0, len = el1.attributes.length, attr1, attr2, name; i < len; ++i) { attr1 = el1.attributes[i]; name = attr1.name; if (name != "class") { attr2 = el2.attributes.getNamedItem(name); if (attr1.specified != attr2.specified) { return false; } if (attr1.specified && attr1.nodeValue !== attr2.nodeValue) { return false; } } } return true; } function isSplitPoint(node, offset) { if (rangy.dom.isCharacterDataNode(node)) { if (offset == 0) { return !!node.previousSibling; } else if (offset == node.length) { return !!node.nextSibling; } else { return true; } } return offset > 0 && offset < node.childNodes.length; } function splitNodeAt(node, descendantNode, descendantOffset) { var newNode; if (rangy.dom.isCharacterDataNode(descendantNode)) { if (descendantOffset == 0) { descendantOffset = rangy.dom.getNodeIndex(descendantNode); descendantNode = descendantNode.parentNode; } else if (descendantOffset == descendantNode.length) { descendantOffset = rangy.dom.getNodeIndex(descendantNode) + 1; descendantNode = descendantNode.parentNode; } else { newNode = rangy.dom.splitDataNode(descendantNode, descendantOffset); } } if (!newNode) { newNode = descendantNode.cloneNode(false); if (newNode.id) { newNode.removeAttribute("id"); } var child; while ((child = descendantNode.childNodes[descendantOffset])) { newNode.appendChild(child); } rangy.dom.insertAfter(newNode, descendantNode); } return (descendantNode == node) ? newNode : splitNodeAt(node, newNode.parentNode, rangy.dom.getNodeIndex(newNode)); } function Merge(firstNode) { this.isElementMerge = (firstNode.nodeType == wysihtml5.ELEMENT_NODE); this.firstTextNode = this.isElementMerge ? firstNode.lastChild : firstNode; this.textNodes = [this.firstTextNode]; } Merge.prototype = { doMerge: function() { var textBits = [], textNode, parent, text; for (var i = 0, len = this.textNodes.length; i < len; ++i) { textNode = this.textNodes[i]; parent = textNode.parentNode; textBits[i] = textNode.data; if (i) { parent.removeChild(textNode); if (!parent.hasChildNodes()) { parent.parentNode.removeChild(parent); } } } this.firstTextNode.data = text = textBits.join(""); return text; }, getLength: function() { var i = this.textNodes.length, len = 0; while (i--) { len += this.textNodes[i].length; } return len; }, toString: function() { var textBits = []; for (var i = 0, len = this.textNodes.length; i < len; ++i) { textBits[i] = "'" + this.textNodes[i].data + "'"; } return "[Merge(" + textBits.join(",") + ")]"; } }; function HTMLApplier(tagNames, cssClass, similarClassRegExp, normalize) { this.tagNames = tagNames || [defaultTagName]; this.cssClass = cssClass || ""; this.similarClassRegExp = similarClassRegExp; this.normalize = normalize; this.applyToAnyTagName = false; } HTMLApplier.prototype = { getAncestorWithClass: function(node) { var cssClassMatch; while (node) { cssClassMatch = this.cssClass ? hasClass(node, this.cssClass, this.similarClassRegExp) : true; if (node.nodeType == wysihtml5.ELEMENT_NODE && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssClassMatch) { return node; } node = node.parentNode; } return false; }, // Normalizes nodes after applying a CSS class to a Range. postApply: function(textNodes, range) { var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1]; var merges = [], currentMerge; var rangeStartNode = firstNode, rangeEndNode = lastNode; var rangeStartOffset = 0, rangeEndOffset = lastNode.length; var textNode, precedingTextNode; for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; precedingTextNode = this.getAdjacentMergeableTextNode(textNode.parentNode, false); if (precedingTextNode) { if (!currentMerge) { currentMerge = new Merge(precedingTextNode); merges.push(currentMerge); } currentMerge.textNodes.push(textNode); if (textNode === firstNode) { rangeStartNode = currentMerge.firstTextNode; rangeStartOffset = rangeStartNode.length; } if (textNode === lastNode) { rangeEndNode = currentMerge.firstTextNode; rangeEndOffset = currentMerge.getLength(); } } else { currentMerge = null; } } // Test whether the first node after the range needs merging var nextTextNode = this.getAdjacentMergeableTextNode(lastNode.parentNode, true); if (nextTextNode) { if (!currentMerge) { currentMerge = new Merge(lastNode); merges.push(currentMerge); } currentMerge.textNodes.push(nextTextNode); } // Do the merges if (merges.length) { for (i = 0, len = merges.length; i < len; ++i) { merges[i].doMerge(); } // Set the range boundaries range.setStart(rangeStartNode, rangeStartOffset); range.setEnd(rangeEndNode, rangeEndOffset); } }, getAdjacentMergeableTextNode: function(node, forward) { var isTextNode = (node.nodeType == wysihtml5.TEXT_NODE); var el = isTextNode ? node.parentNode : node; var adjacentNode; var propName = forward ? "nextSibling" : "previousSibling"; if (isTextNode) { // Can merge if the node's previous/next sibling is a text node adjacentNode = node[propName]; if (adjacentNode && adjacentNode.nodeType == wysihtml5.TEXT_NODE) { return adjacentNode; } } else { // Compare element with its sibling adjacentNode = el[propName]; if (adjacentNode && this.areElementsMergeable(node, adjacentNode)) { return adjacentNode[forward ? "firstChild" : "lastChild"]; } } return null; }, areElementsMergeable: function(el1, el2) { return rangy.dom.arrayContains(this.tagNames, (el1.tagName || "").toLowerCase()) && rangy.dom.arrayContains(this.tagNames, (el2.tagName || "").toLowerCase()) && hasSameClasses(el1, el2) && elementsHaveSameNonClassAttributes(el1, el2); }, createContainer: function(doc) { var el = doc.createElement(this.tagNames[0]); if (this.cssClass) { el.className = this.cssClass; } return el; }, applyToTextNode: function(textNode) { var parent = textNode.parentNode; if (parent.childNodes.length == 1 && rangy.dom.arrayContains(this.tagNames, parent.tagName.toLowerCase())) { if (this.cssClass) { addClass(parent, this.cssClass, this.similarClassRegExp); } } else { var el = this.createContainer(rangy.dom.getDocument(textNode)); textNode.parentNode.insertBefore(el, textNode); el.appendChild(textNode); } }, isRemovable: function(el) { return rangy.dom.arrayContains(this.tagNames, el.tagName.toLowerCase()) && wysihtml5.lang.string(el.className).trim() == this.cssClass; }, undoToTextNode: function(textNode, range, ancestorWithClass) { if (!range.containsNode(ancestorWithClass)) { // Split out the portion of the ancestor from which we can remove the CSS class var ancestorRange = range.cloneRange(); ancestorRange.selectNode(ancestorWithClass); if (ancestorRange.isPointInRange(range.endContainer, range.endOffset) && isSplitPoint(range.endContainer, range.endOffset)) { splitNodeAt(ancestorWithClass, range.endContainer, range.endOffset); range.setEndAfter(ancestorWithClass); } if (ancestorRange.isPointInRange(range.startContainer, range.startOffset) && isSplitPoint(range.startContainer, range.startOffset)) { ancestorWithClass = splitNodeAt(ancestorWithClass, range.startContainer, range.startOffset); } } if (this.similarClassRegExp) { removeClass(ancestorWithClass, this.similarClassRegExp); } if (this.isRemovable(ancestorWithClass)) { replaceWithOwnChildren(ancestorWithClass); } }, applyToRange: function(range) { var textNodes = range.getNodes([wysihtml5.TEXT_NODE]); if (!textNodes.length) { try { var node = this.createContainer(range.endContainer.ownerDocument); range.surroundContents(node); this.selectNode(range, node); return; } catch(e) {} } range.splitBoundaries(); textNodes = range.getNodes([wysihtml5.TEXT_NODE]); if (textNodes.length) { var textNode; for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; if (!this.getAncestorWithClass(textNode)) { this.applyToTextNode(textNode); } } range.setStart(textNodes[0], 0); textNode = textNodes[textNodes.length - 1]; range.setEnd(textNode, textNode.length); if (this.normalize) { this.postApply(textNodes, range); } } }, undoToRange: function(range) { var textNodes = range.getNodes([wysihtml5.TEXT_NODE]), textNode, ancestorWithClass; if (textNodes.length) { range.splitBoundaries(); textNodes = range.getNodes([wysihtml5.TEXT_NODE]); } else { var doc = range.endContainer.ownerDocument, node = doc.createTextNode(wysihtml5.INVISIBLE_SPACE); range.insertNode(node); range.selectNode(node); textNodes = [node]; } for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; ancestorWithClass = this.getAncestorWithClass(textNode); if (ancestorWithClass) { this.undoToTextNode(textNode, range, ancestorWithClass); } } if (len == 1) { this.selectNode(range, textNodes[0]); } else { range.setStart(textNodes[0], 0); textNode = textNodes[textNodes.length - 1]; range.setEnd(textNode, textNode.length); if (this.normalize) { this.postApply(textNodes, range); } } }, selectNode: function(range, node) { var isElement = node.nodeType === wysihtml5.ELEMENT_NODE, canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : true, content = isElement ? node.innerHTML : node.data, isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE); if (isEmpty && isElement && canHaveHTML) { // Make sure that caret is visible in node by inserting a zero width no breaking space try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {} } range.selectNodeContents(node); if (isEmpty && isElement) { range.collapse(false); } else if (isEmpty) { range.setStartAfter(node); range.setEndAfter(node); } }, getTextSelectedByRange: function(textNode, range) { var textRange = range.cloneRange(); textRange.selectNodeContents(textNode); var intersectionRange = textRange.intersection(range); var text = intersectionRange ? intersectionRange.toString() : ""; textRange.detach(); return text; }, isAppliedToRange: function(range) { var ancestors = [], ancestor, textNodes = range.getNodes([wysihtml5.TEXT_NODE]); if (!textNodes.length) { ancestor = this.getAncestorWithClass(range.startContainer); return ancestor ? [ancestor] : false; } for (var i = 0, len = textNodes.length, selectedText; i < len; ++i) { selectedText = this.getTextSelectedByRange(textNodes[i], range); ancestor = this.getAncestorWithClass(textNodes[i]); if (selectedText != "" && !ancestor) { return false; } else { ancestors.push(ancestor); } } return ancestors; }, toggleRange: function(range) { if (this.isAppliedToRange(range)) { this.undoToRange(range); } else { this.applyToRange(range); } } }; wysihtml5.selection.HTMLApplier = HTMLApplier; })(wysihtml5, rangy);/** * Rich Text Query/Formatting Commands * * @example * var commands = new wysihtml5.Commands(editor); */ wysihtml5.Commands = Base.extend( /** @scope wysihtml5.Commands.prototype */ { constructor: function(editor) { this.editor = editor; this.composer = editor.composer; this.doc = this.composer.doc; }, /** * Check whether the browser supports the given command * * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") * @example * commands.supports("createLink"); */ support: function(command) { return wysihtml5.browser.supportsCommand(this.doc, command); }, /** * Check whether the browser supports the given command * * @param {String} command The command string which to execute (eg. "bold", "italic", "insertUnorderedList") * @param {String} [value] The command value parameter, needed for some commands ("createLink", "insertImage", ...), optional for commands that don't require one ("bold", "underline", ...) * @example * commands.exec("insertImage", "http://a1.twimg.com/profile_images/113868655/schrei_twitter_reasonably_small.jpg"); */ exec: function(command, value) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.exec, result = null; this.editor.fire("beforecommand:composer"); if (method) { args.unshift(this.composer); result = method.apply(obj, args); } else { try { // try/catch for buggy firefox result = this.doc.execCommand(command, false, value); } catch(e) {} } this.editor.fire("aftercommand:composer"); return result; }, /** * Check whether the current command is active * If the caret is within a bold text, then calling this with command "bold" should return true * * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") * @param {String} [commandValue] The command value parameter (eg. for "insertImage" the image src) * @return {Boolean} Whether the command is active * @example * var isCurrentSelectionBold = commands.state("bold"); */ state: function(command, commandValue) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.state; if (method) { args.unshift(this.composer); return method.apply(obj, args); } else { try { // try/catch for buggy firefox return this.doc.queryCommandState(command); } catch(e) { return false; } } }, /** * Get the current command's value * * @param {String} command The command string which to check (eg. "formatBlock") * @return {String} The command value * @example * var currentBlockElement = commands.value("formatBlock"); */ value: function(command) { var obj = wysihtml5.commands[command], method = obj && obj.value; if (method) { return method.call(obj, this.composer, command); } else { try { // try/catch for buggy firefox return this.doc.queryCommandValue(command); } catch(e) { return null; } } } }); (function(wysihtml5) { var undef; wysihtml5.commands.bold = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, "b"); }, state: function(composer, command, color) { // element.ownerDocument.queryCommandState("bold") results: // firefox: only <b> // chrome: <b>, <strong>, <h1>, <h2>, ... // ie: <b>, <strong> // opera: <b>, <strong> return wysihtml5.commands.formatInline.state(composer, command, "b"); }, value: function() { return undef; } }; })(wysihtml5); (function(wysihtml5) { var undef, NODE_NAME = "A", dom = wysihtml5.dom; function _removeFormat(composer, anchors) { var length = anchors.length, i = 0, anchor, codeElement, textContent; for (; i<length; i++) { anchor = anchors[i]; codeElement = dom.getParentElement(anchor, { nodeName: "code" }); textContent = dom.getTextContent(anchor); // if <a> contains url-like text content, rename it to <code> to prevent re-autolinking // else replace <a> with its childNodes if (textContent.match(dom.autoLink.URL_REG_EXP) && !codeElement) { // <code> element is used to prevent later auto-linking of the content codeElement = dom.renameElement(anchor, "code"); } else { dom.replaceWithChildNodes(anchor); } } } function _format(composer, attributes) { var doc = composer.doc, tempClass = "_wysihtml5-temp-" + (+new Date()), tempClassRegExp = /non-matching-class/g, i = 0, length, anchors, anchor, hasElementChild, isEmpty, elementToSetCaretAfter, textContent, whiteSpace, j; wysihtml5.commands.formatInline.exec(composer, undef, NODE_NAME, tempClass, tempClassRegExp); anchors = doc.querySelectorAll(NODE_NAME + "." + tempClass); length = anchors.length; for (; i<length; i++) { anchor = anchors[i]; anchor.removeAttribute("class"); for (j in attributes) { anchor.setAttribute(j, attributes[j]); } } elementToSetCaretAfter = anchor; if (length === 1) { textContent = dom.getTextContent(anchor); hasElementChild = !!anchor.querySelector("*"); isEmpty = textContent === "" || textContent === wysihtml5.INVISIBLE_SPACE; if (!hasElementChild && isEmpty) { dom.setTextContent(anchor, attributes.text || anchor.href); whiteSpace = doc.createTextNode(" "); composer.selection.setAfter(anchor); composer.selection.insertNode(whiteSpace); elementToSetCaretAfter = whiteSpace; } } composer.selection.setAfter(elementToSetCaretAfter); } wysihtml5.commands.createLink = { /** * TODO: Use HTMLApplier or formatInline here * * Turns selection into a link * If selection is already a link, it removes the link and wraps it with a <code> element * The <code> element is needed to avoid auto linking * * @example * // either ... * wysihtml5.commands.createLink.exec(composer, "createLink", "http://www.google.de"); * // ... or ... * wysihtml5.commands.createLink.exec(composer, "createLink", { href: "http://www.google.de", target: "_blank" }); */ exec: function(composer, command, value) { var anchors = this.state(composer, command); if (anchors) { // Selection contains links composer.selection.executeAndRestore(function() { _removeFormat(composer, anchors); }); } else { // Create links value = typeof(value) === "object" ? value : { href: value }; _format(composer, value); } }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "A"); }, value: function() { return undef; } }; })(wysihtml5);/** * document.execCommand("fontSize") will create either inline styles (firefox, chrome) or use font tags * which we don't want * Instead we set a css class */ (function(wysihtml5) { var undef, REG_EXP = /wysiwyg-font-size-[a-z\-]+/g; wysihtml5.commands.fontSize = { exec: function(composer, command, size) { return wysihtml5.commands.formatInline.exec(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP); }, state: function(composer, command, size) { return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5); /** * document.execCommand("foreColor") will create either inline styles (firefox, chrome) or use font tags * which we don't want * Instead we set a css class */ (function(wysihtml5) { var undef, REG_EXP = /wysiwyg-color-[a-z]+/g; wysihtml5.commands.foreColor = { exec: function(composer, command, color) { return wysihtml5.commands.formatInline.exec(composer, command, "span", "wysiwyg-color-" + color, REG_EXP); }, state: function(composer, command, color) { return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-color-" + color, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef, dom = wysihtml5.dom, DEFAULT_NODE_NAME = "DIV", // Following elements are grouped // when the caret is within a H1 and the H4 is invoked, the H1 should turn into H4 // instead of creating a H4 within a H1 which would result in semantically invalid html BLOCK_ELEMENTS_GROUP = ["H1", "H2", "H3", "H4", "H5", "H6", "P", "BLOCKQUOTE", DEFAULT_NODE_NAME]; /** * Remove similiar classes (based on classRegExp) * and add the desired class name */ function _addClass(element, className, classRegExp) { if (element.className) { _removeClass(element, classRegExp); element.className += " " + className; } else { element.className = className; } } function _removeClass(element, classRegExp) { element.className = element.className.replace(classRegExp, ""); } /** * Check whether given node is a text node and whether it's empty */ function _isBlankTextNode(node) { return node.nodeType === wysihtml5.TEXT_NODE && !wysihtml5.lang.string(node.data).trim(); } /** * Returns previous sibling node that is not a blank text node */ function _getPreviousSiblingThatIsNotBlank(node) { var previousSibling = node.previousSibling; while (previousSibling && _isBlankTextNode(previousSibling)) { previousSibling = previousSibling.previousSibling; } return previousSibling; } /** * Returns next sibling node that is not a blank text node */ function _getNextSiblingThatIsNotBlank(node) { var nextSibling = node.nextSibling; while (nextSibling && _isBlankTextNode(nextSibling)) { nextSibling = nextSibling.nextSibling; } return nextSibling; } /** * Adds line breaks before and after the given node if the previous and next siblings * aren't already causing a visual line break (block element or <br>) */ function _addLineBreakBeforeAndAfter(node) { var doc = node.ownerDocument, nextSibling = _getNextSiblingThatIsNotBlank(node), previousSibling = _getPreviousSiblingThatIsNotBlank(node); if (nextSibling && !_isLineBreakOrBlockElement(nextSibling)) { node.parentNode.insertBefore(doc.createElement("br"), nextSibling); } if (previousSibling && !_isLineBreakOrBlockElement(previousSibling)) { node.parentNode.insertBefore(doc.createElement("br"), node); } } /** * Removes line breaks before and after the given node */ function _removeLineBreakBeforeAndAfter(node) { var nextSibling = _getNextSiblingThatIsNotBlank(node), previousSibling = _getPreviousSiblingThatIsNotBlank(node); if (nextSibling && _isLineBreak(nextSibling)) { nextSibling.parentNode.removeChild(nextSibling); } if (previousSibling && _isLineBreak(previousSibling)) { previousSibling.parentNode.removeChild(previousSibling); } } function _removeLastChildIfLineBreak(node) { var lastChild = node.lastChild; if (lastChild && _isLineBreak(lastChild)) { lastChild.parentNode.removeChild(lastChild); } } function _isLineBreak(node) { return node.nodeName === "BR"; } /** * Checks whether the elment causes a visual line break * (<br> or block elements) */ function _isLineBreakOrBlockElement(element) { if (_isLineBreak(element)) { return true; } if (dom.getStyle("display").from(element) === "block") { return true; } return false; } /** * Execute native query command * and if necessary modify the inserted node's className */ function _execCommand(doc, command, nodeName, className) { if (className) { var eventListener = dom.observe(doc, "DOMNodeInserted", function(event) { var target = event.target, displayStyle; if (target.nodeType !== wysihtml5.ELEMENT_NODE) { return; } displayStyle = dom.getStyle("display").from(target); if (displayStyle.substr(0, 6) !== "inline") { // Make sure that only block elements receive the given class target.className += " " + className; } }); } doc.execCommand(command, false, nodeName); if (eventListener) { eventListener.stop(); } } function _selectLineAndWrap(composer, element) { composer.selection.selectLine(); composer.selection.surround(element); _removeLineBreakBeforeAndAfter(element); _removeLastChildIfLineBreak(element); composer.selection.selectNode(element); } function _hasClasses(element) { return !!wysihtml5.lang.string(element.className).trim(); } wysihtml5.commands.formatBlock = { exec: function(composer, command, nodeName, className, classRegExp) { var doc = composer.doc, blockElement = this.state(composer, command, nodeName, className, classRegExp), selectedNode; nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName; if (blockElement) { composer.selection.executeAndRestoreSimple(function() { if (classRegExp) { _removeClass(blockElement, classRegExp); } var hasClasses = _hasClasses(blockElement); if (!hasClasses && blockElement.nodeName === (nodeName || DEFAULT_NODE_NAME)) { // Insert a line break afterwards and beforewards when there are siblings // that are not of type line break or block element _addLineBreakBeforeAndAfter(blockElement); dom.replaceWithChildNodes(blockElement); } else if (hasClasses) { // Make sure that styling is kept by renaming the element to <div> and copying over the class name dom.renameElement(blockElement, DEFAULT_NODE_NAME); } }); return; } // Find similiar block element and rename it (<h2 class="foo"></h2> => <h1 class="foo"></h1>) if (nodeName === null || wysihtml5.lang.array(BLOCK_ELEMENTS_GROUP).contains(nodeName)) { selectedNode = composer.selection.getSelectedNode(); blockElement = dom.getParentElement(selectedNode, { nodeName: BLOCK_ELEMENTS_GROUP }); if (blockElement) { composer.selection.executeAndRestoreSimple(function() { // Rename current block element to new block element and add class if (nodeName) { blockElement = dom.renameElement(blockElement, nodeName); } if (className) { _addClass(blockElement, className, classRegExp); } }); return; } } if (composer.commands.support(command)) { _execCommand(doc, command, nodeName || DEFAULT_NODE_NAME, className); return; } blockElement = doc.createElement(nodeName || DEFAULT_NODE_NAME); if (className) { blockElement.className = className; } _selectLineAndWrap(composer, blockElement); }, state: function(composer, command, nodeName, className, classRegExp) { nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName; var selectedNode = composer.selection.getSelectedNode(); return dom.getParentElement(selectedNode, { nodeName: nodeName, className: className, classRegExp: classRegExp }); }, value: function() { return undef; } }; })(wysihtml5);/** * formatInline scenarios for tag "B" (| = caret, |foo| = selected text) * * #1 caret in unformatted text: * abcdefg| * output: * abcdefg<b>|</b> * * #2 unformatted text selected: * abc|deg|h * output: * abc<b>|deg|</b>h * * #3 unformatted text selected across boundaries: * ab|c <span>defg|h</span> * output: * ab<b>|c </b><span><b>defg</b>|h</span> * * #4 formatted text entirely selected * <b>|abc|</b> * output: * |abc| * * #5 formatted text partially selected * <b>ab|c|</b> * output: * <b>ab</b>|c| * * #6 formatted text selected across boundaries * <span>ab|c</span> <b>de|fgh</b> * output: * <span>ab|c</span> de|<b>fgh</b> */ (function(wysihtml5) { var undef, // Treat <b> as <strong> and vice versa ALIAS_MAPPING = { "strong": "b", "em": "i", "b": "strong", "i": "em" }, htmlApplier = {}; function _getTagNames(tagName) { var alias = ALIAS_MAPPING[tagName]; return alias ? [tagName.toLowerCase(), alias.toLowerCase()] : [tagName.toLowerCase()]; } function _getApplier(tagName, className, classRegExp) { var identifier = tagName + ":" + className; if (!htmlApplier[identifier]) { htmlApplier[identifier] = new wysihtml5.selection.HTMLApplier(_getTagNames(tagName), className, classRegExp, true); } return htmlApplier[identifier]; } wysihtml5.commands.formatInline = { exec: function(composer, command, tagName, className, classRegExp) { var range = composer.selection.getRange(); if (!range) { return false; } _getApplier(tagName, className, classRegExp).toggleRange(range); composer.selection.setSelection(range); }, state: function(composer, command, tagName, className, classRegExp) { var doc = composer.doc, aliasTagName = ALIAS_MAPPING[tagName] || tagName, range; // Check whether the document contains a node with the desired tagName if (!wysihtml5.dom.hasElementWithTagName(doc, tagName) && !wysihtml5.dom.hasElementWithTagName(doc, aliasTagName)) { return false; } // Check whether the document contains a node with the desired className if (className && !wysihtml5.dom.hasElementWithClassName(doc, className)) { return false; } range = composer.selection.getRange(); if (!range) { return false; } return _getApplier(tagName, className, classRegExp).isAppliedToRange(range); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.insertHTML = { exec: function(composer, command, html) { if (composer.commands.support(command)) { composer.doc.execCommand(command, false, html); } else { composer.selection.insertHTML(html); } }, state: function() { return false; }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var NODE_NAME = "IMG"; wysihtml5.commands.insertImage = { /** * Inserts an <img> * If selection is already an image link, it removes it * * @example * // either ... * wysihtml5.commands.insertImage.exec(composer, "insertImage", "http://www.google.de/logo.jpg"); * // ... or ... * wysihtml5.commands.insertImage.exec(composer, "insertImage", { src: "http://www.google.de/logo.jpg", title: "foo" }); */ exec: function(composer, command, value) { value = typeof(value) === "object" ? value : { src: value }; var doc = composer.doc, image = this.state(composer), textNode, i, parent; if (image) { // Image already selected, set the caret before it and delete it composer.selection.setBefore(image); parent = image.parentNode; parent.removeChild(image); // and it's parent <a> too if it hasn't got any other relevant child nodes wysihtml5.dom.removeEmptyTextNodes(parent); if (parent.nodeName === "A" && !parent.firstChild) { composer.selection.setAfter(parent); parent.parentNode.removeChild(parent); } // firefox and ie sometimes don't remove the image handles, even though the image got removed wysihtml5.quirks.redraw(composer.element); return; } image = doc.createElement(NODE_NAME); for (i in value) { image[i] = value[i]; } composer.selection.insertNode(image); if (wysihtml5.browser.hasProblemsSettingCaretAfterImg()) { textNode = doc.createTextNode(wysihtml5.INVISIBLE_SPACE); composer.selection.insertNode(textNode); composer.selection.setAfter(textNode); } else { composer.selection.setAfter(image); } }, state: function(composer) { var doc = composer.doc, selectedNode, text, imagesInSelection; if (!wysihtml5.dom.hasElementWithTagName(doc, NODE_NAME)) { return false; } selectedNode = composer.selection.getSelectedNode(); if (!selectedNode) { return false; } if (selectedNode.nodeName === NODE_NAME) { // This works perfectly in IE return selectedNode; } if (selectedNode.nodeType !== wysihtml5.ELEMENT_NODE) { return false; } text = composer.selection.getText(); text = wysihtml5.lang.string(text).trim(); if (text) { return false; } imagesInSelection = composer.selection.getNodes(wysihtml5.ELEMENT_NODE, function(node) { return node.nodeName === "IMG"; }); if (imagesInSelection.length !== 1) { return false; } return imagesInSelection[0]; }, value: function(composer) { var image = this.state(composer); return image && image.src; } }; })(wysihtml5);(function(wysihtml5) { var undef, LINE_BREAK = "<br>" + (wysihtml5.browser.needsSpaceAfterLineBreak() ? " " : ""); wysihtml5.commands.insertLineBreak = { exec: function(composer, command) { if (composer.commands.support(command)) { composer.doc.execCommand(command, false, null); if (!wysihtml5.browser.autoScrollsToCaret()) { composer.selection.scrollIntoView(); } } else { composer.commands.exec("insertHTML", LINE_BREAK); } }, state: function() { return false; }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.insertOrderedList = { exec: function(composer, command) { var doc = composer.doc, selectedNode = composer.selection.getSelectedNode(), list = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }), otherList = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }), tempClassName = "_wysihtml5-temp-" + new Date().getTime(), isEmpty, tempElement; if (composer.commands.support(command)) { doc.execCommand(command, false, null); return; } if (list) { // Unwrap list // <ol><li>foo</li><li>bar</li></ol> // becomes: // foo<br>bar<br> composer.selection.executeAndRestoreSimple(function() { wysihtml5.dom.resolveList(list); }); } else if (otherList) { // Turn an unordered list into an ordered list // <ul><li>foo</li><li>bar</li></ul> // becomes: // <ol><li>foo</li><li>bar</li></ol> composer.selection.executeAndRestoreSimple(function() { wysihtml5.dom.renameElement(otherList, "ol"); }); } else { // Create list composer.commands.exec("formatBlock", "div", tempClassName); tempElement = doc.querySelector("." + tempClassName); isEmpty = tempElement.innerHTML === "" || tempElement.innerHTML === wysihtml5.INVISIBLE_SPACE; composer.selection.executeAndRestoreSimple(function() { list = wysihtml5.dom.convertToList(tempElement, "ol"); }); if (isEmpty) { composer.selection.selectNode(list.querySelector("li")); } } }, state: function(composer) { var selectedNode = composer.selection.getSelectedNode(); return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.insertUnorderedList = { exec: function(composer, command) { var doc = composer.doc, selectedNode = composer.selection.getSelectedNode(), list = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }), otherList = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }), tempClassName = "_wysihtml5-temp-" + new Date().getTime(), isEmpty, tempElement; if (composer.commands.support(command)) { doc.execCommand(command, false, null); return; } if (list) { // Unwrap list // <ul><li>foo</li><li>bar</li></ul> // becomes: // foo<br>bar<br> composer.selection.executeAndRestoreSimple(function() { wysihtml5.dom.resolveList(list); }); } else if (otherList) { // Turn an ordered list into an unordered list // <ol><li>foo</li><li>bar</li></ol> // becomes: // <ul><li>foo</li><li>bar</li></ul> composer.selection.executeAndRestoreSimple(function() { wysihtml5.dom.renameElement(otherList, "ul"); }); } else { // Create list composer.commands.exec("formatBlock", "div", tempClassName); tempElement = doc.querySelector("." + tempClassName); isEmpty = tempElement.innerHTML === "" || tempElement.innerHTML === wysihtml5.INVISIBLE_SPACE; composer.selection.executeAndRestoreSimple(function() { list = wysihtml5.dom.convertToList(tempElement, "ul"); }); if (isEmpty) { composer.selection.selectNode(list.querySelector("li")); } } }, state: function(composer) { var selectedNode = composer.selection.getSelectedNode(); return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.italic = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, "i"); }, state: function(composer, command, color) { // element.ownerDocument.queryCommandState("italic") results: // firefox: only <i> // chrome: <i>, <em>, <blockquote>, ... // ie: <i>, <em> // opera: only <i> return wysihtml5.commands.formatInline.state(composer, command, "i"); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef, CLASS_NAME = "wysiwyg-text-align-center", REG_EXP = /wysiwyg-text-align-[a-z]+/g; wysihtml5.commands.justifyCenter = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef, CLASS_NAME = "wysiwyg-text-align-left", REG_EXP = /wysiwyg-text-align-[a-z]+/g; wysihtml5.commands.justifyLeft = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef, CLASS_NAME = "wysiwyg-text-align-right", REG_EXP = /wysiwyg-text-align-[a-z]+/g; wysihtml5.commands.justifyRight = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.underline = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, "u"); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "u"); }, value: function() { return undef; } }; })(wysihtml5);/** * Undo Manager for wysihtml5 * slightly inspired by http://rniwa.com/editing/undomanager.html#the-undomanager-interface */ (function(wysihtml5) { var Z_KEY = 90, Y_KEY = 89, BACKSPACE_KEY = 8, DELETE_KEY = 46, MAX_HISTORY_ENTRIES = 40, UNDO_HTML = '<span id="_wysihtml5-undo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>', REDO_HTML = '<span id="_wysihtml5-redo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>', dom = wysihtml5.dom; function cleanTempElements(doc) { var tempElement; while (tempElement = doc.querySelector("._wysihtml5-temp")) { tempElement.parentNode.removeChild(tempElement); } } wysihtml5.UndoManager = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.UndoManager.prototype */ { constructor: function(editor) { this.editor = editor; this.composer = editor.composer; this.element = this.composer.element; this.history = [this.composer.getValue()]; this.position = 1; // Undo manager currently only supported in browsers who have the insertHTML command (not IE) if (this.composer.commands.support("insertHTML")) { this._observe(); } }, _observe: function() { var that = this, doc = this.composer.sandbox.getDocument(), lastKey; // Catch CTRL+Z and CTRL+Y dom.observe(this.element, "keydown", function(event) { if (event.altKey || (!event.ctrlKey && !event.metaKey)) { return; } var keyCode = event.keyCode, isUndo = keyCode === Z_KEY && !event.shiftKey, isRedo = (keyCode === Z_KEY && event.shiftKey) || (keyCode === Y_KEY); if (isUndo) { that.undo(); event.preventDefault(); } else if (isRedo) { that.redo(); event.preventDefault(); } }); // Catch delete and backspace dom.observe(this.element, "keydown", function(event) { var keyCode = event.keyCode; if (keyCode === lastKey) { return; } lastKey = keyCode; if (keyCode === BACKSPACE_KEY || keyCode === DELETE_KEY) { that.transact(); } }); // Now this is very hacky: // These days browsers don't offer a undo/redo event which we could hook into // to be notified when the user hits undo/redo in the contextmenu. // Therefore we simply insert two elements as soon as the contextmenu gets opened. // The last element being inserted will be immediately be removed again by a exexCommand("undo") // => When the second element appears in the dom tree then we know the user clicked "redo" in the context menu // => When the first element disappears from the dom tree then we know the user clicked "undo" in the context menu if (wysihtml5.browser.hasUndoInContextMenu()) { var interval, observed, cleanUp = function() { cleanTempElements(doc); clearInterval(interval); }; dom.observe(this.element, "contextmenu", function() { cleanUp(); that.composer.selection.executeAndRestoreSimple(function() { if (that.element.lastChild) { that.composer.selection.setAfter(that.element.lastChild); } // enable undo button in context menu doc.execCommand("insertHTML", false, UNDO_HTML); // enable redo button in context menu doc.execCommand("insertHTML", false, REDO_HTML); doc.execCommand("undo", false, null); }); interval = setInterval(function() { if (doc.getElementById("_wysihtml5-redo")) { cleanUp(); that.redo(); } else if (!doc.getElementById("_wysihtml5-undo")) { cleanUp(); that.undo(); } }, 400); if (!observed) { observed = true; dom.observe(document, "mousedown", cleanUp); dom.observe(doc, ["mousedown", "paste", "cut", "copy"], cleanUp); } }); } this.editor .observe("newword:composer", function() { that.transact(); }) .observe("beforecommand:composer", function() { that.transact(); }); }, transact: function() { var previousHtml = this.history[this.position - 1], currentHtml = this.composer.getValue(); if (currentHtml == previousHtml) { return; } var length = this.history.length = this.position; if (length > MAX_HISTORY_ENTRIES) { this.history.shift(); this.position--; } this.position++; this.history.push(currentHtml); }, undo: function() { this.transact(); if (this.position <= 1) { return; } this.set(this.history[--this.position - 1]); this.editor.fire("undo:composer"); }, redo: function() { if (this.position >= this.history.length) { return; } this.set(this.history[++this.position - 1]); this.editor.fire("redo:composer"); }, set: function(html) { this.composer.setValue(html); this.editor.focus(true); } }); })(wysihtml5); /** * TODO: the following methods still need unit test coverage */ wysihtml5.views.View = Base.extend( /** @scope wysihtml5.views.View.prototype */ { constructor: function(parent, textareaElement, config) { this.parent = parent; this.element = textareaElement; this.config = config; this._observeViewChange(); }, _observeViewChange: function() { var that = this; this.parent.observe("beforeload", function() { that.parent.observe("change_view", function(view) { if (view === that.name) { that.parent.currentView = that; that.show(); // Using tiny delay here to make sure that the placeholder is set before focusing setTimeout(function() { that.focus(); }, 0); } else { that.hide(); } }); }); }, focus: function() { if (this.element.ownerDocument.querySelector(":focus") === this.element) { return; } try { this.element.focus(); } catch(e) {} }, hide: function() { this.element.style.display = "none"; }, show: function() { this.element.style.display = ""; }, disable: function() { this.element.setAttribute("disabled", "disabled"); }, enable: function() { this.element.removeAttribute("disabled"); } });(function(wysihtml5) { var dom = wysihtml5.dom, browser = wysihtml5.browser; wysihtml5.views.Composer = wysihtml5.views.View.extend( /** @scope wysihtml5.views.Composer.prototype */ { name: "composer", // Needed for firefox in order to display a proper caret in an empty contentEditable CARET_HACK: "<br>", constructor: function(parent, textareaElement, config) { this.base(parent, textareaElement, config); this.textarea = this.parent.textarea; this._initSandbox(); }, clear: function() { this.element.innerHTML = browser.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK; }, getValue: function(parse) { var value = this.isEmpty() ? "" : wysihtml5.quirks.getCorrectInnerHTML(this.element); if (parse) { value = this.parent.parse(value); } // Replace all "zero width no breaking space" chars // which are used as hacks to enable some functionalities // Also remove all CARET hacks that somehow got left value = wysihtml5.lang.string(value).replace(wysihtml5.INVISIBLE_SPACE).by(""); return value; }, setValue: function(html, parse) { if (parse) { html = this.parent.parse(html); } this.element.innerHTML = html; }, show: function() { this.iframe.style.display = this._displayStyle || ""; // Firefox needs this, otherwise contentEditable becomes uneditable this.disable(); this.enable(); }, hide: function() { this._displayStyle = dom.getStyle("display").from(this.iframe); if (this._displayStyle === "none") { this._displayStyle = null; } this.iframe.style.display = "none"; }, disable: function() { this.element.removeAttribute("contentEditable"); this.base(); }, enable: function() { this.element.setAttribute("contentEditable", "true"); this.base(); }, focus: function(setToEnd) { // IE 8 fires the focus event after .focus() // This is needed by our simulate_placeholder.js to work // therefore we clear it ourselves this time if (wysihtml5.browser.doesAsyncFocus() && this.hasPlaceholderSet()) { this.clear(); } this.base(); var lastChild = this.element.lastChild; if (setToEnd && lastChild) { if (lastChild.nodeName === "BR") { this.selection.setBefore(this.element.lastChild); } else { this.selection.setAfter(this.element.lastChild); } } }, getTextContent: function() { return dom.getTextContent(this.element); }, hasPlaceholderSet: function() { return this.getTextContent() == this.textarea.element.getAttribute("placeholder"); }, isEmpty: function() { var innerHTML = this.element.innerHTML, elementsWithVisualValue = "blockquote, ul, ol, img, embed, object, table, iframe, svg, video, audio, button, input, select, textarea"; return innerHTML === "" || innerHTML === this.CARET_HACK || this.hasPlaceholderSet() || (this.getTextContent() === "" && !this.element.querySelector(elementsWithVisualValue)); }, _initSandbox: function() { var that = this; this.sandbox = new dom.Sandbox(function() { that._create(); }, { stylesheets: this.config.stylesheets }); this.iframe = this.sandbox.getIframe(); // Create hidden field which tells the server after submit, that the user used an wysiwyg editor var hiddenField = document.createElement("input"); hiddenField.type = "hidden"; hiddenField.name = "_wysihtml5_mode"; hiddenField.value = 1; // Store reference to current wysihtml5 instance on the textarea element var textareaElement = this.textarea.element; dom.insert(this.iframe).after(textareaElement); dom.insert(hiddenField).after(textareaElement); }, _create: function() { var that = this; this.doc = this.sandbox.getDocument(); this.element = this.doc.body; this.textarea = this.parent.textarea; this.element.innerHTML = this.textarea.getValue(true); this.enable(); // Make sure our selection handler is ready this.selection = new wysihtml5.Selection(this.parent); // Make sure commands dispatcher is ready this.commands = new wysihtml5.Commands(this.parent); dom.copyAttributes([ "className", "spellcheck", "title", "lang", "dir", "accessKey" ]).from(this.textarea.element).to(this.element); dom.addClass(this.element, this.config.composerClassName); // Make the editor look like the original textarea, by syncing styles if (this.config.style) { this.style(); } this.observe(); var name = this.config.name; if (name) { dom.addClass(this.element, name); dom.addClass(this.iframe, name); } // Simulate html5 placeholder attribute on contentEditable element var placeholderText = typeof(this.config.placeholder) === "string" ? this.config.placeholder : this.textarea.element.getAttribute("placeholder"); if (placeholderText) { dom.simulatePlaceholder(this.parent, this, placeholderText); } // Make sure that the browser avoids using inline styles whenever possible this.commands.exec("styleWithCSS", false); this._initAutoLinking(); this._initObjectResizing(); this._initUndoManager(); // Simulate html5 autofocus on contentEditable element if (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) { setTimeout(function() { that.focus(); }, 100); } wysihtml5.quirks.insertLineBreakOnReturn(this); // IE sometimes leaves a single paragraph, which can't be removed by the user if (!browser.clearsContentEditableCorrectly()) { wysihtml5.quirks.ensureProperClearing(this); } if (!browser.clearsListsInContentEditableCorrectly()) { wysihtml5.quirks.ensureProperClearingOfLists(this); } // Set up a sync that makes sure that textarea and editor have the same content if (this.initSync && this.config.sync) { this.initSync(); } // Okay hide the textarea, we are ready to go this.textarea.hide(); // Fire global (before-)load event this.parent.fire("beforeload").fire("load"); }, _initAutoLinking: function() { var that = this, supportsDisablingOfAutoLinking = browser.canDisableAutoLinking(), supportsAutoLinking = browser.doesAutoLinkingInContentEditable(); if (supportsDisablingOfAutoLinking) { this.commands.exec("autoUrlDetect", false); } if (!this.config.autoLink) { return; } // Only do the auto linking by ourselves when the browser doesn't support auto linking // OR when he supports auto linking but we were able to turn it off (IE9+) if (!supportsAutoLinking || (supportsAutoLinking && supportsDisablingOfAutoLinking)) { this.parent.observe("newword:composer", function() { that.selection.executeAndRestore(function(startContainer, endContainer) { dom.autoLink(endContainer.parentNode); }); }); } // Assuming we have the following: // <a href="http://www.google.de">http://www.google.de</a> // If a user now changes the url in the innerHTML we want to make sure that // it's synchronized with the href attribute (as long as the innerHTML is still a url) var // Use a live NodeList to check whether there are any links in the document links = this.sandbox.getDocument().getElementsByTagName("a"), // The autoLink helper method reveals a reg exp to detect correct urls urlRegExp = dom.autoLink.URL_REG_EXP, getTextContent = function(element) { var textContent = wysihtml5.lang.string(dom.getTextContent(element)).trim(); if (textContent.substr(0, 4) === "www.") { textContent = "http://" + textContent; } return textContent; }; dom.observe(this.element, "keydown", function(event) { if (!links.length) { return; } var selectedNode = that.selection.getSelectedNode(event.target.ownerDocument), link = dom.getParentElement(selectedNode, { nodeName: "A" }, 4), textContent; if (!link) { return; } textContent = getTextContent(link); // keydown is fired before the actual content is changed // therefore we set a timeout to change the href setTimeout(function() { var newTextContent = getTextContent(link); if (newTextContent === textContent) { return; } // Only set href when new href looks like a valid url if (newTextContent.match(urlRegExp)) { link.setAttribute("href", newTextContent); } }, 0); }); }, _initObjectResizing: function() { var properties = ["width", "height"], propertiesLength = properties.length, element = this.element; this.commands.exec("enableObjectResizing", this.config.allowObjectResizing); if (this.config.allowObjectResizing) { // IE sets inline styles after resizing objects // The following lines make sure that the width/height css properties // are copied over to the width/height attributes if (browser.supportsEvent("resizeend")) { dom.observe(element, "resizeend", function(event) { var target = event.target || event.srcElement, style = target.style, i = 0, property; for(; i<propertiesLength; i++) { property = properties[i]; if (style[property]) { target.setAttribute(property, parseInt(style[property], 10)); style[property] = ""; } } // After resizing IE sometimes forgets to remove the old resize handles wysihtml5.quirks.redraw(element); }); } } else { if (browser.supportsEvent("resizestart")) { dom.observe(element, "resizestart", function(event) { event.preventDefault(); }); } } }, _initUndoManager: function() { new wysihtml5.UndoManager(this.parent); } }); })(wysihtml5);(function(wysihtml5) { var dom = wysihtml5.dom, doc = document, win = window, HOST_TEMPLATE = doc.createElement("div"), /** * Styles to copy from textarea to the composer element */ TEXT_FORMATTING = [ "background-color", "color", "cursor", "font-family", "font-size", "font-style", "font-variant", "font-weight", "line-height", "letter-spacing", "text-align", "text-decoration", "text-indent", "text-rendering", "word-break", "word-wrap", "word-spacing" ], /** * Styles to copy from textarea to the iframe */ BOX_FORMATTING = [ "background-color", "border-collapse", "border-bottom-color", "border-bottom-style", "border-bottom-width", "border-left-color", "border-left-style", "border-left-width", "border-right-color", "border-right-style", "border-right-width", "border-top-color", "border-top-style", "border-top-width", "clear", "display", "float", "margin-bottom", "margin-left", "margin-right", "margin-top", "outline-color", "outline-offset", "outline-width", "outline-style", "padding-left", "padding-right", "padding-top", "padding-bottom", "position", "top", "left", "right", "bottom", "z-index", "vertical-align", "text-align", "-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing", "-webkit-box-shadow", "-moz-box-shadow", "-ms-box-shadow","box-shadow", "-webkit-border-top-right-radius", "-moz-border-radius-topright", "border-top-right-radius", "-webkit-border-bottom-right-radius", "-moz-border-radius-bottomright", "border-bottom-right-radius", "-webkit-border-bottom-left-radius", "-moz-border-radius-bottomleft", "border-bottom-left-radius", "-webkit-border-top-left-radius", "-moz-border-radius-topleft", "border-top-left-radius", "width", "height" ], /** * Styles to sync while the window gets resized */ RESIZE_STYLE = [ "width", "height", "top", "left", "right", "bottom" ], ADDITIONAL_CSS_RULES = [ "html { height: 100%; }", "body { min-height: 100%; padding: 0; margin: 0; margin-top: -1px; padding-top: 1px; }", "._wysihtml5-temp { display: none; }", wysihtml5.browser.isGecko ? "body.placeholder { color: graytext !important; }" : "body.placeholder { color: #a9a9a9 !important; }", "body[disabled] { background-color: #eee !important; color: #999 !important; cursor: default !important; }", // Ensure that user see's broken images and can delete them "img:-moz-broken { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }" ]; /** * With "setActive" IE offers a smart way of focusing elements without scrolling them into view: * http://msdn.microsoft.com/en-us/library/ms536738(v=vs.85).aspx * * Other browsers need a more hacky way: (pssst don't tell my mama) * In order to prevent the element being scrolled into view when focusing it, we simply * move it out of the scrollable area, focus it, and reset it's position */ var focusWithoutScrolling = function(element) { if (element.setActive) { // Following line could cause a js error when the textarea is invisible // See https://github.com/xing/wysihtml5/issues/9 try { element.setActive(); } catch(e) {} } else { var elementStyle = element.style, originalScrollTop = doc.documentElement.scrollTop || doc.body.scrollTop, originalScrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft, originalStyles = { position: elementStyle.position, top: elementStyle.top, left: elementStyle.left, WebkitUserSelect: elementStyle.WebkitUserSelect }; dom.setStyles({ position: "absolute", top: "-99999px", left: "-99999px", // Don't ask why but temporarily setting -webkit-user-select to none makes the whole thing performing smoother WebkitUserSelect: "none" }).on(element); element.focus(); dom.setStyles(originalStyles).on(element); if (win.scrollTo) { // Some browser extensions unset this method to prevent annoyances // "Better PopUp Blocker" for Chrome http://code.google.com/p/betterpopupblocker/source/browse/trunk/blockStart.js#100 // Issue: http://code.google.com/p/betterpopupblocker/issues/detail?id=1 win.scrollTo(originalScrollLeft, originalScrollTop); } } }; wysihtml5.views.Composer.prototype.style = function() { var that = this, originalActiveElement = doc.querySelector(":focus"), textareaElement = this.textarea.element, hasPlaceholder = textareaElement.hasAttribute("placeholder"), originalPlaceholder = hasPlaceholder && textareaElement.getAttribute("placeholder"); this.focusStylesHost = this.focusStylesHost || HOST_TEMPLATE.cloneNode(false); this.blurStylesHost = this.blurStylesHost || HOST_TEMPLATE.cloneNode(false); // Remove placeholder before copying (as the placeholder has an affect on the computed style) if (hasPlaceholder) { textareaElement.removeAttribute("placeholder"); } if (textareaElement === originalActiveElement) { textareaElement.blur(); } // --------- iframe styles (has to be set before editor styles, otherwise IE9 sets wrong fontFamily on blurStylesHost) --------- dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.iframe).andTo(this.blurStylesHost); // --------- editor styles --------- dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.element).andTo(this.blurStylesHost); // --------- apply standard rules --------- dom.insertCSS(ADDITIONAL_CSS_RULES).into(this.element.ownerDocument); // --------- :focus styles --------- focusWithoutScrolling(textareaElement); dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.focusStylesHost); dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.focusStylesHost); // Make sure that we don't change the display style of the iframe when copying styles oblur/onfocus // this is needed for when the change_view event is fired where the iframe is hidden and then // the blur event fires and re-displays it var boxFormattingStyles = wysihtml5.lang.array(BOX_FORMATTING).without(["display"]); // --------- restore focus --------- if (originalActiveElement) { originalActiveElement.focus(); } else { textareaElement.blur(); } // --------- restore placeholder --------- if (hasPlaceholder) { textareaElement.setAttribute("placeholder", originalPlaceholder); } // When copying styles, we only get the computed style which is never returned in percent unit // Therefore we've to recalculate style onresize if (!wysihtml5.browser.hasCurrentStyleProperty()) { var winObserver = dom.observe(win, "resize", function() { // Remove event listener if composer doesn't exist anymore if (!dom.contains(document.documentElement, that.iframe)) { winObserver.stop(); return; } var originalTextareaDisplayStyle = dom.getStyle("display").from(textareaElement), originalComposerDisplayStyle = dom.getStyle("display").from(that.iframe); textareaElement.style.display = ""; that.iframe.style.display = "none"; dom.copyStyles(RESIZE_STYLE) .from(textareaElement) .to(that.iframe) .andTo(that.focusStylesHost) .andTo(that.blurStylesHost); that.iframe.style.display = originalComposerDisplayStyle; textareaElement.style.display = originalTextareaDisplayStyle; }); } // --------- Sync focus/blur styles --------- this.parent.observe("focus:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.focusStylesHost).to(that.iframe); dom.copyStyles(TEXT_FORMATTING) .from(that.focusStylesHost).to(that.element); }); this.parent.observe("blur:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.blurStylesHost).to(that.iframe); dom.copyStyles(TEXT_FORMATTING) .from(that.blurStylesHost).to(that.element); }); return this; }; })(wysihtml5);/** * Taking care of events * - Simulating 'change' event on contentEditable element * - Handling drag & drop logic * - Catch paste events * - Dispatch proprietary newword:composer event * - Keyboard shortcuts */ (function(wysihtml5) { var dom = wysihtml5.dom, browser = wysihtml5.browser, /** * Map keyCodes to query commands */ shortcuts = { "66": "bold", // B "73": "italic", // I "85": "underline" // U }; wysihtml5.views.Composer.prototype.observe = function() { var that = this, state = this.getValue(), iframe = this.sandbox.getIframe(), element = this.element, focusBlurElement = browser.supportsEventsInIframeCorrectly() ? element : this.sandbox.getWindow(), // Firefox < 3.5 doesn't support the drop event, instead it supports a so called "dragdrop" event which behaves almost the same pasteEvents = browser.supportsEvent("drop") ? ["drop", "paste"] : ["dragdrop", "paste"]; // --------- destroy:composer event --------- dom.observe(iframe, "DOMNodeRemoved", function() { clearInterval(domNodeRemovedInterval); that.parent.fire("destroy:composer"); }); // DOMNodeRemoved event is not supported in IE 8 var domNodeRemovedInterval = setInterval(function() { if (!dom.contains(document.documentElement, iframe)) { clearInterval(domNodeRemovedInterval); that.parent.fire("destroy:composer"); } }, 250); // --------- Focus & blur logic --------- dom.observe(focusBlurElement, "focus", function() { that.parent.fire("focus").fire("focus:composer"); // Delay storing of state until all focus handler are fired // especially the one which resets the placeholder setTimeout(function() { state = that.getValue(); }, 0); }); dom.observe(focusBlurElement, "blur", function() { if (state !== that.getValue()) { that.parent.fire("change").fire("change:composer"); } that.parent.fire("blur").fire("blur:composer"); }); if (wysihtml5.browser.isIos()) { // When on iPad/iPhone/IPod after clicking outside of editor, the editor loses focus // but the UI still acts as if the editor has focus (blinking caret and onscreen keyboard visible) // We prevent that by focusing a temporary input element which immediately loses focus dom.observe(element, "blur", function() { var input = element.ownerDocument.createElement("input"), originalScrollTop = document.documentElement.scrollTop || document.body.scrollTop, originalScrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; try { that.selection.insertNode(input); } catch(e) { element.appendChild(input); } input.focus(); input.parentNode.removeChild(input); window.scrollTo(originalScrollLeft, originalScrollTop); }); } // --------- Drag & Drop logic --------- dom.observe(element, "dragenter", function() { that.parent.fire("unset_placeholder"); }); if (browser.firesOnDropOnlyWhenOnDragOverIsCancelled()) { dom.observe(element, ["dragover", "dragenter"], function(event) { event.preventDefault(); }); } dom.observe(element, pasteEvents, function(event) { var dataTransfer = event.dataTransfer, data; if (dataTransfer && browser.supportsDataTransfer()) { data = dataTransfer.getData("text/html") || dataTransfer.getData("text/plain"); } if (data) { element.focus(); that.commands.exec("insertHTML", data); that.parent.fire("paste").fire("paste:composer"); event.stopPropagation(); event.preventDefault(); } else { setTimeout(function() { that.parent.fire("paste").fire("paste:composer"); }, 0); } }); // --------- neword event --------- dom.observe(element, "keyup", function(event) { var keyCode = event.keyCode; if (keyCode === wysihtml5.SPACE_KEY || keyCode === wysihtml5.ENTER_KEY) { that.parent.fire("newword:composer"); } }); this.parent.observe("paste:composer", function() { setTimeout(function() { that.parent.fire("newword:composer"); }, 0); }); // --------- Make sure that images are selected when clicking on them --------- if (!browser.canSelectImagesInContentEditable()) { dom.observe(element, "mousedown", function(event) { var target = event.target; if (target.nodeName === "IMG") { that.selection.selectNode(target); event.preventDefault(); } }); } // --------- Shortcut logic --------- dom.observe(element, "keydown", function(event) { var keyCode = event.keyCode, command = shortcuts[keyCode]; if ((event.ctrlKey || event.metaKey) && !event.altKey && command) { that.commands.exec(command); event.preventDefault(); } }); // --------- Make sure that when pressing backspace/delete on selected images deletes the image and it's anchor --------- dom.observe(element, "keydown", function(event) { var target = that.selection.getSelectedNode(true), keyCode = event.keyCode, parent; if (target && target.nodeName === "IMG" && (keyCode === wysihtml5.BACKSPACE_KEY || keyCode === wysihtml5.DELETE_KEY)) { // 8 => backspace, 46 => delete parent = target.parentNode; // delete the <img> parent.removeChild(target); // and it's parent <a> too if it hasn't got any other child nodes if (parent.nodeName === "A" && !parent.firstChild) { parent.parentNode.removeChild(parent); } setTimeout(function() { wysihtml5.quirks.redraw(element); }, 0); event.preventDefault(); } }); // --------- Show url in tooltip when hovering links or images --------- var titlePrefixes = { IMG: "Image: ", A: "Link: " }; dom.observe(element, "mouseover", function(event) { var target = event.target, nodeName = target.nodeName, title; if (nodeName !== "A" && nodeName !== "IMG") { return; } var hasTitle = target.hasAttribute("title"); if(!hasTitle){ title = titlePrefixes[nodeName] + (target.getAttribute("href") || target.getAttribute("src")); target.setAttribute("title", title); } }); }; })(wysihtml5);/** * Class that takes care that the value of the composer and the textarea is always in sync */ (function(wysihtml5) { var INTERVAL = 400; wysihtml5.views.Synchronizer = Base.extend( /** @scope wysihtml5.views.Synchronizer.prototype */ { constructor: function(editor, textarea, composer) { this.editor = editor; this.textarea = textarea; this.composer = composer; this._observe(); }, /** * Sync html from composer to textarea * Takes care of placeholders * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the textarea */ fromComposerToTextarea: function(shouldParseHtml) { this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue()).trim(), shouldParseHtml); }, /** * Sync value of textarea to composer * Takes care of placeholders * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer */ fromTextareaToComposer: function(shouldParseHtml) { var textareaValue = this.textarea.getValue(); if (textareaValue) { this.composer.setValue(textareaValue, shouldParseHtml); } else { this.composer.clear(); this.editor.fire("set_placeholder"); } }, /** * Invoke syncing based on view state * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer/textarea */ sync: function(shouldParseHtml) { if (this.editor.currentView.name === "textarea") { this.fromTextareaToComposer(shouldParseHtml); } else { this.fromComposerToTextarea(shouldParseHtml); } }, /** * Initializes interval-based syncing * also makes sure that on-submit the composer's content is synced with the textarea * immediately when the form gets submitted */ _observe: function() { var interval, that = this, form = this.textarea.element.form, startInterval = function() { interval = setInterval(function() { that.fromComposerToTextarea(); }, INTERVAL); }, stopInterval = function() { clearInterval(interval); interval = null; }; startInterval(); if (form) { // If the textarea is in a form make sure that after onreset and onsubmit the composer // has the correct state wysihtml5.dom.observe(form, "submit", function() { that.sync(true); }); wysihtml5.dom.observe(form, "reset", function() { setTimeout(function() { that.fromTextareaToComposer(); }, 0); }); } this.editor.observe("change_view", function(view) { if (view === "composer" && !interval) { that.fromTextareaToComposer(true); startInterval(); } else if (view === "textarea") { that.fromComposerToTextarea(true); stopInterval(); } }); this.editor.observe("destroy:composer", stopInterval); } }); })(wysihtml5); wysihtml5.views.Textarea = wysihtml5.views.View.extend( /** @scope wysihtml5.views.Textarea.prototype */ { name: "textarea", constructor: function(parent, textareaElement, config) { this.base(parent, textareaElement, config); this._observe(); }, clear: function() { this.element.value = ""; }, getValue: function(parse) { var value = this.isEmpty() ? "" : this.element.value; if (parse) { value = this.parent.parse(value); } return value; }, setValue: function(html, parse) { if (parse) { html = this.parent.parse(html); } this.element.value = html; }, hasPlaceholderSet: function() { var supportsPlaceholder = wysihtml5.browser.supportsPlaceholderAttributeOn(this.element), placeholderText = this.element.getAttribute("placeholder") || null, value = this.element.value, isEmpty = !value; return (supportsPlaceholder && isEmpty) || (value === placeholderText); }, isEmpty: function() { return !wysihtml5.lang.string(this.element.value).trim() || this.hasPlaceholderSet(); }, _observe: function() { var element = this.element, parent = this.parent, eventMapping = { focusin: "focus", focusout: "blur" }, /** * Calling focus() or blur() on an element doesn't synchronously trigger the attached focus/blur events * This is the case for focusin and focusout, so let's use them whenever possible, kkthxbai */ events = wysihtml5.browser.supportsEvent("focusin") ? ["focusin", "focusout", "change"] : ["focus", "blur", "change"]; parent.observe("beforeload", function() { wysihtml5.dom.observe(element, events, function(event) { var eventName = eventMapping[event.type] || event.type; parent.fire(eventName).fire(eventName + ":textarea"); }); wysihtml5.dom.observe(element, ["paste", "drop"], function() { setTimeout(function() { parent.fire("paste").fire("paste:textarea"); }, 0); }); }); } });/** * Toolbar Dialog * * @param {Element} link The toolbar link which causes the dialog to show up * @param {Element} container The dialog container * * @example * <!-- Toolbar link --> * <a data-wysihtml5-command="insertImage">insert an image</a> * * <!-- Dialog --> * <div data-wysihtml5-dialog="insertImage" style="display: none;"> * <label> * URL: <input data-wysihtml5-dialog-field="src" value="http://"> * </label> * <label> * Alternative text: <input data-wysihtml5-dialog-field="alt" value=""> * </label> * </div> * * <script> * var dialog = new wysihtml5.toolbar.Dialog( * document.querySelector("[data-wysihtml5-command='insertImage']"), * document.querySelector("[data-wysihtml5-dialog='insertImage']") * ); * dialog.observe("save", function(attributes) { * // do something * }); * </script> */ (function(wysihtml5) { var dom = wysihtml5.dom, CLASS_NAME_OPENED = "wysihtml5-command-dialog-opened", SELECTOR_FORM_ELEMENTS = "input, select, textarea", SELECTOR_FIELDS = "[data-wysihtml5-dialog-field]", ATTRIBUTE_FIELDS = "data-wysihtml5-dialog-field"; wysihtml5.toolbar.Dialog = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.toolbar.Dialog.prototype */ { constructor: function(link, container) { this.link = link; this.container = container; }, _observe: function() { if (this._observed) { return; } var that = this, callbackWrapper = function(event) { var attributes = that._serialize(); if (attributes == that.elementToChange) { that.fire("edit", attributes); } else { that.fire("save", attributes); } that.hide(); event.preventDefault(); event.stopPropagation(); }; dom.observe(that.link, "click", function(event) { if (dom.hasClass(that.link, CLASS_NAME_OPENED)) { setTimeout(function() { that.hide(); }, 0); } }); dom.observe(this.container, "keydown", function(event) { var keyCode = event.keyCode; if (keyCode === wysihtml5.ENTER_KEY) { callbackWrapper(event); } if (keyCode === wysihtml5.ESCAPE_KEY) { that.hide(); } }); dom.delegate(this.container, "[data-wysihtml5-dialog-action=save]", "click", callbackWrapper); dom.delegate(this.container, "[data-wysihtml5-dialog-action=cancel]", "click", function(event) { that.fire("cancel"); that.hide(); event.preventDefault(); event.stopPropagation(); }); var formElements = this.container.querySelectorAll(SELECTOR_FORM_ELEMENTS), i = 0, length = formElements.length, _clearInterval = function() { clearInterval(that.interval); }; for (; i<length; i++) { dom.observe(formElements[i], "change", _clearInterval); } this._observed = true; }, /** * Grabs all fields in the dialog and puts them in key=>value style in an object which * then gets returned */ _serialize: function() { var data = this.elementToChange || {}, fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { data[fields[i].getAttribute(ATTRIBUTE_FIELDS)] = fields[i].value; } return data; }, /** * Takes the attributes of the "elementToChange" * and inserts them in their corresponding dialog input fields * * Assume the "elementToChange" looks like this: * <a href="http://www.google.com" target="_blank">foo</a> * * and we have the following dialog: * <input type="text" data-wysihtml5-dialog-field="href" value=""> * <input type="text" data-wysihtml5-dialog-field="target" value=""> * * after calling _interpolate() the dialog will look like this * <input type="text" data-wysihtml5-dialog-field="href" value="http://www.google.com"> * <input type="text" data-wysihtml5-dialog-field="target" value="_blank"> * * Basically it adopted the attribute values into the corresponding input fields * */ _interpolate: function(avoidHiddenFields) { var field, fieldName, newValue, focusedElement = document.querySelector(":focus"), fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { field = fields[i]; // Never change elements where the user is currently typing in if (field === focusedElement) { continue; } // Don't update hidden fields // See https://github.com/xing/wysihtml5/pull/14 if (avoidHiddenFields && field.type === "hidden") { continue; } fieldName = field.getAttribute(ATTRIBUTE_FIELDS); newValue = this.elementToChange ? (this.elementToChange[fieldName] || "") : field.defaultValue; field.value = newValue; } }, /** * Show the dialog element */ show: function(elementToChange) { var that = this, firstField = this.container.querySelector(SELECTOR_FORM_ELEMENTS); this.elementToChange = elementToChange; this._observe(); this._interpolate(); if (elementToChange) { this.interval = setInterval(function() { that._interpolate(true); }, 500); } dom.addClass(this.link, CLASS_NAME_OPENED); this.container.style.display = ""; this.fire("show"); if (firstField && !elementToChange) { try { firstField.focus(); } catch(e) {} } }, /** * Hide the dialog element */ hide: function() { clearInterval(this.interval); this.elementToChange = null; dom.removeClass(this.link, CLASS_NAME_OPENED); this.container.style.display = "none"; this.fire("hide"); } }); })(wysihtml5); /** * Converts speech-to-text and inserts this into the editor * As of now (2011/03/25) this only is supported in Chrome >= 11 * * Note that it sends the recorded audio to the google speech recognition api: * http://stackoverflow.com/questions/4361826/does-chrome-have-buil-in-speech-recognition-for-input-type-text-x-webkit-speec * * Current HTML5 draft can be found here * http://lists.w3.org/Archives/Public/public-xg-htmlspeech/2011Feb/att-0020/api-draft.html * * "Accessing Google Speech API Chrome 11" * http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ */ (function(wysihtml5) { var dom = wysihtml5.dom; var linkStyles = { position: "relative" }; var wrapperStyles = { left: 0, margin: 0, opacity: 0, overflow: "hidden", padding: 0, position: "absolute", top: 0, zIndex: 1 }; var inputStyles = { cursor: "inherit", fontSize: "50px", height: "50px", marginTop: "-25px", outline: 0, padding: 0, position: "absolute", right: "-4px", top: "50%" }; var inputAttributes = { "x-webkit-speech": "", "speech": "" }; wysihtml5.toolbar.Speech = function(parent, link) { var input = document.createElement("input"); if (!wysihtml5.browser.supportsSpeechApiOn(input)) { link.style.display = "none"; return; } var wrapper = document.createElement("div"); wysihtml5.lang.object(wrapperStyles).merge({ width: link.offsetWidth + "px", height: link.offsetHeight + "px" }); dom.insert(input).into(wrapper); dom.insert(wrapper).into(link); dom.setStyles(inputStyles).on(input); dom.setAttributes(inputAttributes).on(input) dom.setStyles(wrapperStyles).on(wrapper); dom.setStyles(linkStyles).on(link); var eventName = "onwebkitspeechchange" in input ? "webkitspeechchange" : "speechchange"; dom.observe(input, eventName, function() { parent.execCommand("insertText", input.value); input.value = ""; }); dom.observe(input, "click", function(event) { if (dom.hasClass(link, "wysihtml5-command-disabled")) { event.preventDefault(); } event.stopPropagation(); }); }; })(wysihtml5);/** * Toolbar * * @param {Object} parent Reference to instance of Editor instance * @param {Element} container Reference to the toolbar container element * * @example * <div id="toolbar"> * <a data-wysihtml5-command="createLink">insert link</a> * <a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1">insert h1</a> * </div> * * <script> * var toolbar = new wysihtml5.toolbar.Toolbar(editor, document.getElementById("toolbar")); * </script> */ (function(wysihtml5) { var CLASS_NAME_COMMAND_DISABLED = "wysihtml5-command-disabled", CLASS_NAME_COMMANDS_DISABLED = "wysihtml5-commands-disabled", CLASS_NAME_COMMAND_ACTIVE = "wysihtml5-command-active", CLASS_NAME_ACTION_ACTIVE = "wysihtml5-action-active", dom = wysihtml5.dom; wysihtml5.toolbar.Toolbar = Base.extend( /** @scope wysihtml5.toolbar.Toolbar.prototype */ { constructor: function(editor, container) { this.editor = editor; this.container = typeof(container) === "string" ? document.getElementById(container) : container; this.composer = editor.composer; this._getLinks("command"); this._getLinks("action"); this._observe(); this.show(); var speechInputLinks = this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"), length = speechInputLinks.length, i = 0; for (; i<length; i++) { new wysihtml5.toolbar.Speech(this, speechInputLinks[i]); } }, _getLinks: function(type) { var links = this[type + "Links"] = wysihtml5.lang.array(this.container.querySelectorAll("[data-wysihtml5-" + type + "]")).get(), length = links.length, i = 0, mapping = this[type + "Mapping"] = {}, link, group, name, value, dialog; for (; i<length; i++) { link = links[i]; name = link.getAttribute("data-wysihtml5-" + type); value = link.getAttribute("data-wysihtml5-" + type + "-value"); group = this.container.querySelector("[data-wysihtml5-" + type + "-group='" + name + "']"); dialog = this._getDialog(link, name); mapping[name + ":" + value] = { link: link, group: group, name: name, value: value, dialog: dialog, state: false }; } }, _getDialog: function(link, command) { var that = this, dialogElement = this.container.querySelector("[data-wysihtml5-dialog='" + command + "']"), dialog, caretBookmark; if (dialogElement) { dialog = new wysihtml5.toolbar.Dialog(link, dialogElement); dialog.observe("show", function() { caretBookmark = that.composer.selection.getBookmark(); that.editor.fire("show:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); dialog.observe("save", function(attributes) { if (caretBookmark) { that.composer.selection.setBookmark(caretBookmark); } that._execCommand(command, attributes); that.editor.fire("save:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); dialog.observe("cancel", function() { that.editor.focus(false); that.editor.fire("cancel:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); } return dialog; }, /** * @example * var toolbar = new wysihtml5.Toolbar(); * // Insert a <blockquote> element or wrap current selection in <blockquote> * toolbar.execCommand("formatBlock", "blockquote"); */ execCommand: function(command, commandValue) { if (this.commandsDisabled) { return; } var commandObj = this.commandMapping[command + ":" + commandValue]; // Show dialog when available if (commandObj && commandObj.dialog && !commandObj.state) { commandObj.dialog.show(); } else { this._execCommand(command, commandValue); } }, _execCommand: function(command, commandValue) { // Make sure that composer is focussed (false => don't move caret to the end) this.editor.focus(false); this.composer.commands.exec(command, commandValue); this._updateLinkStates(); }, execAction: function(action) { var editor = this.editor; switch(action) { case "change_view": if (editor.currentView === editor.textarea) { editor.fire("change_view", "composer"); } else { editor.fire("change_view", "textarea"); } break; } }, _observe: function() { var that = this, editor = this.editor, container = this.container, links = this.commandLinks.concat(this.actionLinks), length = links.length, i = 0; for (; i<length; i++) { // 'javascript:;' and unselectable=on Needed for IE, but done in all browsers to make sure that all get the same css applied // (you know, a:link { ... } doesn't match anchors with missing href attribute) dom.setAttributes({ href: "javascript:;", unselectable: "on" }).on(links[i]); } // Needed for opera dom.delegate(container, "[data-wysihtml5-command]", "mousedown", function(event) { event.preventDefault(); }); dom.delegate(container, "[data-wysihtml5-command]", "click", function(event) { var link = this, command = link.getAttribute("data-wysihtml5-command"), commandValue = link.getAttribute("data-wysihtml5-command-value"); that.execCommand(command, commandValue); event.preventDefault(); }); dom.delegate(container, "[data-wysihtml5-action]", "click", function(event) { var action = this.getAttribute("data-wysihtml5-action"); that.execAction(action); event.preventDefault(); }); editor.observe("focus:composer", function() { that.bookmark = null; clearInterval(that.interval); that.interval = setInterval(function() { that._updateLinkStates(); }, 500); }); editor.observe("blur:composer", function() { clearInterval(that.interval); }); editor.observe("destroy:composer", function() { clearInterval(that.interval); }); editor.observe("change_view", function(currentView) { // Set timeout needed in order to let the blur event fire first setTimeout(function() { that.commandsDisabled = (currentView !== "composer"); that._updateLinkStates(); if (that.commandsDisabled) { dom.addClass(container, CLASS_NAME_COMMANDS_DISABLED); } else { dom.removeClass(container, CLASS_NAME_COMMANDS_DISABLED); } }, 0); }); }, _updateLinkStates: function() { var element = this.composer.element, commandMapping = this.commandMapping, actionMapping = this.actionMapping, i, state, action, command; // every millisecond counts... this is executed quite often for (i in commandMapping) { command = commandMapping[i]; if (this.commandsDisabled) { state = false; dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { command.dialog.hide(); } } else { state = this.composer.commands.state(command.name, command.value); if (wysihtml5.lang.object(state).isArray()) { // Grab first and only object/element in state array, otherwise convert state into boolean // to avoid showing a dialog for multiple selected elements which may have different attributes // eg. when two links with different href are selected, the state will be an array consisting of both link elements // but the dialog interface can only update one state = state.length === 1 ? state[0] : true; } dom.removeClass(command.link, CLASS_NAME_COMMAND_DISABLED); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_DISABLED); } } if (command.state === state) { continue; } command.state = state; if (state) { dom.addClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.addClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { if (typeof(state) === "object") { command.dialog.show(state); } else { command.dialog.hide(); } } } else { dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { command.dialog.hide(); } } } for (i in actionMapping) { action = actionMapping[i]; if (action.name === "change_view") { action.state = this.editor.currentView === this.editor.textarea; if (action.state) { dom.addClass(action.link, CLASS_NAME_ACTION_ACTIVE); } else { dom.removeClass(action.link, CLASS_NAME_ACTION_ACTIVE); } } } }, show: function() { this.container.style.display = ""; }, hide: function() { this.container.style.display = "none"; } }); })(wysihtml5); /** * WYSIHTML5 Editor * * @param {Element} textareaElement Reference to the textarea which should be turned into a rich text interface * @param {Object} [config] See defaultConfig object below for explanation of each individual config option * * @events * load * beforeload (for internal use only) * focus * focus:composer * focus:textarea * blur * blur:composer * blur:textarea * change * change:composer * change:textarea * paste * paste:composer * paste:textarea * newword:composer * destroy:composer * undo:composer * redo:composer * beforecommand:composer * aftercommand:composer * change_view */ (function(wysihtml5) { var undef; var defaultConfig = { // Give the editor a name, the name will also be set as class name on the iframe and on the iframe's body name: undef, // Whether the editor should look like the textarea (by adopting styles) style: true, // Id of the toolbar element, pass falsey value if you don't want any toolbar logic toolbar: undef, // Whether urls, entered by the user should automatically become clickable-links autoLink: true, // Object which includes parser rules to apply when html gets inserted via copy & paste // See parser_rules/*.js for examples parserRules: { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} }, // Parser method to use when the user inserts content via copy & paste parser: wysihtml5.dom.parse, // Class name which should be set on the contentEditable element in the created sandbox iframe, can be styled via the 'stylesheets' option composerClassName: "wysihtml5-editor", // Class name to add to the body when the wysihtml5 editor is supported bodyClassName: "wysihtml5-supported", // Array (or single string) of stylesheet urls to be loaded in the editor's iframe stylesheets: [], // Placeholder text to use, defaults to the placeholder attribute on the textarea element placeholderText: undef, // Whether the composer should allow the user to manually resize images, tables etc. allowObjectResizing: true, // Whether the rich text editor should be rendered on touch devices (wysihtml5 >= 0.3.0 comes with basic support for iOS 5) supportTouchDevices: true }; wysihtml5.Editor = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.Editor.prototype */ { constructor: function(textareaElement, config) { this.textareaElement = typeof(textareaElement) === "string" ? document.getElementById(textareaElement) : textareaElement; this.config = wysihtml5.lang.object({}).merge(defaultConfig).merge(config).get(); this.textarea = new wysihtml5.views.Textarea(this, this.textareaElement, this.config); this.currentView = this.textarea; this._isCompatible = wysihtml5.browser.supported(); // Sort out unsupported/unwanted browsers here if (!this._isCompatible || (!this.config.supportTouchDevices && wysihtml5.browser.isTouchDevice())) { var that = this; setTimeout(function() { that.fire("beforeload").fire("load"); }, 0); return; } // Add class name to body, to indicate that the editor is supported wysihtml5.dom.addClass(document.body, this.config.bodyClassName); this.composer = new wysihtml5.views.Composer(this, this.textareaElement, this.config); this.currentView = this.composer; if (typeof(this.config.parser) === "function") { this._initParser(); } this.observe("beforeload", function() { this.synchronizer = new wysihtml5.views.Synchronizer(this, this.textarea, this.composer); if (this.config.toolbar) { this.toolbar = new wysihtml5.toolbar.Toolbar(this, this.config.toolbar); } }); try { console.log("Heya! This page is using wysihtml5 for rich text editing. Check out https://github.com/xing/wysihtml5"); } catch(e) {} }, isCompatible: function() { return this._isCompatible; }, clear: function() { this.currentView.clear(); return this; }, getValue: function(parse) { return this.currentView.getValue(parse); }, setValue: function(html, parse) { if (!html) { return this.clear(); } this.currentView.setValue(html, parse); return this; }, focus: function(setToEnd) { this.currentView.focus(setToEnd); return this; }, /** * Deactivate editor (make it readonly) */ disable: function() { this.currentView.disable(); return this; }, /** * Activate editor */ enable: function() { this.currentView.enable(); return this; }, isEmpty: function() { return this.currentView.isEmpty(); }, hasPlaceholderSet: function() { return this.currentView.hasPlaceholderSet(); }, parse: function(htmlOrElement) { var returnValue = this.config.parser(htmlOrElement, this.config.parserRules, this.composer.sandbox.getDocument(), true); if (typeof(htmlOrElement) === "object") { wysihtml5.quirks.redraw(htmlOrElement); } return returnValue; }, /** * Prepare html parser logic * - Observes for paste and drop */ _initParser: function() { this.observe("paste:composer", function() { var keepScrollPosition = true, that = this; that.composer.selection.executeAndRestore(function() { wysihtml5.quirks.cleanPastedHTML(that.composer.element); that.parse(that.composer.element); }, keepScrollPosition); }); this.observe("paste:textarea", function() { var value = this.textarea.getValue(), newValue; newValue = this.parse(value); this.textarea.setValue(newValue); }); } }); })(wysihtml5);
JavaScript
/* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable //"sDom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // defaukt datatable without horizobtal scroll "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": " _MENU_ records ", } } ); /* Default class modification */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; // pagination with prev, next link icons $(nPaging).append( '<ul class="pagination">'+ '<li class="prev disabled"><a href="#" title="'+oLang.sPrevious+'"><i class="fa fa-angle-left"></i></a></li>'+ '<li class="next disabled"><a href="#" title="'+oLang.sNext+'"><i class="fa fa-angle-right"></i></a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, iLen=an.length ; i<iLen ; i++ ) { if (oPaging.iTotalPages < 0) { $('.pagination', an[i]).css('visibility', 'hidden'); } else { $('.pagination', an[i]).css('visibility', 'visible'); } // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* Bootstrap style full number pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap_full_number": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).append( '<ul class="pagination">' + '<li class="prev disabled"><a href="#" title="' + oLang.sFirst + '"><i class="fa fa-angle-double-left"></i></a></li>' + '<li class="prev disabled"><a href="#" title="' + oLang.sPrevious + '"><i class="fa fa-angle-left"></i></a></li>'+ '<li class="next disabled"><a href="#" title="' + oLang.sNext + '"><i class="fa fa-angle-right"></i></a></li>' + '<li class="next disabled"><a href="#" title="' + oLang.sLast + '"><i class="fa fa-angle-double-right"></i></a></li>' + '</ul>' ); var els = $('a', nPaging); $(els[0]).bind('click.DT', { action: "first" }, fnClickHandler); $(els[1]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[2]).bind('click.DT', { action: "next" }, fnClickHandler); $(els[3]).bind('click.DT', { action: "last" }, fnClickHandler); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, iLen=an.length ; i<iLen ; i++ ) { if (oPaging.iTotalPages < 0) { $('.pagination', an[i]).css('visibility', 'hidden'); } else { $('.pagination', an[i]).css('visibility', 'visible'); } // Remove the middle elements $('li:gt(1)', an[i]).filter(':not(.next)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li.next:first', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li.prev', an[i]).addClass('disabled'); } else { $('li.prev', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li.next', an[i]).addClass('disabled'); } else { $('li.next', an[i]).removeClass('disabled'); } } } } } ); /* Bootstrap style full number pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap_extended": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var oPaging = oSettings.oInstance.fnPagingInfo(); var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).append( '<div class="pagination-panel"> ' + oLang.sPage + ' ' + '<a href="#" class="btn btn-sm default prev disabled" title="' + oLang.sPrevious + '"><i class="fa fa-angle-left"></i></a>' + '<input type="text" class="pagination-panel-input form-control input-mini input-inline input-sm" maxlenght="5" style="text-align:center; margin: 0 5px;">' + '<a href="#" class="btn btn-sm default next disabled" title="' + oLang.sNext + '"><i class="fa fa-angle-right"></i></a> ' + oLang.sPageOf + ' <span class="pagination-panel-total"></span>' + '</div>' ); var els = $('a', nPaging); $(els[0]).bind('click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind('click.DT', { action: "next" }, fnClickHandler); $('.pagination-panel-input', nPaging).bind('change.DT', function(e) { var oPaging = oSettings.oInstance.fnPagingInfo(); e.preventDefault(); var page = parseInt($(this).val()); if (page > 0 && page < oPaging.iTotalPages) { if ( oSettings.oApi._fnPageChange(oSettings, page-1) ) { fnDraw( oSettings ); } } else { $(this).val(oPaging.iPage + 1); } }); $('.pagination-panel-input', nPaging).bind('keypress.DT', function(e) { var oPaging = oSettings.oInstance.fnPagingInfo(); if (e.which == 13) { var page = parseInt($(this).val()); if (page > 0 && page < oSettings.oInstance.fnPagingInfo().iTotalPages) { if ( oSettings.oApi._fnPageChange(oSettings, page-1) ) { fnDraw( oSettings ); } } else { $(this).val(oPaging.iPage + 1); } e.preventDefault(); } }); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, iLen=an.length ; i<iLen ; i++ ) { var wrapper = $(an[i]).parents(".dataTables_wrapper"); if (oPaging.iTotalPages <= 0) { $('.pagination-panel, .dataTables_length', wrapper).hide(); } else { $('.pagination-panel, .dataTables_length', wrapper).show(); } $('.pagination-panel-total', an[i]).html(oPaging.iTotalPages); $('.pagination-panel-input', an[i]).val(oPaging.iPage + 1); // Remove the middle elements $('li:gt(1)', an[i]).filter(':not(.next)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li.next:first', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('a.prev', an[i]).addClass('disabled'); } else { $('a.prev', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('a.next', an[i]).addClass('disabled'); } else { $('a.next', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "btn-group", "buttons": { "normal": "btn default", "disabled": "btn disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); }
JavaScript
/* * Fuel UX Spinner * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ !function ($) { // SPINNER CONSTRUCTOR AND PROTOTYPE var Spinner = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.spinner.defaults, options); this.$input = this.$element.find('.spinner-input'); this.$element.on('keyup', this.$input, $.proxy(this.change, this)); if (this.options.hold) { this.$element.on('mousedown', '.spinner-up', $.proxy(function() { this.startSpin(true); } , this)); this.$element.on('mouseup', '.spinner-up, .spinner-down', $.proxy(this.stopSpin, this)); this.$element.on('mouseout', '.spinner-up, .spinner-down', $.proxy(this.stopSpin, this)); this.$element.on('mousedown', '.spinner-down', $.proxy(function() {this.startSpin(false);} , this)); } else { this.$element.on('click', '.spinner-up', $.proxy(function() { this.step(true); } , this)); this.$element.on('click', '.spinner-down', $.proxy(function() { this.step(false); }, this)); } this.switches = { count: 1, enabled: true }; if (this.options.speed === 'medium') { this.switches.speed = 300; } else if (this.options.speed === 'fast') { this.switches.speed = 100; } else { this.switches.speed = 500; } this.lastValue = null; this.render(); if (this.options.disabled) { this.disable(); } }; Spinner.prototype = { constructor: Spinner, render: function () { var inputValue = this.$input.val(); if (inputValue) { this.value(inputValue); } else { this.$input.val(this.options.value); } this.$input.attr('maxlength', (this.options.max + '').split('').length); }, change: function () { var newVal = this.$input.val(); if(newVal/1){ this.options.value = newVal/1; }else{ newVal = newVal.replace(/[^0-9]/g,''); this.$input.val(newVal); this.options.value = newVal/1; } this.triggerChangedEvent(); }, stopSpin: function () { clearTimeout(this.switches.timeout); this.switches.count = 1; this.triggerChangedEvent(); }, triggerChangedEvent: function () { var currentValue = this.value(); if (currentValue === this.lastValue) return; this.lastValue = currentValue; // Primary changed event this.$element.trigger('changed', currentValue); // Undocumented, kept for backward compatibility this.$element.trigger('change'); }, startSpin: function (type) { if (!this.options.disabled) { var divisor = this.switches.count; if (divisor === 1) { this.step(type); divisor = 1; } else if (divisor < 3){ divisor = 1.5; } else if (divisor < 8){ divisor = 2.5; } else { divisor = 4; } this.switches.timeout = setTimeout($.proxy(function() {this.iterator(type);} ,this),this.switches.speed/divisor); this.switches.count++; } }, iterator: function (type) { this.step(type); this.startSpin(type); }, step: function (dir) { var curValue = this.options.value; var limValue = dir ? this.options.max : this.options.min; if ((dir ? curValue < limValue : curValue > limValue)) { var newVal = curValue + (dir ? 1 : -1) * this.options.step; if (dir ? newVal > limValue : newVal < limValue) { this.value(limValue); } else { this.value(newVal); } } else if (this.options.cycle) { var cycleVal = dir ? this.options.min : this.options.max; this.value(cycleVal); } }, value: function (value) { if (!isNaN(parseFloat(value)) && isFinite(value)) { value = parseFloat(value); this.options.value = value; this.$input.val(value); return this; } else { return this.options.value; } }, disable: function () { this.options.disabled = true; this.$input.attr('disabled',''); this.$element.find('button').addClass('disabled'); }, enable: function () { this.options.disabled = false; this.$input.removeAttr("disabled"); this.$element.find('button').removeClass('disabled'); } }; // SPINNER PLUGIN DEFINITION $.fn.spinner = function (option,value) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('spinner'); var options = typeof option === 'object' && option; if (!data) $this.data('spinner', (data = new Spinner(this, options))); if (typeof option === 'string') methodReturn = data[option](value); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.spinner.defaults = { value: 1, min: 1, max: 999, step: 1, hold: true, speed: 'medium', disabled: false }; $.fn.spinner.Constructor = Spinner; // SPINNER DATA-API $(function () { $('body').on('mousedown.spinner.data-api', '.spinner', function () { var $this = $(this); if ($this.data('spinner')) return; $this.spinner($this.data()); }); }); }(window.jQuery);
JavaScript
/** * @author Will Steinmetz * * jQuery notification plug-in inspired by the notification style of Windows 8 * * Copyright (c)2013, Will Steinmetz * Licensed under the BSD license. * http://opensource.org/licenses/BSD-3-Clause */ ;(function($) { var settings = { life: 10000, theme: 'teal', sticky: false, verticalEdge: 'right', horizontalEdge: 'top', zindex: 1100 }; var methods = { init: function(message, options) { return this.each(function() { var $this = $(this), data = $this.data('notific8'); $this.data('notific8', { target: $this, settings: {}, message: "" }); data = $this.data('notific8'); data.message = message; // apply the options $.extend(data.settings, settings, options); // add the notification to the stack methods._buildNotification($this); }); }, /** * Destroy the notification */ destroy: function($this) { var data = $this.data('notific8'); $(window).unbind('.notific8'); $this.removeData('notific8'); }, /** * Build the notification and add it to the screen's stack */ _buildNotification: function($this) { var data = $this.data('notific8'), notification = $('<div />'), num = Number($('body').attr('data-notific8s')); num++; notification.addClass('jquery-notific8-notification').addClass(data.settings.theme); notification.attr('id', 'jquery-notific8-notification-' + num); $('body').attr('data-notific8s', num); // check for a heading if (data.settings.hasOwnProperty('heading') && (typeof data.settings.heading == "string")) { notification.append($('<div />').addClass('jquery-notific8-heading').html(data.settings.heading)); } // check if the notification is supposed to be sticky if (data.settings.sticky) { var close = $('<div />').addClass('jquery-notific8-close-sticky').append( $('<span />').html('close x') ); close.click(function(event) { notification.animate({width: 'hide'}, { duration: 'fast', complete: function() { notification.remove(); } }); }); notification.append(close); notification.addClass('sticky'); } // otherwise, put the normal close button up that is only display // when the notification is hovered over else { var close = $('<div />').addClass('jquery-notific8-close').append( $('<span />').html('X') ); close.click(function(event) { notification.animate({width: 'hide'}, { duration: 'fast', complete: function() { notification.remove(); } }); }); notification.append(close); } // add the message notification.append($('<div />').addClass('jquery-notific8-message').html(data.message)); // add the notification to the stack $('.jquery-notific8-container.' + data.settings.verticalEdge + '.' + data.settings.horizontalEdge).append(notification); // slide the message onto the screen notification.animate({width: 'show'}, { duration: 'fast', complete: function() { if (!data.settings.sticky) { (function(n, l) { setTimeout(function() { n.animate({width: 'hide'}, { duration: 'fast', complete: function() { n.remove(); } }); }, l); })(notification, data.settings.life); } data.settings = {}; } }); }, /** * Set up the configuration settings */ configure: function(options) { $.extend(settings, options); }, /** * Set up the z-index */ zindex: function(zindex) { settings.zindex = zindex; } }; // wrapper since this plug-in is called without selecting an item first $.notific8 = function(message, options) { switch (message) { case 'configure': case 'config': return methods.configure.apply(this, [options]); break; case 'zindex': return methods.zindex.apply(this, [options]); break; default: if (typeof options == 'undefined') { options = {}; } // make sure that the stack containers exist if ($('.jquery-notific8-container').size() === 0) { var $body = $('body'); $body.attr('data-notific8s', 0); $body.append($('<div />').addClass('jquery-notific8-container').addClass('top').addClass('right')); $body.append($('<div />').addClass('jquery-notific8-container').addClass('top').addClass('left')); $body.append($('<div />').addClass('jquery-notific8-container').addClass('bottom').addClass('right')); $body.append($('<div />').addClass('jquery-notific8-container').addClass('bottom').addClass('left')); $('.jquery-notific8-container').css('z-index', settings.zindex); } // make sure the edge settings exist if ((!options.hasOwnProperty('verticalEdge')) || ((options.verticalEdge.toLowerCase() != 'right') && (options.verticalEdge.toLowerCase() != 'left'))) { options.verticalEdge = settings.verticalEdge; } if ((!options.hasOwnProperty('horizontalEdge')) || ((options.horizontalEdge.toLowerCase() != 'top') && (options.horizontalEdge.toLowerCase() != 'bottom'))) { options.horizontalEdge = settings.horizontalEdge; } options.verticalEdge = options.verticalEdge.toLowerCase(); options.horizontalEdge = options.horizontalEdge.toLowerCase(); //display the notification in the right corner $('.jquery-notific8-container.' + options.verticalEdge + '.' + options.horizontalEdge).notific8(message, options); break; } }; // plugin setup $.fn.notific8 = function(message, options) { if (typeof message == "string") { return methods.init.apply(this, arguments); } else { $.error('jQuery.notific8 takes a string message as the first parameter'); } }; })(jQuery);
JavaScript
/*! * typeahead.js 0.10.0 * https://github.com/twitter/typeahead.js * Copyright 2013 Twitter, Inc. and other contributors; Licensed MIT */ (function($) { var _ = { isMsie: function() { return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; }, isBlankString: function(str) { return !str || /^\s*$/.test(str); }, escapeRegExChars: function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }, isString: function(obj) { return typeof obj === "string"; }, isNumber: function(obj) { return typeof obj === "number"; }, isArray: $.isArray, isFunction: $.isFunction, isObject: $.isPlainObject, isUndefined: function(obj) { return typeof obj === "undefined"; }, bind: $.proxy, each: function(collection, cb) { $.each(collection, reverseArgs); function reverseArgs(index, value) { return cb(value, index); } }, map: $.map, filter: $.grep, every: function(obj, test) { var result = true; if (!obj) { return result; } $.each(obj, function(key, val) { if (!(result = test.call(null, val, key, obj))) { return false; } }); return !!result; }, some: function(obj, test) { var result = false; if (!obj) { return result; } $.each(obj, function(key, val) { if (result = test.call(null, val, key, obj)) { return false; } }); return !!result; }, mixin: $.extend, getUniqueId: function() { var counter = 0; return function() { return counter++; }; }(), templatify: function templatify(obj) { return $.isFunction(obj) ? obj : template; function template() { return String(obj); } }, defer: function(fn) { setTimeout(fn, 0); }, debounce: function(func, wait, immediate) { var timeout, result; return function() { var context = this, args = arguments, later, callNow; later = function() { timeout = null; if (!immediate) { result = func.apply(context, args); } }; callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; }; }, throttle: function(func, wait) { var context, args, timeout, result, previous, later; previous = 0; later = function() { previous = new Date(); timeout = null; result = func.apply(context, args); }; return function() { var now = new Date(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }, noop: function() {} }; var VERSION = "0.10.0"; var LruCache = function(root, undefined) { function LruCache(maxSize) { this.maxSize = maxSize || 100; this.size = 0; this.hash = {}; this.list = new List(); } _.mixin(LruCache.prototype, { set: function set(key, val) { var tailItem = this.list.tail, node; if (this.size >= this.maxSize) { this.list.remove(tailItem); delete this.hash[tailItem.key]; } if (node = this.hash[key]) { node.val = val; this.list.moveToFront(node); } else { node = new Node(key, val); this.list.add(node); this.hash[key] = node; this.size++; } }, get: function get(key) { var node = this.hash[key]; if (node) { this.list.moveToFront(node); return node.val; } } }); function List() { this.head = this.tail = null; } _.mixin(List.prototype, { add: function add(node) { if (this.head) { node.next = this.head; this.head.prev = node; } this.head = node; this.tail = this.tail || node; }, remove: function remove(node) { node.prev ? node.prev.next = node.next : this.head = node.next; node.next ? node.next.prev = node.prev : this.tail = node.prev; }, moveToFront: function(node) { this.remove(node); this.add(node); } }); function Node(key, val) { this.key = key; this.val = val; this.prev = this.next = null; } return LruCache; }(this); var PersistentStorage = function() { var ls, methods; try { ls = window.localStorage; ls.setItem("~~~", "!"); ls.removeItem("~~~"); } catch (err) { ls = null; } function PersistentStorage(namespace) { this.prefix = [ "__", namespace, "__" ].join(""); this.ttlKey = "__ttl__"; this.keyMatcher = new RegExp("^" + this.prefix); } if (ls && window.JSON) { methods = { _prefix: function(key) { return this.prefix + key; }, _ttlKey: function(key) { return this._prefix(key) + this.ttlKey; }, get: function(key) { if (this.isExpired(key)) { this.remove(key); } return decode(ls.getItem(this._prefix(key))); }, set: function(key, val, ttl) { if (_.isNumber(ttl)) { ls.setItem(this._ttlKey(key), encode(now() + ttl)); } else { ls.removeItem(this._ttlKey(key)); } return ls.setItem(this._prefix(key), encode(val)); }, remove: function(key) { ls.removeItem(this._ttlKey(key)); ls.removeItem(this._prefix(key)); return this; }, clear: function() { var i, key, keys = [], len = ls.length; for (i = 0; i < len; i++) { if ((key = ls.key(i)).match(this.keyMatcher)) { keys.push(key.replace(this.keyMatcher, "")); } } for (i = keys.length; i--; ) { this.remove(keys[i]); } return this; }, isExpired: function(key) { var ttl = decode(ls.getItem(this._ttlKey(key))); return _.isNumber(ttl) && now() > ttl ? true : false; } }; } else { methods = { get: _.noop, set: _.noop, remove: _.noop, clear: _.noop, isExpired: _.noop }; } _.mixin(PersistentStorage.prototype, methods); return PersistentStorage; function now() { return new Date().getTime(); } function encode(val) { return JSON.stringify(_.isUndefined(val) ? null : val); } function decode(val) { return JSON.parse(val); } }(); var Transport = function() { var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, requestCache = new LruCache(10); function Transport(o) { o = o || {}; this._send = o.send ? callbackToDeferred(o.send) : $.ajax; this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get; } Transport.setMaxPendingRequests = function setMaxPendingRequests(num) { maxPendingRequests = num; }; Transport.resetCache = function clearCache() { requestCache = new LruCache(10); }; _.mixin(Transport.prototype, { _get: function(url, o, cb) { var that = this, jqXhr; if (jqXhr = pendingRequests[url]) { jqXhr.done(done); } else if (pendingRequestsCount < maxPendingRequests) { pendingRequestsCount++; pendingRequests[url] = this._send(url, o).done(done).always(always); } else { this.onDeckRequestArgs = [].slice.call(arguments, 0); } function done(resp) { cb && cb(resp); requestCache.set(url, resp); } function always() { pendingRequestsCount--; delete pendingRequests[url]; if (that.onDeckRequestArgs) { that._get.apply(that, that.onDeckRequestArgs); that.onDeckRequestArgs = null; } } }, get: function(url, o, cb) { var that = this, resp; if (_.isFunction(o)) { cb = o; o = {}; } if (resp = requestCache.get(url)) { _.defer(function() { cb && cb(resp); }); } else { this._get(url, o, cb); } return !!resp; } }); return Transport; function callbackToDeferred(fn) { return function customSendWrapper(url, o) { var deferred = $.Deferred(); fn(url, o, onSuccess, onError); return deferred; function onSuccess(resp) { _.defer(function() { deferred.resolve(resp); }); } function onError(err) { _.defer(function() { deferred.reject(err); }); } }; } }(); var SearchIndex = function() { function SearchIndex(o) { o = o || {}; if (!o.datumTokenizer || !o.queryTokenizer) { $.error("datumTokenizer and queryTokenizer are both required"); } this.datumTokenizer = o.datumTokenizer; this.queryTokenizer = o.queryTokenizer; this.datums = []; this.trie = newNode(); } _.mixin(SearchIndex.prototype, { bootstrap: function bootstrap(o) { this.datums = o.datums; this.trie = o.trie; }, add: function(data) { var that = this; data = _.isArray(data) ? data : [ data ]; _.each(data, function(datum) { var id, tokens; id = that.datums.push(datum) - 1; tokens = normalizeTokens(that.datumTokenizer(datum)); _.each(tokens, function(token) { var node, chars, ch, ids; node = that.trie; chars = token.split(""); while (ch = chars.shift()) { node = node.children[ch] || (node.children[ch] = newNode()); node.ids.push(id); } }); }); }, get: function get(query) { var that = this, tokens, matches; tokens = normalizeTokens(this.queryTokenizer(query)); _.each(tokens, function(token) { var node, chars, ch, ids; if (matches && matches.length === 0) { return false; } node = that.trie; chars = token.split(""); while (node && (ch = chars.shift())) { node = node.children[ch]; } if (node && chars.length === 0) { ids = node.ids.slice(0); matches = matches ? getIntersection(matches, ids) : ids; } else { matches = []; return false; } }); return matches ? _.map(unique(matches), function(id) { return that.datums[id]; }) : []; }, serialize: function serialize() { return { datums: this.datums, trie: this.trie }; } }); return SearchIndex; function normalizeTokens(tokens) { tokens = _.filter(tokens, function(token) { return !!token; }); tokens = _.map(tokens, function(token) { return token.toLowerCase(); }); return tokens; } function newNode() { return { ids: [], children: {} }; } function unique(array) { var seen = {}, uniques = []; for (var i = 0; i < array.length; i++) { if (!seen[array[i]]) { seen[array[i]] = true; uniques.push(array[i]); } } return uniques; } function getIntersection(arrayA, arrayB) { var ai = 0, bi = 0, intersection = []; arrayA = arrayA.sort(compare); arrayB = arrayB.sort(compare); while (ai < arrayA.length && bi < arrayB.length) { if (arrayA[ai] < arrayB[bi]) { ai++; } else if (arrayA[ai] > arrayB[bi]) { bi++; } else { intersection.push(arrayA[ai]); ai++; bi++; } } return intersection; function compare(a, b) { return a - b; } } }(); var oParser = function() { return { local: getLocal, prefetch: getPrefetch, remote: getRemote }; function getLocal(o) { return o.local || null; } function getPrefetch(o) { var prefetch, defaults; defaults = { url: null, thumbprint: "", ttl: 24 * 60 * 60 * 1e3, filter: null, ajax: {} }; if (prefetch = o.prefetch || null) { prefetch = _.isString(prefetch) ? { url: prefetch } : prefetch; prefetch = _.mixin(defaults, prefetch); prefetch.thumbprint = VERSION + prefetch.thumbprint; prefetch.ajax.method = prefetch.ajax.method || "get"; prefetch.ajax.dataType = prefetch.ajax.dataType || "json"; !prefetch.url && $.error("prefetch requires url to be set"); } return prefetch; } function getRemote(o) { var remote, defaults; defaults = { url: null, wildcard: "%QUERY", replace: null, rateLimitBy: "debounce", rateLimitWait: 300, send: null, filter: null, ajax: {} }; if (remote = o.remote || null) { remote = _.isString(remote) ? { url: remote } : remote; remote = _.mixin(defaults, remote); remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ? byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait); remote.ajax.method = remote.ajax.method || "get"; remote.ajax.dataType = remote.ajax.dataType || "json"; delete remote.rateLimitBy; delete remote.rateLimitWait; !remote.url && $.error("remote requires url to be set"); } return remote; function byDebounce(wait) { return function(fn) { return _.debounce(fn, wait); }; } function byThrottle(wait) { return function(fn) { return _.throttle(fn, wait); }; } } }(); var Bloodhound = window.Bloodhound = function() { var keys; keys = { data: "data", protocol: "protocol", thumbprint: "thumbprint" }; function Bloodhound(o) { if (!o || !o.local && !o.prefetch && !o.remote) { $.error("one of local, prefetch, or remote is required"); } this.limit = o.limit || 5; this.sorter = o.sorter || noSort; this.dupDetector = o.dupDetector || ignoreDuplicates; this.local = oParser.local(o); this.prefetch = oParser.prefetch(o); this.remote = oParser.remote(o); this.cacheKey = this.prefetch ? this.prefetch.cacheKey || this.prefetch.url : null; this.index = new SearchIndex({ datumTokenizer: o.datumTokenizer, queryTokenizer: o.queryTokenizer }); this.storage = this.cacheKey ? new PersistentStorage(this.cacheKey) : null; } Bloodhound.tokenizers = { whitespace: function whitespaceTokenizer(s) { return s.split(/\s+/); }, nonword: function nonwordTokenizer(s) { return s.split(/\W+/); } }; _.mixin(Bloodhound.prototype, { _loadPrefetch: function loadPrefetch(o) { var that = this, serialized, deferred; if (serialized = this._readFromStorage(o.thumbprint)) { this.index.bootstrap(serialized); deferred = $.Deferred().resolve(); } else { deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse); } return deferred; function handlePrefetchResponse(resp) { var filtered; filtered = o.filter ? o.filter(resp) : resp; that.add(filtered); that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl); } }, _getFromRemote: function getFromRemote(query, cb) { var that = this, url, uriEncodedQuery; query = query || ""; uriEncodedQuery = encodeURIComponent(query); url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery); return this.transport.get(url, this.remote.ajax, handleRemoteResponse); function handleRemoteResponse(resp) { var filtered = that.remote.filter ? that.remote.filter(resp) : resp; cb(filtered); } }, _saveToStorage: function saveToStorage(data, thumbprint, ttl) { if (this.storage) { this.storage.set(keys.data, data, ttl); this.storage.set(keys.protocol, location.protocol, ttl); this.storage.set(keys.thumbprint, thumbprint, ttl); } }, _readFromStorage: function readFromStorage(thumbprint) { var stored = {}; if (this.storage) { stored.data = this.storage.get(keys.data); stored.protocol = this.storage.get(keys.protocol); stored.thumbprint = this.storage.get(keys.thumbprint); } isExpired = stored.thumbprint !== thumbprint || stored.protocol !== location.protocol; return stored.data && !isExpired ? stored.data : null; }, initialize: function initialize() { var that = this, deferred; deferred = this.prefetch ? this._loadPrefetch(this.prefetch) : $.Deferred().resolve(); this.local && deferred.done(addLocalToIndex); this.transport = this.remote ? new Transport(this.remote) : null; this.initialize = function initialize() { return deferred.promise(); }; return deferred.promise(); function addLocalToIndex() { that.add(that.local); } }, add: function add(data) { this.index.add(data); }, get: function get(query, cb) { var that = this, matches, cacheHit = false; matches = this.index.get(query).sort(this.sorter).slice(0, this.limit); if (matches.length < this.limit && this.transport) { cacheHit = this._getFromRemote(query, returnRemoteMatches); } !cacheHit && cb && cb(matches); function returnRemoteMatches(remoteMatches) { var matchesWithBackfill = matches.slice(0); _.each(remoteMatches, function(remoteMatch) { var isDuplicate; isDuplicate = _.some(matchesWithBackfill, function(match) { return that.dupDetector(remoteMatch, match); }); !isDuplicate && matchesWithBackfill.push(remoteMatch); return matchesWithBackfill.length < that.limit; }); cb && cb(matchesWithBackfill.sort(that.sorter)); } }, ttAdapter: function ttAdapter() { return _.bind(this.get, this); } }); return Bloodhound; function noSort() { return 0; } function ignoreDuplicates() { return false; } }(); var html = { wrapper: '<span class="twitter-typeahead"></span>', dropdown: '<span class="tt-dropdown-menu"></span>', dataset: '<div class="tt-dataset-%CLASS%"></div>', suggestions: '<span class="tt-suggestions"></span>', suggestion: '<div class="tt-suggestion">%BODY%</div>' }; var css = { wrapper: { position: "relative", display: "inline-block" }, hint: { position: "absolute", top: "0", left: "0", borderColor: "transparent", boxShadow: "none" }, input: { position: "relative", verticalAlign: "top", backgroundColor: "transparent" }, inputWithNoHint: { position: "relative", verticalAlign: "top" }, dropdown: { position: "absolute", top: "100%", left: "0", zIndex: "100", display: "none" }, suggestions: { display: "block" }, suggestion: { whiteSpace: "nowrap", cursor: "pointer" }, suggestionChild: { whiteSpace: "normal" }, ltr: { left: "0", right: "auto" }, rtl: { left: "auto", right: " 0" } }; if (_.isMsie()) { _.mixin(css.input, { backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" }); } if (_.isMsie() && _.isMsie() <= 7) { _.mixin(css.input, { marginTop: "-1px" }); } var EventBus = function() { var namespace = "typeahead:"; function EventBus(o) { if (!o || !o.el) { $.error("EventBus initialized without el"); } this.$el = $(o.el); } _.mixin(EventBus.prototype, { trigger: function(type) { var args = [].slice.call(arguments, 1); this.$el.trigger(namespace + type, args); } }); return EventBus; }(); var EventEmitter = function() { var splitter = /\s+/, nextTick = getNextTick(); return { onSync: onSync, onAsync: onAsync, off: off, trigger: trigger }; function on(method, types, cb, context) { var type; if (!cb) { return this; } types = types.split(splitter); cb = context ? bindContext(cb, context) : cb; this._callbacks = this._callbacks || {}; while (type = types.shift()) { this._callbacks[type] = this._callbacks[type] || { sync: [], async: [] }; this._callbacks[type][method].push(cb); } return this; } function onAsync(types, cb, context) { return on.call(this, "async", types, cb, context); } function onSync(types, cb, context) { return on.call(this, "sync", types, cb, context); } function off(types) { var type; if (!this._callbacks) { return this; } types = types.split(splitter); while (type = types.shift()) { delete this._callbacks[type]; } return this; } function trigger(types) { var that = this, type, callbacks, args, syncFlush, asyncFlush; if (!this._callbacks) { return this; } types = types.split(splitter); args = [].slice.call(arguments, 1); while ((type = types.shift()) && (callbacks = this._callbacks[type])) { syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args)); asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args)); syncFlush() && nextTick(asyncFlush); } return this; } function getFlush(callbacks, context, args) { return flush; function flush() { var cancelled; for (var i = 0; !cancelled && i < callbacks.length; i += 1) { cancelled = callbacks[i].apply(context, args) === false; } return !cancelled; } } function getNextTick() { var nextTickFn, messageChannel; if (window.setImmediate) { nextTickFn = function nextTickSetImmediate(fn) { setImmediate(function() { fn(); }); }; } else { nextTickFn = function nextTickSetTimeout(fn) { setTimeout(function() { fn(); }, 0); }; } return nextTickFn; } function bindContext(fn, context) { return fn.bind ? fn.bind(context) : function() { fn.apply(context, [].slice.call(arguments, 0)); }; } }(); var highlight = function(doc) { var defaults = { node: null, pattern: null, tagName: "strong", className: null, wordsOnly: false, caseSensitive: false }; return function hightlight(o) { var regex; o = _.mixin({}, defaults, o); if (!o.node || !o.pattern) { return; } o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ]; regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly); traverse(o.node, hightlightTextNode); function hightlightTextNode(textNode) { var match, patternNode; if (match = regex.exec(textNode.data)) { wrapperNode = doc.createElement(o.tagName); o.className && (wrapperNode.className = o.className); patternNode = textNode.splitText(match.index); patternNode.splitText(match[0].length); wrapperNode.appendChild(patternNode.cloneNode(true)); textNode.parentNode.replaceChild(wrapperNode, patternNode); } return !!match; } function traverse(el, hightlightTextNode) { var childNode, TEXT_NODE_TYPE = 3; for (var i = 0; i < el.childNodes.length; i++) { childNode = el.childNodes[i]; if (childNode.nodeType === TEXT_NODE_TYPE) { i += hightlightTextNode(childNode) ? 1 : 0; } else { traverse(childNode, hightlightTextNode); } } } }; function getRegex(patterns, caseSensitive, wordsOnly) { var escapedPatterns = [], regexStr; for (var i = 0; i < patterns.length; i++) { escapedPatterns.push(_.escapeRegExChars(patterns[i])); } regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")"; return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i"); } }(window.document); var Input = function() { var specialKeyCodeMap; specialKeyCodeMap = { 9: "tab", 27: "esc", 37: "left", 39: "right", 13: "enter", 38: "up", 40: "down" }; function Input(o) { var that = this, onBlur, onFocus, onKeydown, onInput; o = o || {}; if (!o.input) { $.error("input is missing"); } onBlur = _.bind(this._onBlur, this); onFocus = _.bind(this._onFocus, this); onKeydown = _.bind(this._onKeydown, this); onInput = _.bind(this._onInput, this); this.$hint = $(o.hint); this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown); if (this.$hint.length === 0) { this.setHintValue = this.getHintValue = this.clearHint = _.noop; } if (!_.isMsie()) { this.$input.on("input.tt", onInput); } else { this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) { if (specialKeyCodeMap[$e.which || $e.keyCode]) { return; } _.defer(_.bind(that._onInput, that, $e)); }); } this.query = this.$input.val(); this.$overflowHelper = buildOverflowHelper(this.$input); } Input.normalizeQuery = function(str) { return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " "); }; _.mixin(Input.prototype, EventEmitter, { _onBlur: function onBlur($e) { this.resetInputValue(); this.trigger("blurred"); }, _onFocus: function onFocus($e) { this.trigger("focused"); }, _onKeydown: function onKeydown($e) { var keyName = specialKeyCodeMap[$e.which || $e.keyCode]; this._managePreventDefault(keyName, $e); if (keyName && this._shouldTrigger(keyName, $e)) { this.trigger(keyName + "Keyed", $e); } }, _onInput: function onInput($e) { this._checkInputValue(); }, _managePreventDefault: function managePreventDefault(keyName, $e) { var preventDefault, hintValue, inputValue; switch (keyName) { case "tab": hintValue = this.getHintValue(); inputValue = this.getInputValue(); preventDefault = hintValue && hintValue !== inputValue && !withModifier($e); break; case "up": case "down": preventDefault = !withModifier($e); break; default: preventDefault = false; } preventDefault && $e.preventDefault(); }, _shouldTrigger: function shouldTrigger(keyName, $e) { var trigger; switch (keyName) { case "tab": trigger = !withModifier($e); break; default: trigger = true; } return trigger; }, _checkInputValue: function checkInputValue() { var inputValue, areEquivalent, hasDifferentWhitespace; inputValue = this.getInputValue(); areEquivalent = areQueriesEquivalent(inputValue, this.query); hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false; if (!areEquivalent) { this.trigger("queryChanged", this.query = inputValue); } else if (hasDifferentWhitespace) { this.trigger("whitespaceChanged", this.query); } }, focus: function focus() { this.$input.focus(); }, blur: function blur() { this.$input.blur(); }, getQuery: function getQuery() { return this.query; }, setQuery: function setQuery(query) { this.query = query; }, getInputValue: function getInputValue() { return this.$input.val(); }, setInputValue: function setInputValue(value, silent) { this.$input.val(value); !silent && this._checkInputValue(); }, getHintValue: function getHintValue() { return this.$hint.val(); }, setHintValue: function setHintValue(value) { this.$hint.val(value); }, resetInputValue: function resetInputValue() { this.$input.val(this.query); }, clearHint: function clearHint() { this.$hint.val(""); }, getLanguageDirection: function getLanguageDirection() { return (this.$input.css("direction") || "ltr").toLowerCase(); }, hasOverflow: function hasOverflow() { var constraint = this.$input.width() - 2; this.$overflowHelper.text(this.getInputValue()); return this.$overflowHelper.width() >= constraint; }, isCursorAtEnd: function() { var valueLength, selectionStart, range; valueLength = this.$input.val().length; selectionStart = this.$input[0].selectionStart; if (_.isNumber(selectionStart)) { return selectionStart === valueLength; } else if (document.selection) { range = document.selection.createRange(); range.moveStart("character", -valueLength); return valueLength === range.text.length; } return true; }, destroy: function destroy() { this.$hint.off(".tt"); this.$input.off(".tt"); this.$hint = this.$input = this.$overflowHelper = null; } }); return Input; function buildOverflowHelper($input) { return $('<pre aria-hidden="true"></pre>').css({ position: "absolute", visibility: "hidden", whiteSpace: "nowrap", fontFamily: $input.css("font-family"), fontSize: $input.css("font-size"), fontStyle: $input.css("font-style"), fontVariant: $input.css("font-variant"), fontWeight: $input.css("font-weight"), wordSpacing: $input.css("word-spacing"), letterSpacing: $input.css("letter-spacing"), textIndent: $input.css("text-indent"), textRendering: $input.css("text-rendering"), textTransform: $input.css("text-transform") }).insertAfter($input); } function areQueriesEquivalent(a, b) { return Input.normalizeQuery(a) === Input.normalizeQuery(b); } function withModifier($e) { return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey; } }(); var Dataset = function() { var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum"; function Dataset(o) { o = o || {}; o.templates = o.templates || {}; if (!o.source) { $.error("missing source"); } this.query = null; this.highlight = !!o.highlight; this.name = o.name || _.getUniqueId(); this.source = o.source; this.valueKey = o.displayKey || "value"; this.templates = getTemplates(o.templates, this.valueKey); this.$el = $(html.dataset.replace("%CLASS%", this.name)); } Dataset.extractDatasetName = function extractDatasetName(el) { return $(el).data(datasetKey); }; Dataset.extractValue = function extractDatum(el) { return $(el).data(valueKey); }; Dataset.extractDatum = function extractDatum(el) { return $(el).data(datumKey); }; _.mixin(Dataset.prototype, EventEmitter, { _render: function render(query, suggestions) { if (!this.$el) { return; } var that = this, hasSuggestions; this.$el.empty(); hasSuggestions = suggestions && suggestions.length; if (!hasSuggestions && this.templates.empty) { this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null); } else if (hasSuggestions) { this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null); } this.trigger("rendered"); function getEmptyHtml() { return that.templates.empty({ query: query }); } function getSuggestionsHtml() { var $suggestions; $suggestions = $(html.suggestions).css(css.suggestions).append(_.map(suggestions, getSuggestionNode)); that.highlight && highlight({ node: $suggestions[0], pattern: query }); return $suggestions; function getSuggestionNode(suggestion) { var $el, innerHtml, outerHtml; innerHtml = that.templates.suggestion(suggestion); outerHtml = html.suggestion.replace("%BODY%", innerHtml); $el = $(outerHtml).data(datasetKey, that.name).data(valueKey, suggestion[that.valueKey]).data(datumKey, suggestion); $el.children().each(function() { $(this).css(css.suggestionChild); }); return $el; } } function getHeaderHtml() { return that.templates.header({ query: query, isEmpty: !hasSuggestions }); } function getFooterHtml() { return that.templates.footer({ query: query, isEmpty: !hasSuggestions }); } }, getRoot: function getRoot() { return this.$el; }, update: function update(query) { var that = this; this.query = query; this.source(query, renderIfQueryIsSame); function renderIfQueryIsSame(suggestions) { query === that.query && that._render(query, suggestions); } }, clear: function clear() { this._render(this.query || ""); }, isEmpty: function isEmpty() { return this.$el.is(":empty"); }, destroy: function destroy() { this.$el = null; } }); return Dataset; function getTemplates(templates, valueKey) { return { empty: templates.empty && _.templatify(templates.empty), header: templates.header && _.templatify(templates.header), footer: templates.footer && _.templatify(templates.footer), suggestion: templates.suggestion || suggestionTemplate }; function suggestionTemplate(context) { return "<p>" + context[valueKey] + "</p>"; } } }(); var Dropdown = function() { function Dropdown(o) { var that = this, onMouseEnter, onMouseLeave, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave; o = o || {}; if (!o.menu) { $.error("menu is required"); } this.isOpen = false; this.isEmpty = true; this.isMouseOverDropdown = false; this.datasets = _.map(o.datasets, initializeDataset); onMouseEnter = _.bind(this._onMouseEnter, this); onMouseLeave = _.bind(this._onMouseLeave, this); onSuggestionClick = _.bind(this._onSuggestionClick, this); onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this); onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this); this.$menu = $(o.menu).on("mouseenter.tt", onMouseEnter).on("mouseleave.tt", onMouseLeave).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave); _.each(this.datasets, function(dataset) { that.$menu.append(dataset.getRoot()); dataset.onSync("rendered", that._onRendered, that); }); } _.mixin(Dropdown.prototype, EventEmitter, { _onMouseEnter: function onMouseEnter($e) { this.isMouseOverDropdown = true; }, _onMouseLeave: function onMouseLeave($e) { this.isMouseOverDropdown = false; }, _onSuggestionClick: function onSuggestionClick($e) { this.trigger("suggestionClicked", $($e.currentTarget)); }, _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) { this._removeCursor(); this._setCursor($($e.currentTarget), true); }, _onSuggestionMouseLeave: function onSuggestionMouseLeave($e) { this._removeCursor(); }, _onRendered: function onRendered() { this.isEmpty = _.every(this.datasets, isDatasetEmpty); this.isEmpty ? this._hide() : this.isOpen && this._show(); this.trigger("datasetRendered"); function isDatasetEmpty(dataset) { return dataset.isEmpty(); } }, _hide: function() { this.$menu.hide(); }, _show: function() { this.$menu.css("display", "block"); }, _getSuggestions: function getSuggestions() { return this.$menu.find(".tt-suggestion"); }, _getCursor: function getCursor() { return this.$menu.find(".tt-cursor").first(); }, _setCursor: function setCursor($el, silent) { $el.first().addClass("tt-cursor"); !silent && this.trigger("cursorMoved"); }, _removeCursor: function removeCursor() { this._getCursor().removeClass("tt-cursor"); }, _moveCursor: function moveCursor(increment) { var $suggestions, $oldCursor, newCursorIndex, $newCursor; if (!this.isOpen) { return; } $oldCursor = this._getCursor(); $suggestions = this._getSuggestions(); this._removeCursor(); newCursorIndex = $suggestions.index($oldCursor) + increment; newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1; if (newCursorIndex === -1) { this.trigger("cursorRemoved"); return; } else if (newCursorIndex < -1) { newCursorIndex = $suggestions.length - 1; } this._setCursor($newCursor = $suggestions.eq(newCursorIndex)); this._ensureVisible($newCursor); }, _ensureVisible: function ensureVisible($el) { var elTop, elBottom, menuScrollTop, menuHeight; elTop = $el.position().top; elBottom = elTop + $el.outerHeight(true); menuScrollTop = this.$menu.scrollTop(); menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10); if (elTop < 0) { this.$menu.scrollTop(menuScrollTop + elTop); } else if (menuHeight < elBottom) { this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight)); } }, close: function close() { if (this.isOpen) { this.isOpen = this.isMouseOverDropdown = false; this._removeCursor(); this._hide(); this.trigger("closed"); } }, open: function open() { if (!this.isOpen) { this.isOpen = true; !this.isEmpty && this._show(); this.trigger("opened"); } }, setLanguageDirection: function setLanguageDirection(dir) { this.$menu.css(dir === "ltr" ? css.ltr : css.rtl); }, moveCursorUp: function moveCursorUp() { this._moveCursor(-1); }, moveCursorDown: function moveCursorDown() { this._moveCursor(+1); }, getDatumForSuggestion: function getDatumForSuggestion($el) { var datum = null; if ($el.length) { datum = { raw: Dataset.extractDatum($el), value: Dataset.extractValue($el), datasetName: Dataset.extractDatasetName($el) }; } return datum; }, getDatumForCursor: function getDatumForCursor() { return this.getDatumForSuggestion(this._getCursor().first()); }, getDatumForTopSuggestion: function getDatumForTopSuggestion() { return this.getDatumForSuggestion(this._getSuggestions().first()); }, update: function update(query) { _.each(this.datasets, updateDataset); function updateDataset(dataset) { dataset.update(query); } }, empty: function empty() { _.each(this.datasets, clearDataset); function clearDataset(dataset) { dataset.clear(); } }, isVisible: function isVisible() { return this.isOpen && !this.isEmpty; }, destroy: function destroy() { this.$menu.off(".tt"); this.$menu = null; _.each(this.datasets, destroyDataset); function destroyDataset(dataset) { dataset.destroy(); } } }); return Dropdown; function initializeDataset(oDataset) { return new Dataset(oDataset); } }(); var Typeahead = function() { var attrsKey = "ttAttrs"; function Typeahead(o) { var $menu, $input, $hint, datasets; o = o || {}; if (!o.input) { $.error("missing input"); } this.autoselect = !!o.autoselect; this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; this.$node = buildDomStructure(o.input, o.withHint); $menu = this.$node.find(".tt-dropdown-menu"); $input = this.$node.find(".tt-input"); $hint = this.$node.find(".tt-hint"); this.eventBus = o.eventBus || new EventBus({ el: $input }); this.dropdown = new Dropdown({ menu: $menu, datasets: o.datasets }).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this); this.input = new Input({ input: $input, hint: $hint }).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this); $menu.on("mousedown.tt", function($e) { if (_.isMsie() && _.isMsie() < 9) { $input[0].onbeforedeactivate = function() { window.event.returnValue = false; $input[0].onbeforedeactivate = null; }; } $e.preventDefault(); }); } _.mixin(Typeahead.prototype, { _onSuggestionClicked: function onSuggestionClicked(type, $el) { var datum; if (datum = this.dropdown.getDatumForSuggestion($el)) { this._select(datum); } }, _onCursorMoved: function onCursorMoved() { var datum = this.dropdown.getDatumForCursor(); this.input.clearHint(); this.input.setInputValue(datum.value, true); this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName); }, _onCursorRemoved: function onCursorRemoved() { this.input.resetInputValue(); this._updateHint(); }, _onDatasetRendered: function onDatasetRendered() { this._updateHint(); }, _onOpened: function onOpened() { this._updateHint(); this.eventBus.trigger("opened"); }, _onClosed: function onClosed() { this.input.clearHint(); this.eventBus.trigger("closed"); }, _onFocused: function onFocused() { this.dropdown.open(); }, _onBlurred: function onBlurred() { !this.dropdown.isMouseOverDropdown && this.dropdown.close(); }, _onEnterKeyed: function onEnterKeyed(type, $e) { var cursorDatum, topSuggestionDatum; cursorDatum = this.dropdown.getDatumForCursor(); topSuggestionDatum = this.dropdown.getDatumForTopSuggestion(); if (cursorDatum) { this._select(cursorDatum); $e.preventDefault(); } else if (this.autoselect && topSuggestionDatum) { this._select(topSuggestionDatum); $e.preventDefault(); } }, _onTabKeyed: function onTabKeyed(type, $e) { var datum; if (datum = this.dropdown.getDatumForCursor()) { this._select(datum); $e.preventDefault(); } else { this._autocomplete(); } }, _onEscKeyed: function onEscKeyed() { this.dropdown.close(); this.input.resetInputValue(); }, _onUpKeyed: function onUpKeyed() { var query = this.input.getQuery(); if (!this.dropdown.isOpen && query.length >= this.minLength) { this.dropdown.update(query); } this.dropdown.open(); this.dropdown.moveCursorUp(); }, _onDownKeyed: function onDownKeyed() { var query = this.input.getQuery(); if (!this.dropdown.isOpen && query.length >= this.minLength) { this.dropdown.update(query); } this.dropdown.open(); this.dropdown.moveCursorDown(); }, _onLeftKeyed: function onLeftKeyed() { this.dir === "rtl" && this._autocomplete(); }, _onRightKeyed: function onRightKeyed() { this.dir === "ltr" && this._autocomplete(); }, _onQueryChanged: function onQueryChanged(e, query) { this.input.clearHint(); this.dropdown.empty(); query.length >= this.minLength && this.dropdown.update(query); this.dropdown.open(); this._setLanguageDirection(); }, _onWhitespaceChanged: function onWhitespaceChanged() { this._updateHint(); this.dropdown.open(); }, _setLanguageDirection: function setLanguageDirection() { var dir; if (this.dir !== (dir = this.input.getLanguageDirection())) { this.dir = dir; this.$node.css("direction", dir); this.dropdown.setLanguageDirection(dir); } }, _updateHint: function updateHint() { var datum, inputValue, query, escapedQuery, frontMatchRegEx, match; datum = this.dropdown.getDatumForTopSuggestion(); if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) { inputValue = this.input.getInputValue(); query = Input.normalizeQuery(inputValue); escapedQuery = _.escapeRegExChars(query); frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.*$)", "i"); match = frontMatchRegEx.exec(datum.value); this.input.setHintValue(inputValue + (match ? match[1] : "")); } }, _autocomplete: function autocomplete() { var hint, query, datum; hint = this.input.getHintValue(); query = this.input.getQuery(); if (hint && query !== hint && this.input.isCursorAtEnd()) { datum = this.dropdown.getDatumForTopSuggestion(); datum && this.input.setInputValue(datum.value); this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName); } }, _select: function select(datum) { this.input.clearHint(); this.input.setQuery(datum.value); this.input.setInputValue(datum.value, true); this.dropdown.empty(); this._setLanguageDirection(); _.defer(_.bind(this.dropdown.close, this.dropdown)); this.eventBus.trigger("selected", datum.raw, datum.datasetName); }, open: function open() { this.dropdown.open(); }, close: function close() { this.dropdown.close(); }, getQuery: function getQuery() { return this.input.getQuery(); }, setQuery: function setQuery(val) { this.input.setInputValue(val); }, destroy: function destroy() { this.input.destroy(); this.dropdown.destroy(); destroyDomStructure(this.$node); this.$node = null; } }); return Typeahead; function buildDomStructure(input, withHint) { var $input, $wrapper, $dropdown, $hint; $input = $(input); $wrapper = $(html.wrapper).css(css.wrapper); $dropdown = $(html.dropdown).css(css.dropdown); $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input)); $hint.removeData().addClass("tt-hint").removeAttr("id name placeholder").prop("disabled", true).attr({ autocomplete: "off", spellcheck: "false" }); $input.data(attrsKey, { dir: $input.attr("dir"), autocomplete: $input.attr("autocomplete"), spellcheck: $input.attr("spellcheck"), style: $input.attr("style") }); $input.addClass("tt-input").attr({ autocomplete: "off", spellcheck: false }).css(withHint ? css.input : css.inputWithNoHint); try { !$input.attr("dir") && $input.attr("dir", "auto"); } catch (e) {} return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown); } function getBackgroundStyles($el) { return { backgroundAttachment: $el.css("background-attachment"), backgroundClip: $el.css("background-clip"), backgroundColor: $el.css("background-color"), backgroundImage: $el.css("background-image"), backgroundOrigin: $el.css("background-origin"), backgroundPosition: $el.css("background-position"), backgroundRepeat: $el.css("background-repeat"), backgroundSize: $el.css("background-size") }; } function destroyDomStructure($node) { var $input = $node.find(".tt-input"); _.each($input.data(attrsKey), function(val, key) { _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val); }); $input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node); $node.remove(); } }(); (function() { var typeaheadKey, methods; typeaheadKey = "ttTypeahead"; methods = { initialize: function initialize(o) { var datasets = [].slice.call(arguments, 1); o = o || {}; return this.each(attach); function attach() { var $input = $(this), eventBus, typeahead; _.each(datasets, function(d) { d.highlight = !!o.highlight; }); typeahead = new Typeahead({ input: $input, eventBus: eventBus = new EventBus({ el: $input }), withHint: _.isUndefined(o.hint) ? true : !!o.hint, minLength: o.minLength, autoselect: o.autoselect, datasets: datasets }); $input.data(typeaheadKey, typeahead); function trigger(eventName) { return function() { _.defer(function() { eventBus.trigger(eventName); }); }; } } }, open: function open() { return this.each(openTypeahead); function openTypeahead() { var $input = $(this), typeahead; if (typeahead = $input.data(typeaheadKey)) { typeahead.open(); } } }, close: function close() { return this.each(closeTypeahead); function closeTypeahead() { var $input = $(this), typeahead; if (typeahead = $input.data(typeaheadKey)) { typeahead.close(); } } }, val: function val(newVal) { return _.isString(newVal) ? this.each(setQuery) : this.map(getQuery).get(); function setQuery() { var $input = $(this), typeahead; if (typeahead = $input.data(typeaheadKey)) { typeahead.setQuery(newVal); } } function getQuery() { var $input = $(this), typeahead, query; if (typeahead = $input.data(typeaheadKey)) { query = typeahead.getQuery(); } return query; } }, destroy: function destroy() { return this.each(unattach); function unattach() { var $input = $(this), typeahead; if (typeahead = $input.data(typeaheadKey)) { typeahead.destroy(); $input.removeData(typeaheadKey); } } } }; jQuery.fn.typeahead = function(method) { if (methods[method]) { return methods[method].apply(this, [].slice.call(arguments, 1)); } else { return methods.initialize.apply(this, arguments); } }; })(); })(window.jQuery);
JavaScript
/* Holder - 2.0 - client side image placeholders (c) 2012-2013 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //getElementsByClassName polyfill document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s}) //getComputedStyle polyfill window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}) //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} //hasOwnProperty polyfill if (!Object.prototype.hasOwnProperty) Object.prototype.hasOwnProperty = function(prop) { var proto = this.__proto__ || this.constructor.prototype; return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]); } function text_size(width, height, template) { height = parseInt(height,10); width = parseInt(width,10); var bigSide = Math.max(height, width) var smallSide = Math.min(height, width) var scale = 1 / 12; var newHeight = Math.min(smallSide * 0.75, 0.75 * bigSide * scale); return { height: Math.round(Math.max(template.size, newHeight)) } } function draw(ctx, dimensions, template, ratio) { var ts = text_size(dimensions.width, dimensions.height, template); var text_height = ts.height; var width = dimensions.width * ratio, height = dimensions.height * ratio; var font = template.font ? template.font : "sans-serif"; canvas.width = width; canvas.height = height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, width, height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px " + font; var text = template.text ? template.text : (Math.floor(dimensions.width) + "x" + Math.floor(dimensions.height)); var text_width = ctx.measureText(text).width; if (text_width / width >= 0.75) { text_height = Math.floor(text_height * 0.75 * (width/text_width)); } //Resetting font size if necessary ctx.font = "bold " + (text_height * ratio) + "px " + font; ctx.fillText(text, (width / 2), (height / 2), width); return canvas.toDataURL("image/png"); } function render(mode, el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text ? decodeURIComponent(holder.text) : holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); theme = (holder.font ? extend(theme, { font: holder.font }) : theme); if (mode == "image") { el.setAttribute("data-src", src); el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); if (fallback || !holder.auto) { el.style.width = dimensions.width + "px"; el.style.height = dimensions.height + "px"; } if (fallback) { el.style.backgroundColor = theme.background; } else { el.setAttribute("src", draw(ctx, dimensions, theme, ratio)); } } else if (mode == "background") { if (!fallback) { el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")"; el.style.backgroundSize = dimensions.width + "px " + dimensions.height + "px"; } } else if (mode == "fluid") { el.setAttribute("data-src", src); el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); if (dimensions.height.substr(-1) == "%") { el.style.height = dimensions.height } else { el.style.height = dimensions.height + "px" } if (dimensions.width.substr(-1) == "%") { el.style.width = dimensions.width } else { el.style.width = dimensions.width + "px" } if (el.style.display == "inline" || el.style.display == "") { el.style.display = "block"; } if (fallback) { el.style.backgroundColor = theme.background; } else { el.holderData = holder; fluid_images.push(el); fluid_update(el); } } }; function fluid_update(element) { var images; if (element.nodeType == null) { images = fluid_images; } else { images = [element] } for (i in images) { var el = images[i] if (el.holderData) { var holder = el.holderData; el.setAttribute("src", draw(ctx, { height: el.clientHeight, width: el.clientWidth }, holder.theme, ratio)); } } } function parse_flags(flags, options) { var ret = { theme: settings.themes.gray }, render = false; for (sl = flags.length, j = 0; j < sl; j++) { var flag = flags[j]; if (app.flags.dimensions.match(flag)) { render = true; ret.dimensions = app.flags.dimensions.output(flag); } else if (app.flags.fluid.match(flag)) { render = true; ret.dimensions = app.flags.fluid.output(flag); ret.fluid = true; } else if (app.flags.colors.match(flag)) { ret.theme = app.flags.colors.output(flag); } else if (options.themes[flag]) { //If a theme is specified, it will override custom colors ret.theme = options.themes[flag]; } else if (app.flags.text.match(flag)) { ret.text = app.flags.text.output(flag); } else if (app.flags.font.match(flag)) { ret.font = app.flags.font.output(flag); } else if (app.flags.auto.match(flag)) { ret.auto = true; } } return render ? ret : false; }; if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png") .indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var dpr = 1, bsr = 1; if(!fallback){ dpr = window.devicePixelRatio || 1, bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; } var ratio = dpr / bsr; var fluid_images = []; var settings = { domain: "holder.js", images: "img", bgnodes: ".holderjs", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } }, stylesheet: "" }; app.flags = { dimensions: { regex: /^(\d+)x(\d+)$/, output: function (val) { var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, fluid: { regex: /^([0-9%]+)x([0-9%]+)$/, output: function (val) { var exec = this.regex.exec(val); return { width: exec[1], height: exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function (val) { var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } }, font: { regex: /font\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } }, auto: { regex: /^auto$/ } } for (var flag in app.flags) { if (!app.flags.hasOwnProperty(flag)) continue; app.flags[flag].match = function (val) { return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images = [], imageNodes = [], bgnodes = []; if(typeof(options.images) == "string"){ imageNodes = selector(options.images); } else if (window.NodeList && options.images instanceof window.NodeList) { imageNodes = options.images; } else if (window.Node && options.images instanceof window.Node) { imageNodes = [options.images]; } if(typeof(options.bgnodes) == "string"){ bgnodes = selector(options.bgnodes); } else if (window.NodeList && options.elements instanceof window.NodeList) { bgnodes = options.bgnodes; } else if (window.Node && options.bgnodes instanceof window.Node) { bgnodes = [options.bgnodes]; } preempted = true; for (i = 0, l = imageNodes.length; i < l; i++) images.push(imageNodes[i]); var holdercss = document.getElementById("holderjs-style"); if (!holdercss) { holdercss = document.createElement("style"); holdercss.setAttribute("id", "holderjs-style"); holdercss.type = "text/css"; document.getElementsByTagName("head")[0].appendChild(holdercss); } if (!options.nocss) { if (holdercss.styleSheet) { holdercss.styleSheet.cssText += options.stylesheet; } else { holdercss.appendChild(document.createTextNode(options.stylesheet)); } } var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)"); for (var l = bgnodes.length, i = 0; i < l; i++) { var src = window.getComputedStyle(bgnodes[i], null) .getPropertyValue("background-image"); var flags = src.match(cssregex); var bgsrc = bgnodes[i].getAttribute("data-background-src"); if (flags) { var holder = parse_flags(flags[1].split("/"), options); if (holder) { render("background", bgnodes[i], holder, src); } } else if(bgsrc != null){ var holder = parse_flags(bgsrc.substr(bgsrc.lastIndexOf(options.domain) + options.domain.length + 1) .split("/"), options); if(holder){ render("background", bgnodes[i], holder, src); } } } for (l = images.length, i = 0; i < l; i++) { var attr_src = attr_data_src = src = null; try{ attr_src = images[i].getAttribute("src"); attr_datasrc = images[i].getAttribute("data-src"); }catch(e){} if (attr_datasrc == null && !! attr_src && attr_src.indexOf(options.domain) >= 0) { src = attr_src; } else if ( !! attr_datasrc && attr_datasrc.indexOf(options.domain) >= 0) { src = attr_datasrc; } if (src) { var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1) .split("/"), options); if (holder) { if (holder.fluid) { render("fluid", images[i], holder, src) } else { render("image", images[i], holder, src); } } } } return app; }; contentLoaded(win, function () { if (window.addEventListener) { window.addEventListener("resize", fluid_update, false); window.addEventListener("orientationchange", fluid_update, false); } else { window.attachEvent("onresize", fluid_update) } preempted || app.run(); }); if (typeof define === "function" && define.amd) { define("Holder", [], function () { return app; }); } })(Holder, window);
JavaScript
/** * jquery.plupload.queue.js * * Copyright 2009, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /* global jQuery:true, alert:true */ /** jQuery based implementation of the Plupload API - multi-runtime file uploading API. To use the widget you must include _jQuery_. It is not meant to be extended in any way and is provided to be used as it is. @example <!-- Instantiating: --> <div id="uploader"> <p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p> </div> <script> $('#uploader').pluploadQueue({ url : '../upload.php', filters : [ {title : "Image files", extensions : "jpg,gif,png"} ], rename: true, flash_swf_url : '../../js/Moxie.swf', silverlight_xap_url : '../../js/Moxie.xap', }); </script> @example // Retrieving a reference to plupload.Uploader object var uploader = $('#uploader').pluploadQueue(); uploader.bind('FilesAdded', function() { // Autostart setTimeout(uploader.start, 1); // "detach" from the main thread }); @class pluploadQueue @constructor @param {Object} settings For detailed information about each option check documentation. @param {String} settings.url URL of the server-side upload handler. @param {Number|String} [settings.chunk_size=0] Chunk size in bytes to slice the file into. Shorcuts with b, kb, mb, gb, tb suffixes also supported. `e.g. 204800 or "204800b" or "200kb"`. By default - disabled. @param {String} [settings.file_data_name="file"] Name for the file field in Multipart formated message. @param {Array} [settings.filters=[]] Set of file type filters, each one defined by hash of title and extensions. `e.g. {title : "Image files", extensions : "jpg,jpeg,gif,png"}`. Dispatches `plupload.FILE_EXTENSION_ERROR` @param {String} [settings.flash_swf_url] URL of the Flash swf. @param {Object} [settings.headers] Custom headers to send with the upload. Hash of name/value pairs. @param {Number|String} [settings.max_file_size] Maximum file size that the user can pick, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. `e.g. "10mb" or "1gb"`. By default - not set. Dispatches `plupload.FILE_SIZE_ERROR`. @param {Number} [settings.max_retries=0] How many times to retry the chunk or file, before triggering Error event. @param {Boolean} [settings.multipart=true] Whether to send file and additional parameters as Multipart formated message. @param {Object} [settings.multipart_params] Hash of key/value pairs to send with every file upload. @param {Boolean} [settings.multi_selection=true] Enable ability to select multiple files at once in file dialog. @param {Boolean} [settings.prevent_duplicates=false] Do not let duplicates into the queue. Dispatches `plupload.FILE_DUPLICATE_ERROR`. @param {String|Object} [settings.required_features] Either comma-separated list or hash of required features that chosen runtime should absolutely possess. @param {Object} [settings.resize] Enable resizng of images on client-side. Applies to `image/jpeg` and `image/png` only. `e.g. {width : 200, height : 200, quality : 90, crop: true}` @param {Number} [settings.resize.width] If image is bigger, it will be resized. @param {Number} [settings.resize.height] If image is bigger, it will be resized. @param {Number} [settings.resize.quality=90] Compression quality for jpegs (1-100). @param {Boolean} [settings.resize.crop=false] Whether to crop images to exact dimensions. By default they will be resized proportionally. @param {String} [settings.runtimes="html5,flash,silverlight,html4"] Comma separated list of runtimes, that Plupload will try in turn, moving to the next if previous fails. @param {String} [settings.silverlight_xap_url] URL of the Silverlight xap. @param {Boolean} [settings.unique_names=false] If true will generate unique filenames for uploaded files. @param {Boolean} [settings.dragdrop=true] Enable ability to add file to the queue by drag'n'dropping them from the desktop. @param {Boolean} [settings.rename=false] Enable ability to rename files in the queue. @param {Boolean} [settings.multiple_queues=true] Re-activate the widget after each upload procedure. */ (function($) { var uploaders = {}; function _(str) { return plupload.translate(str) || str; } function renderUI(id, target) { // Remove all existing non plupload items target.contents().each(function(i, node) { node = $(node); if (!node.is('.plupload')) { node.remove(); } }); target.prepend( '<div class="plupload_wrapper plupload_scroll">' + '<div id="' + id + '_container" class="plupload_container">' + '<div class="plupload">' + '<div class="plupload_header">' + '<div class="plupload_header_content">' + '<div class="plupload_header_title">' + _('Select files') + '</div>' + '<div class="plupload_header_text">' + _('Add files to the upload queue and click the start button.') + '</div>' + '</div>' + '</div>' + '<div class="plupload_content">' + '<div class="plupload_filelist_header">' + '<div class="plupload_file_name">' + _('Filename') + '</div>' + '<div class="plupload_file_action">&nbsp;</div>' + '<div class="plupload_file_status"><span>' + _('Status') + '</span></div>' + '<div class="plupload_file_size">' + _('Size') + '</div>' + '<div class="plupload_clearer">&nbsp;</div>' + '</div>' + '<ul id="' + id + '_filelist" class="plupload_filelist"></ul>' + '<div class="plupload_filelist_footer">' + '<div class="plupload_file_name">' + '<div class="plupload_buttons">' + '<a href="#" class="plupload_button plupload_add" id="' + id + '_browse">' + _('Add Files') + '</a>' + '<a href="#" class="plupload_button plupload_start">' + _('Start Upload') + '</a>' + '</div>' + '<span class="plupload_upload_status"></span>' + '</div>' + '<div class="plupload_file_action"></div>' + '<div class="plupload_file_status"><span class="plupload_total_status">0%</span></div>' + '<div class="plupload_file_size"><span class="plupload_total_file_size">0 b</span></div>' + '<div class="plupload_progress">' + '<div class="plupload_progress_container">' + '<div class="plupload_progress_bar"></div>' + '</div>' + '</div>' + '<div class="plupload_clearer">&nbsp;</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '<input type="hidden" id="' + id + '_count" name="' + id + '_count" value="0" />' + '</div>' ); } $.fn.pluploadQueue = function(settings) { if (settings) { this.each(function() { var uploader, target, id, contents_bak; target = $(this); id = target.attr('id'); if (!id) { id = plupload.guid(); target.attr('id', id); } contents_bak = target.html(); renderUI(id, target); settings = $.extend({ dragdrop : true, browse_button : id + '_browse', container : id }, settings); // Enable drag/drop (see PostInit handler as well) if (settings.dragdrop) { settings.drop_element = id + '_filelist'; } uploader = new plupload.Uploader(settings); uploaders[id] = uploader; function handleStatus(file) { var actionClass; if (file.status == plupload.DONE) { actionClass = 'plupload_done'; } if (file.status == plupload.FAILED) { actionClass = 'plupload_failed'; } if (file.status == plupload.QUEUED) { actionClass = 'plupload_delete'; } if (file.status == plupload.UPLOADING) { actionClass = 'plupload_uploading'; } var icon = $('#' + file.id).attr('class', actionClass).find('a').css('display', 'block'); if (file.hint) { icon.attr('title', file.hint); } } function updateTotalProgress() { $('span.plupload_total_status', target).html(uploader.total.percent + '%'); $('div.plupload_progress_bar', target).css('width', uploader.total.percent + '%'); $('span.plupload_upload_status', target).html( _('Uploaded %d/%d files').replace(/%d\/%d/, uploader.total.uploaded+'/'+uploader.files.length) ); } function updateList() { var fileList = $('ul.plupload_filelist', target).html(''), inputCount = 0, inputHTML; $.each(uploader.files, function(i, file) { inputHTML = ''; if (file.status == plupload.DONE) { if (file.target_name) { inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_tmpname" value="' + plupload.xmlEncode(file.target_name) + '" />'; } inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_name" value="' + plupload.xmlEncode(file.name) + '" />'; inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_status" value="' + (file.status == plupload.DONE ? 'done' : 'failed') + '" />'; inputCount++; $('#' + id + '_count').val(inputCount); } fileList.append( '<li id="' + file.id + '">' + '<div class="plupload_file_name"><span>' + file.name + '</span></div>' + '<div class="plupload_file_action"><a href="#"></a></div>' + '<div class="plupload_file_status">' + file.percent + '%</div>' + '<div class="plupload_file_size">' + plupload.formatSize(file.size) + '</div>' + '<div class="plupload_clearer">&nbsp;</div>' + inputHTML + '</li>' ); handleStatus(file); $('#' + file.id + '.plupload_delete a').click(function(e) { $('#' + file.id).remove(); uploader.removeFile(file); e.preventDefault(); }); }); $('span.plupload_total_file_size', target).html(plupload.formatSize(uploader.total.size)); if (uploader.total.queued === 0) { $('span.plupload_add_text', target).html(_('Add Files')); } else { $('span.plupload_add_text', target).html(_('%d files queued').replace(/%d/, uploader.total.queued)); } $('a.plupload_start', target).toggleClass('plupload_disabled', uploader.files.length == (uploader.total.uploaded + uploader.total.failed)); // Scroll to end of file list fileList[0].scrollTop = fileList[0].scrollHeight; updateTotalProgress(); // Re-add drag message if there is no files if (!uploader.files.length && uploader.features.dragdrop && uploader.settings.dragdrop) { $('#' + id + '_filelist').append('<li class="plupload_droptext">' + _("Drag files here.") + '</li>'); } } function destroy() { delete uploaders[id]; uploader.destroy(); target.html(contents_bak); uploader = target = contents_bak = null; } uploader.bind("UploadFile", function(up, file) { $('#' + file.id).addClass('plupload_current_file'); }); uploader.bind('Init', function(up, res) { // Enable rename support if (!settings.unique_names && settings.rename) { target.on('click', '#' + id + '_filelist div.plupload_file_name span', function(e) { var targetSpan = $(e.target), file, parts, name, ext = ""; // Get file name and split out name and extension file = up.getFile(targetSpan.parents('li')[0].id); name = file.name; parts = /^(.+)(\.[^.]+)$/.exec(name); if (parts) { name = parts[1]; ext = parts[2]; } // Display input element targetSpan.hide().after('<input type="text" />'); targetSpan.next().val(name).focus().blur(function() { targetSpan.show().next().remove(); }).keydown(function(e) { var targetInput = $(this); if (e.keyCode == 13) { e.preventDefault(); // Rename file and glue extension back on file.name = targetInput.val() + ext; targetSpan.html(file.name); targetInput.blur(); } }); }); } $('#' + id + '_container').attr('title', 'Using runtime: ' + res.runtime); $('a.plupload_start', target).click(function(e) { if (!$(this).hasClass('plupload_disabled')) { uploader.start(); } e.preventDefault(); }); $('a.plupload_stop', target).click(function(e) { e.preventDefault(); uploader.stop(); }); $('a.plupload_start', target).addClass('plupload_disabled'); }); uploader.bind("Error", function(up, err) { var file = err.file, message; if (file) { message = err.message; if (err.details) { message += " (" + err.details + ")"; } if (err.code == plupload.FILE_SIZE_ERROR) { alert(_("Error: File too large:") + " " + file.name); } if (err.code == plupload.FILE_EXTENSION_ERROR) { alert(_("Error: Invalid file extension:") + " " + file.name); } file.hint = message; $('#' + file.id).attr('class', 'plupload_failed').find('a').css('display', 'block').attr('title', message); } if (err.code === plupload.INIT_ERROR) { setTimeout(function() { destroy(); }, 1); } }); uploader.bind("PostInit", function(up) { // features are populated only after input components are fully instantiated if (up.settings.dragdrop && up.features.dragdrop) { $('#' + id + '_filelist').append('<li class="plupload_droptext">' + _("Drag files here.") + '</li>'); } }); uploader.init(); uploader.bind('StateChanged', function() { if (uploader.state === plupload.STARTED) { $('li.plupload_delete a,div.plupload_buttons', target).hide(); $('span.plupload_upload_status,div.plupload_progress,a.plupload_stop', target).css('display', 'block'); $('span.plupload_upload_status', target).html('Uploaded ' + uploader.total.uploaded + '/' + uploader.files.length + ' files'); if (settings.multiple_queues) { $('span.plupload_total_status,span.plupload_total_file_size', target).show(); } } else { updateList(); $('a.plupload_stop,div.plupload_progress', target).hide(); $('a.plupload_delete', target).css('display', 'block'); if (settings.multiple_queues && uploader.total.uploaded + uploader.total.failed == uploader.files.length) { $(".plupload_buttons,.plupload_upload_status", target).css("display", "inline"); $(".plupload_start", target).addClass("plupload_disabled"); $('span.plupload_total_status,span.plupload_total_file_size', target).hide(); } } }); uploader.bind('FilesAdded', updateList); uploader.bind('FilesRemoved', function() { // since the whole file list is redrawn for every change in the queue // we need to scroll back to the file removal point to avoid annoying // scrolling to the bottom bug (see #926) var scrollTop = $('#' + id + '_filelist').scrollTop(); updateList(); $('#' + id + '_filelist').scrollTop(scrollTop); }); uploader.bind('FileUploaded', function(up, file) { handleStatus(file); }); uploader.bind("UploadProgress", function(up, file) { // Set file specific progress $('#' + file.id + ' div.plupload_file_status', target).html(file.percent + '%'); handleStatus(file); updateTotalProgress(); }); // Call setup function if (settings.setup) { settings.setup(uploader); } }); return this; } else { // Get uploader instance for specified element return uploaders[$(this[0]).attr('id')]; } }; })(jQuery);
JavaScript
/** * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill * v1.1.0 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2013-12-27 */ /** * Compiled inline version. (Library mode) */ /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ /*globals $code */ (function(exports, undefined) { "use strict"; var modules = {}; function require(ids, callback) { var module, defs = []; for (var i = 0; i < ids.length; ++i) { module = modules[ids[i]] || resolve(ids[i]); if (!module) { throw 'module definition dependecy not found: ' + ids[i]; } defs.push(module); } callback.apply(null, defs); } function define(id, dependencies, definition) { if (typeof id !== 'string') { throw 'invalid module definition, module id must be defined and be a string'; } if (dependencies === undefined) { throw 'invalid module definition, dependencies must be specified'; } if (definition === undefined) { throw 'invalid module definition, definition function must be specified'; } require(dependencies, function() { modules[id] = definition.apply(null, arguments); }); } function defined(id) { return !!modules[id]; } function resolve(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length; ++fi) { if (!target[fragments[fi]]) { return; } target = target[fragments[fi]]; } return target; } function expose(ids) { for (var i = 0; i < ids.length; i++) { var target = exports; var id = ids[i]; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length - 1; ++fi) { if (target[fragments[fi]] === undefined) { target[fragments[fi]] = {}; } target = target[fragments[fi]]; } target[fragments[fragments.length - 1]] = modules[id]; } } // Included from: src/javascript/core/utils/Basic.js /** * Basic.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Basic', [], function() { /** Gets the true type of the built-in object (better version of typeof). @author Angus Croll (http://javascriptweblog.wordpress.com/) @method typeOf @for Utils @static @param {Object} o Object to check. @return {String} Object [[Class]] */ var typeOf = function(o) { var undef; if (o === undef) { return 'undefined'; } else if (o === null) { return 'null'; } else if (o.nodeType) { return 'node'; } // the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8 return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); }; /** Extends the specified object with another object. @method extend @static @param {Object} target Object to extend. @param {Object} [obj]* Multiple objects to extend with. @return {Object} Same as target, the extended object. */ var extend = function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }; /** Executes the callback function for each item in array/object. If you return false in the callback it will break the loop. @method each @static @param {Object} obj Object to iterate. @param {function} callback Callback function to execute for each item. */ var each = function(obj, callback) { var length, key, i, undef; if (obj) { try { length = obj.length; } catch(ex) { length = undef; } if (length === undef) { // Loop object items for (key in obj) { if (obj.hasOwnProperty(key)) { if (callback(obj[key], key) === false) { return; } } } } else { // Loop array items for (i = 0; i < length; i++) { if (callback(obj[i], i) === false) { return; } } } } }; /** Checks if object is empty. @method isEmptyObj @static @param {Object} o Object to check. @return {Boolean} */ var isEmptyObj = function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }; /** Recieve an array of functions (usually async) to call in sequence, each function receives a callback as first argument that it should call, when it completes. Finally, after everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the sequence and invoke main callback immediately. @method inSeries @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of erro */ var inSeries = function(queue, cb) { var i = 0, length = queue.length; if (typeOf(cb) !== 'function') { cb = function() {}; } if (!queue || !queue.length) { cb(); } function callNext(i) { if (typeOf(queue[i]) === 'function') { queue[i](function(error) { /*jshint expr:true */ ++i < length && !error ? callNext(i) : cb(error); }); } } callNext(i); }; /** Find an element in array and return it's index if present, otherwise return -1. @method inArray @static @param {Mixed} needle Element to find @param {Array} array @return {Int} Index of the element, or -1 if not found */ var inArray = function(needle, array) { if (array) { if (Array.prototype.indexOf) { return Array.prototype.indexOf.call(array, needle); } for (var i = 0, length = array.length; i < length; i++) { if (array[i] === needle) { return i; } } } return -1; }; /** Returns elements of first array if they are not present in second. And false - otherwise. @private @method arrayDiff @param {Array} needles @param {Array} array @return {Array|Boolean} */ var arrayDiff = function(needles, array) { var diff = []; if (typeOf(needles) !== 'array') { needles = [needles]; } if (typeOf(array) !== 'array') { array = [array]; } for (var i in needles) { if (inArray(needles[i], array) === -1) { diff.push(needles[i]); } } return diff.length ? diff : false; }; /** Find intersection of two arrays. @private @method arrayIntersect @param {Array} array1 @param {Array} array2 @return {Array} Intersection of two arrays or null if there is none */ var arrayIntersect = function(array1, array2) { var result = []; each(array1, function(item) { if (inArray(item, array2) !== -1) { result.push(item); } }); return result.length ? result : null; }; /** Forces anything into an array. @method toArray @static @param {Object} obj Object with length field. @return {Array} Array object containing all items. */ var toArray = function(obj) { var i, arr = []; for (i = 0; i < obj.length; i++) { arr[i] = obj[i]; } return arr; }; /** Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers. The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique. It's more probable for the earth to be hit with an ansteriod. Y @method guid @static @param {String} prefix to prepend (by default 'o' will be prepended). @method guid @return {String} Virtually unique id. */ var guid = (function() { var counter = 0; return function(prefix) { var guid = new Date().getTime().toString(32), i; for (i = 0; i < 5; i++) { guid += Math.floor(Math.random() * 65535).toString(32); } return (prefix || 'o_') + guid + (counter++).toString(32); }; }()); /** Trims white spaces around the string @method trim @static @param {String} str @return {String} */ var trim = function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }; /** Parses the specified size string into a byte value. For example 10kb becomes 10240. @method parseSizeStr @static @param {String/Number} size String to parse or number to just pass through. @return {Number} Size in bytes. */ var parseSizeStr = function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }; return { guid: guid, typeOf: typeOf, extend: extend, each: each, isEmptyObj: isEmptyObj, inSeries: inSeries, inArray: inArray, arrayDiff: arrayDiff, arrayIntersect: arrayIntersect, toArray: toArray, trim: trim, parseSizeStr: parseSizeStr }; }); // Included from: src/javascript/core/I18n.js /** * I18n.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/I18n", [ "moxie/core/utils/Basic" ], function(Basic) { var i18n = {}; return { /** * Extends the language pack object with new items. * * @param {Object} pack Language pack items to add. * @return {Object} Extended language pack object. */ addI18n: function(pack) { return Basic.extend(i18n, pack); }, /** * Translates the specified string by checking for the english string in the language pack lookup. * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ translate: function(str) { return i18n[str] || str; }, /** * Shortcut for translate function * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ _: function(str) { return this.translate(str); }, /** * Pseudo sprintf implementation - simple way to replace tokens with specified values. * * @param {String} str String with tokens * @return {String} String with replaced tokens */ sprintf: function(str) { var args = [].slice.call(arguments, 1); return str.replace(/%[a-z]/g, function() { return args.shift() || ''; }); } }; }); // Included from: src/javascript/core/utils/Mime.js /** * Mime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Mime", [ "moxie/core/utils/Basic", "moxie/core/I18n" ], function(Basic, I18n) { var mimeData = "" + "application/msword,doc dot," + "application/pdf,pdf," + "application/pgp-signature,pgp," + "application/postscript,ps ai eps," + "application/rtf,rtf," + "application/vnd.ms-excel,xls xlb," + "application/vnd.ms-powerpoint,ppt pps pot," + "application/zip,zip," + "application/x-shockwave-flash,swf swfl," + "application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," + "application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," + "application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," + "application/vnd.openxmlformats-officedocument.presentationml.template,potx," + "application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," + "application/x-javascript,js," + "application/json,json," + "audio/mpeg,mp3 mpga mpega mp2," + "audio/x-wav,wav," + "audio/x-m4a,m4a," + "audio/ogg,oga ogg," + "audio/aiff,aiff aif," + "audio/flac,flac," + "audio/aac,aac," + "audio/ac3,ac3," + "audio/x-ms-wma,wma," + "image/bmp,bmp," + "image/gif,gif," + "image/jpeg,jpg jpeg jpe," + "image/photoshop,psd," + "image/png,png," + "image/svg+xml,svg svgz," + "image/tiff,tiff tif," + "text/plain,asc txt text diff log," + "text/html,htm html xhtml," + "text/css,css," + "text/csv,csv," + "text/rtf,rtf," + "video/mpeg,mpeg mpg mpe m2v," + "video/quicktime,qt mov," + "video/mp4,mp4," + "video/x-m4v,m4v," + "video/x-flv,flv," + "video/x-ms-wmv,wmv," + "video/avi,avi," + "video/webm,webm," + "video/3gpp,3gpp 3gp," + "video/3gpp2,3g2," + "video/vnd.rn-realvideo,rv," + "video/ogg,ogv," + "video/x-matroska,mkv," + "application/vnd.oasis.opendocument.formula-template,otf," + "application/octet-stream,exe"; var Mime = { mimes: {}, extensions: {}, // Parses the default mime types string into a mimes and extensions lookup maps addMimeType: function (mimeData) { var items = mimeData.split(/,/), i, ii, ext; for (i = 0; i < items.length; i += 2) { ext = items[i + 1].split(/ /); // extension to mime lookup for (ii = 0; ii < ext.length; ii++) { this.mimes[ext[ii]] = items[i]; } // mime to extension lookup this.extensions[items[i]] = ext; } }, extList2mimes: function (filters, addMissingExtensions) { var self = this, ext, i, ii, type, mimes = []; // convert extensions to mime types list for (i = 0; i < filters.length; i++) { ext = filters[i].extensions.split(/\s*,\s*/); for (ii = 0; ii < ext.length; ii++) { // if there's an asterisk in the list, then accept attribute is not required if (ext[ii] === '*') { return []; } type = self.mimes[ext[ii]]; if (!type) { if (addMissingExtensions && /^\w+$/.test(ext[ii])) { mimes.push('.' + ext[ii]); } else { return []; // accept all } } else if (Basic.inArray(type, mimes) === -1) { mimes.push(type); } } } return mimes; }, mimes2exts: function(mimes) { var self = this, exts = []; Basic.each(mimes, function(mime) { if (mime === '*') { exts = []; return false; } // check if this thing looks like mime type var m = mime.match(/^(\w+)\/(\*|\w+)$/); if (m) { if (m[2] === '*') { // wildcard mime type detected Basic.each(self.extensions, function(arr, mime) { if ((new RegExp('^' + m[1] + '/')).test(mime)) { [].push.apply(exts, self.extensions[mime]); } }); } else if (self.extensions[mime]) { [].push.apply(exts, self.extensions[mime]); } } }); return exts; }, mimes2extList: function(mimes) { var accept = [], exts = []; if (Basic.typeOf(mimes) === 'string') { mimes = Basic.trim(mimes).split(/\s*,\s*/); } exts = this.mimes2exts(mimes); accept.push({ title: I18n.translate('Files'), extensions: exts.length ? exts.join(',') : '*' }); // save original mimes string accept.mimes = mimes; return accept; }, getFileExtension: function(fileName) { var matches = fileName && fileName.match(/\.([^.]+)$/); if (matches) { return matches[1].toLowerCase(); } return ''; }, getFileMime: function(fileName) { return this.mimes[this.getFileExtension(fileName)] || ''; } }; Mime.addMimeType(mimeData); return Mime; }); // Included from: src/javascript/core/utils/Env.js /** * Env.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Env", [ "moxie/core/utils/Basic" ], function(Basic) { // UAParser.js v0.6.2 // Lightweight JavaScript-based User-Agent string parser // https://github.com/faisalman/ua-parser-js // // Copyright © 2012-2013 Faisalman <fyzlman@gmail.com> // Dual licensed under GPLv2 & MIT var UAParser = (function (undefined) { ////////////// // Constants ///////////// var EMPTY = '', UNKNOWN = '?', FUNC_TYPE = 'function', UNDEF_TYPE = 'undefined', OBJ_TYPE = 'object', MAJOR = 'major', MODEL = 'model', NAME = 'name', TYPE = 'type', VENDOR = 'vendor', VERSION = 'version', ARCHITECTURE= 'architecture', CONSOLE = 'console', MOBILE = 'mobile', TABLET = 'tablet'; /////////// // Helper ////////// var util = { has : function (str1, str2) { return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; }, lowerize : function (str) { return str.toLowerCase(); } }; /////////////// // Map helper ////////////// var mapper = { rgx : function () { // loop through all regexes maps for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) { var regex = args[i], // even sequence (0,2,4,..) props = args[i + 1]; // odd sequence (1,3,5,..) // construct object barebones if (typeof(result) === UNDEF_TYPE) { result = {}; for (p in props) { q = props[p]; if (typeof(q) === OBJ_TYPE) { result[q[0]] = undefined; } else { result[q] = undefined; } } } // try matching uastring with regexes for (j = k = 0; j < regex.length; j++) { matches = regex[j].exec(this.getUA()); if (!!matches) { for (p = 0; p < props.length; p++) { match = matches[++k]; q = props[p]; // check if given property is actually array if (typeof(q) === OBJ_TYPE && q.length > 0) { if (q.length == 2) { if (typeof(q[1]) == FUNC_TYPE) { // assign modified match result[q[0]] = q[1].call(this, match); } else { // assign given value, ignore regex match result[q[0]] = q[1]; } } else if (q.length == 3) { // check whether function or regex if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) { // call function (usually string mapper) result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; } else { // sanitize match using given regex result[q[0]] = match ? match.replace(q[1], q[2]) : undefined; } } else if (q.length == 4) { result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; } } else { result[q] = match ? match : undefined; } } break; } } if(!!matches) break; // break the loop immediately if match found } return result; }, str : function (str, map) { for (var i in map) { // check if array if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) { for (var j = 0; j < map[i].length; j++) { if (util.has(map[i][j], str)) { return (i === UNKNOWN) ? undefined : i; } } } else if (util.has(map[i], str)) { return (i === UNKNOWN) ? undefined : i; } } return str; } }; /////////////// // String map ////////////// var maps = { browser : { oldsafari : { major : { '1' : ['/8', '/1', '/3'], '2' : '/4', '?' : '/' }, version : { '1.0' : '/8', '1.2' : '/1', '1.3' : '/3', '2.0' : '/412', '2.0.2' : '/416', '2.0.3' : '/417', '2.0.4' : '/419', '?' : '/' } } }, device : { sprint : { model : { 'Evo Shift 4G' : '7373KT' }, vendor : { 'HTC' : 'APA', 'Sprint' : 'Sprint' } } }, os : { windows : { version : { 'ME' : '4.90', 'NT 3.11' : 'NT3.51', 'NT 4.0' : 'NT4.0', '2000' : 'NT 5.0', 'XP' : ['NT 5.1', 'NT 5.2'], 'Vista' : 'NT 6.0', '7' : 'NT 6.1', '8' : 'NT 6.2', '8.1' : 'NT 6.3', 'RT' : 'ARM' } } } }; ////////////// // Regex map ///////////// var regexes = { browser : [[ // Presto based /(opera\smini)\/((\d+)?[\w\.-]+)/i, // Opera Mini /(opera\s[mobiletab]+).+version\/((\d+)?[\w\.-]+)/i, // Opera Mobi/Tablet /(opera).+version\/((\d+)?[\w\.]+)/i, // Opera > 9.80 /(opera)[\/\s]+((\d+)?[\w\.]+)/i // Opera < 9.80 ], [NAME, VERSION, MAJOR], [ /\s(opr)\/((\d+)?[\w\.]+)/i // Opera Webkit ], [[NAME, 'Opera'], VERSION, MAJOR], [ // Mixed /(kindle)\/((\d+)?[\w\.]+)/i, // Kindle /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?((\d+)?[\w\.]+)*/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer // Trident based /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?((\d+)?[\w\.]*)/i, // Avant/IEMobile/SlimBrowser/Baidu /(?:ms|\()(ie)\s((\d+)?[\w\.]+)/i, // Internet Explorer // Webkit/KHTML based /(rekonq)((?:\/)[\w\.]+)*/i, // Rekonq /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron)\/((\d+)?[\w\.-]+)/i // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron ], [NAME, VERSION, MAJOR], [ /(trident).+rv[:\s]((\d+)?[\w\.]+).+like\sgecko/i // IE11 ], [[NAME, 'IE'], VERSION, MAJOR], [ /(yabrowser)\/((\d+)?[\w\.]+)/i // Yandex ], [[NAME, 'Yandex'], VERSION, MAJOR], [ /(comodo_dragon)\/((\d+)?[\w\.]+)/i // Comodo Dragon ], [[NAME, /_/g, ' '], VERSION, MAJOR], [ /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?((\d+)?[\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia ], [NAME, VERSION, MAJOR], [ /(dolfin)\/((\d+)?[\w\.]+)/i // Dolphin ], [[NAME, 'Dolphin'], VERSION, MAJOR], [ /((?:android.+)crmo|crios)\/((\d+)?[\w\.]+)/i // Chrome for Android/iOS ], [[NAME, 'Chrome'], VERSION, MAJOR], [ /((?:android.+))version\/((\d+)?[\w\.]+)\smobile\ssafari/i // Android Browser ], [[NAME, 'Android Browser'], VERSION, MAJOR], [ /version\/((\d+)?[\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari ], [VERSION, MAJOR, [NAME, 'Mobile Safari']], [ /version\/((\d+)?[\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile ], [VERSION, MAJOR, NAME], [ /webkit.+?(mobile\s?safari|safari)((\/[\w\.]+))/i // Safari < 3.0 ], [NAME, [MAJOR, mapper.str, maps.browser.oldsafari.major], [VERSION, mapper.str, maps.browser.oldsafari.version]], [ /(konqueror)\/((\d+)?[\w\.]+)/i, // Konqueror /(webkit|khtml)\/((\d+)?[\w\.]+)/i ], [NAME, VERSION, MAJOR], [ // Gecko based /(navigator|netscape)\/((\d+)?[\w\.-]+)/i // Netscape ], [[NAME, 'Netscape'], VERSION, MAJOR], [ /(swiftfox)/i, // Swiftfox /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?((\d+)?[\w\.\+]+)/i, // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/((\d+)?[\w\.-]+)/i, // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix /(mozilla)\/((\d+)?[\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla // Other /(uc\s?browser|polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|qqbrowser)[\/\s]?((\d+)?[\w\.]+)/i, // UCBrowser/Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/QQBrowser /(links)\s\(((\d+)?[\w\.]+)/i, // Links /(gobrowser)\/?((\d+)?[\w\.]+)*/i, // GoBrowser /(ice\s?browser)\/v?((\d+)?[\w\._]+)/i, // ICE Browser /(mosaic)[\/\s]((\d+)?[\w\.]+)/i // Mosaic ], [NAME, VERSION, MAJOR] ], engine : [[ /(presto)\/([\w\.]+)/i, // Presto /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab ], [NAME, VERSION], [ /rv\:([\w\.]+).*(gecko)/i // Gecko ], [VERSION, NAME] ], os : [[ // Windows based /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [ /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ // Mobile/Embedded OS /\((bb)(10);/i // BlackBerry 10 ], [[NAME, 'BlackBerry'], VERSION], [ /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry /(tizen)\/([\w\.]+)/i, // Tizen /(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego)[\/\s-]?([\w\.]+)*/i // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo ], [NAME, VERSION], [ /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian ], [[NAME, 'Symbian'], VERSION],[ /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS ], [[NAME, 'Firefox OS'], VERSION], [ // Console /(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation // GNU/Linux based /(mint)[\/\s\(]?(\w+)*/i, // Mint /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)[\/\s-]?([\w\.-]+)*/i, // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux /(gnu)\s?([\w\.]+)*/i // GNU ], [NAME, VERSION], [ /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS ], [[NAME, 'Chromium OS'], VERSION],[ // Solaris /(sunos)\s?([\w\.]+\d)*/i // Solaris ], [[NAME, 'Solaris'], VERSION], [ // BSD based /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly ], [NAME, VERSION],[ /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [ /(mac\sos\sx)\s?([\w\s\.]+\w)*/i // Mac OS ], [NAME, [VERSION, /_/g, '.']], [ // Other /(haiku)\s(\w+)/i, // Haiku /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX /(macintosh|mac(?=_powerpc)|plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos)/i, // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS /(unix)\s?([\w\.]+)*/i // UNIX ], [NAME, VERSION] ] }; ///////////////// // Constructor //////////////// var UAParser = function (uastring) { var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY); this.getBrowser = function () { return mapper.rgx.apply(this, regexes.browser); }; this.getEngine = function () { return mapper.rgx.apply(this, regexes.engine); }; this.getOS = function () { return mapper.rgx.apply(this, regexes.os); }; this.getResult = function() { return { ua : this.getUA(), browser : this.getBrowser(), engine : this.getEngine(), os : this.getOS() }; }; this.getUA = function () { return ua; }; this.setUA = function (uastring) { ua = uastring; return this; }; this.setUA(ua); }; return new UAParser().getResult(); })(); function version_compare(v1, v2, operator) { // From: http://phpjs.org/functions // + original by: Philippe Jausions (http://pear.php.net/user/jausions) // + original by: Aidan Lister (http://aidanlister.com/) // + reimplemented by: Kankrelune (http://www.webfaktory.info/) // + improved by: Brett Zamir (http://brett-zamir.me) // + improved by: Scott Baker // + improved by: Theriault // * example 1: version_compare('8.2.5rc', '8.2.5a'); // * returns 1: 1 // * example 2: version_compare('8.2.50', '8.2.52', '<'); // * returns 2: true // * example 3: version_compare('5.3.0-dev', '5.3.0'); // * returns 3: -1 // * example 4: version_compare('4.1.0.52','4.01.0.51'); // * returns 4: 1 // Important: compare must be initialized at 0. var i = 0, x = 0, compare = 0, // vm maps textual PHP versions to negatives so they're less than 0. // PHP currently defines these as CASE-SENSITIVE. It is important to // leave these as negatives so that they can come before numerical versions // and as if no letters were there to begin with. // (1alpha is < 1 and < 1.1 but > 1dev1) // If a non-numerical value can't be mapped to this table, it receives // -7 as its value. vm = { 'dev': -6, 'alpha': -5, 'a': -5, 'beta': -4, 'b': -4, 'RC': -3, 'rc': -3, '#': -2, 'p': 1, 'pl': 1 }, // This function will be called to prepare each version argument. // It replaces every _, -, and + with a dot. // It surrounds any nonsequence of numbers/dots with dots. // It replaces sequences of dots with a single dot. // version_compare('4..0', '4.0') == 0 // Important: A string of 0 length needs to be converted into a value // even less than an unexisting value in vm (-7), hence [-8]. // It's also important to not strip spaces because of this. // version_compare('', ' ') == 1 prepVersion = function (v) { v = ('' + v).replace(/[_\-+]/g, '.'); v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.'); return (!v.length ? [-8] : v.split('.')); }, // This converts a version component to a number. // Empty component becomes 0. // Non-numerical component becomes a negative number. // Numerical component becomes itself as an integer. numVersion = function (v) { return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10)); }; v1 = prepVersion(v1); v2 = prepVersion(v2); x = Math.max(v1.length, v2.length); for (i = 0; i < x; i++) { if (v1[i] == v2[i]) { continue; } v1[i] = numVersion(v1[i]); v2[i] = numVersion(v2[i]); if (v1[i] < v2[i]) { compare = -1; break; } else if (v1[i] > v2[i]) { compare = 1; break; } } if (!operator) { return compare; } // Important: operator is CASE-SENSITIVE. // "No operator" seems to be treated as "<." // Any other values seem to make the function return null. switch (operator) { case '>': case 'gt': return (compare > 0); case '>=': case 'ge': return (compare >= 0); case '<=': case 'le': return (compare <= 0); case '==': case '=': case 'eq': return (compare === 0); case '<>': case '!=': case 'ne': return (compare !== 0); case '': case '<': case 'lt': return (compare < 0); default: return null; } } var can = (function() { var caps = { define_property: (function() { /* // currently too much extra code required, not exactly worth it try { // as of IE8, getters/setters are supported only on DOM elements var obj = {}; if (Object.defineProperty) { Object.defineProperty(obj, 'prop', { enumerable: true, configurable: true }); return true; } } catch(ex) {} if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { return true; }*/ return false; }()), create_canvas: (function() { // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ var el = document.createElement('canvas'); return !!(el.getContext && el.getContext('2d')); }()), return_response_type: function(responseType) { try { if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) { return true; } else if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); xhr.open('get', '/'); // otherwise Gecko throws an exception if ('responseType' in xhr) { xhr.responseType = responseType; // as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?) if (xhr.responseType !== responseType) { return false; } return true; } } } catch (ex) {} return false; }, // ideas for this heavily come from Modernizr (http://modernizr.com/) use_data_uri: (function() { var du = new Image(); du.onload = function() { caps.use_data_uri = (du.width === 1 && du.height === 1); }; setTimeout(function() { du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; }, 1); return false; }()), use_data_uri_over32kb: function() { // IE8 return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9); }, use_data_uri_of: function(bytes) { return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb()); }, use_fileinput: function() { var el = document.createElement('input'); el.setAttribute('type', 'file'); return !el.disabled; } }; return function(cap) { var args = [].slice.call(arguments); args.shift(); // shift of cap return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap]; }; }()); var Env = { can: can, browser: UAParser.browser.name, version: parseFloat(UAParser.browser.major), os: UAParser.os.name, // everybody intuitively types it in a lowercase for some reason osVersion: UAParser.os.version, verComp: version_compare, swf_url: "../flash/Moxie.swf", xap_url: "../silverlight/Moxie.xap", global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent" }; // for backward compatibility // @deprecated Use `Env.os` instead Env.OS = Env.os; return Env; }); // Included from: src/javascript/core/utils/Dom.js /** * Dom.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) { /** Get DOM Element by it's id. @method get @for Utils @param {String} id Identifier of the DOM Element @return {DOMElement} */ var get = function(id) { if (typeof id !== 'string') { return id; } return document.getElementById(id); }; /** Checks if specified DOM element has specified class. @method hasClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var hasClass = function(obj, name) { if (!obj.className) { return false; } var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); return regExp.test(obj.className); }; /** Adds specified className to specified DOM element. @method addClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var addClass = function(obj, name) { if (!hasClass(obj, name)) { obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name; } }; /** Removes specified className from specified DOM element. @method removeClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var removeClass = function(obj, name) { if (obj.className) { var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); obj.className = obj.className.replace(regExp, function($0, $1, $2) { return $1 === ' ' && $2 === ' ' ? ' ' : ''; }); } }; /** Returns a given computed style of a DOM element. @method getStyle @static @param {Object} obj DOM element like object. @param {String} name Style you want to get from the DOM element */ var getStyle = function(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else if (window.getComputedStyle) { return window.getComputedStyle(obj, null)[name]; } }; /** Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields. @method getPos @static @param {Element} node HTML element or element id to get x, y position from. @param {Element} root Optional root element to stop calculations at. @return {object} Absolute position of the specified element object with x, y fields. */ var getPos = function(node, root) { var x = 0, y = 0, parent, doc = document, nodeRect, rootRect; node = node; root = root || doc.body; // Returns the x, y cordinate for an element on IE 6 and IE 7 function getIEPos(node) { var bodyElm, rect, x = 0, y = 0; if (node) { rect = node.getBoundingClientRect(); bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body; x = rect.left + bodyElm.scrollLeft; y = rect.top + bodyElm.scrollTop; } return { x : x, y : y }; } // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) { nodeRect = getIEPos(node); rootRect = getIEPos(root); return { x : nodeRect.x - rootRect.x, y : nodeRect.y - rootRect.y }; } parent = node; while (parent && parent != root && parent.nodeType) { x += parent.offsetLeft || 0; y += parent.offsetTop || 0; parent = parent.offsetParent; } parent = node.parentNode; while (parent && parent != root && parent.nodeType) { x -= parent.scrollLeft || 0; y -= parent.scrollTop || 0; parent = parent.parentNode; } return { x : x, y : y }; }; /** Returns the size of the specified node in pixels. @method getSize @static @param {Node} node Node to get the size of. @return {Object} Object with a w and h property. */ var getSize = function(node) { return { w : node.offsetWidth || node.clientWidth, h : node.offsetHeight || node.clientHeight }; }; return { get: get, hasClass: hasClass, addClass: addClass, removeClass: removeClass, getStyle: getStyle, getPos: getPos, getSize: getSize }; }); // Included from: src/javascript/core/Exceptions.js /** * Exceptions.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/Exceptions', [ 'moxie/core/utils/Basic' ], function(Basic) { function _findKey(obj, value) { var key; for (key in obj) { if (obj[key] === value) { return key; } } return null; } return { RuntimeError: (function() { var namecodes = { NOT_INIT_ERR: 1, NOT_SUPPORTED_ERR: 9, JS_ERR: 4 }; function RuntimeError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": RuntimeError " + this.code; } Basic.extend(RuntimeError, namecodes); RuntimeError.prototype = Error.prototype; return RuntimeError; }()), OperationNotAllowedException: (function() { function OperationNotAllowedException(code) { this.code = code; this.name = 'OperationNotAllowedException'; } Basic.extend(OperationNotAllowedException, { NOT_ALLOWED_ERR: 1 }); OperationNotAllowedException.prototype = Error.prototype; return OperationNotAllowedException; }()), ImageError: (function() { var namecodes = { WRONG_FORMAT: 1, MAX_RESOLUTION_ERR: 2 }; function ImageError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": ImageError " + this.code; } Basic.extend(ImageError, namecodes); ImageError.prototype = Error.prototype; return ImageError; }()), FileException: (function() { var namecodes = { NOT_FOUND_ERR: 1, SECURITY_ERR: 2, ABORT_ERR: 3, NOT_READABLE_ERR: 4, ENCODING_ERR: 5, NO_MODIFICATION_ALLOWED_ERR: 6, INVALID_STATE_ERR: 7, SYNTAX_ERR: 8 }; function FileException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": FileException " + this.code; } Basic.extend(FileException, namecodes); FileException.prototype = Error.prototype; return FileException; }()), DOMException: (function() { var namecodes = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; function DOMException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": DOMException " + this.code; } Basic.extend(DOMException, namecodes); DOMException.prototype = Error.prototype; return DOMException; }()), EventException: (function() { function EventException(code) { this.code = code; this.name = 'EventException'; } Basic.extend(EventException, { UNSPECIFIED_EVENT_TYPE_ERR: 0 }); EventException.prototype = Error.prototype; return EventException; }()) }; }); // Included from: src/javascript/core/EventTarget.js /** * EventTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/EventTarget', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic' ], function(x, Basic) { /** Parent object for all event dispatching components and objects @class EventTarget @constructor EventTarget */ function EventTarget() { // hash of event listeners by object uid var eventpool = {}; Basic.extend(this, { /** Unique id of the event dispatcher, usually overriden by children @property uid @type String */ uid: null, /** Can be called from within a child in order to acquire uniqie id in automated manner @method init */ init: function() { if (!this.uid) { this.uid = Basic.guid('uid_'); } }, /** Register a handler to a specific event dispatched by the object @method addEventListener @param {String} type Type or basically a name of the event to subscribe to @param {Function} fn Callback function that will be called when event happens @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first @param {Object} [scope=this] A scope to invoke event handler in */ addEventListener: function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }, /** Check if any handlers were registered to the specified event @method hasEventListener @param {String} type Type or basically a name of the event to check @return {Mixed} Returns a handler if it was found and false, if - not */ hasEventListener: function(type) { return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid]; }, /** Unregister the handler from the event, or if former was not specified - unregister all handlers @method removeEventListener @param {String} type Type or basically a name of the event @param {Function} [fn] Handler to unregister */ removeEventListener: function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }, /** Remove all event handlers from the object @method removeAllEventListeners */ removeAllEventListeners: function() { if (eventpool[this.uid]) { delete eventpool[this.uid]; } }, /** Dispatch the event @method dispatchEvent @param {String/Object} Type of event or event object to dispatch @param {Mixed} [...] Variable number of arguments to be passed to a handlers @return {Boolean} true by default and false if any handler returned false */ dispatchEvent: function(type) { var uid, list, args, tmpEvt, evt = {}, result = true, undef; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue, function(err) { result = !err; }); } } return result; }, /** Alias for addEventListener @method bind @protected */ bind: function() { this.addEventListener.apply(this, arguments); }, /** Alias for removeEventListener @method unbind @protected */ unbind: function() { this.removeEventListener.apply(this, arguments); }, /** Alias for removeAllEventListeners @method unbindAll @protected */ unbindAll: function() { this.removeAllEventListeners.apply(this, arguments); }, /** Alias for dispatchEvent @method trigger @protected */ trigger: function() { return this.dispatchEvent.apply(this, arguments); }, /** Converts properties of on[event] type to corresponding event handlers, is used to avoid extra hassle around the process of calling them back @method convertEventPropsToHandlers @private */ convertEventPropsToHandlers: function(handlers) { var h; if (Basic.typeOf(handlers) !== 'array') { handlers = [handlers]; } for (var i = 0; i < handlers.length; i++) { h = 'on' + handlers[i]; if (Basic.typeOf(this[h]) === 'function') { this.addEventListener(handlers[i], this[h]); } else if (Basic.typeOf(this[h]) === 'undefined') { this[h] = null; // object must have defined event properties, even if it doesn't make use of them } } } }); } EventTarget.instance = new EventTarget(); return EventTarget; }); // Included from: src/javascript/core/utils/Encode.js /** * Encode.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Encode', [], function() { /** Encode string with UTF-8 @method utf8_encode @for Utils @static @param {String} str String to encode @return {String} UTF-8 encoded string */ var utf8_encode = function(str) { return unescape(encodeURIComponent(str)); }; /** Decode UTF-8 encoded string @method utf8_decode @static @param {String} str String to decode @return {String} Decoded string */ var utf8_decode = function(str_data) { return decodeURIComponent(escape(str_data)); }; /** Decode Base64 encoded string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js @method atob @static @param {String} data String to decode @return {String} Decoded string */ var atob = function(data, utf8) { if (typeof(window.atob) === 'function') { return utf8 ? utf8_decode(window.atob(data)) : window.atob(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Thunder.m // + input by: Aman Gupta // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA=='); // * returns 1: 'Kevin van Zonneveld' // mozilla has this native // - but breaks in 2.0.0.12! //if (typeof this.window.atob == 'function') { // return atob(data); //} var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); return utf8 ? utf8_decode(dec) : dec; }; /** Base64 encode string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js @method btoa @static @param {String} data String to encode @return {String} Base64 encoded string */ var btoa = function(data, utf8) { if (utf8) { utf8_encode(data); } if (typeof(window.btoa) === 'function') { return window.btoa(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Bayron Guevara // + improved by: Thunder.m // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Rafał Kukawski (http://kukawski.pl) // * example 1: base64_encode('Kevin van Zonneveld'); // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' // mozilla has this native // - but breaks in 2.0.0.12! var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmp_arr = []; if (!data) { return data; } do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); var r = data.length % 3; return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); }; return { utf8_encode: utf8_encode, utf8_decode: utf8_decode, atob: atob, btoa: btoa }; }); // Included from: src/javascript/runtime/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/Runtime', [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/EventTarget" ], function(Basic, Dom, EventTarget) { var runtimeConstructors = {}, runtimes = {}; /** Common set of methods and properties for every runtime instance @class Runtime @param {Object} options @param {String} type Sanitized name of the runtime @param {Object} [caps] Set of capabilities that differentiate specified runtime @param {Object} [modeCaps] Set of capabilities that do require specific operational mode @param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested */ function Runtime(options, type, caps, modeCaps, preferredMode) { /** Dispatched when runtime is initialized and ready. Results in RuntimeInit on a connected component. @event Init */ /** Dispatched when runtime fails to initialize. Results in RuntimeError on a connected component. @event Error */ var self = this , _shim , _uid = Basic.guid(type + '_') , defaultMode = preferredMode || 'browser' ; options = options || {}; // register runtime in private hash runtimes[_uid] = this; /** Default set of capabilities, which can be redifined later by specific runtime @private @property caps @type Object */ caps = Basic.extend({ // Runtime can: // provide access to raw binary data of the file access_binary: false, // provide access to raw binary data of the image (image extension is optional) access_image_binary: false, // display binary data as thumbs for example display_media: false, // make cross-domain requests do_cors: false, // accept files dragged and dropped from the desktop drag_and_drop: false, // filter files in selection dialog by their extensions filter_by_extension: true, // resize image (and manipulate it raw data of any file in general) resize_image: false, // periodically report how many bytes of total in the file were uploaded (loaded) report_upload_progress: false, // provide access to the headers of http response return_response_headers: false, // support response of specific type, which should be passed as an argument // e.g. runtime.can('return_response_type', 'blob') return_response_type: false, // return http status code of the response return_status_code: true, // send custom http header with the request send_custom_headers: false, // pick up the files from a dialog select_file: false, // select whole folder in file browse dialog select_folder: false, // select multiple files at once in file browse dialog select_multiple: true, // send raw binary data, that is generated after image resizing or manipulation of other kind send_binary_string: false, // send cookies with http request and therefore retain session send_browser_cookies: true, // send data formatted as multipart/form-data send_multipart: true, // slice the file or blob to smaller parts slice_blob: false, // upload file without preloading it to memory, stream it out directly from disk stream_upload: false, // programmatically trigger file browse dialog summon_file_dialog: false, // upload file of specific size, size should be passed as argument // e.g. runtime.can('upload_filesize', '500mb') upload_filesize: true, // initiate http request with specific http method, method should be passed as argument // e.g. runtime.can('use_http_method', 'put') use_http_method: true }, caps); // default to the mode that is compatible with preferred caps if (options.preferred_caps) { defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode); } // small extension factory here (is meant to be extended with actual extensions constructors) _shim = (function() { var objpool = {}; return { exec: function(uid, comp, fn, args) { if (_shim[comp]) { if (!objpool[uid]) { objpool[uid] = { context: this, instance: new _shim[comp]() }; } if (objpool[uid].instance[fn]) { return objpool[uid].instance[fn].apply(this, args); } } }, removeInstance: function(uid) { delete objpool[uid]; }, removeAllInstances: function() { var self = this; Basic.each(objpool, function(obj, uid) { if (Basic.typeOf(obj.instance.destroy) === 'function') { obj.instance.destroy.call(obj.context); } self.removeInstance(uid); }); } }; }()); // public methods Basic.extend(this, { /** Specifies whether runtime instance was initialized or not @property initialized @type {Boolean} @default false */ initialized: false, // shims require this flag to stop initialization retries /** Unique ID of the runtime @property uid @type {String} */ uid: _uid, /** Runtime type (e.g. flash, html5, etc) @property type @type {String} */ type: type, /** Runtime (not native one) may operate in browser or client mode. @property mode @private @type {String|Boolean} current mode or false, if none possible */ mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode), /** id of the DOM container for the runtime (if available) @property shimid @type {String} */ shimid: _uid + '_container', /** Number of connected clients. If equal to zero, runtime can be destroyed @property clients @type {Number} */ clients: 0, /** Runtime initialization options @property options @type {Object} */ options: options, /** Checks if the runtime has specific capability @method can @param {String} cap Name of capability to check @param {Mixed} [value] If passed, capability should somehow correlate to the value @param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set) @return {Boolean} true if runtime has such capability and false, if - not */ can: function(cap, value) { var refCaps = arguments[2] || caps; // if cap var is a comma-separated list of caps, convert it to object (key/value) if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') { cap = Runtime.parseCaps(cap); } if (Basic.typeOf(cap) === 'object') { for (var key in cap) { if (!this.can(key, cap[key], refCaps)) { return false; } } return true; } // check the individual cap if (Basic.typeOf(refCaps[cap]) === 'function') { return refCaps[cap].call(this, value); } else { return (value === refCaps[cap]); } }, /** Returns container for the runtime as DOM element @method getShimContainer @return {DOMElement} */ getShimContainer: function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }, /** Returns runtime as DOM element (if appropriate) @method getShim @return {DOMElement} */ getShim: function() { return _shim; }, /** Invokes a method within the runtime itself (might differ across the runtimes) @method shimExec @param {Mixed} [] @protected @return {Mixed} Depends on the action and component */ shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return self.getShim().exec.call(this, this.uid, component, action, args); }, /** Operaional interface that is used by components to invoke specific actions on the runtime (is invoked in the scope of component) @method exec @param {Mixed} []* @protected @return {Mixed} Depends on the action and component */ exec: function(component, action) { // this is called in the context of component, not runtime var args = [].slice.call(arguments, 2); if (self[component] && self[component][action]) { return self[component][action].apply(this, args); } return self.shimExec.apply(this, arguments); }, /** Destroys the runtime (removes all events and deletes DOM structures) @method destroy */ destroy: function() { if (!self) { return; // obviously already destroyed } var shimContainer = Dom.get(this.shimid); if (shimContainer) { shimContainer.parentNode.removeChild(shimContainer); } if (_shim) { _shim.removeAllInstances(); } this.unbindAll(); delete runtimes[this.uid]; this.uid = null; // mark this runtime as destroyed _uid = self = _shim = shimContainer = null; } }); // once we got the mode, test against all caps if (this.mode && options.required_caps && !this.can(options.required_caps)) { this.mode = false; } } /** Default order to try different runtime types @property order @type String @static */ Runtime.order = 'html5,flash,silverlight,html4'; /** Retrieves runtime from private hash by it's uid @method getRuntime @private @static @param {String} uid Unique identifier of the runtime @return {Runtime|Boolean} Returns runtime, if it exists and false, if - not */ Runtime.getRuntime = function(uid) { return runtimes[uid] ? runtimes[uid] : false; }; /** Register constructor for the Runtime of new (or perhaps modified) type @method addConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {Function} construct Constructor for the Runtime type */ Runtime.addConstructor = function(type, constructor) { constructor.prototype = EventTarget.instance; runtimeConstructors[type] = constructor; }; /** Get the constructor for the specified type. method getConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @return {Function} Constructor for the Runtime type */ Runtime.getConstructor = function(type) { return runtimeConstructors[type] || null; }; /** Get info about the runtime (uid, type, capabilities) @method getInfo @static @param {String} uid Unique identifier of the runtime @return {Mixed} Info object or null if runtime doesn't exist */ Runtime.getInfo = function(uid) { var runtime = Runtime.getRuntime(uid); if (runtime) { return { uid: runtime.uid, type: runtime.type, mode: runtime.mode, can: function() { return runtime.can.apply(runtime, arguments); } }; } return null; }; /** Convert caps represented by a comma-separated string to the object representation. @method parseCaps @static @param {String} capStr Comma-separated list of capabilities @return {Object} */ Runtime.parseCaps = function(capStr) { var capObj = {}; if (Basic.typeOf(capStr) !== 'string') { return capStr || {}; } Basic.each(capStr.split(','), function(key) { capObj[key] = true; // we assume it to be - true }); return capObj; }; /** Test the specified runtime for specific capabilities. @method can @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {String|Object} caps Set of capabilities to check @return {Boolean} Result of the test */ Runtime.can = function(type, caps) { var runtime , constructor = Runtime.getConstructor(type) , mode ; if (constructor) { runtime = new constructor({ required_caps: caps }); mode = runtime.mode; runtime.destroy(); return !!mode; } return false; }; /** Figure out a runtime that supports specified capabilities. @method thatCan @static @param {String|Object} caps Set of capabilities to check @param {String} [runtimeOrder] Comma-separated list of runtimes to check against @return {String} Usable runtime identifier or null */ Runtime.thatCan = function(caps, runtimeOrder) { var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/); for (var i in types) { if (Runtime.can(types[i], caps)) { return types[i]; } } return null; }; /** Figure out an operational mode for the specified set of capabilities. @method getMode @static @param {Object} modeCaps Set of capabilities that depend on particular runtime mode @param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for @param {String|Boolean} [defaultMode='browser'] Default mode to use @return {String|Boolean} Compatible operational mode */ Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) { var mode = null; if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified defaultMode = 'browser'; } if (requiredCaps && !Basic.isEmptyObj(modeCaps)) { // loop over required caps and check if they do require the same mode Basic.each(requiredCaps, function(value, cap) { if (modeCaps.hasOwnProperty(cap)) { var capMode = modeCaps[cap](value); // make sure we always have an array if (typeof(capMode) === 'string') { capMode = [capMode]; } if (!mode) { mode = capMode; } else if (!(mode = Basic.arrayIntersect(mode, capMode))) { // if cap requires conflicting mode - runtime cannot fulfill required caps return (mode = false); } } }); if (mode) { return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0]; } else if (mode === false) { return false; } } return defaultMode; }; /** Capability check that always returns true @private @static @return {True} */ Runtime.capTrue = function() { return true; }; /** Capability check that always returns false @private @static @return {False} */ Runtime.capFalse = function() { return false; }; /** Evaluate the expression to boolean value and create a function that always returns it. @private @static @param {Mixed} expr Expression to evaluate @return {Function} Function returning the result of evaluation */ Runtime.capTest = function(expr) { return function() { return !!expr; }; }; return Runtime; }); // Included from: src/javascript/runtime/RuntimeClient.js /** * RuntimeClient.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeClient', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/runtime/Runtime' ], function(x, Basic, Runtime) { /** Set of methods and properties, required by a component to acquire ability to connect to a runtime @class RuntimeClient */ return function RuntimeClient() { var runtime; Basic.extend(this, { /** Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one. Increments number of clients connected to the specified runtime. @method connectRuntime @param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites */ connectRuntime: function(options) { var comp = this, ruid; function initialize(items) { var type, constructor; // if we ran out of runtimes if (!items.length) { comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); runtime = null; return; } type = items.shift(); constructor = Runtime.getConstructor(type); if (!constructor) { initialize(items); return; } // try initializing the runtime runtime = new constructor(options); runtime.bind('Init', function() { // mark runtime as initialized runtime.initialized = true; // jailbreak ... setTimeout(function() { runtime.clients++; // this will be triggered on component comp.trigger('RuntimeInit', runtime); }, 1); }); runtime.bind('Error', function() { runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here initialize(items); }); /*runtime.bind('Exception', function() { });*/ // check if runtime managed to pick-up operational mode if (!runtime.mode) { runtime.trigger('Error'); return; } runtime.init(); } // check if a particular runtime was requested if (Basic.typeOf(options) === 'string') { ruid = options; } else if (Basic.typeOf(options.ruid) === 'string') { ruid = options.ruid; } if (ruid) { runtime = Runtime.getRuntime(ruid); if (runtime) { runtime.clients++; return runtime; } else { // there should be a runtime and there's none - weird case throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR); } } // initialize a fresh one, that fits runtime list and required features best initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/)); }, /** Returns the runtime to which the client is currently connected. @method getRuntime @return {Runtime} Runtime or null if client is not connected */ getRuntime: function() { if (runtime && runtime.uid) { return runtime; } runtime = null; // make sure we do not leave zombies rambling around return null; }, /** Disconnects from the runtime. Decrements number of clients connected to the specified runtime. @method disconnectRuntime */ disconnectRuntime: function() { if (runtime && --runtime.clients <= 0) { runtime.destroy(); runtime = null; } } }); }; }); // Included from: src/javascript/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/Blob', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/runtime/RuntimeClient' ], function(Basic, Encode, RuntimeClient) { var blobpool = {}; /** @class Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} blob Object "Native" blob object, as it is represented in the runtime */ function Blob(ruid, blob) { function _sliceDetached(start, end, type) { var blob, data = blobpool[this.uid]; if (Basic.typeOf(data) !== 'string' || !data.length) { return null; // or throw exception } blob = new Blob(null, { type: type, size: end - start }); blob.detach(data.substr(start, blob.size)); return blob; } RuntimeClient.call(this); if (ruid) { this.connectRuntime(ruid); } if (!blob) { blob = {}; } else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string blob = { data: blob }; } Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: blob.uid || Basic.guid('uid_'), /** Unique id of the connected runtime, if falsy, then runtime will have to be initialized before this Blob can be used, modified or sent @property ruid @type {String} */ ruid: ruid, /** Size of blob @property size @type {Number} @default 0 */ size: blob.size || 0, /** Mime type of blob @property type @type {String} @default '' */ type: blob.type || '', /** @method slice @param {Number} [start=0] */ slice: function(start, end, type) { if (this.isDetached()) { return _sliceDetached.apply(this, arguments); } return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type); }, /** Returns "native" blob object (as it is represented in connected runtime) or null if not found @method getSource @return {Blob} Returns "native" blob object or null if not found */ getSource: function() { if (!blobpool[this.uid]) { return null; } return blobpool[this.uid]; }, /** Detaches blob from any runtime that it depends on and initialize with standalone value @method detach @protected @param {DOMString} [data=''] Standalone value */ detach: function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy', blobpool[this.uid]); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }, /** Checks if blob is standalone (detached of any runtime) @method isDetached @protected @return {Boolean} */ isDetached: function() { return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string'; }, /** Destroy Blob and free any resources it was using @method destroy */ destroy: function() { this.detach(); delete blobpool[this.uid]; } }); if (blob.data) { this.detach(blob.data); // auto-detach if payload has been passed } else { blobpool[this.uid] = blob; } } return Blob; }); // Included from: src/javascript/file/File.js /** * File.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/File', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/file/Blob' ], function(Basic, Mime, Blob) { /** @class File @extends Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} file Object "Native" file object, as it is represented in the runtime */ function File(ruid, file) { var name, type; if (!file) { // avoid extra errors in case we overlooked something file = {}; } // figure out the type if (file.type && file.type !== '') { type = file.type; } else { type = Mime.getFileMime(file.name); } // sanitize file name or generate new one if (file.name) { name = file.name.replace(/\\/g, '/'); name = name.substr(name.lastIndexOf('/') + 1); } else { var prefix = type.split('/')[0]; name = Basic.guid((prefix !== '' ? prefix : 'file') + '_'); if (Mime.extensions[type]) { name += '.' + Mime.extensions[type][0]; // append proper extension if possible } } Blob.apply(this, arguments); Basic.extend(this, { /** File mime type @property type @type {String} @default '' */ type: type || '', /** File name @property name @type {String} @default UID */ name: name || Basic.guid('file_'), /** Date of last modification @property lastModifiedDate @type {String} @default now */ lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET) }); } File.prototype = Blob.prototype; return File; }); // Included from: src/javascript/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileInput', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/core/I18n', 'moxie/file/File', 'moxie/runtime/Runtime', 'moxie/runtime/RuntimeClient' ], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) { /** Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click, converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @class FileInput @constructor @extends EventTarget @uses RuntimeClient @param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_. @param {String|DOMElement} options.browse_button DOM Element to turn into file picker. @param {Array} [options.accept] Array of mime types to accept. By default accepts all. @param {String} [options.file='file'] Name of the file field (not the filename). @param {Boolean} [options.multiple=false] Enable selection of multiple files. @param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time). @param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode for _browse\_button_. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support. @example <div id="container"> <a id="file-picker" href="javascript:;">Browse...</a> </div> <script> var fileInput = new mOxie.FileInput({ browse_button: 'file-picker', // or document.getElementById('file-picker') container: 'container', accept: [ {title: "Image files", extensions: "jpg,gif,png"} // accept only images ], multiple: true // allow multiple file selection }); fileInput.onchange = function(e) { // do something to files array console.info(e.target.files); // or this.files or fileInput.files }; fileInput.init(); // initialize </script> */ var dispatches = [ /** Dispatched when runtime is connected and file-picker is ready to be used. @event ready @param {Object} event */ 'ready', /** Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked. Check [corresponding documentation entry](#method_refresh) for more info. @event refresh @param {Object} event */ /** Dispatched when selection of files in the dialog is complete. @event change @param {Object} event */ 'change', 'cancel', // TODO: might be useful /** Dispatched when mouse cursor enters file-picker area. Can be used to style element accordingly. @event mouseenter @param {Object} event */ 'mouseenter', /** Dispatched when mouse cursor leaves file-picker area. Can be used to style element accordingly. @event mouseleave @param {Object} event */ 'mouseleave', /** Dispatched when functional mouse button is pressed on top of file-picker area. @event mousedown @param {Object} event */ 'mousedown', /** Dispatched when functional mouse button is released on top of file-picker area. @event mouseup @param {Object} event */ 'mouseup' ]; function FileInput(options) { var self = this, container, browseButton, defaults; // if flat argument passed it should be browse_button id if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) { options = { browse_button : options }; } // this will help us to find proper default container browseButton = Dom.get(options.browse_button); if (!browseButton) { // browse button is required throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], name: 'file', multiple: false, required_caps: false, container: browseButton.parentNode || document.body }; options = Basic.extend({}, defaults, options); // convert to object representation if (typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } container = Dom.get(options.container); // make sure we have container if (!container) { container = document.body; } // make container relative, if it's not if (Dom.getStyle(container, 'position') === 'static') { container.style.position = 'relative'; } container = browseButton = null; // IE RuntimeClient.call(self); Basic.extend(self, { /** Unique id of the component @property uid @protected @readOnly @type {String} @default UID */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @protected @type {String} */ ruid: null, /** Unique id of the runtime container. Useful to get hold of it for various manipulations. @property shimid @protected @type {String} */ shimid: null, /** Array of selected mOxie.File objects @property files @type {Array} @default null */ files: null, /** Initializes the file-picker, connects it to runtime and dispatches event ready when done. @method init */ init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.shimid = runtime.shimid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }, /** Disables file-picker element, so that it doesn't react to mouse clicks. @method disable @param {Boolean} [state=true] Disable component if - true, enable if - false */ disable: function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }, /** Reposition and resize dialog trigger to match the position and size of browse_button element. @method refresh */ refresh: function() { self.trigger("Refresh"); }, /** Destroy component. @method destroy */ destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; } }); } FileInput.prototype = EventTarget.instance; return FileInput; }); // Included from: src/javascript/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileDrop', [ 'moxie/core/I18n', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/file/File', 'moxie/runtime/RuntimeClient', 'moxie/core/EventTarget', 'moxie/core/utils/Mime' ], function(I18n, Dom, x, Basic, File, RuntimeClient, EventTarget, Mime) { /** Turn arbitrary DOM element to a drop zone accepting files. Converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @example <div id="drop_zone"> Drop files here </div> <br /> <div id="filelist"></div> <script type="text/javascript"> var fileDrop = new mOxie.FileDrop('drop_zone'), fileList = mOxie.get('filelist'); fileDrop.ondrop = function() { mOxie.each(this.files, function(file) { fileList.innerHTML += '<div>' + file.name + '</div>'; }); }; fileDrop.init(); </script> @class FileDrop @constructor @extends EventTarget @uses RuntimeClient @param {Object|String} options If options has typeof string, argument is considered as options.drop_zone @param {String|DOMElement} options.drop_zone DOM Element to turn into a drop zone @param {Array} [options.accept] Array of mime types to accept. By default accepts all @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support */ var dispatches = [ /** Dispatched when runtime is connected and drop zone is ready to accept files. @event ready @param {Object} event */ 'ready', /** Dispatched when dragging cursor enters the drop zone. @event dragenter @param {Object} event */ 'dragenter', /** Dispatched when dragging cursor leaves the drop zone. @event dragleave @param {Object} event */ 'dragleave', /** Dispatched when file is dropped onto the drop zone. @event drop @param {Object} event */ 'drop', /** Dispatched if error occurs. @event error @param {Object} event */ 'error' ]; function FileDrop(options) { var self = this, defaults; // if flat argument passed it should be drop_zone id if (typeof(options) === 'string') { options = { drop_zone : options }; } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], required_caps: { drag_and_drop: true } }; options = typeof(options) === 'object' ? Basic.extend({}, defaults, options) : defaults; // this will help us to find proper default container options.container = Dom.get(options.drop_zone) || document.body; // make container relative, if it is not if (Dom.getStyle(options.container, 'position') === 'static') { options.container.style.position = 'relative'; } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } RuntimeClient.call(self); Basic.extend(self, { uid: Basic.guid('uid_'), ruid: null, files: null, init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.bind("Drop", function() { var files = runtime.exec.call(self, 'FileDrop', 'getFiles'); self.files = []; Basic.each(files, function(file) { self.files.push(new File(self.ruid, file)); }); }, 999); runtime.exec.call(self, 'FileDrop', 'init', options); self.dispatchEvent('ready'); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(options); // throws RuntimeError }, destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileDrop', 'destroy'); this.disconnectRuntime(); } this.files = null; } }); } FileDrop.prototype = EventTarget.instance; return FileDrop; }); // Included from: src/javascript/runtime/RuntimeTarget.js /** * RuntimeTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeTarget', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', "moxie/core/EventTarget" ], function(Basic, RuntimeClient, EventTarget) { /** Instance of this class can be used as a target for the events dispatched by shims, when allowing them onto components is for either reason inappropriate @class RuntimeTarget @constructor @protected @extends EventTarget */ function RuntimeTarget() { this.uid = Basic.guid('uid_'); RuntimeClient.call(this); this.destroy = function() { this.disconnectRuntime(); this.unbindAll(); }; } RuntimeTarget.prototype = EventTarget.instance; return RuntimeTarget; }); // Included from: src/javascript/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReader', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/file/Blob', 'moxie/file/File', 'moxie/runtime/RuntimeTarget' ], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) { /** Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader) interface. Where possible uses native FileReader, where - not falls back to shims. @class FileReader @constructor FileReader @extends EventTarget @uses RuntimeClient */ var dispatches = [ /** Dispatched when the read starts. @event loadstart @param {Object} event */ 'loadstart', /** Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total). @event progress @param {Object} event */ 'progress', /** Dispatched when the read has successfully completed. @event load @param {Object} event */ 'load', /** Dispatched when the read has been aborted. For instance, by invoking the abort() method. @event abort @param {Object} event */ 'abort', /** Dispatched when the read has failed. @event error @param {Object} event */ 'error', /** Dispatched when the request has completed (either in success or failure). @event loadend @param {Object} event */ 'loadend' ]; function FileReader() { var self = this, _fr; Basic.extend(this, { /** UID of the component instance. @property uid @type {String} */ uid: Basic.guid('uid_'), /** Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING and FileReader.DONE. @property readyState @type {Number} @default FileReader.EMPTY */ readyState: FileReader.EMPTY, /** Result of the successful read operation. @property result @type {String} */ result: null, /** Stores the error of failed asynchronous read operation. @property error @type {DOMError} */ error: null, /** Initiates reading of File/Blob object contents to binary string. @method readAsBinaryString @param {Blob|File} blob Object to preload */ readAsBinaryString: function(blob) { _read.call(this, 'readAsBinaryString', blob); }, /** Initiates reading of File/Blob object contents to dataURL string. @method readAsDataURL @param {Blob|File} blob Object to preload */ readAsDataURL: function(blob) { _read.call(this, 'readAsDataURL', blob); }, /** Initiates reading of File/Blob object contents to string. @method readAsText @param {Blob|File} blob Object to preload */ readAsText: function(blob) { _read.call(this, 'readAsText', blob); }, /** Aborts preloading process. @method abort */ abort: function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }, /** Destroy component and release resources. @method destroy */ destroy: function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; } }); function _read(op, blob) { _fr = new RuntimeTarget(); function error(err) { self.readyState = FileReader.DONE; self.error = err; self.trigger('error'); loadEnd(); } function loadEnd() { _fr.destroy(); _fr = null; self.trigger('loadend'); } function exec(runtime) { _fr.bind('Error', function(e, err) { error(err); }); _fr.bind('Progress', function(e) { self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); }); _fr.bind('Load', function(e) { self.readyState = FileReader.DONE; self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); loadEnd(); }); runtime.exec.call(_fr, 'FileReader', 'read', op, blob); } this.convertEventPropsToHandlers(dispatches); if (this.readyState === FileReader.LOADING) { return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR)); } this.readyState = FileReader.LOADING; this.trigger('loadstart'); // if source is o.Blob/o.File if (blob instanceof Blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsText': case 'readAsBinaryString': this.result = src; break; case 'readAsDataURL': this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src); break; } this.readyState = FileReader.DONE; this.trigger('load'); loadEnd(); } else { exec(_fr.connectRuntime(blob.ruid)); } } else { error(new x.DOMException(x.DOMException.NOT_FOUND_ERR)); } } } /** Initial FileReader state @property EMPTY @type {Number} @final @static @default 0 */ FileReader.EMPTY = 0; /** FileReader switches to this state when it is preloading the source @property LOADING @type {Number} @final @static @default 1 */ FileReader.LOADING = 1; /** Preloading is complete, this is a final state @property DONE @type {Number} @final @static @default 2 */ FileReader.DONE = 2; FileReader.prototype = EventTarget.instance; return FileReader; }); // Included from: src/javascript/core/utils/Url.js /** * Url.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Url', [], function() { /** Parse url into separate components and fill in absent parts with parts from current url, based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js @method parseUrl @for Utils @static @param {String} url Url to parse (defaults to empty string if undefined) @return {Object} Hash containing extracted uri components */ var parseUrl = function(url, currentUrl) { var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment'] , i = key.length , ports = { http: 80, https: 443 } , uri = {} , regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/ , m = regex.exec(url || '') ; while (i--) { if (m[i]) { uri[key[i]] = m[i]; } } // when url is relative, we set the origin and the path ourselves if (!uri.scheme) { // come up with defaults if (!currentUrl || typeof(currentUrl) === 'string') { currentUrl = parseUrl(currentUrl || document.location.href); } uri.scheme = currentUrl.scheme; uri.host = currentUrl.host; uri.port = currentUrl.port; var path = ''; // for urls without trailing slash we need to figure out the path if (/^[^\/]/.test(uri.path)) { path = currentUrl.path; // if path ends with a filename, strip it if (!/(\/|\/[^\.]+)$/.test(path)) { path = path.replace(/\/[^\/]+$/, '/'); } else { path += '/'; } } uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir } if (!uri.port) { uri.port = ports[uri.scheme] || 80; } uri.port = parseInt(uri.port, 10); if (!uri.path) { uri.path = "/"; } delete uri.source; return uri; }; /** Resolve url - among other things will turn relative url to absolute @method resolveUrl @static @param {String} url Either absolute or relative @return {String} Resolved, absolute url */ var resolveUrl = function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }; /** Check if specified url has the same origin as the current document @method hasSameOrigin @param {String|Object} url @return {Boolean} */ var hasSameOrigin = function(url) { function origin(url) { return [url.scheme, url.host, url.port].join('/'); } if (typeof url === 'string') { url = parseUrl(url); } return origin(parseUrl()) === origin(url); }; return { parseUrl: parseUrl, resolveUrl: resolveUrl, hasSameOrigin: hasSameOrigin }; }); // Included from: src/javascript/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReaderSync', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', 'moxie/core/utils/Encode' ], function(Basic, RuntimeClient, Encode) { /** Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be, but probably < 1mb). Not meant to be used directly by user. @class FileReaderSync @private @constructor */ return function() { RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), readAsBinaryString: function(blob) { return _read.call(this, 'readAsBinaryString', blob); }, readAsDataURL: function(blob) { return _read.call(this, 'readAsDataURL', blob); }, /*readAsArrayBuffer: function(blob) { return _read.call(this, 'readAsArrayBuffer', blob); },*/ readAsText: function(blob) { return _read.call(this, 'readAsText', blob); } }); function _read(op, blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsBinaryString': return src; case 'readAsDataURL': return 'data:' + blob.type + ';base64,' + Encode.btoa(src); case 'readAsText': var txt = ''; for (var i = 0, length = src.length; i < length; i++) { txt += String.fromCharCode(src[i]); } return txt; } } else { var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob); this.disconnectRuntime(); return result; } } }; }); // Included from: src/javascript/xhr/FormData.js /** * FormData.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/FormData", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/file/Blob" ], function(x, Basic, Blob) { /** FormData @class FormData @constructor */ function FormData() { var _blob, _fields = []; Basic.extend(this, { /** Append another key-value pair to the FormData object @method append @param {String} name Name for the new field @param {String|Blob|Array|Object} value Value for the field */ append: function(name, value) { var self = this, valueType = Basic.typeOf(value); // according to specs value might be either Blob or String if (value instanceof Blob) { _blob = { name: name, value: value // unfortunately we can only send single Blob in one FormData }; } else if ('array' === valueType) { name += '[]'; Basic.each(value, function(value) { self.append(name, value); }); } else if ('object' === valueType) { Basic.each(value, function(value, key) { self.append(name + '[' + key + ']', value); }); } else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) { self.append(name, "false"); } else { _fields.push({ name: name, value: value.toString() }); } }, /** Checks if FormData contains Blob. @method hasBlob @return {Boolean} */ hasBlob: function() { return !!this.getBlob(); }, /** Retrieves blob. @method getBlob @return {Object} Either Blob if found or null */ getBlob: function() { return _blob && _blob.value || null; }, /** Retrieves blob field name. @method getBlobName @return {String} Either Blob field name or null */ getBlobName: function() { return _blob && _blob.name || null; }, /** Loop over the fields in FormData and invoke the callback for each of them. @method each @param {Function} cb Callback to call for each field */ each: function(cb) { Basic.each(_fields, function(field) { cb(field.value, field.name); }); if (_blob) { cb(_blob.value, _blob.name); } }, destroy: function() { _blob = null; _fields = []; } }); } return FormData; }); // Included from: src/javascript/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/XMLHttpRequest", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/EventTarget", "moxie/core/utils/Encode", "moxie/core/utils/Url", "moxie/runtime/Runtime", "moxie/runtime/RuntimeTarget", "moxie/file/Blob", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/core/utils/Env", "moxie/core/utils/Mime" ], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) { var httpCode = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: 'Reserved', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 426: 'Upgrade Required', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 510: 'Not Extended' }; function XMLHttpRequestUpload() { this.uid = Basic.guid('uid_'); } XMLHttpRequestUpload.prototype = EventTarget.instance; /** Implementation of XMLHttpRequest @class XMLHttpRequest @constructor @uses RuntimeClient @extends EventTarget */ var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons) var NATIVE = 1, RUNTIME = 2; function XMLHttpRequest() { var self = this, // this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible props = { /** The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout. @property timeout @type Number @default 0 */ timeout: 0, /** Current state, can take following values: UNSENT (numeric value 0) The object has been constructed. OPENED (numeric value 1) The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method. HEADERS_RECEIVED (numeric value 2) All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available. LOADING (numeric value 3) The response entity body is being received. DONE (numeric value 4) @property readyState @type Number @default 0 (UNSENT) */ readyState: XMLHttpRequest.UNSENT, /** True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. @property withCredentials @type Boolean @default false */ withCredentials: false, /** Returns the HTTP status code. @property status @type Number @default 0 */ status: 0, /** Returns the HTTP status text. @property statusText @type String */ statusText: "", /** Returns the response type. Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". @property responseType @type String */ responseType: "", /** Returns the document response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "document". @property responseXML @type Document */ responseXML: null, /** Returns the text response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "text". @property responseText @type String */ responseText: null, /** Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body). Can become: ArrayBuffer, Blob, Document, JSON, Text @property response @type Mixed */ response: null }, _async = true, _url, _method, _headers = {}, _user, _password, _encoding = null, _mimeType = null, // flags _sync_flag = false, _send_flag = false, _upload_events_flag = false, _upload_complete_flag = false, _error_flag = false, _same_origin_flag = false, // times _start_time, _timeoutset_time, _finalMime = null, _finalCharset = null, _options = {}, _xhr, _responseHeaders = '', _responseHeadersBag ; Basic.extend(this, props, { /** Unique id of the component @property uid @type String */ uid: Basic.guid('uid_'), /** Target for Upload events @property upload @type XMLHttpRequestUpload */ upload: new XMLHttpRequestUpload(), /** Sets the request method, request URL, synchronous flag, request username, and request password. Throws a "SyntaxError" exception if one of the following is true: method is not a valid HTTP method. url cannot be resolved. url contains the "user:password" format in the userinfo production. Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK. Throws an "InvalidAccessError" exception if one of the following is true: Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin. There is an associated XMLHttpRequest document and either the timeout attribute is not zero, the withCredentials attribute is true, or the responseType attribute is not the empty string. @method open @param {String} method HTTP method to use on request @param {String} url URL to request @param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default. @param {String} [user] Username to use in HTTP authentication process on server-side @param {String} [password] Password to use in HTTP authentication process on server-side */ open: function(method, url, async, user, password) { var urlp; // first two arguments are required if (!method || !url) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3 if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) { _method = method.toUpperCase(); } // 4 - allowing these methods poses a security risk if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) { throw new x.DOMException(x.DOMException.SECURITY_ERR); } // 5 url = Encode.utf8_encode(url); // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError". urlp = Url.parseUrl(url); _same_origin_flag = Url.hasSameOrigin(urlp); // 7 - manually build up absolute url _url = Url.resolveUrl(url); // 9-10, 12-13 if ((user || password) && !_same_origin_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } _user = user || urlp.user; _password = password || urlp.pass; // 11 _async = async || true; if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 14 - terminate abort() // 15 - terminate send() // 18 _sync_flag = !_async; _send_flag = false; _headers = {}; _reset.call(this); // 19 _p('readyState', XMLHttpRequest.OPENED); // 20 this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers this.dispatchEvent('readystatechange'); }, /** Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value is not a valid HTTP header field value. @method setRequestHeader @param {String} header @param {String|Number} value */ setRequestHeader: function(header, value) { var uaHeaders = [ // these headers are controlled by the user agent "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "content-transfer-encoding", "date", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" ]; // 1-2 if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 4 /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); }*/ header = Basic.trim(header).toLowerCase(); // setting of proxy-* and sec-* headers is prohibited by spec if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) { return false; } // camelize // browsers lowercase header names (at least for custom ones) // header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); }); if (!_headers[header]) { _headers[header] = value; } else { // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph) _headers[header] += ', ' + value; } return true; }, /** Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2. @method getAllResponseHeaders @return {String} reponse headers or empty string */ getAllResponseHeaders: function() { return _responseHeaders || ''; }, /** Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2. @method getResponseHeader @param {String} header @return {String} value(s) for the specified header or null */ getResponseHeader: function(header) { header = header.toLowerCase(); if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) { return null; } if (_responseHeaders && _responseHeaders !== '') { // if we didn't parse response headers until now, do it and keep for later if (!_responseHeadersBag) { _responseHeadersBag = {}; Basic.each(_responseHeaders.split(/\r\n/), function(line) { var pair = line.split(/:\s+/); if (pair.length === 2) { // last line might be empty, omit pair[0] = Basic.trim(pair[0]); // just in case _responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form header: pair[0], value: Basic.trim(pair[1]) }; } }); } if (_responseHeadersBag.hasOwnProperty(header)) { return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value; } } return null; }, /** Sets the Content-Type header for the response to mime. Throws an "InvalidStateError" exception if the state is LOADING or DONE. Throws a "SyntaxError" exception if mime is not a valid media type. @method overrideMimeType @param String mime Mime type to set */ overrideMimeType: function(mime) { var matches, charset; // 1 if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 mime = Basic.trim(mime.toLowerCase()); if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) { mime = matches[1]; if (matches[2]) { charset = matches[2]; } } if (!Mime.mimes[mime]) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3-4 _finalMime = mime; _finalCharset = charset; }, /** Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. @method send @param {Blob|Document|String|FormData} [data] Request entity body @param {Object} [options] Set of requirements and pre-requisities for runtime initialization */ send: function(data, options) { if (Basic.typeOf(options) === 'string') { _options = { ruid: options }; } else if (!options) { _options = {}; } else { _options = options; } this.convertEventPropsToHandlers(dispatches); this.upload.convertEventPropsToHandlers(dispatches); // 1-2 if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 // sending Blob if (data instanceof Blob) { _options.ruid = data.ruid; _mimeType = data.type || 'application/octet-stream'; } // FormData else if (data instanceof FormData) { if (data.hasBlob()) { var blob = data.getBlob(); _options.ruid = blob.ruid; _mimeType = blob.type || 'application/octet-stream'; } } // DOMString else if (typeof data === 'string') { _encoding = 'UTF-8'; _mimeType = 'text/plain;charset=UTF-8'; // data should be converted to Unicode and encoded as UTF-8 data = Encode.utf8_encode(data); } // if withCredentials not set, but requested, set it automatically if (!this.withCredentials) { this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag; } // 4 - storage mutex // 5 _upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP // 6 _error_flag = false; // 7 _upload_complete_flag = !data; // 8 - Asynchronous steps if (!_sync_flag) { // 8.1 _send_flag = true; // 8.2 // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr // 8.3 //if (!_upload_complete_flag) { // this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr //} } // 8.5 - Return the send() method call, but continue running the steps in this algorithm. _doXHR.call(this, data); }, /** Cancels any network activity. @method abort */ abort: function() { _error_flag = true; _sync_flag = false; if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) { _p('readyState', XMLHttpRequest.DONE); _send_flag = false; if (_xhr) { _xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag); } else { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _upload_complete_flag = true; } else { _p('readyState', XMLHttpRequest.UNSENT); } }, destroy: function() { if (_xhr) { if (Basic.typeOf(_xhr.destroy) === 'function') { _xhr.destroy(); } _xhr = null; } this.unbindAll(); if (this.upload) { this.upload.unbindAll(); this.upload = null; } } }); /* this is nice, but maybe too lengthy // if supported by JS version, set getters/setters for specific properties o.defineProperty(this, 'readyState', { configurable: false, get: function() { return _p('readyState'); } }); o.defineProperty(this, 'timeout', { configurable: false, get: function() { return _p('timeout'); }, set: function(value) { if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // timeout still should be measured relative to the start time of request _timeoutset_time = (new Date).getTime(); _p('timeout', value); } }); // the withCredentials attribute has no effect when fetching same-origin resources o.defineProperty(this, 'withCredentials', { configurable: false, get: function() { return _p('withCredentials'); }, set: function(value) { // 1-2 if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3-4 if (_anonymous_flag || _sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 5 _p('withCredentials', value); } }); o.defineProperty(this, 'status', { configurable: false, get: function() { return _p('status'); } }); o.defineProperty(this, 'statusText', { configurable: false, get: function() { return _p('statusText'); } }); o.defineProperty(this, 'responseType', { configurable: false, get: function() { return _p('responseType'); }, set: function(value) { // 1 if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 3 _p('responseType', value.toLowerCase()); } }); o.defineProperty(this, 'responseText', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'text'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseText'); } }); o.defineProperty(this, 'responseXML', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'document'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseXML'); } }); o.defineProperty(this, 'response', { configurable: false, get: function() { if (!!~o.inArray(_p('responseType'), ['', 'text'])) { if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { return ''; } } if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { return null; } return _p('response'); } }); */ function _p(prop, value) { if (!props.hasOwnProperty(prop)) { return; } if (arguments.length === 1) { // get return Env.can('define_property') ? props[prop] : self[prop]; } else { // set if (Env.can('define_property')) { props[prop] = value; } else { self[prop] = value; } } } /* function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) { // TODO: http://tools.ietf.org/html/rfc3490#section-4.1 return str.toLowerCase(); } */ function _doXHR(data) { var self = this; _start_time = new Date().getTime(); _xhr = new RuntimeTarget(); function loadEnd() { _xhr.destroy(); _xhr = null; self.dispatchEvent('loadend'); self = null; } function exec(runtime) { _xhr.bind('LoadStart', function(e) { _p('readyState', XMLHttpRequest.LOADING); self.dispatchEvent('readystatechange'); self.dispatchEvent(e); if (_upload_events_flag) { self.upload.dispatchEvent(e); } }); _xhr.bind('Progress', function(e) { if (_p('readyState') !== XMLHttpRequest.LOADING) { _p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example) self.dispatchEvent('readystatechange'); } self.dispatchEvent(e); }); _xhr.bind('UploadProgress', function(e) { if (_upload_events_flag) { self.upload.dispatchEvent({ type: 'progress', lengthComputable: false, total: e.total, loaded: e.loaded }); } }); _xhr.bind('Load', function(e) { _p('readyState', XMLHttpRequest.DONE); _p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0)); _p('statusText', httpCode[_p('status')] || ""); _p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType'))); if (!!~Basic.inArray(_p('responseType'), ['text', ''])) { _p('responseText', _p('response')); } else if (_p('responseType') === 'document') { _p('responseXML', _p('response')); } _responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders'); self.dispatchEvent('readystatechange'); if (_p('status') > 0) { // status 0 usually means that server is unreachable if (_upload_events_flag) { self.upload.dispatchEvent(e); } self.dispatchEvent(e); } else { _error_flag = true; self.dispatchEvent('error'); } loadEnd(); }); _xhr.bind('Abort', function(e) { self.dispatchEvent(e); loadEnd(); }); _xhr.bind('Error', function(e) { _error_flag = true; _p('readyState', XMLHttpRequest.DONE); self.dispatchEvent('readystatechange'); _upload_complete_flag = true; self.dispatchEvent(e); loadEnd(); }); runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', { url: _url, method: _method, async: _async, user: _user, password: _password, headers: _headers, mimeType: _mimeType, encoding: _encoding, responseType: self.responseType, withCredentials: self.withCredentials, options: _options }, data); } // clarify our requirements if (typeof(_options.required_caps) === 'string') { _options.required_caps = Runtime.parseCaps(_options.required_caps); } _options.required_caps = Basic.extend({}, _options.required_caps, { return_response_type: self.responseType }); if (data instanceof FormData) { _options.required_caps.send_multipart = true; } if (!_same_origin_flag) { _options.required_caps.do_cors = true; } if (_options.ruid) { // we do not need to wait if we can connect directly exec(_xhr.connectRuntime(_options)); } else { _xhr.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); _xhr.bind('RuntimeError', function(e, err) { self.dispatchEvent('RuntimeError', err); }); _xhr.connectRuntime(_options); } } function _reset() { _p('responseText', ""); _p('responseXML', null); _p('response', null); _p('status', 0); _p('statusText', ""); _start_time = _timeoutset_time = null; } } XMLHttpRequest.UNSENT = 0; XMLHttpRequest.OPENED = 1; XMLHttpRequest.HEADERS_RECEIVED = 2; XMLHttpRequest.LOADING = 3; XMLHttpRequest.DONE = 4; XMLHttpRequest.prototype = EventTarget.instance; return XMLHttpRequest; }); // Included from: src/javascript/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/runtime/Transporter", [ "moxie/core/utils/Basic", "moxie/core/utils/Encode", "moxie/runtime/RuntimeClient", "moxie/core/EventTarget" ], function(Basic, Encode, RuntimeClient, EventTarget) { function Transporter() { var mod, _runtime, _data, _size, _pos, _chunk_size; RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), state: Transporter.IDLE, result: null, transport: function(data, type, options) { var self = this; options = Basic.extend({ chunk_size: 204798 }, options); // should divide by three, base64 requires this if ((mod = options.chunk_size % 3)) { options.chunk_size += 3 - mod; } _chunk_size = options.chunk_size; _reset.call(this); _data = data; _size = data.length; if (Basic.typeOf(options) === 'string' || options.ruid) { _run.call(self, type, this.connectRuntime(options)); } else { // we require this to run only once var cb = function(e, runtime) { self.unbind("RuntimeInit", cb); _run.call(self, type, runtime); }; this.bind("RuntimeInit", cb); this.connectRuntime(options); } }, abort: function() { var self = this; self.state = Transporter.IDLE; if (_runtime) { _runtime.exec.call(self, 'Transporter', 'clear'); self.trigger("TransportingAborted"); } _reset.call(self); }, destroy: function() { this.unbindAll(); _runtime = null; this.disconnectRuntime(); _reset.call(this); } }); function _reset() { _size = _pos = 0; _data = this.result = null; } function _run(type, runtime) { var self = this; _runtime = runtime; //self.unbind("RuntimeInit"); self.bind("TransportingProgress", function(e) { _pos = e.loaded; if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) { _transport.call(self); } }, 999); self.bind("TransportingComplete", function() { _pos = _size; self.state = Transporter.DONE; _data = null; // clean a bit self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || ''); }, 999); self.state = Transporter.BUSY; self.trigger("TransportingStarted"); _transport.call(self); } function _transport() { var self = this, chunk, bytesLeft = _size - _pos; if (_chunk_size > bytesLeft) { _chunk_size = bytesLeft; } chunk = Encode.btoa(_data.substr(_pos, _chunk_size)); _runtime.exec.call(self, 'Transporter', 'receive', chunk, _size); } } Transporter.IDLE = 0; Transporter.BUSY = 1; Transporter.DONE = 2; Transporter.prototype = EventTarget.instance; return Transporter; }); // Included from: src/javascript/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/image/Image", [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/file/FileReaderSync", "moxie/xhr/XMLHttpRequest", "moxie/runtime/Runtime", "moxie/runtime/RuntimeClient", "moxie/runtime/Transporter", "moxie/core/utils/Env", "moxie/core/EventTarget", "moxie/file/Blob", "moxie/file/File", "moxie/core/utils/Encode" ], function(Basic, Dom, x, FileReaderSync, XMLHttpRequest, Runtime, RuntimeClient, Transporter, Env, EventTarget, Blob, File, Encode) { /** Image preloading and manipulation utility. Additionally it provides access to image meta info (Exif, GPS) and raw binary data. @class Image @constructor @extends EventTarget */ var dispatches = [ 'progress', /** Dispatched when loading is complete. @event load @param {Object} event */ 'load', 'error', /** Dispatched when resize operation is complete. @event resize @param {Object} event */ 'resize', /** Dispatched when visual representation of the image is successfully embedded into the corresponsing container. @event embedded @param {Object} event */ 'embedded' ]; function Image() { RuntimeClient.call(this); Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @type {String} */ ruid: null, /** Name of the file, that was used to create an image, if available. If not equals to empty string. @property name @type {String} @default "" */ name: "", /** Size of the image in bytes. Actual value is set only after image is preloaded. @property size @type {Number} @default 0 */ size: 0, /** Width of the image. Actual value is set only after image is preloaded. @property width @type {Number} @default 0 */ width: 0, /** Height of the image. Actual value is set only after image is preloaded. @property height @type {Number} @default 0 */ height: 0, /** Mime type of the image. Currently only image/jpeg and image/png are supported. Actual value is set only after image is preloaded. @property type @type {String} @default "" */ type: "", /** Holds meta info (Exif, GPS). Is populated only for image/jpeg. Actual value is set only after image is preloaded. @property meta @type {Object} @default {} */ meta: {}, /** Alias for load method, that takes another mOxie.Image object as a source (see load). @method clone @param {Image} src Source for the image @param {Boolean} [exact=false] Whether to activate in-depth clone mode */ clone: function() { this.load.apply(this, arguments); }, /** Loads image from various sources. Currently the source for new image can be: mOxie.Image, mOxie.Blob/mOxie.File, native Blob/File, dataUrl or URL. Depending on the type of the source, arguments - differ. When source is URL, Image will be downloaded from remote destination and loaded in memory. @example var img = new mOxie.Image(); img.onload = function() { var blob = img.getAsBlob(); var formData = new mOxie.FormData(); formData.append('file', blob); var xhr = new mOxie.XMLHttpRequest(); xhr.onload = function() { // upload complete }; xhr.open('post', 'upload.php'); xhr.send(formData); }; img.load("http://www.moxiecode.com/images/mox-logo.jpg"); // notice file extension (.jpg) @method load @param {Image|Blob|File|String} src Source for the image @param {Boolean|Object} [mixed] */ load: function() { // this is here because to bind properly we need an uid first, which is created above this.bind('Load Resize', function() { _updateInfo.call(this); }, 999); this.convertEventPropsToHandlers(dispatches); _load.apply(this, arguments); }, /** Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions. @method downsize @param {Number} width Resulting width @param {Number} [height=width] Resulting height (optional, if not supplied will default to width) @param {Boolean} [crop=false] Whether to crop the image to exact dimensions @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize) */ downsize: function(width, height, crop, preserveHeaders) { try { if (!this.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // no way to reliably intercept the crash due to high resolution, so we simply avoid it if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) { throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } if (!width && !height || Basic.typeOf(crop) === 'undefined') { crop = false; } width = width || this.width; height = height || this.height; preserveHeaders = (Basic.typeOf(preserveHeaders) === 'undefined' ? true : !!preserveHeaders); this.getRuntime().exec.call(this, 'Image', 'downsize', width, height, crop, preserveHeaders); } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } }, /** Alias for downsize(width, height, true). (see downsize) @method crop @param {Number} width Resulting width @param {Number} [height=width] Resulting height (optional, if not supplied will default to width) @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize) */ crop: function(width, height, preserveHeaders) { this.downsize(width, height, true, preserveHeaders); }, getAsCanvas: function() { if (!Env.can('create_canvas')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } var runtime = this.connectRuntime(this.ruid); return runtime.exec.call(this, 'Image', 'getAsCanvas'); }, /** Retrieves image in it's current state as mOxie.Blob object. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsBlob @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {Blob} Image as Blob */ getAsBlob: function(type, quality) { if (!this.size) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } if (!type) { type = 'image/jpeg'; } if (type === 'image/jpeg' && !quality) { quality = 90; } return this.getRuntime().exec.call(this, 'Image', 'getAsBlob', type, quality); }, /** Retrieves image in it's current state as dataURL string. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsDataURL @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {String} Image as dataURL string */ getAsDataURL: function(type, quality) { if (!this.size) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return this.getRuntime().exec.call(this, 'Image', 'getAsDataURL', type, quality); }, /** Retrieves image in it's current state as binary string. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsBinaryString @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {String} Image as binary string */ getAsBinaryString: function(type, quality) { var dataUrl = this.getAsDataURL(type, quality); return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)); }, /** Embeds the image, or better to say, it's visual representation into the specified node. Depending on the runtime in use, might be a canvas, or image (actual ) element or shim object (Flash or SilverLight - very rare, used for legacy browsers that do not have canvas or proper dataURI support). @method embed @param {DOMElement} el DOM element to insert the image object into @param {Object} options Set of key/value pairs controlling the mime type, dimensions and cropping factor of resulting representation */ embed: function(el) { var self = this , imgCopy , type, quality, crop , options = arguments[1] || {} , width = this.width , height = this.height , runtime // this has to be outside of all the closures to contain proper runtime ; function onResize() { // if possible, embed a canvas element directly if (Env.can('create_canvas')) { var canvas = imgCopy.getAsCanvas(); if (canvas) { el.appendChild(canvas); canvas = null; imgCopy.destroy(); self.trigger('embedded'); return; } } var dataUrl = imgCopy.getAsDataURL(type, quality); if (!dataUrl) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } if (Env.can('use_data_uri_of', dataUrl.length)) { el.innerHTML = '<img src="' + dataUrl + '" width="' + imgCopy.width + '" height="' + imgCopy.height + '" />'; imgCopy.destroy(); self.trigger('embedded'); } else { var tr = new Transporter(); tr.bind("TransportingComplete", function() { runtime = self.connectRuntime(this.result.ruid); self.bind("Embedded", function() { // position and size properly Basic.extend(runtime.getShimContainer().style, { //position: 'relative', top: '0px', left: '0px', width: imgCopy.width + 'px', height: imgCopy.height + 'px' }); // some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's // position type changes (in Gecko), but since we basically need this only in IEs 6/7 and // sometimes 8 and they do not have this problem, we can comment this for now /*tr.bind("RuntimeInit", function(e, runtime) { tr.destroy(); runtime.destroy(); onResize.call(self); // re-feed our image data });*/ runtime = null; }, 999); runtime.exec.call(self, "ImageView", "display", this.result.uid, width, height); imgCopy.destroy(); }); tr.transport(Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)), type, Basic.extend({}, options, { required_caps: { display_media: true }, runtime_order: 'flash,silverlight', container: el })); } } try { if (!(el = Dom.get(el))) { throw new x.DOMException(x.DOMException.INVALID_NODE_TYPE_ERR); } if (!this.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) { throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } type = options.type || this.type || 'image/jpeg'; quality = options.quality || 90; crop = Basic.typeOf(options.crop) !== 'undefined' ? options.crop : false; // figure out dimensions for the thumb if (options.width) { width = options.width; height = options.height || width; } else { // if container element has > 0 dimensions, take them var dimensions = Dom.getSize(el); if (dimensions.w && dimensions.h) { // both should be > 0 width = dimensions.w; height = dimensions.h; } } imgCopy = new Image(); imgCopy.bind("Resize", function() { onResize.call(self); }); imgCopy.bind("Load", function() { imgCopy.downsize(width, height, crop, false); }); imgCopy.clone(this, false); return imgCopy; } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } }, /** Properly destroys the image and frees resources in use. If any. Recommended way to dispose mOxie.Image object. @method destroy */ destroy: function() { if (this.ruid) { this.getRuntime().exec.call(this, 'Image', 'destroy'); this.disconnectRuntime(); } this.unbindAll(); } }); function _updateInfo(info) { if (!info) { info = this.getRuntime().exec.call(this, 'Image', 'getInfo'); } this.size = info.size; this.width = info.width; this.height = info.height; this.type = info.type; this.meta = info.meta; // update file name, only if empty if (this.name === '') { this.name = info.name; } } function _load(src) { var srcType = Basic.typeOf(src); try { // if source is Image if (src instanceof Image) { if (!src.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _loadFromImage.apply(this, arguments); } // if source is o.Blob/o.File else if (src instanceof Blob) { if (!~Basic.inArray(src.type, ['image/jpeg', 'image/png'])) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } _loadFromBlob.apply(this, arguments); } // if native blob/file else if (Basic.inArray(srcType, ['blob', 'file']) !== -1) { _load.call(this, new File(null, src), arguments[1]); } // if String else if (srcType === 'string') { // if dataUrl String if (/^data:[^;]*;base64,/.test(src)) { _load.call(this, new Blob(null, { data: src }), arguments[1]); } // else assume Url, either relative or absolute else { _loadFromUrl.apply(this, arguments); } } // if source seems to be an img node else if (srcType === 'node' && src.nodeName.toLowerCase() === 'img') { _load.call(this, src.src, arguments[1]); } else { throw new x.DOMException(x.DOMException.TYPE_MISMATCH_ERR); } } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } } function _loadFromImage(img, exact) { var runtime = this.connectRuntime(img.ruid); this.ruid = runtime.uid; runtime.exec.call(this, 'Image', 'loadFromImage', img, (Basic.typeOf(exact) === 'undefined' ? true : exact)); } function _loadFromBlob(blob, options) { var self = this; self.name = blob.name || ''; function exec(runtime) { self.ruid = runtime.uid; runtime.exec.call(self, 'Image', 'loadFromBlob', blob); } if (blob.isDetached()) { this.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); // convert to object representation if (options && typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } this.connectRuntime(Basic.extend({ required_caps: { access_image_binary: true, resize_image: true } }, options)); } else { exec(this.connectRuntime(blob.ruid)); } } function _loadFromUrl(url, options) { var self = this, xhr; xhr = new XMLHttpRequest(); xhr.open('get', url); xhr.responseType = 'blob'; xhr.onprogress = function(e) { self.trigger(e); }; xhr.onload = function() { _loadFromBlob.call(self, xhr.response, true); }; xhr.onerror = function(e) { self.trigger(e); }; xhr.onloadend = function() { xhr.destroy(); }; xhr.bind('RuntimeError', function(e, err) { self.trigger('RuntimeError', err); }); xhr.send(null, options); } } // virtual world will crash on you if image has a resolution higher than this: Image.MAX_RESIZE_WIDTH = 6500; Image.MAX_RESIZE_HEIGHT = 6500; Image.prototype = EventTarget.instance; return Image; }); // Included from: src/javascript/runtime/html5/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML5 runtime. @class moxie/runtime/html5/Runtime @private */ define("moxie/runtime/html5/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = "html5", extensions = {}; function Html5Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; var caps = Basic.extend({ access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL), access_image_binary: function() { return I.can('access_binary') && !!extensions.Image; }, display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')), do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()), drag_and_drop: Test(function() { // this comes directly from Modernizr: http://www.modernizr.com/ var div = document.createElement('div'); // IE has support for drag and drop since version 5, but doesn't support dropping files from desktop return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9); }()), filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), return_response_headers: True, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported return true; } return Env.can('return_response_type', responseType); }, return_status_code: True, report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload), resize_image: function() { return I.can('access_binary') && Env.can('create_canvas'); }, select_file: function() { return Env.can('use_fileinput') && window.File; }, select_folder: function() { return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21; }, select_multiple: function() { // it is buggy on Safari Windows and iOS return I.can('select_file') && !(Env.browser === 'Safari' && Env.os === 'Windows') && !(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.4", '<')); }, send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))), send_custom_headers: Test(window.XMLHttpRequest), send_multipart: function() { return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string'); }, slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)), stream_upload: function(){ return I.can('slice_blob') && I.can('send_multipart'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || (Env.browser === 'IE' && Env.version >= 10) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True }, arguments[2] ); Runtime.call(this, options, (arguments[1] || type), caps); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html5Runtime); return extensions; }); // Included from: src/javascript/runtime/html5/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/Blob @private */ define("moxie/runtime/html5/file/Blob", [ "moxie/runtime/html5/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { function HTML5Blob() { function w3cBlobSlice(blob, start, end) { var blobSlice; if (window.File.prototype.slice) { try { blob.slice(); // depricated version will throw WRONG_ARGUMENTS_ERR exception return blob.slice(start, end); } catch (e) { // depricated slice method return blob.slice(start, end - start); } // slice method got prefixed: https://bugzilla.mozilla.org/show_bug.cgi?id=649672 } else if ((blobSlice = window.File.prototype.webkitSlice || window.File.prototype.mozSlice)) { return blobSlice.call(blob, start, end); } else { return null; // or throw some exception } } this.slice = function() { return new Blob(this.getRuntime().uid, w3cBlobSlice.apply(this, arguments)); }; } return (extensions.Blob = HTML5Blob); }); // Included from: src/javascript/core/utils/Events.js /** * Events.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Events', [ 'moxie/core/utils/Basic' ], function(Basic) { var eventhash = {}, uid = 'moxie_' + Basic.guid(); // IE W3C like event funcs function preventDefault() { this.returnValue = false; } function stopPropagation() { this.cancelBubble = true; } /** Adds an event handler to the specified object and store reference to the handler in objects internal Plupload registry (@see removeEvent). @method addEvent @for Utils @static @param {Object} obj DOM element like object to add handler to. @param {String} name Name to add event listener to. @param {Function} callback Function to call when event occurs. @param {String} [key] that might be used to add specifity to the event record. */ var addEvent = function(obj, name, callback, key) { var func, events; name = name.toLowerCase(); // Add event listener if (obj.addEventListener) { func = callback; obj.addEventListener(name, func, false); } else if (obj.attachEvent) { func = function() { var evt = window.event; if (!evt.target) { evt.target = evt.srcElement; } evt.preventDefault = preventDefault; evt.stopPropagation = stopPropagation; callback(evt); }; obj.attachEvent('on' + name, func); } // Log event handler to objects internal mOxie registry if (!obj[uid]) { obj[uid] = Basic.guid(); } if (!eventhash.hasOwnProperty(obj[uid])) { eventhash[obj[uid]] = {}; } events = eventhash[obj[uid]]; if (!events.hasOwnProperty(name)) { events[name] = []; } events[name].push({ func: func, orig: callback, // store original callback for IE key: key }); }; /** Remove event handler from the specified object. If third argument (callback) is not specified remove all events with the specified name. @method removeEvent @static @param {Object} obj DOM element to remove event listener(s) from. @param {String} name Name of event listener to remove. @param {Function|String} [callback] might be a callback or unique key to match. */ var removeEvent = function(obj, name, callback) { var type, undef; name = name.toLowerCase(); if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) { type = eventhash[obj[uid]][name]; } else { return; } for (var i = type.length - 1; i >= 0; i--) { // undefined or not, key should match if (type[i].orig === callback || type[i].key === callback) { if (obj.removeEventListener) { obj.removeEventListener(name, type[i].func, false); } else if (obj.detachEvent) { obj.detachEvent('on'+name, type[i].func); } type[i].orig = null; type[i].func = null; type.splice(i, 1); // If callback was passed we are done here, otherwise proceed if (callback !== undef) { break; } } } // If event array got empty, remove it if (!type.length) { delete eventhash[obj[uid]][name]; } // If mOxie registry has become empty, remove it if (Basic.isEmptyObj(eventhash[obj[uid]])) { delete eventhash[obj[uid]]; // IE doesn't let you remove DOM object property with - delete try { delete obj[uid]; } catch(e) { obj[uid] = undef; } } }; /** Remove all kind of events from the specified object @method removeAllEvents @static @param {Object} obj DOM element to remove event listeners from. @param {String} [key] unique key to match, when removing events. */ var removeAllEvents = function(obj, key) { if (!obj || !obj[uid]) { return; } Basic.each(eventhash[obj[uid]], function(events, name) { removeEvent(obj, name, key); }); }; return { addEvent: addEvent, removeEvent: removeEvent, removeAllEvents: removeAllEvents }; }); // Included from: src/javascript/runtime/html5/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileInput @private */ define("moxie/runtime/html5/file/FileInput", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _files = [], _options; Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), input, shimContainer, mimes, browseButton, zIndex, top; _options = options; _files = []; // figure out accept string mimes = _options.accept.mimes || Mime.extList2mimes(_options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); shimContainer.innerHTML = '<input id="' + I.uid +'" type="file" style="font-size:999px;opacity:0;"' + (_options.multiple && I.can('select_multiple') ? 'multiple' : '') + (_options.directory && I.can('select_folder') ? 'webkitdirectory directory' : '') + // Chrome 11+ (mimes ? ' accept="' + mimes.join(',') + '"' : '') + ' />'; input = Dom.get(I.uid); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); browseButton = Dom.get(_options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; Events.addEvent(browseButton, 'click', function(e) { var input = Dom.get(I.uid); if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(_options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); input.onchange = function onChange() { // there should be only one handler for this _files = []; if (_options.directory) { // folders are represented by dots, filter them out (Chrome 11+) Basic.each(this.files, function(file) { if (file.name !== ".") { // if it doesn't looks like a folder _files.push(file); } }); } else { _files = [].slice.call(this.files); } // clearing the value enables the user to select the same file again if they want to if (Env.browser !== 'IE') { this.value = ''; } else { // in IE input[type="file"] is read-only so the only way to reset it is to re-insert it var clone = this.cloneNode(true); this.parentNode.replaceChild(clone, this); clone.onchange = onChange; } comp.trigger('change'); }; // ready event is perfectly asynchronous comp.trigger({ type: 'ready', async: true }); shimContainer = null; }, getFiles: function() { return _files; }, disable: function(state) { var I = this.getRuntime(), input; if ((input = Dom.get(I.uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime() , shim = I.getShim() , shimContainer = I.getShimContainer() ; Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } shim.removeInstance(this.uid); _files = _options = shimContainer = shim = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html5/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileDrop @private */ define("moxie/runtime/html5/file/FileDrop", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime" ], function(extensions, Basic, Dom, Events, Mime) { function FileDrop() { var _files = [], _allowedExts = [], _options; Basic.extend(this, { init: function(options) { var comp = this, dropZone; _options = options; _allowedExts = _extractExts(_options.accept); dropZone = _options.container; Events.addEvent(dropZone, 'dragover', function(e) { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy'; }, comp.uid); Events.addEvent(dropZone, 'drop', function(e) { e.preventDefault(); e.stopPropagation(); _files = []; // Chrome 21+ accepts folders via Drag'n'Drop if (e.dataTransfer.items && e.dataTransfer.items[0].webkitGetAsEntry) { var entries = []; Basic.each(e.dataTransfer.items, function(item) { entries.push(item.webkitGetAsEntry()); }); _readEntries(entries, function() { comp.trigger("drop"); }); } else { Basic.each(e.dataTransfer.files, function(file) { if (_isAcceptable(file)) { _files.push(file); } }); comp.trigger("drop"); } }, comp.uid); Events.addEvent(dropZone, 'dragenter', function(e) { e.preventDefault(); e.stopPropagation(); comp.trigger("dragenter"); }, comp.uid); Events.addEvent(dropZone, 'dragleave', function(e) { e.preventDefault(); e.stopPropagation(); comp.trigger("dragleave"); }, comp.uid); }, getFiles: function() { return _files; }, destroy: function() { Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); _files = _allowedExts = _options = null; } }); function _extractExts(accept) { var exts = []; for (var i = 0; i < accept.length; i++) { [].push.apply(exts, accept[i].extensions.split(/\s*,\s*/)); } return Basic.inArray('*', exts) === -1 ? exts : []; } function _isAcceptable(file) { var ext = Mime.getFileExtension(file.name); return !ext || !_allowedExts.length || Basic.inArray(ext, _allowedExts) !== -1; } function _readEntries(entries, cb) { var queue = []; Basic.each(entries, function(entry) { queue.push(function(cbcb) { _readEntry(entry, cbcb); }); }); Basic.inSeries(queue, function() { cb(); }); } function _readEntry(entry, cb) { if (entry.isFile) { entry.file(function(file) { if (_isAcceptable(file)) { _files.push(file); } cb(); }, function() { // fire an error event maybe cb(); }); } else if (entry.isDirectory) { _readDirEntry(entry, cb); } else { cb(); // not file, not directory? what then?.. } } function _readDirEntry(dirEntry, cb) { var entries = [], dirReader = dirEntry.createReader(); // keep quering recursively till no more entries function getEntries(cbcb) { dirReader.readEntries(function(moreEntries) { if (moreEntries.length) { [].push.apply(entries, moreEntries); getEntries(cbcb); } else { cbcb(); } }, cbcb); } // ...and you thought FileReader was crazy... getEntries(function() { _readEntries(entries, cb); }); } } return (extensions.FileDrop = FileDrop); }); // Included from: src/javascript/runtime/html5/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileReader @private */ define("moxie/runtime/html5/file/FileReader", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Encode", "moxie/core/utils/Basic" ], function(extensions, Encode, Basic) { function FileReader() { var _fr, _convertToBinary = false; Basic.extend(this, { read: function(op, blob) { var target = this; _fr = new window.FileReader(); _fr.addEventListener('progress', function(e) { target.trigger(e); }); _fr.addEventListener('load', function(e) { target.trigger(e); }); _fr.addEventListener('error', function(e) { target.trigger(e, _fr.error); }); _fr.addEventListener('loadend', function() { _fr = null; }); if (Basic.typeOf(_fr[op]) === 'function') { _convertToBinary = false; _fr[op](blob.getSource()); } else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+ _convertToBinary = true; _fr.readAsDataURL(blob.getSource()); } }, getResult: function() { return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null; }, abort: function() { if (_fr) { _fr.abort(); } }, destroy: function() { _fr = null; } }); function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } } return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html5/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** @class moxie/runtime/html5/xhr/XMLHttpRequest @private */ define("moxie/runtime/html5/xhr/XMLHttpRequest", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Mime", "moxie/core/utils/Url", "moxie/file/File", "moxie/file/Blob", "moxie/xhr/FormData", "moxie/core/Exceptions", "moxie/core/utils/Env" ], function(extensions, Basic, Mime, Url, File, Blob, FormData, x, Env) { function XMLHttpRequest() { var self = this , _xhr , _filename ; Basic.extend(this, { send: function(meta, data) { var target = this , isGecko2_5_6 = (Env.browser === 'Mozilla' && Env.version >= 4 && Env.version < 7) , isAndroidBrowser = Env.browser === 'Android Browser' , mustSendAsBinary = false ; // extract file name _filename = meta.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase(); _xhr = _getNativeXHR(); _xhr.open(meta.method, meta.url, meta.async, meta.user, meta.password); // prepare data to be sent if (data instanceof Blob) { if (data.isDetached()) { mustSendAsBinary = true; } data = data.getSource(); } else if (data instanceof FormData) { if (data.hasBlob()) { if (data.getBlob().isDetached()) { data = _prepareMultipart.call(target, data); // _xhr must be instantiated and be in OPENED state mustSendAsBinary = true; } else if ((isGecko2_5_6 || isAndroidBrowser) && Basic.typeOf(data.getBlob().getSource()) === 'blob' && window.FileReader) { // Gecko 2/5/6 can't send blob in FormData: https://bugzilla.mozilla.org/show_bug.cgi?id=649150 // Android browsers (default one and Dolphin) seem to have the same issue, see: #613 _preloadAndSend.call(target, meta, data); return; // _preloadAndSend will reinvoke send() with transmutated FormData =%D } } // transfer fields to real FormData if (data instanceof FormData) { // if still a FormData, e.g. not mangled by _prepareMultipart() var fd = new window.FormData(); data.each(function(value, name) { if (value instanceof Blob) { fd.append(name, value.getSource()); } else { fd.append(name, value); } }); data = fd; } } // if XHR L2 if (_xhr.upload) { if (meta.withCredentials) { _xhr.withCredentials = true; } _xhr.addEventListener('load', function(e) { target.trigger(e); }); _xhr.addEventListener('error', function(e) { target.trigger(e); }); // additionally listen to progress events _xhr.addEventListener('progress', function(e) { target.trigger(e); }); _xhr.upload.addEventListener('progress', function(e) { target.trigger({ type: 'UploadProgress', loaded: e.loaded, total: e.total }); }); // ... otherwise simulate XHR L2 } else { _xhr.onreadystatechange = function onReadyStateChange() { // fake Level 2 events switch (_xhr.readyState) { case 1: // XMLHttpRequest.OPENED // readystatechanged is fired twice for OPENED state (in IE and Mozilla) - neu break; // looks like HEADERS_RECEIVED (state 2) is not reported in Opera (or it's old versions) - neu case 2: // XMLHttpRequest.HEADERS_RECEIVED break; case 3: // XMLHttpRequest.LOADING // try to fire progress event for not XHR L2 var total, loaded; try { if (Url.hasSameOrigin(meta.url)) { // Content-Length not accessible for cross-domain on some browsers total = _xhr.getResponseHeader('Content-Length') || 0; // old Safari throws an exception here } if (_xhr.responseText) { // responseText was introduced in IE7 loaded = _xhr.responseText.length; } } catch(ex) { total = loaded = 0; } target.trigger({ type: 'progress', lengthComputable: !!total, total: parseInt(total, 10), loaded: loaded }); break; case 4: // XMLHttpRequest.DONE // release readystatechange handler (mostly for IE) _xhr.onreadystatechange = function() {}; // usually status 0 is returned when server is unreachable, but FF also fails to status 0 for 408 timeout if (_xhr.status === 0) { target.trigger('error'); } else { target.trigger('load'); } break; } }; } // set request headers if (!Basic.isEmptyObj(meta.headers)) { Basic.each(meta.headers, function(value, header) { _xhr.setRequestHeader(header, value); }); } // request response type if ("" !== meta.responseType && 'responseType' in _xhr) { if ('json' === meta.responseType && !Env.can('return_response_type', 'json')) { // we can fake this one _xhr.responseType = 'text'; } else { _xhr.responseType = meta.responseType; } } // send ... if (!mustSendAsBinary) { _xhr.send(data); } else { if (_xhr.sendAsBinary) { // Gecko _xhr.sendAsBinary(data); } else { // other browsers having support for typed arrays (function() { // mimic Gecko's sendAsBinary var ui8a = new Uint8Array(data.length); for (var i = 0; i < data.length; i++) { ui8a[i] = (data.charCodeAt(i) & 0xff); } _xhr.send(ui8a.buffer); }()); } } target.trigger('loadstart'); }, getStatus: function() { // according to W3C spec it should return 0 for readyState < 3, but instead it throws an exception try { if (_xhr) { return _xhr.status; } } catch(ex) {} return 0; }, getResponse: function(responseType) { var I = this.getRuntime(); try { switch (responseType) { case 'blob': var file = new File(I.uid, _xhr.response); // try to extract file name from content-disposition if possible (might be - not, if CORS for example) var disposition = _xhr.getResponseHeader('Content-Disposition'); if (disposition) { // extract filename from response header if available var match = disposition.match(/filename=([\'\"'])([^\1]+)\1/); if (match) { _filename = match[2]; } } file.name = _filename; // pre-webkit Opera doesn't set type property on the blob response if (!file.type) { file.type = Mime.getFileMime(_filename); } return file; case 'json': if (!Env.can('return_response_type', 'json')) { return _xhr.status === 200 && !!window.JSON ? JSON.parse(_xhr.responseText) : null; } return _xhr.response; case 'document': return _getDocument(_xhr); default: return _xhr.responseText !== '' ? _xhr.responseText : null; // against the specs, but for consistency across the runtimes } } catch(ex) { return null; } }, getAllResponseHeaders: function() { try { return _xhr.getAllResponseHeaders(); } catch(ex) {} return ''; }, abort: function() { if (_xhr) { _xhr.abort(); } }, destroy: function() { self = _filename = null; } }); // here we go... ugly fix for ugly bug function _preloadAndSend(meta, data) { var target = this, blob, fr; // get original blob blob = data.getBlob().getSource(); // preload blob in memory to be sent as binary string fr = new window.FileReader(); fr.onload = function() { // overwrite original blob data.append(data.getBlobName(), new Blob(null, { type: blob.type, data: fr.result })); // invoke send operation again self.send.call(target, meta, data); }; fr.readAsBinaryString(blob); } function _getNativeXHR() { if (window.XMLHttpRequest && !(Env.browser === 'IE' && Env.version < 8)) { // IE7 has native XHR but it's buggy return new window.XMLHttpRequest(); } else { return (function() { var progIDs = ['Msxml2.XMLHTTP.6.0', 'Microsoft.XMLHTTP']; // if 6.0 available, use it, otherwise failback to default 3.0 for (var i = 0; i < progIDs.length; i++) { try { return new ActiveXObject(progIDs[i]); } catch (ex) {} } })(); } } // @credits Sergey Ilinsky (http://www.ilinsky.com/) function _getDocument(xhr) { var rXML = xhr.responseXML; var rText = xhr.responseText; // Try parsing responseText (@see: http://www.ilinsky.com/articles/XMLHttpRequest/#bugs-ie-responseXML-content-type) if (Env.browser === 'IE' && rText && rXML && !rXML.documentElement && /[^\/]+\/[^\+]+\+xml/.test(xhr.getResponseHeader("Content-Type"))) { rXML = new window.ActiveXObject("Microsoft.XMLDOM"); rXML.async = false; rXML.validateOnParse = false; rXML.loadXML(rText); } // Check if there is no error in document if (rXML) { if ((Env.browser === 'IE' && rXML.parseError !== 0) || !rXML.documentElement || rXML.documentElement.tagName === "parsererror") { return null; } } return rXML; } function _prepareMultipart(fd) { var boundary = '----moxieboundary' + new Date().getTime() , dashdash = '--' , crlf = '\r\n' , multipart = '' , I = this.getRuntime() ; if (!I.can('send_binary_string')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } _xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); // append multipart parameters fd.each(function(value, name) { // Firefox 3.6 failed to convert multibyte characters to UTF-8 in sendAsBinary(), // so we try it here ourselves with: unescape(encodeURIComponent(value)) if (value instanceof Blob) { // Build RFC2388 blob multipart += dashdash + boundary + crlf + 'Content-Disposition: form-data; name="' + name + '"; filename="' + unescape(encodeURIComponent(value.name || 'blob')) + '"' + crlf + 'Content-Type: ' + value.type + crlf + crlf + value.getSource() + crlf; } else { multipart += dashdash + boundary + crlf + 'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf + unescape(encodeURIComponent(value)) + crlf; } }); multipart += dashdash + boundary + dashdash + crlf; return multipart; } } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html5/utils/BinaryReader.js /** * BinaryReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/utils/BinaryReader @private */ define("moxie/runtime/html5/utils/BinaryReader", [], function() { return function() { var II = false, bin; // Private functions function read(idx, size) { var mv = II ? 0 : -8 * (size - 1), sum = 0, i; for (i = 0; i < size; i++) { sum |= (bin.charCodeAt(idx + i) << Math.abs(mv + i*8)); } return sum; } function putstr(segment, idx, length) { length = arguments.length === 3 ? length : bin.length - idx - 1; bin = bin.substr(0, idx) + segment + bin.substr(length + idx); } function write(idx, num, size) { var str = '', mv = II ? 0 : -8 * (size - 1), i; for (i = 0; i < size; i++) { str += String.fromCharCode((num >> Math.abs(mv + i*8)) & 255); } putstr(str, idx, size); } // Public functions return { II: function(order) { if (order === undefined) { return II; } else { II = order; } }, init: function(binData) { II = false; bin = binData; }, SEGMENT: function(idx, length, segment) { switch (arguments.length) { case 1: return bin.substr(idx, bin.length - idx - 1); case 2: return bin.substr(idx, length); case 3: putstr(segment, idx, length); break; default: return bin; } }, BYTE: function(idx) { return read(idx, 1); }, SHORT: function(idx) { return read(idx, 2); }, LONG: function(idx, num) { if (num === undefined) { return read(idx, 4); } else { write(idx, num, 4); } }, SLONG: function(idx) { // 2's complement notation var num = read(idx, 4); return (num > 2147483647 ? num - 4294967296 : num); }, STRING: function(idx, size) { var str = ''; for (size += idx; idx < size; idx++) { str += String.fromCharCode(read(idx, 1)); } return str; } }; }; }); // Included from: src/javascript/runtime/html5/image/JPEGHeaders.js /** * JPEGHeaders.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/JPEGHeaders @private */ define("moxie/runtime/html5/image/JPEGHeaders", [ "moxie/runtime/html5/utils/BinaryReader" ], function(BinaryReader) { return function JPEGHeaders(data) { var headers = [], read, idx, marker, length = 0; read = new BinaryReader(); read.init(data); // Check if data is jpeg if (read.SHORT(0) !== 0xFFD8) { return; } idx = 2; while (idx <= data.length) { marker = read.SHORT(idx); // omit RST (restart) markers if (marker >= 0xFFD0 && marker <= 0xFFD7) { idx += 2; continue; } // no headers allowed after SOS marker if (marker === 0xFFDA || marker === 0xFFD9) { break; } length = read.SHORT(idx + 2) + 2; // APPn marker detected if (marker >= 0xFFE1 && marker <= 0xFFEF) { headers.push({ hex: marker, name: 'APP' + (marker & 0x000F), start: idx, length: length, segment: read.SEGMENT(idx, length) }); } idx += length; } read.init(null); // free memory return { headers: headers, restore: function(data) { var max, i; read.init(data); idx = read.SHORT(2) == 0xFFE0 ? 4 + read.SHORT(4) : 2; for (i = 0, max = headers.length; i < max; i++) { read.SEGMENT(idx, 0, headers[i].segment); idx += headers[i].length; } data = read.SEGMENT(); read.init(null); return data; }, strip: function(data) { var headers, jpegHeaders, i; jpegHeaders = new JPEGHeaders(data); headers = jpegHeaders.headers; jpegHeaders.purge(); read.init(data); i = headers.length; while (i--) { read.SEGMENT(headers[i].start, headers[i].length, ''); } data = read.SEGMENT(); read.init(null); return data; }, get: function(name) { var array = []; for (var i = 0, max = headers.length; i < max; i++) { if (headers[i].name === name.toUpperCase()) { array.push(headers[i].segment); } } return array; }, set: function(name, segment) { var array = [], i, ii, max; if (typeof(segment) === 'string') { array.push(segment); } else { array = segment; } for (i = ii = 0, max = headers.length; i < max; i++) { if (headers[i].name === name.toUpperCase()) { headers[i].segment = array[ii]; headers[i].length = array[ii].length; ii++; } if (ii >= array.length) { break; } } }, purge: function() { headers = []; read.init(null); read = null; } }; }; }); // Included from: src/javascript/runtime/html5/image/ExifParser.js /** * ExifParser.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/ExifParser @private */ define("moxie/runtime/html5/image/ExifParser", [ "moxie/core/utils/Basic", "moxie/runtime/html5/utils/BinaryReader" ], function(Basic, BinaryReader) { return function ExifParser() { // Private ExifParser fields var data, tags, Tiff, offsets = {}, tagDescs; data = new BinaryReader(); tags = { tiff : { /* The image orientation viewed in terms of rows and columns. 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom. */ 0x0112: 'Orientation', 0x010E: 'ImageDescription', 0x010F: 'Make', 0x0110: 'Model', 0x0131: 'Software', 0x8769: 'ExifIFDPointer', 0x8825: 'GPSInfoIFDPointer' }, exif : { 0x9000: 'ExifVersion', 0xA001: 'ColorSpace', 0xA002: 'PixelXDimension', 0xA003: 'PixelYDimension', 0x9003: 'DateTimeOriginal', 0x829A: 'ExposureTime', 0x829D: 'FNumber', 0x8827: 'ISOSpeedRatings', 0x9201: 'ShutterSpeedValue', 0x9202: 'ApertureValue' , 0x9207: 'MeteringMode', 0x9208: 'LightSource', 0x9209: 'Flash', 0x920A: 'FocalLength', 0xA402: 'ExposureMode', 0xA403: 'WhiteBalance', 0xA406: 'SceneCaptureType', 0xA404: 'DigitalZoomRatio', 0xA408: 'Contrast', 0xA409: 'Saturation', 0xA40A: 'Sharpness' }, gps : { 0x0000: 'GPSVersionID', 0x0001: 'GPSLatitudeRef', 0x0002: 'GPSLatitude', 0x0003: 'GPSLongitudeRef', 0x0004: 'GPSLongitude' } }; tagDescs = { 'ColorSpace': { 1: 'sRGB', 0: 'Uncalibrated' }, 'MeteringMode': { 0: 'Unknown', 1: 'Average', 2: 'CenterWeightedAverage', 3: 'Spot', 4: 'MultiSpot', 5: 'Pattern', 6: 'Partial', 255: 'Other' }, 'LightSource': { 1: 'Daylight', 2: 'Fliorescent', 3: 'Tungsten', 4: 'Flash', 9: 'Fine weather', 10: 'Cloudy weather', 11: 'Shade', 12: 'Daylight fluorescent (D 5700 - 7100K)', 13: 'Day white fluorescent (N 4600 -5400K)', 14: 'Cool white fluorescent (W 3900 - 4500K)', 15: 'White fluorescent (WW 3200 - 3700K)', 17: 'Standard light A', 18: 'Standard light B', 19: 'Standard light C', 20: 'D55', 21: 'D65', 22: 'D75', 23: 'D50', 24: 'ISO studio tungsten', 255: 'Other' }, 'Flash': { 0x0000: 'Flash did not fire.', 0x0001: 'Flash fired.', 0x0005: 'Strobe return light not detected.', 0x0007: 'Strobe return light detected.', 0x0009: 'Flash fired, compulsory flash mode', 0x000D: 'Flash fired, compulsory flash mode, return light not detected', 0x000F: 'Flash fired, compulsory flash mode, return light detected', 0x0010: 'Flash did not fire, compulsory flash mode', 0x0018: 'Flash did not fire, auto mode', 0x0019: 'Flash fired, auto mode', 0x001D: 'Flash fired, auto mode, return light not detected', 0x001F: 'Flash fired, auto mode, return light detected', 0x0020: 'No flash function', 0x0041: 'Flash fired, red-eye reduction mode', 0x0045: 'Flash fired, red-eye reduction mode, return light not detected', 0x0047: 'Flash fired, red-eye reduction mode, return light detected', 0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode', 0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected', 0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected', 0x0059: 'Flash fired, auto mode, red-eye reduction mode', 0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode', 0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode' }, 'ExposureMode': { 0: 'Auto exposure', 1: 'Manual exposure', 2: 'Auto bracket' }, 'WhiteBalance': { 0: 'Auto white balance', 1: 'Manual white balance' }, 'SceneCaptureType': { 0: 'Standard', 1: 'Landscape', 2: 'Portrait', 3: 'Night scene' }, 'Contrast': { 0: 'Normal', 1: 'Soft', 2: 'Hard' }, 'Saturation': { 0: 'Normal', 1: 'Low saturation', 2: 'High saturation' }, 'Sharpness': { 0: 'Normal', 1: 'Soft', 2: 'Hard' }, // GPS related 'GPSLatitudeRef': { N: 'North latitude', S: 'South latitude' }, 'GPSLongitudeRef': { E: 'East longitude', W: 'West longitude' } }; function extractTags(IFD_offset, tags2extract) { var length = data.SHORT(IFD_offset), i, ii, tag, type, count, tagOffset, offset, value, values = [], hash = {}; for (i = 0; i < length; i++) { // Set binary reader pointer to beginning of the next tag offset = tagOffset = IFD_offset + 12 * i + 2; tag = tags2extract[data.SHORT(offset)]; if (tag === undefined) { continue; // Not the tag we requested } type = data.SHORT(offset+=2); count = data.LONG(offset+=2); offset += 4; values = []; switch (type) { case 1: // BYTE case 7: // UNDEFINED if (count > 4) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.BYTE(offset + ii); } break; case 2: // STRING if (count > 4) { offset = data.LONG(offset) + offsets.tiffHeader; } hash[tag] = data.STRING(offset, count - 1); continue; case 3: // SHORT if (count > 2) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.SHORT(offset + ii*2); } break; case 4: // LONG if (count > 1) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.LONG(offset + ii*4); } break; case 5: // RATIONAL offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.LONG(offset + ii*4) / data.LONG(offset + ii*4 + 4); } break; case 9: // SLONG offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.SLONG(offset + ii*4); } break; case 10: // SRATIONAL offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.SLONG(offset + ii*4) / data.SLONG(offset + ii*4 + 4); } break; default: continue; } value = (count == 1 ? values[0] : values); if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') { hash[tag] = tagDescs[tag][value]; } else { hash[tag] = value; } } return hash; } function getIFDOffsets() { var idx = offsets.tiffHeader; // Set read order of multi-byte data data.II(data.SHORT(idx) == 0x4949); // Check if always present bytes are indeed present if (data.SHORT(idx+=2) !== 0x002A) { return false; } offsets.IFD0 = offsets.tiffHeader + data.LONG(idx += 2); Tiff = extractTags(offsets.IFD0, tags.tiff); if ('ExifIFDPointer' in Tiff) { offsets.exifIFD = offsets.tiffHeader + Tiff.ExifIFDPointer; delete Tiff.ExifIFDPointer; } if ('GPSInfoIFDPointer' in Tiff) { offsets.gpsIFD = offsets.tiffHeader + Tiff.GPSInfoIFDPointer; delete Tiff.GPSInfoIFDPointer; } return true; } // At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported function setTag(ifd, tag, value) { var offset, length, tagOffset, valueOffset = 0; // If tag name passed translate into hex key if (typeof(tag) === 'string') { var tmpTags = tags[ifd.toLowerCase()]; for (var hex in tmpTags) { if (tmpTags[hex] === tag) { tag = hex; break; } } } offset = offsets[ifd.toLowerCase() + 'IFD']; length = data.SHORT(offset); for (var i = 0; i < length; i++) { tagOffset = offset + 12 * i + 2; if (data.SHORT(tagOffset) == tag) { valueOffset = tagOffset + 8; break; } } if (!valueOffset) { return false; } data.LONG(valueOffset, value); return true; } // Public functions return { init: function(segment) { // Reset internal data offsets = { tiffHeader: 10 }; if (segment === undefined || !segment.length) { return false; } data.init(segment); // Check if that's APP1 and that it has EXIF if (data.SHORT(0) === 0xFFE1 && data.STRING(4, 5).toUpperCase() === "EXIF\0") { return getIFDOffsets(); } return false; }, TIFF: function() { return Tiff; }, EXIF: function() { var Exif; // Populate EXIF hash Exif = extractTags(offsets.exifIFD, tags.exif); // Fix formatting of some tags if (Exif.ExifVersion && Basic.typeOf(Exif.ExifVersion) === 'array') { for (var i = 0, exifVersion = ''; i < Exif.ExifVersion.length; i++) { exifVersion += String.fromCharCode(Exif.ExifVersion[i]); } Exif.ExifVersion = exifVersion; } return Exif; }, GPS: function() { var GPS; GPS = extractTags(offsets.gpsIFD, tags.gps); // iOS devices (and probably some others) do not put in GPSVersionID tag (why?..) if (GPS.GPSVersionID && Basic.typeOf(GPS.GPSVersionID) === 'array') { GPS.GPSVersionID = GPS.GPSVersionID.join('.'); } return GPS; }, setExif: function(tag, value) { // Right now only setting of width/height is possible if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') {return false;} return setTag('exif', tag, value); }, getBinary: function() { return data.SEGMENT(); }, purge: function() { data.init(null); data = Tiff = null; offsets = {}; } }; }; }); // Included from: src/javascript/runtime/html5/image/JPEG.js /** * JPEG.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/JPEG @private */ define("moxie/runtime/html5/image/JPEG", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/html5/image/JPEGHeaders", "moxie/runtime/html5/utils/BinaryReader", "moxie/runtime/html5/image/ExifParser" ], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) { function JPEG(binstr) { var _binstr, _br, _hm, _ep, _info, hasExif; function _getDimensions() { var idx = 0, marker, length; // examine all through the end, since some images might have very large APP segments while (idx <= _binstr.length) { marker = _br.SHORT(idx += 2); if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte) return { height: _br.SHORT(idx), width: _br.SHORT(idx += 2) }; } length = _br.SHORT(idx += 2); idx += length - 2; } return null; } _binstr = binstr; _br = new BinaryReader(); _br.init(_binstr); // check if it is jpeg if (_br.SHORT(0) !== 0xFFD8) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } // backup headers _hm = new JPEGHeaders(binstr); // extract exif info _ep = new ExifParser(); hasExif = !!_ep.init(_hm.get('app1')[0]); // get dimensions _info = _getDimensions.call(this); Basic.extend(this, { type: 'image/jpeg', size: _binstr.length, width: _info && _info.width || 0, height: _info && _info.height || 0, setExif: function(tag, value) { if (!hasExif) { return false; // or throw an exception } if (Basic.typeOf(tag) === 'object') { Basic.each(tag, function(value, tag) { _ep.setExif(tag, value); }); } else { _ep.setExif(tag, value); } // update internal headers _hm.set('app1', _ep.getBinary()); }, writeHeaders: function() { if (!arguments.length) { // if no arguments passed, update headers internally return (_binstr = _hm.restore(_binstr)); } return _hm.restore(arguments[0]); }, stripHeaders: function(binstr) { return _hm.strip(binstr); }, purge: function() { _purge.call(this); } }); if (hasExif) { this.meta = { tiff: _ep.TIFF(), exif: _ep.EXIF(), gps: _ep.GPS() }; } function _purge() { if (!_ep || !_hm || !_br) { return; // ignore any repeating purge requests } _ep.purge(); _hm.purge(); _br.init(null); _binstr = _info = _hm = _ep = _br = null; } } return JPEG; }); // Included from: src/javascript/runtime/html5/image/PNG.js /** * PNG.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/PNG @private */ define("moxie/runtime/html5/image/PNG", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/runtime/html5/utils/BinaryReader" ], function(x, Basic, BinaryReader) { function PNG(binstr) { var _binstr, _br, _hm, _ep, _info; _binstr = binstr; _br = new BinaryReader(); _br.init(_binstr); // check if it's png (function() { var idx = 0, i = 0 , signature = [0x8950, 0x4E47, 0x0D0A, 0x1A0A] ; for (i = 0; i < signature.length; i++, idx += 2) { if (signature[i] != _br.SHORT(idx)) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } } }()); function _getDimensions() { var chunk, idx; chunk = _getChunkAt.call(this, 8); if (chunk.type == 'IHDR') { idx = chunk.start; return { width: _br.LONG(idx), height: _br.LONG(idx += 4) }; } return null; } function _purge() { if (!_br) { return; // ignore any repeating purge requests } _br.init(null); _binstr = _info = _hm = _ep = _br = null; } _info = _getDimensions.call(this); Basic.extend(this, { type: 'image/png', size: _binstr.length, width: _info.width, height: _info.height, purge: function() { _purge.call(this); } }); // for PNG we can safely trigger purge automatically, as we do not keep any data for later _purge.call(this); function _getChunkAt(idx) { var length, type, start, CRC; length = _br.LONG(idx); type = _br.STRING(idx += 4, 4); start = idx += 4; CRC = _br.LONG(idx + length); return { length: length, type: type, start: start, CRC: CRC }; } } return PNG; }); // Included from: src/javascript/runtime/html5/image/ImageInfo.js /** * ImageInfo.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/ImageInfo @private */ define("moxie/runtime/html5/image/ImageInfo", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/html5/image/JPEG", "moxie/runtime/html5/image/PNG" ], function(Basic, x, JPEG, PNG) { /** Optional image investigation tool for HTML5 runtime. Provides the following features: - ability to distinguish image type (JPEG or PNG) by signature - ability to extract image width/height directly from it's internals, without preloading in memory (fast) - ability to extract APP headers from JPEGs (Exif, GPS, etc) - ability to replace width/height tags in extracted JPEG headers - ability to restore APP headers, that were for example stripped during image manipulation @class ImageInfo @constructor @param {String} binstr Image source as binary string */ return function(binstr) { var _cs = [JPEG, PNG], _img; // figure out the format, throw: ImageError.WRONG_FORMAT if not supported _img = (function() { for (var i = 0; i < _cs.length; i++) { try { return new _cs[i](binstr); } catch (ex) { // console.info(ex); } } throw new x.ImageError(x.ImageError.WRONG_FORMAT); }()); Basic.extend(this, { /** Image Mime Type extracted from it's depths @property type @type {String} @default '' */ type: '', /** Image size in bytes @property size @type {Number} @default 0 */ size: 0, /** Image width extracted from image source @property width @type {Number} @default 0 */ width: 0, /** Image height extracted from image source @property height @type {Number} @default 0 */ height: 0, /** Sets Exif tag. Currently applicable only for width and height tags. Obviously works only with JPEGs. @method setExif @param {String} tag Tag to set @param {Mixed} value Value to assign to the tag */ setExif: function() {}, /** Restores headers to the source. @method writeHeaders @param {String} data Image source as binary string @return {String} Updated binary string */ writeHeaders: function(data) { return data; }, /** Strip all headers from the source. @method stripHeaders @param {String} data Image source as binary string @return {String} Updated binary string */ stripHeaders: function(data) { return data; }, /** Dispose resources. @method purge */ purge: function() {} }); Basic.extend(this, _img); this.purge = function() { _img.purge(); _img = null; }; }; }); // Included from: src/javascript/runtime/html5/image/MegaPixel.js /** (The MIT License) Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>; 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. */ /** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com> * Released under the MIT license */ /** @class moxie/runtime/html5/image/MegaPixel @private */ define("moxie/runtime/html5/image/MegaPixel", [], function() { /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options) { var iw = img.naturalWidth, ih = img.naturalHeight; var width = options.width, height = options.height; var x = options.x || 0, y = options.y || 0; var ctx = canvas.getContext('2d'); if (detectSubsampling(img)) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = detectVerticalSquash(img, iw, ih); var sy = 0; while (sy < ih) { var sh = sy + d > ih ? ih - sy : d; var sx = 0; while (sx < iw) { var sw = sx + d > iw ? iw - sx : d; tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); var dx = (sx * width / iw + x) << 0; var dw = Math.ceil(sw * width / iw); var dy = (sy * height / ih / vertSquashRatio + y) << 0; var dh = Math.ceil(sh * height / ih / vertSquashRatio); ctx.drawImage(tmpCanvas, 0, 0, sw, sh, dx, dy, dw, dh); sx += d; } sy += d; } tmpCanvas = tmpCtx = null; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } canvas = null; var ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } return { isSubsampled: detectSubsampling, renderTo: renderImageToCanvas }; }); // Included from: src/javascript/runtime/html5/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/Image @private */ define("moxie/runtime/html5/image/Image", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/utils/Encode", "moxie/file/File", "moxie/runtime/html5/image/ImageInfo", "moxie/runtime/html5/image/MegaPixel", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, x, Encode, File, ImageInfo, MegaPixel, Mime, Env) { function HTML5Image() { var me = this , _img, _imgInfo, _canvas, _binStr, _blob , _modified = false // is set true whenever image is modified , _preserveHeaders = true ; Basic.extend(this, { loadFromBlob: function(blob) { var comp = this, I = comp.getRuntime() , asBinary = arguments.length > 1 ? arguments[1] : true ; if (!I.can('access_binary')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } _blob = blob; if (blob.isDetached()) { _binStr = blob.getSource(); _preload.call(this, _binStr); return; } else { _readAsDataUrl.call(this, blob.getSource(), function(dataUrl) { if (asBinary) { _binStr = _toBinary(dataUrl); } _preload.call(comp, dataUrl); }); } }, loadFromImage: function(img, exact) { this.meta = img.meta; _blob = new File(null, { name: img.name, size: img.size, type: img.type }); _preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL()); }, getInfo: function() { var I = this.getRuntime(), info; if (!_imgInfo && _binStr && I.can('access_image_binary')) { _imgInfo = new ImageInfo(_binStr); } info = { width: _getImg().width || 0, height: _getImg().height || 0, type: _blob.type || Mime.getFileMime(_blob.name), size: _binStr && _binStr.length || _blob.size || 0, name: _blob.name || '', meta: _imgInfo && _imgInfo.meta || this.meta || {} }; return info; }, downsize: function() { _downsize.apply(this, arguments); }, getAsCanvas: function() { if (_canvas) { _canvas.id = this.uid + '_canvas'; } return _canvas; }, getAsBlob: function(type, quality) { if (type !== this.type) { // if different mime type requested prepare image for conversion _downsize.call(this, this.width, this.height, false); } return new File(null, { name: _blob.name || '', type: type, data: me.getAsBinaryString.call(this, type, quality) }); }, getAsDataURL: function(type) { var quality = arguments[1] || 90; // if image has not been modified, return the source right away if (!_modified) { return _img.src; } if ('image/jpeg' !== type) { return _canvas.toDataURL('image/png'); } else { try { // older Geckos used to result in an exception on quality argument return _canvas.toDataURL('image/jpeg', quality/100); } catch (ex) { return _canvas.toDataURL('image/jpeg'); } } }, getAsBinaryString: function(type, quality) { // if image has not been modified, return the source right away if (!_modified) { // if image was not loaded from binary string if (!_binStr) { _binStr = _toBinary(me.getAsDataURL(type, quality)); } return _binStr; } if ('image/jpeg' !== type) { _binStr = _toBinary(me.getAsDataURL(type, quality)); } else { var dataUrl; // if jpeg if (!quality) { quality = 90; } try { // older Geckos used to result in an exception on quality argument dataUrl = _canvas.toDataURL('image/jpeg', quality/100); } catch (ex) { dataUrl = _canvas.toDataURL('image/jpeg'); } _binStr = _toBinary(dataUrl); if (_imgInfo) { _binStr = _imgInfo.stripHeaders(_binStr); if (_preserveHeaders) { // update dimensions info in exif if (_imgInfo.meta && _imgInfo.meta.exif) { _imgInfo.setExif({ PixelXDimension: this.width, PixelYDimension: this.height }); } // re-inject the headers _binStr = _imgInfo.writeHeaders(_binStr); } // will be re-created from fresh on next getInfo call _imgInfo.purge(); _imgInfo = null; } } _modified = false; return _binStr; }, destroy: function() { me = null; _purge.call(this); this.getRuntime().getShim().removeInstance(this.uid); } }); function _getImg() { if (!_canvas && !_img) { throw new x.ImageError(x.DOMException.INVALID_STATE_ERR); } return _canvas || _img; } function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } function _toDataUrl(str, type) { return 'data:' + (type || '') + ';base64,' + Encode.btoa(str); } function _preload(str) { var comp = this; _img = new Image(); _img.onerror = function() { _purge.call(this); comp.trigger('error', new x.ImageError(x.ImageError.WRONG_FORMAT)); }; _img.onload = function() { comp.trigger('load'); }; _img.src = /^data:[^;]*;base64,/.test(str) ? str : _toDataUrl(str, _blob.type); } function _readAsDataUrl(file, callback) { var comp = this, fr; // use FileReader if it's available if (window.FileReader) { fr = new FileReader(); fr.onload = function() { callback(this.result); }; fr.onerror = function() { comp.trigger('error', new x.FileException(x.FileException.NOT_READABLE_ERR)); }; fr.readAsDataURL(file); } else { return callback(file.getAsDataURL()); } } function _downsize(width, height, crop, preserveHeaders) { var self = this , scale , mathFn , x = 0 , y = 0 , img , destWidth , destHeight , orientation ; _preserveHeaders = preserveHeaders; // we will need to check this on export (see getAsBinaryString()) // take into account orientation tag orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1; if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation // swap dimensions var tmp = width; width = height; height = tmp; } img = _getImg(); // unify dimensions mathFn = !crop ? Math.min : Math.max; scale = mathFn(width/img.width, height/img.height); // we only downsize here if (scale > 1 && (!crop || preserveHeaders)) { // when cropping one of dimensions may still exceed max, so process it anyway this.trigger('Resize'); return; } // prepare canvas if necessary if (!_canvas) { _canvas = document.createElement("canvas"); } // calculate dimensions of proportionally resized image destWidth = Math.round(img.width * scale); destHeight = Math.round(img.height * scale); // scale image and canvas if (crop) { _canvas.width = width; _canvas.height = height; // if dimensions of the resulting image still larger than canvas, center it if (destWidth > width) { x = Math.round((destWidth - width) / 2); } if (destHeight > height) { y = Math.round((destHeight - height) / 2); } } else { _canvas.width = destWidth; _canvas.height = destHeight; } // rotate if required, according to orientation tag if (!_preserveHeaders) { _rotateToOrientaion(_canvas.width, _canvas.height, orientation); } _drawToCanvas.call(this, img, _canvas, -x, -y, destWidth, destHeight); this.width = _canvas.width; this.height = _canvas.height; _modified = true; self.trigger('Resize'); } function _drawToCanvas(img, canvas, x, y, w, h) { if (Env.OS === 'iOS') { // avoid squish bug in iOS6 MegaPixel.renderTo(img, canvas, { width: w, height: h, x: x, y: y }); } else { var ctx = canvas.getContext('2d'); ctx.drawImage(img, x, y, w, h); } } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag * @author Shinichi Tomita <shinichi.tomita@gmail.com> */ function _rotateToOrientaion(width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: _canvas.width = height; _canvas.height = width; break; default: _canvas.width = width; _canvas.height = height; } /** 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom. */ var ctx = _canvas.getContext('2d'); switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; } } function _purge() { if (_imgInfo) { _imgInfo.purge(); _imgInfo = null; } _binStr = _img = _canvas = _blob = null; _modified = false; } } return (extensions.Image = HTML5Image); }); // Included from: src/javascript/runtime/flash/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Flash runtime. @class moxie/runtime/flash/Runtime @private */ define("moxie/runtime/flash/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = 'flash', extensions = {}; /** Get the version of the Flash Player @method getShimVersion @private @return {Number} Flash Player version */ function getShimVersion() { var version; try { version = navigator.plugins['Shockwave Flash']; version = version.description; } catch (e1) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); } catch (e2) { version = '0.0'; } } version = version.match(/\d+/g); return parseFloat(version[0] + '.' + version[1]); } /** Constructor for the Flash Runtime @class FlashRuntime @extends Runtime */ function FlashRuntime(options) { var I = this, initTimer; options = Basic.extend({ swf_url: Env.swf_url }, options); Runtime.call(this, options, type, { access_binary: function(value) { return value && I.mode === 'browser'; }, access_image_binary: function(value) { return value && I.mode === 'browser'; }, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: function() { return I.mode === 'client'; }, resize_image: Runtime.capTrue, return_response_headers: false, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { return true; } return !Basic.arrayDiff(responseType, ['', 'text', 'document']) || I.mode === 'browser'; }, return_status_code: function(code) { return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: function(value) { return value && I.mode === 'browser'; }, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'browser'; }, send_multipart: Runtime.capTrue, slice_blob: Runtime.capTrue, stream_upload: function(value) { return value && I.mode === 'browser'; }, summon_file_dialog: false, upload_filesize: function(size) { return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client'; }, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode access_binary: function(value) { return value ? 'browser' : 'client'; }, access_image_binary: function(value) { return value ? 'browser' : 'client'; }, report_upload_progress: function(value) { return value ? 'browser' : 'client'; }, return_response_type: function(responseType) { return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser']; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser']; }, send_binary_string: function(value) { return value ? 'browser' : 'client'; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'browser' : 'client'; }, stream_upload: function(value) { return value ? 'client' : 'browser'; }, upload_filesize: function(size) { return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser'; } }, 'client'); // minimal requirement for Flash Player version if (getShimVersion() < 10) { this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before } Basic.extend(this, { getShim: function() { return Dom.get(this.uid); }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init: function() { var html, el, container; container = this.getShimContainer(); // if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc) Basic.extend(container.style, { position: 'absolute', top: '-8px', left: '-8px', width: '9px', height: '9px', overflow: 'hidden' }); // insert flash object html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" '; if (Env.browser === 'IE') { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + options.swf_url + '" />' + '<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; if (Env.browser === 'IE') { el = document.createElement('div'); container.appendChild(el); el.outerHTML = html; el = container = null; // just in case } else { container.innerHTML = html; } // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, 5000); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, FlashRuntime); return extensions; }); // Included from: src/javascript/runtime/flash/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/Blob @private */ define("moxie/runtime/flash/file/Blob", [ "moxie/runtime/flash/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { var FlashBlob = { slice: function(blob, start, end, type) { var self = this.getRuntime(); if (start < 0) { start = Math.max(blob.size + start, 0); } else if (start > 0) { start = Math.min(start, blob.size); } if (end < 0) { end = Math.max(blob.size + end, 0); } else if (end > 0) { end = Math.min(end, blob.size); } blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || ''); if (blob) { blob = new Blob(self.uid, blob); } return blob; } }; return (extensions.Blob = FlashBlob); }); // Included from: src/javascript/runtime/flash/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileInput @private */ define("moxie/runtime/flash/file/FileInput", [ "moxie/runtime/flash/Runtime" ], function(extensions) { var FileInput = { init: function(options) { this.getRuntime().shimExec.call(this, 'FileInput', 'init', { name: options.name, accept: options.accept, multiple: options.multiple }); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/flash/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReader @private */ define("moxie/runtime/flash/file/FileReader", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { var _result = ''; function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReader = { read: function(op, blob) { var target = this, self = target.getRuntime(); // special prefix for DataURL read mode if (op === 'readAsDataURL') { _result = 'data:' + (blob.type || '') + ';base64,'; } target.bind('Progress', function(e, data) { if (data) { _result += _formatData(data, op); } }); return self.shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid); }, getResult: function() { return _result; }, destroy: function() { _result = null; } }; return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/flash/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReaderSync @private */ define("moxie/runtime/flash/file/FileReaderSync", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReaderSync = { read: function(op, blob) { var result, self = this.getRuntime(); result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid); if (!result) { return null; // or throw ex } // special prefix for DataURL read mode if (op === 'readAsDataURL') { result = 'data:' + (blob.type || '') + ';base64,' + result; } return _formatData(result, op, blob.type); } }; return (extensions.FileReaderSync = FileReaderSync); }); // Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/xhr/XMLHttpRequest @private */ define("moxie/runtime/flash/xhr/XMLHttpRequest", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Basic", "moxie/file/Blob", "moxie/file/File", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/runtime/Transporter" ], function(extensions, Basic, Blob, File, FileReaderSync, FormData, Transporter) { var XMLHttpRequest = { send: function(meta, data) { var target = this, self = target.getRuntime(); function send() { meta.transport = self.mode; self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data); } function appendBlob(name, blob) { self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid); data = null; send(); } function attachBlob(blob, cb) { var tr = new Transporter(); tr.bind("TransportingComplete", function() { cb(this.result); }); tr.transport(blob.getSource(), blob.type, { ruid: self.uid }); } // copy over the headers if any if (!Basic.isEmptyObj(meta.headers)) { Basic.each(meta.headers, function(value, header) { self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object }); } // transfer over multipart params and blob itself if (data instanceof FormData) { var blobField; data.each(function(value, name) { if (value instanceof Blob) { blobField = name; } else { self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value); } }); if (!data.hasBlob()) { data = null; send(); } else { var blob = data.getBlob(); if (blob.isDetached()) { attachBlob(blob, function(attachedBlob) { blob.destroy(); appendBlob(blobField, attachedBlob); }); } else { appendBlob(blobField, blob); } } } else if (data instanceof Blob) { if (data.isDetached()) { attachBlob(data, function(attachedBlob) { data.destroy(); data = attachedBlob.uid; send(); }); } else { data = data.uid; send(); } } else { send(); } }, getResponse: function(responseType) { var frs, blob, self = this.getRuntime(); blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob'); if (blob) { blob = new File(self.uid, blob); if ('blob' === responseType) { return blob; } try { frs = new FileReaderSync(); if (!!~Basic.inArray(responseType, ["", "text"])) { return frs.readAsText(blob); } else if ('json' === responseType && !!window.JSON) { return JSON.parse(frs.readAsText(blob)); } } finally { blob.destroy(); } } return null; }, abort: function(upload_complete_flag) { var self = this.getRuntime(); self.shimExec.call(this, 'XMLHttpRequest', 'abort'); this.dispatchEvent('readystatechange'); // this.dispatchEvent('progress'); this.dispatchEvent('abort'); //if (!upload_complete_flag) { // this.dispatchEvent('uploadprogress'); //} } }; return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/flash/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/runtime/Transporter @private */ define("moxie/runtime/flash/runtime/Transporter", [ "moxie/runtime/flash/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { var Transporter = { getAsBlob: function(type) { var self = this.getRuntime() , blob = self.shimExec.call(this, 'Transporter', 'getAsBlob', type) ; if (blob) { return new Blob(self.uid, blob); } return null; } }; return (extensions.Transporter = Transporter); }); // Included from: src/javascript/runtime/flash/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/image/Image @private */ define("moxie/runtime/flash/image/Image", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Basic", "moxie/runtime/Transporter", "moxie/file/Blob", "moxie/file/FileReaderSync" ], function(extensions, Basic, Transporter, Blob, FileReaderSync) { var Image = { loadFromBlob: function(blob) { var comp = this, self = comp.getRuntime(); function exec(srcBlob) { self.shimExec.call(comp, 'Image', 'loadFromBlob', srcBlob.uid); comp = self = null; } if (blob.isDetached()) { // binary string var tr = new Transporter(); tr.bind("TransportingComplete", function() { exec(tr.result.getSource()); }); tr.transport(blob.getSource(), blob.type, { ruid: self.uid }); } else { exec(blob.getSource()); } }, loadFromImage: function(img) { var self = this.getRuntime(); return self.shimExec.call(this, 'Image', 'loadFromImage', img.uid); }, getAsBlob: function(type, quality) { var self = this.getRuntime() , blob = self.shimExec.call(this, 'Image', 'getAsBlob', type, quality) ; if (blob) { return new Blob(self.uid, blob); } return null; }, getAsDataURL: function() { var self = this.getRuntime() , blob = self.Image.getAsBlob.apply(this, arguments) , frs ; if (!blob) { return null; } frs = new FileReaderSync(); return frs.readAsDataURL(blob); } }; return (extensions.Image = Image); }); // Included from: src/javascript/runtime/silverlight/Runtime.js /** * RunTime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Silverlight runtime. @class moxie/runtime/silverlight/Runtime @private */ define("moxie/runtime/silverlight/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = "silverlight", extensions = {}; function isInstalled(version) { var isVersionSupported = false, control = null, actualVer, actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0; try { try { control = new ActiveXObject('AgControl.AgControl'); if (control.IsVersionSupported(version)) { isVersionSupported = true; } control = null; } catch (e) { var plugin = navigator.plugins["Silverlight Plug-In"]; if (plugin) { actualVer = plugin.description; if (actualVer === "1.0.30226.2") { actualVer = "2.0.30226.2"; } actualVerArray = actualVer.split("."); while (actualVerArray.length > 3) { actualVerArray.pop(); } while ( actualVerArray.length < 4) { actualVerArray.push(0); } reqVerArray = version.split("."); while (reqVerArray.length > 4) { reqVerArray.pop(); } do { requiredVersionPart = parseInt(reqVerArray[index], 10); actualVersionPart = parseInt(actualVerArray[index], 10); index++; } while (index < reqVerArray.length && requiredVersionPart === actualVersionPart); if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) { isVersionSupported = true; } } } } catch (e2) { isVersionSupported = false; } return isVersionSupported; } /** Constructor for the Silverlight Runtime @class SilverlightRuntime @extends Runtime */ function SilverlightRuntime(options) { var I = this, initTimer; options = Basic.extend({ xap_url: Env.xap_url }, options); Runtime.call(this, options, type, { access_binary: Runtime.capTrue, access_image_binary: Runtime.capTrue, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: Runtime.capTrue, resize_image: Runtime.capTrue, return_response_headers: function(value) { return value && I.mode === 'client'; }, return_response_type: function(responseType) { if (responseType !== 'json') { return true; } else { return !!window.JSON; } }, return_status_code: function(code) { return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: Runtime.capTrue, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'client'; }, send_multipart: Runtime.capTrue, slice_blob: Runtime.capTrue, stream_upload: true, summon_file_dialog: false, upload_filesize: Runtime.capTrue, use_http_method: function(methods) { return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode return_response_headers: function(value) { return value ? 'client' : 'browser'; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser']; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'client' : 'browser'; }, use_http_method: function(methods) { return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser']; } }); // minimal requirement if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') { this.mode = false; } Basic.extend(this, { getShim: function() { return Dom.get(this.uid).content.Moxie; }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init : function() { var container; container = this.getShimContainer(); container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' + '<param name="source" value="' + options.xap_url + '"/>' + '<param name="background" value="Transparent"/>' + '<param name="windowless" value="true"/>' + '<param name="enablehtmlaccess" value="true"/>' + '<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' + '</object>'; // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac) }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, SilverlightRuntime); return extensions; }); // Included from: src/javascript/runtime/silverlight/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/Blob @private */ define("moxie/runtime/silverlight/file/Blob", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/Blob" ], function(extensions, Basic, Blob) { return (extensions.Blob = Basic.extend({}, Blob)); }); // Included from: src/javascript/runtime/silverlight/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileInput @private */ define("moxie/runtime/silverlight/file/FileInput", [ "moxie/runtime/silverlight/Runtime" ], function(extensions) { var FileInput = { init: function(options) { function toFilters(accept) { var filter = ''; for (var i = 0; i < accept.length; i++) { filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.'); } return filter; } this.getRuntime().shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.name, options.multiple); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/silverlight/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileDrop @private */ define("moxie/runtime/silverlight/file/FileDrop", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Dom", "moxie/core/utils/Events" ], function(extensions, Dom, Events) { // not exactly useful, since works only in safari (...crickets...) var FileDrop = { init: function() { var comp = this, self = comp.getRuntime(), dropZone; dropZone = self.getShimContainer(); Events.addEvent(dropZone, 'dragover', function(e) { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy'; }, comp.uid); Events.addEvent(dropZone, 'dragenter', function(e) { e.preventDefault(); var flag = Dom.get(self.uid).dragEnter(e); // If handled, then stop propagation of event in DOM if (flag) { e.stopPropagation(); } }, comp.uid); Events.addEvent(dropZone, 'drop', function(e) { e.preventDefault(); var flag = Dom.get(self.uid).dragDrop(e); // If handled, then stop propagation of event in DOM if (flag) { e.stopPropagation(); } }, comp.uid); return self.shimExec.call(this, 'FileDrop', 'init'); } }; return (extensions.FileDrop = FileDrop); }); // Included from: src/javascript/runtime/silverlight/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReader @private */ define("moxie/runtime/silverlight/file/FileReader", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReader" ], function(extensions, Basic, FileReader) { return (extensions.FileReader = Basic.extend({}, FileReader)); }); // Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReaderSync @private */ define("moxie/runtime/silverlight/file/FileReaderSync", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReaderSync" ], function(extensions, Basic, FileReaderSync) { return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync)); }); // Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/xhr/XMLHttpRequest @private */ define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/xhr/XMLHttpRequest" ], function(extensions, Basic, XMLHttpRequest) { return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest)); }); // Included from: src/javascript/runtime/silverlight/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/runtime/Transporter @private */ define("moxie/runtime/silverlight/runtime/Transporter", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/runtime/Transporter" ], function(extensions, Basic, Transporter) { return (extensions.Transporter = Basic.extend({}, Transporter)); }); // Included from: src/javascript/runtime/silverlight/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/image/Image @private */ define("moxie/runtime/silverlight/image/Image", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/image/Image" ], function(extensions, Basic, Image) { return (extensions.Image = Basic.extend({}, Image, { getInfo: function() { var self = this.getRuntime() , grps = ['tiff', 'exif', 'gps'] , info = { meta: {} } , rawInfo = self.shimExec.call(this, 'Image', 'getInfo') ; if (rawInfo.meta) { Basic.each(grps, function(grp) { var meta = rawInfo.meta[grp] , tag , i , length , value ; if (meta && meta.keys) { info.meta[grp] = {}; for (i = 0, length = meta.keys.length; i < length; i++) { tag = meta.keys[i]; value = meta[tag]; if (value) { // convert numbers if (/^(\d|[1-9]\d+)$/.test(value)) { // integer (make sure doesn't start with zero) value = parseInt(value, 10); } else if (/^\d*\.\d+$/.test(value)) { // double value = parseFloat(value); } info.meta[grp][tag] = value; } } } }); } info.width = parseInt(rawInfo.width, 10); info.height = parseInt(rawInfo.height, 10); info.size = parseInt(rawInfo.size, 10); info.type = rawInfo.type; info.name = rawInfo.name; return info; } })); }); // Included from: src/javascript/runtime/html4/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML4 runtime. @class moxie/runtime/html4/Runtime @private */ define("moxie/runtime/html4/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = 'html4', extensions = {}; function Html4Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; Runtime.call(this, options, type, { access_binary: Test(window.FileReader || window.File && File.getAsDataURL), access_image_binary: false, display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))), do_cors: false, drag_and_drop: false, filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), resize_image: function() { return extensions.Image && I.can('access_binary') && Env.can('create_canvas'); }, report_upload_progress: false, return_response_headers: false, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { return true; } return !!~Basic.inArray(responseType, ['text', 'document', '']); }, return_status_code: function(code) { return !Basic.arrayDiff(code, [200, 404]); }, select_file: function() { return Env.can('use_fileinput'); }, select_multiple: false, send_binary_string: false, send_custom_headers: false, send_multipart: true, slice_blob: false, stream_upload: function() { return I.can('select_file'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html4Runtime); return extensions; }); // Included from: src/javascript/runtime/html4/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileInput @private */ define("moxie/runtime/html4/file/FileInput", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _uid, _files = [], _mimes = [], _options; function addInput() { var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid; uid = Basic.guid('uid_'); shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE if (_uid) { // move previous form out of the view currForm = Dom.get(_uid + '_form'); if (currForm) { Basic.extend(currForm.style, { top: '100%' }); } } // build form in DOM, since innerHTML version not able to submit file for some reason form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', 'post'); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); Basic.extend(form.style, { overflow: 'hidden', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); input = document.createElement('input'); input.setAttribute('id', uid); input.setAttribute('type', 'file'); input.setAttribute('name', _options.name || 'Filedata'); input.setAttribute('accept', _mimes.join(',')); Basic.extend(input.style, { fontSize: '999px', opacity: 0 }); form.appendChild(input); shimContainer.appendChild(form); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); if (Env.browser === 'IE' && Env.version < 10) { Basic.extend(input.style, { filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)" }); } input.onchange = function() { // there should be only one handler for this var file; if (!this.value) { return; } if (this.files) { file = this.files[0]; } else { file = { name: this.value }; } _files = [file]; this.onchange = function() {}; // clear event handler addInput.call(comp); // after file is initialized as o.File, we need to update form and input ids comp.bind('change', function onChange() { var input = Dom.get(uid), form = Dom.get(uid + '_form'), file; comp.unbind('change', onChange); if (comp.files.length && input && form) { file = comp.files[0]; input.setAttribute('id', file.uid); form.setAttribute('id', file.uid + '_form'); // set upload target form.setAttribute('target', file.uid + '_iframe'); } input = form = null; }, 998); input = form = null; comp.trigger('change'); }; // route click event to the input if (I.can('summon_file_dialog')) { browseButton = Dom.get(_options.browse_button); Events.removeEvent(browseButton, 'click', comp.uid); Events.addEvent(browseButton, 'click', function(e) { if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } _uid = uid; shimContainer = currForm = browseButton = null; } Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), shimContainer; // figure out accept string _options = options; _mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); (function() { var browseButton, zIndex, top; browseButton = Dom.get(options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); browseButton = null; }()); addInput.call(this); shimContainer = null; // trigger ready event asynchronously comp.trigger({ type: 'ready', async: true }); }, getFiles: function() { return _files; }, disable: function(state) { var input; if ((input = Dom.get(_uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime() , shim = I.getShim() , shimContainer = I.getShimContainer() ; Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } shim.removeInstance(this.uid); _uid = _files = _mimes = _options = shimContainer = shim = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html4/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileReader @private */ define("moxie/runtime/html4/file/FileReader", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/file/FileReader" ], function(extensions, FileReader) { return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/xhr/XMLHttpRequest @private */ define("moxie/runtime/html4/xhr/XMLHttpRequest", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Url", "moxie/core/Exceptions", "moxie/core/utils/Events", "moxie/file/Blob", "moxie/xhr/FormData" ], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) { function XMLHttpRequest() { var _status, _response, _iframe; function cleanup(cb) { var target = this, uid, form, inputs, i, hasFile = false; if (!_iframe) { return; } uid = _iframe.id.replace(/_iframe$/, ''); form = Dom.get(uid + '_form'); if (form) { inputs = form.getElementsByTagName('input'); i = inputs.length; while (i--) { switch (inputs[i].getAttribute('type')) { case 'hidden': inputs[i].parentNode.removeChild(inputs[i]); break; case 'file': hasFile = true; // flag the case for later break; } } inputs = []; if (!hasFile) { // we need to keep the form for sake of possible retries form.parentNode.removeChild(form); } form = null; } // without timeout, request is marked as canceled (in console) setTimeout(function() { Events.removeEvent(_iframe, 'load', target.uid); if (_iframe.parentNode) { // #382 _iframe.parentNode.removeChild(_iframe); } // check if shim container has any other children, if - not, remove it as well var shimContainer = target.getRuntime().getShimContainer(); if (!shimContainer.children.length) { shimContainer.parentNode.removeChild(shimContainer); } shimContainer = _iframe = null; cb(); }, 1); } Basic.extend(this, { send: function(meta, data) { var target = this, I = target.getRuntime(), uid, form, input, blob; _status = _response = null; function createIframe() { var container = I.getShimContainer() || document.body , temp = document.createElement('div') ; // IE 6 won't be able to set the name using setAttribute or iframe.name temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>'; _iframe = temp.firstChild; container.appendChild(_iframe); /* _iframe.onreadystatechange = function() { console.info(_iframe.readyState); };*/ Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8 var el; try { el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document; // try to detect some standard error pages if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error _status = el.title.replace(/^(\d+).*$/, '$1'); } else { _status = 200; // get result _response = Basic.trim(el.body.innerHTML); // we need to fire these at least once target.trigger({ type: 'progress', loaded: _response.length, total: _response.length }); if (blob) { // if we were uploading a file target.trigger({ type: 'uploadprogress', loaded: blob.size || 1025, total: blob.size || 1025 }); } } } catch (ex) { if (Url.hasSameOrigin(meta.url)) { // if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm // which obviously results to cross domain error (wtf?) _status = 404; } else { cleanup.call(target, function() { target.trigger('error'); }); return; } } cleanup.call(target, function() { target.trigger('load'); }); }, target.uid); } // end createIframe // prepare data to be sent and convert if required if (data instanceof FormData && data.hasBlob()) { blob = data.getBlob(); uid = blob.uid; input = Dom.get(uid); form = Dom.get(uid + '_form'); if (!form) { throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } } else { uid = Basic.guid('uid_'); form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', meta.method); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); form.setAttribute('target', uid + '_iframe'); I.getShimContainer().appendChild(form); } if (data instanceof FormData) { data.each(function(value, name) { if (value instanceof Blob) { if (input) { input.setAttribute('name', name); } } else { var hidden = document.createElement('input'); Basic.extend(hidden, { type : 'hidden', name : name, value : value }); // make sure that input[type="file"], if it's there, comes last if (input) { form.insertBefore(hidden, input); } else { form.appendChild(hidden); } } }); } // set destination url form.setAttribute("action", meta.url); createIframe(); form.submit(); target.trigger('loadstart'); }, getStatus: function() { return _status; }, getResponse: function(responseType) { if ('json' === responseType) { // strip off <pre>..</pre> tags that might be enclosing the response if (Basic.typeOf(_response) === 'string' && !!window.JSON) { try { return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, '')); } catch (ex) { return null; } } } else if ('document' === responseType) { } return _response; }, abort: function() { var target = this; if (_iframe && _iframe.contentWindow) { if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome _iframe.contentWindow.stop(); } else if (_iframe.contentWindow.document.execCommand) { // IE _iframe.contentWindow.document.execCommand('Stop'); } else { _iframe.src = "about:blank"; } } cleanup.call(this, function() { // target.dispatchEvent('readystatechange'); target.dispatchEvent('abort'); }); } }); } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html4/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/image/Image @private */ define("moxie/runtime/html4/image/Image", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/image/Image" ], function(extensions, Image) { return (extensions.Image = Image); }); expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/file/FileDrop","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/image/Image","moxie/core/utils/Events"]); })(this);/** * o.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global moxie:true */ /** Globally exposed namespace with the most frequently used public classes and handy methods. @class o @static @private */ (function() { "use strict"; var o = {}, inArray = moxie.core.utils.Basic.inArray; // directly add some public classes // (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included) (function addAlias(ns) { var name, itemType; for (name in ns) { itemType = typeof(ns[name]); if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) { addAlias(ns[name]); } else if (itemType === 'function') { o[name] = ns[name]; } } })(window.moxie); // add some manually o.Env = window.moxie.core.utils.Env; o.Mime = window.moxie.core.utils.Mime; o.Exceptions = window.moxie.core.Exceptions; // expose globally window.mOxie = o; if (!window.o) { window.o = o; } return o; })();
JavaScript
/** * Plupload - multi-runtime File Uploader * v2.1.0 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2013-12-27 */ /** * Plupload.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global mOxie:true */ ;(function(window, o, undef) { var delay = window.setTimeout , fileFilters = {} ; // convert plupload features to caps acceptable by mOxie function normalizeCaps(settings) { var features = settings.required_features, caps = {}; function resolve(feature, value, strict) { // Feature notation is deprecated, use caps (this thing here is required for backward compatibility) var map = { chunks: 'slice_blob', jpgresize: 'send_binary_string', pngresize: 'send_binary_string', progress: 'report_upload_progress', multi_selection: 'select_multiple', max_file_size: 'access_binary', dragdrop: 'drag_and_drop', drop_element: 'drag_and_drop', headers: 'send_custom_headers', canSendBinary: 'send_binary', triggerDialog: 'summon_file_dialog' }; if (map[feature]) { caps[map[feature]] = value; } else if (!strict) { caps[feature] = value; } } if (typeof(features) === 'string') { plupload.each(features.split(/\s*,\s*/), function(feature) { resolve(feature, true); }); } else if (typeof(features) === 'object') { plupload.each(features, function(value, feature) { resolve(feature, value); }); } else if (features === true) { // check settings for required features if (!settings.multipart) { // special care for multipart: false caps.send_binary_string = true; } if (settings.chunk_size > 0) { caps.slice_blob = true; } if (settings.resize.enabled) { caps.send_binary_string = true; } plupload.each(settings, function(value, feature) { resolve(feature, !!value, true); // strict check }); } return caps; } /** * @module plupload * @static */ var plupload = { /** * Plupload version will be replaced on build. * * @property VERSION * @for Plupload * @static * @final */ VERSION : '2.1.0', /** * Inital state of the queue and also the state ones it's finished all it's uploads. * * @property STOPPED * @static * @final */ STOPPED : 1, /** * Upload process is running * * @property STARTED * @static * @final */ STARTED : 2, /** * File is queued for upload * * @property QUEUED * @static * @final */ QUEUED : 1, /** * File is being uploaded * * @property UPLOADING * @static * @final */ UPLOADING : 2, /** * File has failed to be uploaded * * @property FAILED * @static * @final */ FAILED : 4, /** * File has been uploaded successfully * * @property DONE * @static * @final */ DONE : 5, // Error constants used by the Error event /** * Generic error for example if an exception is thrown inside Silverlight. * * @property GENERIC_ERROR * @static * @final */ GENERIC_ERROR : -100, /** * HTTP transport error. For example if the server produces a HTTP status other than 200. * * @property HTTP_ERROR * @static * @final */ HTTP_ERROR : -200, /** * Generic I/O error. For exampe if it wasn't possible to open the file stream on local machine. * * @property IO_ERROR * @static * @final */ IO_ERROR : -300, /** * Generic I/O error. For exampe if it wasn't possible to open the file stream on local machine. * * @property SECURITY_ERROR * @static * @final */ SECURITY_ERROR : -400, /** * Initialization error. Will be triggered if no runtime was initialized. * * @property INIT_ERROR * @static * @final */ INIT_ERROR : -500, /** * File size error. If the user selects a file that is too large it will be blocked and an error of this type will be triggered. * * @property FILE_SIZE_ERROR * @static * @final */ FILE_SIZE_ERROR : -600, /** * File extension error. If the user selects a file that isn't valid according to the filters setting. * * @property FILE_EXTENSION_ERROR * @static * @final */ FILE_EXTENSION_ERROR : -601, /** * Duplicate file error. If prevent_duplicates is set to true and user selects the same file again. * * @property FILE_DUPLICATE_ERROR * @static * @final */ FILE_DUPLICATE_ERROR : -602, /** * Runtime will try to detect if image is proper one. Otherwise will throw this error. * * @property IMAGE_FORMAT_ERROR * @static * @final */ IMAGE_FORMAT_ERROR : -700, /** * While working on the image runtime will try to detect if the operation may potentially run out of memeory and will throw this error. * * @property IMAGE_MEMORY_ERROR * @static * @final */ IMAGE_MEMORY_ERROR : -701, /** * Each runtime has an upper limit on a dimension of the image it can handle. If bigger, will throw this error. * * @property IMAGE_DIMENSIONS_ERROR * @static * @final */ IMAGE_DIMENSIONS_ERROR : -702, /** * Mime type lookup table. * * @property mimeTypes * @type Object * @final */ mimeTypes : o.mimes, /** * In some cases sniffing is the only way around :( */ ua: o.ua, /** * Gets the true type of the built-in object (better version of typeof). * @credits Angus Croll (http://javascriptweblog.wordpress.com/) * * @method typeOf * @static * @param {Object} o Object to check. * @return {String} Object [[Class]] */ typeOf: o.typeOf, /** * Extends the specified object with another object. * * @method extend * @static * @param {Object} target Object to extend. * @param {Object..} obj Multiple objects to extend with. * @return {Object} Same as target, the extended object. */ extend : o.extend, /** * Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers. * The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages * to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique. * It's more probable for the earth to be hit with an ansteriod. You can also if you want to be 100% sure set the plupload.guidPrefix property * to an user unique key. * * @method guid * @static * @return {String} Virtually unique id. */ guid : o.guid, /** * Get array of DOM Elements by their ids. * * @method get * @for Utils * @param {String} id Identifier of the DOM Element * @return {Array} */ get : function get(ids) { var els = [], el; if (o.typeOf(ids) !== 'array') { ids = [ids]; } var i = ids.length; while (i--) { el = o.get(ids[i]); if (el) { els.push(el); } } return els.length ? els : null; }, /** * Executes the callback function for each item in array/object. If you return false in the * callback it will break the loop. * * @method each * @static * @param {Object} obj Object to iterate. * @param {function} callback Callback function to execute for each item. */ each : o.each, /** * Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields. * * @method getPos * @static * @param {Element} node HTML element or element id to get x, y position from. * @param {Element} root Optional root element to stop calculations at. * @return {object} Absolute position of the specified element object with x, y fields. */ getPos : o.getPos, /** * Returns the size of the specified node in pixels. * * @method getSize * @static * @param {Node} node Node to get the size of. * @return {Object} Object with a w and h property. */ getSize : o.getSize, /** * Encodes the specified string. * * @method xmlEncode * @static * @param {String} s String to encode. * @return {String} Encoded string. */ xmlEncode : function(str) { var xmlEncodeChars = {'<' : 'lt', '>' : 'gt', '&' : 'amp', '"' : 'quot', '\'' : '#39'}, xmlEncodeRegExp = /[<>&\"\']/g; return str ? ('' + str).replace(xmlEncodeRegExp, function(chr) { return xmlEncodeChars[chr] ? '&' + xmlEncodeChars[chr] + ';' : chr; }) : str; }, /** * Forces anything into an array. * * @method toArray * @static * @param {Object} obj Object with length field. * @return {Array} Array object containing all items. */ toArray : o.toArray, /** * Find an element in array and return it's index if present, otherwise return -1. * * @method inArray * @static * @param {mixed} needle Element to find * @param {Array} array * @return {Int} Index of the element, or -1 if not found */ inArray : o.inArray, /** * Extends the language pack object with new items. * * @method addI18n * @static * @param {Object} pack Language pack items to add. * @return {Object} Extended language pack object. */ addI18n : o.addI18n, /** * Translates the specified string by checking for the english string in the language pack lookup. * * @method translate * @static * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ translate : o.translate, /** * Checks if object is empty. * * @method isEmptyObj * @static * @param {Object} obj Object to check. * @return {Boolean} */ isEmptyObj : o.isEmptyObj, /** * Checks if specified DOM element has specified class. * * @method hasClass * @static * @param {Object} obj DOM element like object to add handler to. * @param {String} name Class name */ hasClass : o.hasClass, /** * Adds specified className to specified DOM element. * * @method addClass * @static * @param {Object} obj DOM element like object to add handler to. * @param {String} name Class name */ addClass : o.addClass, /** * Removes specified className from specified DOM element. * * @method removeClass * @static * @param {Object} obj DOM element like object to add handler to. * @param {String} name Class name */ removeClass : o.removeClass, /** * Returns a given computed style of a DOM element. * * @method getStyle * @static * @param {Object} obj DOM element like object. * @param {String} name Style you want to get from the DOM element */ getStyle : o.getStyle, /** * Adds an event handler to the specified object and store reference to the handler * in objects internal Plupload registry (@see removeEvent). * * @method addEvent * @static * @param {Object} obj DOM element like object to add handler to. * @param {String} name Name to add event listener to. * @param {Function} callback Function to call when event occurs. * @param {String} (optional) key that might be used to add specifity to the event record. */ addEvent : o.addEvent, /** * Remove event handler from the specified object. If third argument (callback) * is not specified remove all events with the specified name. * * @method removeEvent * @static * @param {Object} obj DOM element to remove event listener(s) from. * @param {String} name Name of event listener to remove. * @param {Function|String} (optional) might be a callback or unique key to match. */ removeEvent: o.removeEvent, /** * Remove all kind of events from the specified object * * @method removeAllEvents * @static * @param {Object} obj DOM element to remove event listeners from. * @param {String} (optional) unique key to match, when removing events. */ removeAllEvents: o.removeAllEvents, /** * Cleans the specified name from national characters (diacritics). The result will be a name with only a-z, 0-9 and _. * * @method cleanName * @static * @param {String} s String to clean up. * @return {String} Cleaned string. */ cleanName : function(name) { var i, lookup; // Replace diacritics lookup = [ /[\300-\306]/g, 'A', /[\340-\346]/g, 'a', /\307/g, 'C', /\347/g, 'c', /[\310-\313]/g, 'E', /[\350-\353]/g, 'e', /[\314-\317]/g, 'I', /[\354-\357]/g, 'i', /\321/g, 'N', /\361/g, 'n', /[\322-\330]/g, 'O', /[\362-\370]/g, 'o', /[\331-\334]/g, 'U', /[\371-\374]/g, 'u' ]; for (i = 0; i < lookup.length; i += 2) { name = name.replace(lookup[i], lookup[i + 1]); } // Replace whitespace name = name.replace(/\s+/g, '_'); // Remove anything else name = name.replace(/[^a-z0-9_\-\.]+/gi, ''); return name; }, /** * Builds a full url out of a base URL and an object with items to append as query string items. * * @method buildUrl * @static * @param {String} url Base URL to append query string items to. * @param {Object} items Name/value object to serialize as a querystring. * @return {String} String with url + serialized query string items. */ buildUrl : function(url, items) { var query = ''; plupload.each(items, function(value, name) { query += (query ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(value); }); if (query) { url += (url.indexOf('?') > 0 ? '&' : '?') + query; } return url; }, /** * Formats the specified number as a size string for example 1024 becomes 1 KB. * * @method formatSize * @static * @param {Number} size Size to format as string. * @return {String} Formatted size string. */ formatSize : function(size) { if (size === undef || /\D/.test(size)) { return plupload.translate('N/A'); } function round(num, precision) { return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision); } var boundary = Math.pow(1024, 4); // TB if (size > boundary) { return round(size / boundary, 1) + " " + plupload.translate('tb'); } // GB if (size > (boundary/=1024)) { return round(size / boundary, 1) + " " + plupload.translate('gb'); } // MB if (size > (boundary/=1024)) { return round(size / boundary, 1) + " " + plupload.translate('mb'); } // KB if (size > 1024) { return Math.round(size / 1024) + " " + plupload.translate('kb'); } return size + " " + plupload.translate('b'); }, /** * Parses the specified size string into a byte value. For example 10kb becomes 10240. * * @method parseSize * @static * @param {String|Number} size String to parse or number to just pass through. * @return {Number} Size in bytes. */ parseSize : o.parseSizeStr, /** * A way to predict what runtime will be choosen in the current environment with the * specified settings. * * @method predictRuntime * @static * @param {Object|String} config Plupload settings to check * @param {String} [runtimes] Comma-separated list of runtimes to check against * @return {String} Type of compatible runtime */ predictRuntime : function(config, runtimes) { var up, runtime; up = new plupload.Uploader(config); runtime = o.Runtime.thatCan(up.getOption().required_features, runtimes || config.runtimes); up.destroy(); return runtime; }, /** * Registers a filter that will be executed for each file added to the queue. * If callback returns false, file will not be added. * * Callback receives two arguments: a value for the filter as it was specified in settings.filters * and a file to be filtered. Callback is executed in the context of uploader instance. * * @method addFileFilter * @static * @param {String} name Name of the filter by which it can be referenced in settings.filters * @param {String} cb Callback - the actual routine that every added file must pass */ addFileFilter: function(name, cb) { fileFilters[name] = cb; } }; plupload.addFileFilter('mime_types', function(filters, file, cb) { if (filters.length && !filters.regexp.test(file.name)) { this.trigger('Error', { code : plupload.FILE_EXTENSION_ERROR, message : plupload.translate('File extension error.'), file : file }); cb(false); } else { cb(true); } }); plupload.addFileFilter('max_file_size', function(maxSize, file, cb) { var undef; maxSize = plupload.parseSize(maxSize); // Invalid file size if (file.size !== undef && maxSize && file.size > maxSize) { this.trigger('Error', { code : plupload.FILE_SIZE_ERROR, message : plupload.translate('File size error.'), file : file }); cb(false); } else { cb(true); } }); plupload.addFileFilter('prevent_duplicates', function(value, file, cb) { if (value) { var ii = this.files.length; while (ii--) { // Compare by name and size (size might be 0 or undefined, but still equivalent for both) if (file.name === this.files[ii].name && file.size === this.files[ii].size) { this.trigger('Error', { code : plupload.FILE_DUPLICATE_ERROR, message : plupload.translate('Duplicate file error.'), file : file }); cb(false); return; } } } cb(true); }); /** @class Uploader @constructor @param {Object} settings For detailed information about each option check documentation. @param {String|DOMElement} settings.browse_button id of the DOM element or DOM element itself to use as file dialog trigger. @param {String} settings.url URL of the server-side upload handler. @param {Number|String} [settings.chunk_size=0] Chunk size in bytes to slice the file into. Shorcuts with b, kb, mb, gb, tb suffixes also supported. `e.g. 204800 or "204800b" or "200kb"`. By default - disabled. @param {String} [settings.container] id of the DOM element to use as a container for uploader structures. Defaults to document.body. @param {String|DOMElement} [settings.drop_element] id of the DOM element or DOM element itself to use as a drop zone for Drag-n-Drop. @param {String} [settings.file_data_name="file"] Name for the file field in Multipart formated message. @param {Object} [settings.filters={}] Set of file type filters. @param {Array} [settings.filters.mime_types=[]] List of file types to accept, each one defined by title and list of extensions. `e.g. {title : "Image files", extensions : "jpg,jpeg,gif,png"}`. Dispatches `plupload.FILE_EXTENSION_ERROR` @param {String|Number} [settings.filters.max_file_size=0] Maximum file size that the user can pick, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. `e.g. "10mb" or "1gb"`. By default - not set. Dispatches `plupload.FILE_SIZE_ERROR`. @param {Boolean} [settings.filters.prevent_duplicates=false] Do not let duplicates into the queue. Dispatches `plupload.FILE_DUPLICATE_ERROR`. @param {String} [settings.flash_swf_url] URL of the Flash swf. @param {Object} [settings.headers] Custom headers to send with the upload. Hash of name/value pairs. @param {Number} [settings.max_retries=0] How many times to retry the chunk or file, before triggering Error event. @param {Boolean} [settings.multipart=true] Whether to send file and additional parameters as Multipart formated message. @param {Object} [settings.multipart_params] Hash of key/value pairs to send with every file upload. @param {Boolean} [settings.multi_selection=true] Enable ability to select multiple files at once in file dialog. @param {String|Object} [settings.required_features] Either comma-separated list or hash of required features that chosen runtime should absolutely possess. @param {Object} [settings.resize] Enable resizng of images on client-side. Applies to `image/jpeg` and `image/png` only. `e.g. {width : 200, height : 200, quality : 90, crop: true}` @param {Number} [settings.resize.width] If image is bigger, it will be resized. @param {Number} [settings.resize.height] If image is bigger, it will be resized. @param {Number} [settings.resize.quality=90] Compression quality for jpegs (1-100). @param {Boolean} [settings.resize.crop=false] Whether to crop images to exact dimensions. By default they will be resized proportionally. @param {String} [settings.runtimes="html5,flash,silverlight,html4"] Comma separated list of runtimes, that Plupload will try in turn, moving to the next if previous fails. @param {String} [settings.silverlight_xap_url] URL of the Silverlight xap. @param {Boolean} [settings.unique_names=false] If true will generate unique filenames for uploaded files. */ plupload.Uploader = function(options) { /** * Fires when the current RunTime has been initialized. * * @event Init * @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** * Fires after the init event incase you need to perform actions there. * * @event PostInit * @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** * Fires when the option is changed in via uploader.setOption(). * * @event OptionChanged * @since 2.1 * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {String} name Name of the option that was changed * @param {Mixed} value New value for the specified option * @param {Mixed} oldValue Previous value of the option */ /** * Fires when the silverlight/flash or other shim needs to move. * * @event Refresh * @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** * Fires when the overall state is being changed for the upload queue. * * @event StateChanged * @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** * Fires when a file is to be uploaded by the runtime. * * @event UploadFile * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {plupload.File} file File to be uploaded. */ /** * Fires when just before a file is uploaded. This event enables you to override settings * on the uploader instance before the file is uploaded. * * @event BeforeUpload * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {plupload.File} file File to be uploaded. */ /** * Fires when the file queue is changed. In other words when files are added/removed to the files array of the uploader instance. * * @event QueueChanged * @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** * Fires while a file is being uploaded. Use this event to update the current file upload progress. * * @event UploadProgress * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {plupload.File} file File that is currently being uploaded. */ /** * Fires when file is removed from the queue. * * @event FilesRemoved * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {Array} files Array of files that got removed. */ /** * Fires for every filtered file before it is added to the queue. * * @event FileFiltered * @since 2.1 * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {plupload.File} file Another file that has to be added to the queue. */ /** * Fires after files were filtered and added to the queue. * * @event FilesAdded * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {Array} files Array of file objects that were added to queue by the user. */ /** * Fires when a file is successfully uploaded. * * @event FileUploaded * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {plupload.File} file File that was uploaded. * @param {Object} response Object with response properties. */ /** * Fires when file chunk is uploaded. * * @event ChunkUploaded * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {plupload.File} file File that the chunk was uploaded for. * @param {Object} response Object with response properties. */ /** * Fires when all files in a queue are uploaded. * * @event UploadComplete * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {Array} files Array of file objects that was added to queue/selected by the user. */ /** * Fires when a error occurs. * * @event Error * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {Object} error Contains code, message and sometimes file and other details. */ /** * Fires when destroy method is called. * * @event Destroy * @param {plupload.Uploader} uploader Uploader instance sending the event. */ var uid = plupload.guid() , settings , files = [] , preferred_caps = {} , fileInputs = [] , fileDrops = [] , startTime , total , disabled = false , xhr ; // Private methods function uploadNext() { var file, count = 0, i; if (this.state == plupload.STARTED) { // Find first QUEUED file for (i = 0; i < files.length; i++) { if (!file && files[i].status == plupload.QUEUED) { file = files[i]; if (this.trigger("BeforeUpload", file)) { file.status = plupload.UPLOADING; this.trigger("UploadFile", file); } } else { count++; } } // All files are DONE or FAILED if (count == files.length) { if (this.state !== plupload.STOPPED) { this.state = plupload.STOPPED; this.trigger("StateChanged"); } this.trigger("UploadComplete", files); } } } function calcFile(file) { file.percent = file.size > 0 ? Math.ceil(file.loaded / file.size * 100) : 100; calc(); } function calc() { var i, file; // Reset stats total.reset(); // Check status, size, loaded etc on all files for (i = 0; i < files.length; i++) { file = files[i]; if (file.size !== undef) { // We calculate totals based on original file size total.size += file.origSize; // Since we cannot predict file size after resize, we do opposite and // interpolate loaded amount to match magnitude of total total.loaded += file.loaded * file.origSize / file.size; } else { total.size = undef; } if (file.status == plupload.DONE) { total.uploaded++; } else if (file.status == plupload.FAILED) { total.failed++; } else { total.queued++; } } // If we couldn't calculate a total file size then use the number of files to calc percent if (total.size === undef) { total.percent = files.length > 0 ? Math.ceil(total.uploaded / files.length * 100) : 0; } else { total.bytesPerSec = Math.ceil(total.loaded / ((+new Date() - startTime || 1) / 1000.0)); total.percent = total.size > 0 ? Math.ceil(total.loaded / total.size * 100) : 0; } } function getRUID() { var ctrl = fileInputs[0] || fileDrops[0]; if (ctrl) { return ctrl.getRuntime().uid; } return false; } function runtimeCan(file, cap) { if (file.ruid) { var info = o.Runtime.getInfo(file.ruid); if (info) { return info.can(cap); } } return false; } function bindEventListeners() { this.bind('FilesAdded', onFilesAdded); this.bind('CancelUpload', onCancelUpload); this.bind('BeforeUpload', onBeforeUpload); this.bind('UploadFile', onUploadFile); this.bind('UploadProgress', onUploadProgress); this.bind('StateChanged', onStateChanged); this.bind('QueueChanged', calc); this.bind('Error', onError); this.bind('FileUploaded', onFileUploaded); this.bind('Destroy', onDestroy); } function initControls(settings, cb) { var self = this, inited = 0, queue = []; // common settings var options = { accept: settings.filters.mime_types, runtime_order: settings.runtimes, required_caps: settings.required_features, preferred_caps: preferred_caps, swf_url: settings.flash_swf_url, xap_url: settings.silverlight_xap_url }; // add runtime specific options if any plupload.each(settings.runtimes.split(/\s*,\s*/), function(runtime) { if (settings[runtime]) { options[runtime] = settings[runtime]; } }); // initialize file pickers - there can be many if (settings.browse_button) { plupload.each(settings.browse_button, function(el) { queue.push(function(cb) { var fileInput = new o.FileInput(plupload.extend({}, options, { name: settings.file_data_name, multiple: settings.multi_selection, container: settings.container, browse_button: el })); fileInput.onready = function() { var info = o.Runtime.getInfo(this.ruid); // for backward compatibility o.extend(self.features, { chunks: info.can('slice_blob'), multipart: info.can('send_multipart'), multi_selection: info.can('select_multiple') }); inited++; fileInputs.push(this); cb(); }; fileInput.onchange = function() { self.addFile(this.files); }; fileInput.bind('mouseenter mouseleave mousedown mouseup', function(e) { if (!disabled) { if (settings.browse_button_hover) { if ('mouseenter' === e.type) { o.addClass(el, settings.browse_button_hover); } else if ('mouseleave' === e.type) { o.removeClass(el, settings.browse_button_hover); } } if (settings.browse_button_active) { if ('mousedown' === e.type) { o.addClass(el, settings.browse_button_active); } else if ('mouseup' === e.type) { o.removeClass(el, settings.browse_button_active); } } } }); fileInput.bind('error runtimeerror', function() { fileInput = null; cb(); }); fileInput.init(); }); }); } // initialize drop zones if (settings.drop_element) { plupload.each(settings.drop_element, function(el) { queue.push(function(cb) { var fileDrop = new o.FileDrop(plupload.extend({}, options, { drop_zone: el })); fileDrop.onready = function() { var info = o.Runtime.getInfo(this.ruid); self.features.dragdrop = info.can('drag_and_drop'); // for backward compatibility inited++; fileDrops.push(this); cb(); }; fileDrop.ondrop = function() { self.addFile(this.files); }; fileDrop.bind('error runtimeerror', function() { fileDrop = null; cb(); }); fileDrop.init(); }); }); } o.inSeries(queue, function() { if (typeof(cb) === 'function') { cb(inited); } }); } function resizeImage(blob, params, cb) { var img = new o.Image(); try { img.onload = function() { img.downsize(params.width, params.height, params.crop, params.preserve_headers); }; img.onresize = function() { cb(this.getAsBlob(blob.type, params.quality)); this.destroy(); }; img.onerror = function() { cb(blob); }; img.load(blob); } catch(ex) { cb(blob); } } function setOption(option, value, init) { var self = this, reinitRequired = false; function _setOption(option, value, init) { var oldValue = settings[option]; switch (option) { case 'max_file_size': if (option === 'max_file_size') { settings.max_file_size = settings.filters.max_file_size = value; } break; case 'chunk_size': if (value = plupload.parseSize(value)) { settings[option] = value; } break; case 'filters': // for sake of backward compatibility if (plupload.typeOf(value) === 'array') { value = { mime_types: value }; } if (init) { plupload.extend(settings.filters, value); } else { settings.filters = value; } // if file format filters are being updated, regenerate the matching expressions if (value.mime_types) { settings.filters.mime_types.regexp = (function(filters) { var extensionsRegExp = []; plupload.each(filters, function(filter) { plupload.each(filter.extensions.split(/,/), function(ext) { if (/^\s*\*\s*$/.test(ext)) { extensionsRegExp.push('\\.*'); } else { extensionsRegExp.push('\\.' + ext.replace(new RegExp('[' + ('/^$.*+?|()[]{}\\'.replace(/./g, '\\$&')) + ']', 'g'), '\\$&')); } }); }); return new RegExp('(' + extensionsRegExp.join('|') + ')$', 'i'); }(settings.filters.mime_types)); } break; case 'resize': if (init) { plupload.extend(settings.resize, value, { enabled: true }); } else { settings.resize = value; } break; case 'prevent_duplicates': settings.prevent_duplicates = settings.filters.prevent_duplicates = !!value; break; case 'browse_button': case 'drop_element': value = plupload.get(value); case 'container': case 'runtimes': case 'multi_selection': case 'flash_swf_url': case 'silverlight_xap_url': settings[option] = value; if (!init) { reinitRequired = true; } break; default: settings[option] = value; } if (!init) { self.trigger('OptionChanged', option, value, oldValue); } } if (typeof(option) === 'object') { plupload.each(option, function(value, option) { _setOption(option, value, init); }); } else { _setOption(option, value, init); } if (init) { // Normalize the list of required capabilities settings.required_features = normalizeCaps(plupload.extend({}, settings)); // Come up with the list of capabilities that can affect default mode in a multi-mode runtimes preferred_caps = normalizeCaps(plupload.extend({}, settings, { required_features: true })); } else if (reinitRequired) { self.trigger('Destroy'); initControls.call(self, settings, function(inited) { if (inited) { self.runtime = o.Runtime.getInfo(getRUID()).type; self.trigger('Init', { runtime: self.runtime }); self.trigger('PostInit'); } else { self.trigger('Error', { code : plupload.INIT_ERROR, message : plupload.translate('Init error.') }); } }); } } // Internal event handlers function onFilesAdded(up, filteredFiles) { // Add files to queue [].push.apply(files, filteredFiles); up.trigger('QueueChanged'); up.refresh(); } function onBeforeUpload(up, file) { // Generate unique target filenames if (settings.unique_names) { var matches = file.name.match(/\.([^.]+)$/), ext = "part"; if (matches) { ext = matches[1]; } file.target_name = file.id + '.' + ext; } } function onUploadFile(up, file) { var url = up.settings.url , chunkSize = up.settings.chunk_size , retries = up.settings.max_retries , features = up.features , offset = 0 , blob ; // make sure we start at a predictable offset if (file.loaded) { offset = file.loaded = chunkSize * Math.floor(file.loaded / chunkSize); } function handleError() { if (retries-- > 0) { delay(uploadNextChunk, 1000); } else { file.loaded = offset; // reset all progress up.trigger('Error', { code : plupload.HTTP_ERROR, message : plupload.translate('HTTP Error.'), file : file, response : xhr.responseText, status : xhr.status, responseHeaders: xhr.getAllResponseHeaders() }); } } function uploadNextChunk() { var chunkBlob, formData, args, curChunkSize; // File upload finished if (file.status == plupload.DONE || file.status == plupload.FAILED || up.state == plupload.STOPPED) { return; } // Standard arguments args = {name : file.target_name || file.name}; if (chunkSize && features.chunks && blob.size > chunkSize) { // blob will be of type string if it was loaded in memory curChunkSize = Math.min(chunkSize, blob.size - offset); chunkBlob = blob.slice(offset, offset + curChunkSize); } else { curChunkSize = blob.size; chunkBlob = blob; } // If chunking is enabled add corresponding args, no matter if file is bigger than chunk or smaller if (chunkSize && features.chunks) { // Setup query string arguments if (up.settings.send_chunk_number) { args.chunk = Math.ceil(offset / chunkSize); args.chunks = Math.ceil(blob.size / chunkSize); } else { // keep support for experimental chunk format, just in case args.offset = offset; args.total = blob.size; } } xhr = new o.XMLHttpRequest(); // Do we have upload progress support if (xhr.upload) { xhr.upload.onprogress = function(e) { file.loaded = Math.min(file.size, offset + e.loaded); up.trigger('UploadProgress', file); }; } xhr.onload = function() { // check if upload made itself through if (xhr.status >= 400) { handleError(); return; } retries = up.settings.max_retries; // reset the counter // Handle chunk response if (curChunkSize < blob.size) { chunkBlob.destroy(); offset += curChunkSize; file.loaded = Math.min(offset, blob.size); up.trigger('ChunkUploaded', file, { offset : file.loaded, total : blob.size, response : xhr.responseText, status : xhr.status, responseHeaders: xhr.getAllResponseHeaders() }); // stock Android browser doesn't fire upload progress events, but in chunking mode we can fake them if (o.Env.browser === 'Android Browser') { // doesn't harm in general, but is not required anywhere else up.trigger('UploadProgress', file); } } else { file.loaded = file.size; } chunkBlob = formData = null; // Free memory // Check if file is uploaded if (!offset || offset >= blob.size) { // If file was modified, destory the copy if (file.size != file.origSize) { blob.destroy(); blob = null; } up.trigger('UploadProgress', file); file.status = plupload.DONE; up.trigger('FileUploaded', file, { response : xhr.responseText, status : xhr.status, responseHeaders: xhr.getAllResponseHeaders() }); } else { // Still chunks left delay(uploadNextChunk, 1); // run detached, otherwise event handlers interfere } }; xhr.onerror = function() { handleError(); }; xhr.onloadend = function() { this.destroy(); xhr = null; }; // Build multipart request if (up.settings.multipart && features.multipart) { args.name = file.target_name || file.name; xhr.open("post", url, true); // Set custom headers plupload.each(up.settings.headers, function(value, name) { xhr.setRequestHeader(name, value); }); formData = new o.FormData(); // Add multipart params plupload.each(plupload.extend(args, up.settings.multipart_params), function(value, name) { formData.append(name, value); }); // Add file and send it formData.append(up.settings.file_data_name, chunkBlob); xhr.send(formData, { runtime_order: up.settings.runtimes, required_caps: up.settings.required_features, preferred_caps: preferred_caps, swf_url: up.settings.flash_swf_url, xap_url: up.settings.silverlight_xap_url }); } else { // if no multipart, send as binary stream url = plupload.buildUrl(up.settings.url, plupload.extend(args, up.settings.multipart_params)); xhr.open("post", url, true); xhr.setRequestHeader('Content-Type', 'application/octet-stream'); // Binary stream header // Set custom headers plupload.each(up.settings.headers, function(value, name) { xhr.setRequestHeader(name, value); }); xhr.send(chunkBlob, { runtime_order: up.settings.runtimes, required_caps: up.settings.required_features, preferred_caps: preferred_caps, swf_url: up.settings.flash_swf_url, xap_url: up.settings.silverlight_xap_url }); } } blob = file.getSource(); // Start uploading chunks if (up.settings.resize.enabled && runtimeCan(blob, 'send_binary_string') && !!~o.inArray(blob.type, ['image/jpeg', 'image/png'])) { // Resize if required resizeImage.call(this, blob, up.settings.resize, function(resizedBlob) { blob = resizedBlob; file.size = resizedBlob.size; uploadNextChunk(); }); } else { uploadNextChunk(); } } function onUploadProgress(up, file) { calcFile(file); } function onStateChanged(up) { if (up.state == plupload.STARTED) { // Get start time to calculate bps startTime = (+new Date()); } else if (up.state == plupload.STOPPED) { // Reset currently uploading files for (var i = up.files.length - 1; i >= 0; i--) { if (up.files[i].status == plupload.UPLOADING) { up.files[i].status = plupload.QUEUED; calc(); } } } } function onCancelUpload() { if (xhr) { xhr.abort(); } } function onFileUploaded(up) { calc(); // Upload next file but detach it from the error event // since other custom listeners might want to stop the queue delay(function() { uploadNext.call(up); }, 1); } function onError(up, err) { // Set failed status if an error occured on a file if (err.file) { err.file.status = plupload.FAILED; calcFile(err.file); // Upload next file but detach it from the error event // since other custom listeners might want to stop the queue if (up.state == plupload.STARTED) { // upload in progress up.trigger('CancelUpload'); delay(function() { uploadNext.call(up); }, 1); } } } function onDestroy(up) { up.stop(); // Purge the queue plupload.each(files, function(file) { file.destroy(); }); files = []; if (fileInputs.length) { plupload.each(fileInputs, function(fileInput) { fileInput.destroy(); }); fileInputs = []; } if (fileDrops.length) { plupload.each(fileDrops, function(fileDrop) { fileDrop.destroy(); }); fileDrops = []; } preferred_caps = {}; disabled = false; settings = startTime = xhr = null; total.reset(); } // Default settings settings = { runtimes: o.Runtime.order, max_retries: 0, chunk_size: 0, multipart: true, multi_selection: true, file_data_name: 'file', flash_swf_url: 'js/Moxie.swf', silverlight_xap_url: 'js/Moxie.xap', filters: { mime_types: [], prevent_duplicates: false, max_file_size: 0 }, resize: { enabled: false, preserve_headers: true, crop: false }, send_chunk_number: true // whether to send chunks and chunk numbers, or total and offset bytes }; setOption.call(this, options, null, true); // Inital total state total = new plupload.QueueProgress(); // Add public methods plupload.extend(this, { /** * Unique id for the Uploader instance. * * @property id * @type String */ id : uid, uid : uid, // mOxie uses this to differentiate between event targets /** * Current state of the total uploading progress. This one can either be plupload.STARTED or plupload.STOPPED. * These states are controlled by the stop/start methods. The default value is STOPPED. * * @property state * @type Number */ state : plupload.STOPPED, /** * Map of features that are available for the uploader runtime. Features will be filled * before the init event is called, these features can then be used to alter the UI for the end user. * Some of the current features that might be in this map is: dragdrop, chunks, jpgresize, pngresize. * * @property features * @type Object */ features : {}, /** * Current runtime name. * * @property runtime * @type String */ runtime : null, /** * Current upload queue, an array of File instances. * * @property files * @type Array * @see plupload.File */ files : files, /** * Object with name/value settings. * * @property settings * @type Object */ settings : settings, /** * Total progess information. How many files has been uploaded, total percent etc. * * @property total * @type plupload.QueueProgress */ total : total, /** * Initializes the Uploader instance and adds internal event listeners. * * @method init */ init : function() { var self = this; if (typeof(settings.preinit) == "function") { settings.preinit(self); } else { plupload.each(settings.preinit, function(func, name) { self.bind(name, func); }); } // Check for required options if (!settings.browse_button || !settings.url) { this.trigger('Error', { code : plupload.INIT_ERROR, message : plupload.translate('Init error.') }); return; } bindEventListeners.call(this); initControls.call(this, settings, function(inited) { if (typeof(settings.init) == "function") { settings.init(self); } else { plupload.each(settings.init, function(func, name) { self.bind(name, func); }); } if (inited) { self.runtime = o.Runtime.getInfo(getRUID()).type; self.trigger('Init', { runtime: self.runtime }); self.trigger('PostInit'); } else { self.trigger('Error', { code : plupload.INIT_ERROR, message : plupload.translate('Init error.') }); } }); }, /** * Set the value for the specified option(s). * * @method setOption * @since 2.1 * @param {String|Object} option Name of the option to change or the set of key/value pairs * @param {Mixed} [value] Value for the option (is ignored, if first argument is object) */ setOption: function(option, value) { setOption.call(this, option, value, !this.runtime); // until runtime not set we do not need to reinitialize }, /** * Get the value for the specified option or the whole configuration, if not specified. * * @method getOption * @since 2.1 * @param {String} [option] Name of the option to get * @return {Mixed} Value for the option or the whole set */ getOption: function(option) { if (!option) { return settings; } return settings[option]; }, /** * Refreshes the upload instance by dispatching out a refresh event to all runtimes. * This would for example reposition flash/silverlight shims on the page. * * @method refresh */ refresh : function() { if (fileInputs.length) { plupload.each(fileInputs, function(fileInput) { fileInput.trigger('Refresh'); }); } this.trigger('Refresh'); }, /** * Starts uploading the queued files. * * @method start */ start : function() { if (this.state != plupload.STARTED) { this.state = plupload.STARTED; this.trigger('StateChanged'); uploadNext.call(this); } }, /** * Stops the upload of the queued files. * * @method stop */ stop : function() { if (this.state != plupload.STOPPED) { this.state = plupload.STOPPED; this.trigger('StateChanged'); this.trigger('CancelUpload'); } }, /** * Disables/enables browse button on request. * * @method disableBrowse * @param {Boolean} disable Whether to disable or enable (default: true) */ disableBrowse : function() { disabled = arguments[0] !== undef ? arguments[0] : true; if (fileInputs.length) { plupload.each(fileInputs, function(fileInput) { fileInput.disable(disabled); }); } this.trigger('DisableBrowse', disabled); }, /** * Returns the specified file object by id. * * @method getFile * @param {String} id File id to look for. * @return {plupload.File} File object or undefined if it wasn't found; */ getFile : function(id) { var i; for (i = files.length - 1; i >= 0; i--) { if (files[i].id === id) { return files[i]; } } }, /** * Adds file to the queue programmatically. Can be native file, instance of Plupload.File, * instance of mOxie.File, input[type="file"] element, or array of these. Fires FilesAdded, * if any files were added to the queue. Otherwise nothing happens. * * @method addFile * @since 2.0 * @param {plupload.File|mOxie.File|File|Node|Array} file File or files to add to the queue. * @param {String} [fileName] If specified, will be used as a name for the file */ addFile : function(file, fileName) { var self = this , queue = [] , files = [] , ruid ; function filterFile(file, cb) { var queue = []; o.each(self.settings.filters, function(rule, name) { if (fileFilters[name]) { queue.push(function(cb) { fileFilters[name].call(self, rule, file, function(res) { cb(!res); }); }); } }); o.inSeries(queue, cb); } /** * @method resolveFile * @private * @param {o.File|o.Blob|plupload.File|File|Blob|input[type="file"]} file */ function resolveFile(file) { var type = o.typeOf(file); // o.File if (file instanceof o.File) { if (!file.ruid && !file.isDetached()) { if (!ruid) { // weird case return false; } file.ruid = ruid; file.connectRuntime(ruid); } resolveFile(new plupload.File(file)); } // o.Blob else if (file instanceof o.Blob) { resolveFile(file.getSource()); file.destroy(); } // plupload.File - final step for other branches else if (file instanceof plupload.File) { if (fileName) { file.name = fileName; } queue.push(function(cb) { // run through the internal and user-defined filters, if any filterFile(file, function(err) { if (!err) { files.push(file); self.trigger("FileFiltered", file); } delay(cb, 1); // do not build up recursions or eventually we might hit the limits }); }); } // native File or blob else if (o.inArray(type, ['file', 'blob']) !== -1) { resolveFile(new o.File(null, file)); } // input[type="file"] else if (type === 'node' && o.typeOf(file.files) === 'filelist') { // if we are dealing with input[type="file"] o.each(file.files, resolveFile); } // mixed array of any supported types (see above) else if (type === 'array') { fileName = null; // should never happen, but unset anyway to avoid funny situations o.each(file, resolveFile); } } ruid = getRUID(); resolveFile(file); if (queue.length) { o.inSeries(queue, function() { // if any files left after filtration, trigger FilesAdded if (files.length) { self.trigger("FilesAdded", files); } }); } }, /** * Removes a specific file. * * @method removeFile * @param {plupload.File|String} file File to remove from queue. */ removeFile : function(file) { var id = typeof(file) === 'string' ? file : file.id; for (var i = files.length - 1; i >= 0; i--) { if (files[i].id === id) { return this.splice(i, 1)[0]; } } }, /** * Removes part of the queue and returns the files removed. This will also trigger the FilesRemoved and QueueChanged events. * * @method splice * @param {Number} start (Optional) Start index to remove from. * @param {Number} length (Optional) Lengh of items to remove. * @return {Array} Array of files that was removed. */ splice : function(start, length) { // Splice and trigger events var removed = files.splice(start === undef ? 0 : start, length === undef ? files.length : length); // if upload is in progress we need to stop it and restart after files are removed var restartRequired = false; if (this.state == plupload.STARTED) { // upload in progress restartRequired = true; this.stop(); } this.trigger("FilesRemoved", removed); // Dispose any resources allocated by those files plupload.each(removed, function(file) { file.destroy(); }); this.trigger("QueueChanged"); this.refresh(); if (restartRequired) { this.start(); } return removed; }, /** * Dispatches the specified event name and it's arguments to all listeners. * * * @method trigger * @param {String} name Event name to fire. * @param {Object..} Multiple arguments to pass along to the listener functions. */ /** * Check whether uploader has any listeners to the specified event. * * @method hasEventListener * @param {String} name Event name to check for. */ /** * Adds an event listener by name. * * @method bind * @param {String} name Event name to listen for. * @param {function} func Function to call ones the event gets fired. * @param {Object} scope Optional scope to execute the specified function in. */ bind : function(name, func, scope) { var self = this; // adapt moxie EventTarget style to Plupload-like plupload.Uploader.prototype.bind.call(this, name, function() { var args = [].slice.call(arguments); args.splice(0, 1, self); // replace event object with uploader instance return func.apply(this, args); }, 0, scope); }, /** * Removes the specified event listener. * * @method unbind * @param {String} name Name of event to remove. * @param {function} func Function to remove from listener. */ /** * Removes all event listeners. * * @method unbindAll */ /** * Destroys Plupload instance and cleans after itself. * * @method destroy */ destroy : function() { this.trigger('Destroy'); total = null; // purge this one exclusively this.unbindAll(); } }); }; plupload.Uploader.prototype = o.EventTarget.instance; /** * Constructs a new file instance. * * @class File * @constructor * * @param {Object} file Object containing file properties * @param {String} file.name Name of the file. * @param {Number} file.size File size. */ plupload.File = (function() { var filepool = {}; function PluploadFile(file) { plupload.extend(this, { /** * File id this is a globally unique id for the specific file. * * @property id * @type String */ id: plupload.guid(), /** * File name for example "myfile.gif". * * @property name * @type String */ name: file.name || file.fileName, /** * File type, `e.g image/jpeg` * * @property type * @type String */ type: file.type || '', /** * File size in bytes (may change after client-side manupilation). * * @property size * @type Number */ size: file.size || file.fileSize, /** * Original file size in bytes. * * @property origSize * @type Number */ origSize: file.size || file.fileSize, /** * Number of bytes uploaded of the files total size. * * @property loaded * @type Number */ loaded: 0, /** * Number of percentage uploaded of the file. * * @property percent * @type Number */ percent: 0, /** * Status constant matching the plupload states QUEUED, UPLOADING, FAILED, DONE. * * @property status * @type Number * @see plupload */ status: plupload.QUEUED, /** * Date of last modification. * * @property lastModifiedDate * @type {String} */ lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString(), // Thu Aug 23 2012 19:40:00 GMT+0400 (GET) /** * Returns native window.File object, when it's available. * * @method getNative * @return {window.File} or null, if plupload.File is of different origin */ getNative: function() { var file = this.getSource().getSource(); return o.inArray(o.typeOf(file), ['blob', 'file']) !== -1 ? file : null; }, /** * Returns mOxie.File - unified wrapper object that can be used across runtimes. * * @method getSource * @return {mOxie.File} or null */ getSource: function() { if (!filepool[this.id]) { return null; } return filepool[this.id]; }, /** * Destroys plupload.File object. * * @method destroy */ destroy: function() { var src = this.getSource(); if (src) { src.destroy(); delete filepool[this.id]; } } }); filepool[this.id] = file; } return PluploadFile; }()); /** * Constructs a queue progress. * * @class QueueProgress * @constructor */ plupload.QueueProgress = function() { var self = this; // Setup alias for self to reduce code size when it's compressed /** * Total queue file size. * * @property size * @type Number */ self.size = 0; /** * Total bytes uploaded. * * @property loaded * @type Number */ self.loaded = 0; /** * Number of files uploaded. * * @property uploaded * @type Number */ self.uploaded = 0; /** * Number of files failed to upload. * * @property failed * @type Number */ self.failed = 0; /** * Number of files yet to be uploaded. * * @property queued * @type Number */ self.queued = 0; /** * Total percent of the uploaded bytes. * * @property percent * @type Number */ self.percent = 0; /** * Bytes uploaded per second. * * @property bytesPerSec * @type Number */ self.bytesPerSec = 0; /** * Resets the progress to it's initial values. * * @method reset */ self.reset = function() { self.size = self.loaded = self.uploaded = self.failed = self.queued = self.percent = self.bytesPerSec = 0; }; }; window.plupload = plupload; }(window, mOxie));
JavaScript
/*! Backstretch - v2.0.3 - 2012-11-30 * http://srobbin.com/jquery-plugins/backstretch/ * Copyright (c) 2012 Scott Robbin; Licensed MIT */ ;(function ($, window, undefined) { 'use strict'; /* PLUGIN DEFINITION * ========================= */ $.fn.backstretch = function (images, options) { // We need at least one image if (images === undefined || images.length === 0) { $.error("No images were supplied for Backstretch"); } /* * Scroll the page one pixel to get the right window height on iOS * Pretty harmless for everyone else */ if ($(window).scrollTop() === 0 ) { window.scrollTo(0, 0); } return this.each(function () { var $this = $(this) , obj = $this.data('backstretch'); // If we've already attached Backstretch to this element, remove the old instance. if (obj) { // Merge the old options with the new options = $.extend(obj.options, options); // Remove the old instance obj.destroy(true); } obj = new Backstretch(this, images, options); $this.data('backstretch', obj); }); }; // If no element is supplied, we'll attach to body $.backstretch = function (images, options) { // Return the instance return $('body') .backstretch(images, options) .data('backstretch'); }; // Custom selector $.expr[':'].backstretch = function(elem) { return $(elem).data('backstretch') !== undefined; }; /* DEFAULTS * ========================= */ $.fn.backstretch.defaults = { centeredX: true // Should we center the image on the X axis? , centeredY: true // Should we center the image on the Y axis? , duration: 5000 // Amount of time in between slides (if slideshow) , fade: 0 // Speed of fade transition between slides }; /* STYLES * * Baked-in styles that we'll apply to our elements. * In an effort to keep the plugin simple, these are not exposed as options. * That said, anyone can override these in their own stylesheet. * ========================= */ var styles = { wrap: { left: 0 , top: 0 , overflow: 'hidden' , margin: 0 , padding: 0 , height: '100%' , width: '100%' , zIndex: -999999 } , img: { position: 'absolute' , display: 'none' , margin: 0 , padding: 0 , border: 'none' , width: 'auto' , height: 'auto' , maxWidth: 'none' , zIndex: -999999 } }; /* CLASS DEFINITION * ========================= */ var Backstretch = function (container, images, options) { this.options = $.extend({}, $.fn.backstretch.defaults, options || {}); /* In its simplest form, we allow Backstretch to be called on an image path. * e.g. $.backstretch('/path/to/image.jpg') * So, we need to turn this back into an array. */ this.images = $.isArray(images) ? images : [images]; // Preload images $.each(this.images, function () { $('<img />')[0].src = this; }); // Convenience reference to know if the container is body. this.isBody = container === document.body; /* We're keeping track of a few different elements * * Container: the element that Backstretch was called on. * Wrap: a DIV that we place the image into, so we can hide the overflow. * Root: Convenience reference to help calculate the correct height. */ this.$container = $(container); this.$wrap = $('<div class="backstretch"></div>').css(styles.wrap).appendTo(this.$container); this.$root = this.isBody ? supportsFixedPosition ? $(window) : $(document) : this.$container; // Non-body elements need some style adjustments if (!this.isBody) { // If the container is statically positioned, we need to make it relative, // and if no zIndex is defined, we should set it to zero. var position = this.$container.css('position') , zIndex = this.$container.css('zIndex'); this.$container.css({ position: position === 'static' ? 'relative' : position , zIndex: zIndex === 'auto' ? 0 : zIndex , background: 'none' }); // Needs a higher z-index this.$wrap.css({zIndex: -999998}); } // Fixed or absolute positioning? this.$wrap.css({ position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute' }); // Set the first image this.index = 0; this.show(this.index); // Listen for resize $(window).on('resize.backstretch', $.proxy(this.resize, this)) .on('orientationchange.backstretch', $.proxy(function () { // Need to do this in order to get the right window height if (this.isBody && window.pageYOffset === 0) { window.scrollTo(0, 1); this.resize(); } }, this)); }; /* PUBLIC METHODS * ========================= */ Backstretch.prototype = { resize: function () { try { var bgCSS = {left: 0, top: 0} , rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth() , bgWidth = rootWidth , rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight() , bgHeight = bgWidth / this.$img.data('ratio') , bgOffset; // Make adjustments based on image ratio if (bgHeight >= rootHeight) { bgOffset = (bgHeight - rootHeight) / 2; if(this.options.centeredY) { bgCSS.top = '-' + bgOffset + 'px'; } } else { bgHeight = rootHeight; bgWidth = bgHeight * this.$img.data('ratio'); bgOffset = (bgWidth - rootWidth) / 2; if(this.options.centeredX) { bgCSS.left = '-' + bgOffset + 'px'; } } this.$wrap.css({width: rootWidth, height: rootHeight}) .find('img:not(.deleteable)').css({width: bgWidth, height: bgHeight}).css(bgCSS); } catch(err) { // IE7 seems to trigger resize before the image is loaded. // This try/catch block is a hack to let it fail gracefully. } return this; } // Show the slide at a certain position , show: function (index) { // Validate index if (Math.abs(index) > this.images.length - 1) { return; } else { this.index = index; } // Vars var self = this , oldImage = self.$wrap.find('img').addClass('deleteable') , evt = $.Event('backstretch.show', { relatedTarget: self.$container[0] }); // Pause the slideshow clearInterval(self.interval); // New image self.$img = $('<img />') .css(styles.img) .bind('load', function (e) { var imgWidth = this.width || $(e.target).width() , imgHeight = this.height || $(e.target).height(); // Save the ratio $(this).data('ratio', imgWidth / imgHeight); // Show the image, then delete the old one // "speed" option has been deprecated, but we want backwards compatibilty $(this).fadeIn(self.options.speed || self.options.fade, function () { oldImage.remove(); // Resume the slideshow if (!self.paused) { self.cycle(); } // Trigger the event self.$container.trigger(evt, self); }); // Resize self.resize(); }) .appendTo(self.$wrap); // Hack for IE img onload event self.$img.attr('src', self.images[index]); return self; } , next: function () { // Next slide return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0); } , prev: function () { // Previous slide return this.show(this.index === 0 ? this.images.length - 1 : this.index - 1); } , pause: function () { // Pause the slideshow this.paused = true; return this; } , resume: function () { // Resume the slideshow this.paused = false; this.next(); return this; } , cycle: function () { // Start/resume the slideshow if(this.images.length > 1) { // Clear the interval, just in case clearInterval(this.interval); this.interval = setInterval($.proxy(function () { // Check for paused slideshow if (!this.paused) { this.next(); } }, this), this.options.duration); } return this; } , destroy: function (preserveBackground) { // Stop the resize events $(window).off('resize.backstretch orientationchange.backstretch'); // Clear the interval clearInterval(this.interval); // Remove Backstretch if(!preserveBackground) { this.$wrap.remove(); } this.$container.removeData('backstretch'); } }; /* SUPPORTS FIXED POSITION? * * Based on code from jQuery Mobile 1.1.0 * http://jquerymobile.com/ * * In a nutshell, we need to figure out if fixed positioning is supported. * Unfortunately, this is very difficult to do on iOS, and usually involves * injecting content, scrolling the page, etc.. It's ugly. * jQuery Mobile uses this workaround. It's not ideal, but works. * * Modified to detect IE6 * ========================= */ var supportsFixedPosition = (function () { var ua = navigator.userAgent , platform = navigator.platform // Rendering engine is Webkit, and capture major version , wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ) , wkversion = !!wkmatch && wkmatch[ 1 ] , ffmatch = ua.match( /Fennec\/([0-9]+)/ ) , ffversion = !!ffmatch && ffmatch[ 1 ] , operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ) , omversion = !!operammobilematch && operammobilematch[ 1 ] , iematch = ua.match( /MSIE ([0-9]+)/ ) , ieversion = !!iematch && iematch[ 1 ]; return !( // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5) ((platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534) || // Opera Mini (window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]") || (operammobilematch && omversion < 7458) || //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2) (ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533) || // Firefox Mobile before 6.0 - (ffversion && ffversion < 6) || // WebOS less than 3 ("palmGetResource" in window && wkversion && wkversion < 534) || // MeeGo (ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1) || // IE6 (ieversion && ieversion <= 6) ); }()); }(jQuery, window));
JavaScript
/* * MultiSelect v0.9.10 * Copyright (c) 2012 Louis Cuny * * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://sam.zoy.org/wtfpl/COPYING for more details. */ !function ($) { "use strict"; /* MULTISELECT CLASS DEFINITION * ====================== */ var MultiSelect = function (element, options) { this.options = options; this.$element = $(element); this.$container = $('<div/>', { 'class': "ms-container" }); this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' }); this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' }); this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.scrollTo = 0; this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')'; }; MultiSelect.prototype = { constructor: MultiSelect, init: function(){ var that = this, ms = this.$element; if (ms.next('.ms-container').length === 0){ ms.css({ position: 'absolute', left: '-9999px' }); ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect'); this.$container.attr('id', 'ms-'+ms.attr('id')); this.$container.addClass(that.options.cssClass); ms.find('option').each(function(){ that.generateLisFromOption(this); }); this.$selectionUl.find('.ms-optgroup-label').hide(); if (that.options.selectableHeader){ that.$selectableContainer.append(that.options.selectableHeader); } that.$selectableContainer.append(that.$selectableUl); if (that.options.selectableFooter){ that.$selectableContainer.append(that.options.selectableFooter); } if (that.options.selectionHeader){ that.$selectionContainer.append(that.options.selectionHeader); } that.$selectionContainer.append(that.$selectionUl); if (that.options.selectionFooter){ that.$selectionContainer.append(that.options.selectionFooter); } that.$container.append(that.$selectableContainer); that.$container.append(that.$selectionContainer); ms.after(that.$container); that.activeMouse(that.$selectableUl); that.activeKeyboard(that.$selectableUl); var action = that.options.dblClick ? 'dblclick' : 'click'; that.$selectableUl.on(action, '.ms-elem-selectable', function(){ that.select($(this).data('ms-value')); }); that.$selectionUl.on(action, '.ms-elem-selection', function(){ that.deselect($(this).data('ms-value')); }); that.activeMouse(that.$selectionUl); that.activeKeyboard(that.$selectionUl); ms.on('focus', function(){ that.$selectableUl.focus(); }) } var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get(); that.select(selectedValues, 'init'); if (typeof that.options.afterInit === 'function') { that.options.afterInit.call(this, this.$container); } }, 'generateLisFromOption' : function(option, index, $container){ var that = this, ms = that.$element, attributes = "", $option = $(option); for (var cpt = 0; cpt < option.attributes.length; cpt++){ var attr = option.attributes[cpt]; if(attr.name !== 'value' && attr.name !== 'disabled'){ attributes += attr.name+'="'+attr.value+'" '; } } var selectableLi = $('<li '+attributes+'><span>'+that.escapeHTML($option.text())+'</span></li>'), selectedLi = selectableLi.clone(), value = $option.val(), elementId = that.sanitize(value); selectableLi .data('ms-value', value) .addClass('ms-elem-selectable') .attr('id', elementId+'-selectable'); selectedLi .data('ms-value', value) .addClass('ms-elem-selection') .attr('id', elementId+'-selection') .hide(); if ($option.prop('disabled') || ms.prop('disabled')){ selectedLi.addClass(that.options.disabledClass); selectableLi.addClass(that.options.disabledClass); } var $optgroup = $option.parent('optgroup'); if ($optgroup.length > 0){ var optgroupLabel = $optgroup.attr('label'), optgroupId = that.sanitize(optgroupLabel), $selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId), $selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId); if ($selectableOptgroup.length === 0){ var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>', optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>'; $selectableOptgroup = $(optgroupContainerTpl); $selectionOptgroup = $(optgroupContainerTpl); $selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId); $selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId); $selectableOptgroup.append($(optgroupTpl)); $selectionOptgroup.append($(optgroupTpl)); if (that.options.selectableOptgroup){ $selectableOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':not(:selected)').map(function(){ return $(this).val() }).get(); that.select(values); }); $selectionOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':selected').map(function(){ return $(this).val() }).get(); that.deselect(values); }); } that.$selectableUl.append($selectableOptgroup); that.$selectionUl.append($selectionOptgroup); } index = index == undefined ? $selectableOptgroup.children().length : index + 1; selectableLi.insertAt(index, $selectableOptgroup.children()); selectedLi.insertAt(index, $selectionOptgroup.children()); } else { index = index == undefined ? that.$selectableUl.children().length : index; selectableLi.insertAt(index, that.$selectableUl); selectedLi.insertAt(index, that.$selectionUl); } }, 'addOption' : function(options){ var that = this; if (options.value) options = [options]; $.each(options, function(index, option){ if (option.value && that.$element.find("option[value='"+option.value+"']").length === 0){ var $option = $('<option value="'+option.value+'">'+option.text+'</option>'), index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)), $container = option.nested == undefined ? that.$element : $("optgroup[label='"+option.nested+"']") $option.insertAt(index, $container); that.generateLisFromOption($option.get(0), index, option.nested); } }) }, 'escapeHTML' : function(text){ return $("<div>").text(text).html(); }, 'activeKeyboard' : function($list){ var that = this; $list.on('focus', function(){ $(this).addClass('ms-focus'); }) .on('blur', function(){ $(this).removeClass('ms-focus'); }) .on('keydown', function(e){ switch (e.which) { case 40: case 38: e.preventDefault(); e.stopPropagation(); that.moveHighlight($(this), (e.which === 38) ? -1 : 1); return; case 37: case 39: e.preventDefault(); e.stopPropagation(); that.switchList($list); return; case 9: if(that.$element.is('[tabindex]')){ e.preventDefault(); var tabindex = parseInt(that.$element.attr('tabindex'), 10); tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1; $('[tabindex="'+(tabindex)+'"]').focus(); return; }else{ if(e.shiftKey){ that.$element.trigger('focus'); } } } if($.inArray(e.which, that.options.keySelect) > -1){ e.preventDefault(); e.stopPropagation(); that.selectHighlighted($list); return; } }); }, 'moveHighlight': function($list, direction){ var $elems = $list.find(this.elemsSelector), $currElem = $elems.filter('.ms-hover'), $nextElem = null, elemHeight = $elems.first().outerHeight(), containerHeight = $list.height(), containerSelector = '#'+this.$container.prop('id'); // Deactive mouseenter event when move is active // It fixes a bug when mouse is over the list $elems.off('mouseenter'); $elems.removeClass('ms-hover'); if (direction === 1){ // DOWN $nextElem = $currElem.nextAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $nextOptgroupLi = $optgroupLi.next(':visible'); if ($nextOptgroupLi.length > 0){ $nextElem = $nextOptgroupLi.find(this.elemsSelector).first(); } else { $nextElem = $elems.first(); } } else { $nextElem = $elems.first(); } } } else if (direction === -1){ // UP $nextElem = $currElem.prevAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $prevOptgroupLi = $optgroupLi.prev(':visible'); if ($prevOptgroupLi.length > 0){ $nextElem = $prevOptgroupLi.find(this.elemsSelector).last(); } else { $nextElem = $elems.last(); } } else { $nextElem = $elems.last(); } } } if ($nextElem.length > 0){ $nextElem.addClass('ms-hover'); var scrollTo = $list.scrollTop() + $nextElem.position().top - containerHeight / 2 + elemHeight / 2; $list.scrollTop(scrollTo); } }, 'selectHighlighted' : function($list){ var $elems = $list.find(this.elemsSelector), $highlightedElem = $elems.filter('.ms-hover').first(); if ($highlightedElem.length > 0){ if ($list.parent().hasClass('ms-selectable')){ this.select($highlightedElem.data('ms-value')); } else { this.deselect($highlightedElem.data('ms-value')); } $elems.removeClass('ms-hover'); } }, 'switchList' : function($list){ $list.blur(); if ($list.parent().hasClass('ms-selectable')){ this.$selectionUl.focus(); } else { this.$selectableUl.focus(); } }, 'activeMouse' : function($list){ var that = this; var lastMovedDom = false; $list.on('mousemove', function(){ if (lastMovedDom === this) return; lastMovedDom = this; var elems = $list.find(that.elemsSelector); elems.on('mouseenter', function(){ elems.removeClass('ms-hover'); $(this).addClass('ms-hover'); }); }); }, 'refresh' : function() { this.destroy(); this.$element.multiSelect(this.options); }, 'destroy' : function(){ $("#ms-"+this.$element.attr("id")).remove(); this.$element.removeData('multiselect'); }, 'select' : function(value, method){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'), options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); }); if (method === 'init'){ selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection'); } if (selectables.length > 0){ selectables.addClass('ms-selected').hide(); selections.addClass('ms-selected').show(); options.prop('selected', true); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){ $(this).find('.ms-optgroup-label').hide(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); } else { if (that.options.keepOrder){ var selectionLiLast = that.$selectionUl.find('.ms-selected'); if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) { selections.insertAfter(selectionLiLast.last()); } } } if (method !== 'init'){ ms.trigger('change'); if (typeof that.options.afterSelect === 'function') { that.options.afterSelect.call(this, value); } } } }, 'deselect' : function(value){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected').filter(':not(.'+that.options.disabledClass+')'), options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); }); if (selections.length > 0){ selectables.removeClass('ms-selected').show(); selections.removeClass('ms-selected').hide(); options.prop('selected', false); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.filter(':not(.ms-selected)').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length === 0){ $(this).find('.ms-optgroup-label').hide(); } }); } ms.trigger('change'); if (typeof that.options.afterDeselect === 'function') { that.options.afterDeselect.call(this, value); } } }, 'select_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option:not(":disabled")').prop('selected', true); this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide(); this.$selectionUl.find('.ms-optgroup-label').show(); this.$selectableUl.find('.ms-optgroup-label').hide(); this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show(); this.$selectionUl.focus(); ms.trigger('change'); if (typeof this.options.afterSelect === 'function') { var selectedValues = $.grep(ms.val(), function(item){ return $.inArray(item, values) < 0; }); this.options.afterSelect.call(this, selectedValues); } }, 'deselect_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option').prop('selected', false); this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show(); this.$selectionUl.find('.ms-optgroup-label').hide(); this.$selectableUl.find('.ms-optgroup-label').show(); this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide(); this.$selectableUl.focus(); ms.trigger('change'); if (typeof this.options.afterDeselect === 'function') { this.options.afterDeselect.call(this, values); } }, sanitize: function(value){ var hash = 0, i, char; if (value.length == 0) return hash; var ls = 0; for (i = 0, ls = value.length; i < ls; i++) { char = value.charCodeAt(i); hash = ((hash<<5)-hash)+char; hash |= 0; // Convert to 32bit integer } return hash; } }; /* MULTISELECT PLUGIN DEFINITION * ======================= */ $.fn.multiSelect = function () { var option = arguments[0], args = arguments; return this.each(function () { var $this = $(this), data = $this.data('multiselect'), options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option); if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); } if (typeof option === 'string'){ data[option](args[1]); } else { data.init(); } }); }; $.fn.multiSelect.defaults = { keySelect: [32], selectableOptgroup: false, disabledClass : 'disabled', dblClick : false, keepOrder: false, cssClass: '' }; $.fn.multiSelect.Constructor = MultiSelect; $.fn.insertAt = function(index, $parent) { return this.each(function() { if (index === 0) { $parent.prepend(this); } else { $parent.children().eq(index - 1).after(this); } }); } }(window.jQuery);
JavaScript
/*! * Media helper for fancyBox * version: 1.0.5 (Tue, 23 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * media: true * } * }); * * Set custom URL parameters: * $(".fancybox").fancybox({ * helpers : { * media: { * youtube : { * params : { * autoplay : 0 * } * } * } * } * }); * * Or: * $(".fancybox").fancybox({, * helpers : { * media: true * }, * youtube : { * autoplay: 0 * } * }); * * Supports: * * Youtube * http://www.youtube.com/watch?v=opj24KnzrWo * http://www.youtube.com/embed/opj24KnzrWo * http://youtu.be/opj24KnzrWo * Vimeo * http://vimeo.com/40648169 * http://vimeo.com/channels/staffpicks/38843628 * http://vimeo.com/groups/surrealism/videos/36516384 * http://player.vimeo.com/video/45074303 * Metacafe * http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/ * http://www.metacafe.com/watch/7635964/ * Dailymotion * http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people * Twitvid * http://twitvid.com/QY7MD * Twitpic * http://twitpic.com/7p93st * Instagram * http://instagr.am/p/IejkuUGxQn/ * http://instagram.com/p/IejkuUGxQn/ * Google maps * http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17 * http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16 * http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56 */ (function ($) { "use strict"; //Shortcut for fancyBox object var F = $.fancybox, format = function( url, rez, params ) { params = params || ''; if ( $.type( params ) === "object" ) { params = $.param(params, true); } $.each(rez, function(key, value) { url = url.replace( '$' + key, value || '' ); }); if (params.length) { url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params; } return url; }; //Add helper object F.helpers.media = { defaults : { youtube : { matcher : /(youtube\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i, params : { autoplay : 1, autohide : 1, fs : 1, rel : 0, hd : 1, wmode : 'opaque', enablejsapi : 1 }, type : 'iframe', url : '//www.youtube.com/embed/$3' }, vimeo : { matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/, params : { autoplay : 1, hd : 1, show_title : 1, show_byline : 1, show_portrait : 0, fullscreen : 1 }, type : 'iframe', url : '//player.vimeo.com/video/$1' }, metacafe : { matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/, params : { autoPlay : 'yes' }, type : 'swf', url : function( rez, params, obj ) { obj.swf.flashVars = 'playerVars=' + $.param( params, true ); return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf'; } }, dailymotion : { matcher : /dailymotion.com\/video\/(.*)\/?(.*)/, params : { additionalInfos : 0, autoStart : 1 }, type : 'swf', url : '//www.dailymotion.com/swf/video/$1' }, twitvid : { matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i, params : { autoplay : 0 }, type : 'iframe', url : '//www.twitvid.com/embed.php?guid=$1' }, twitpic : { matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i, type : 'image', url : '//twitpic.com/show/full/$1/' }, instagram : { matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i, type : 'image', url : '//$1/p/$2/media/' }, google_maps : { matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i, type : 'iframe', url : function( rez ) { return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed'); } } }, beforeLoad : function(opts, obj) { var url = obj.href || '', type = false, what, item, rez, params; for (what in opts) { item = opts[ what ]; rez = url.match( item.matcher ); if (rez) { type = item.type; params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null)); url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params ); break; } } if (type) { obj.href = url; obj.type = type; obj.autoHeight = false; } } }; }(jQuery));
JavaScript
/*! * Buttons helper for fancyBox * version: 1.0.5 (Mon, 15 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * buttons: { * position : 'top' * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.buttons = { defaults : { skipSingle : false, // disables if gallery contains single image position : 'top', // 'top' or 'bottom' tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:jQuery.fancybox.close();"></a></li></ul></div>' }, list : null, buttons: null, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (opts.skipSingle && obj.group.length < 2) { obj.helpers.buttons = false; obj.closeBtn = true; return; } //Increase top margin to give space for buttons obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30; }, onPlayStart: function () { if (this.buttons) { this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn'); } }, onPlayEnd: function () { if (this.buttons) { this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn'); } }, afterShow: function (opts, obj) { var buttons = this.buttons; if (!buttons) { this.list = $(opts.tpl).addClass(opts.position).appendTo('body'); buttons = { prev : this.list.find('.btnPrev').click( F.prev ), next : this.list.find('.btnNext').click( F.next ), play : this.list.find('.btnPlay').click( F.play ), toggle : this.list.find('.btnToggle').click( F.toggle ) } } //Prev if (obj.index > 0 || obj.loop) { buttons.prev.removeClass('btnDisabled'); } else { buttons.prev.addClass('btnDisabled'); } //Next / Play if (obj.loop || obj.index < obj.group.length - 1) { buttons.next.removeClass('btnDisabled'); buttons.play.removeClass('btnDisabled'); } else { buttons.next.addClass('btnDisabled'); buttons.play.addClass('btnDisabled'); } this.buttons = buttons; this.onUpdate(opts, obj); }, onUpdate: function (opts, obj) { var toggle; if (!this.buttons) { return; } toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn'); //Size toggle button if (obj.canShrink) { toggle.addClass('btnToggleOn'); } else if (!obj.canExpand) { toggle.addClass('btnDisabled'); } }, beforeClose: function () { if (this.list) { this.list.remove(); } this.list = null; this.buttons = null; } }; }(jQuery));
JavaScript
/*! * Thumbnail helper for fancyBox * version: 1.0.7 (Mon, 01 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * thumbs: { * width : 50, * height : 50 * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.thumbs = { defaults : { width : 50, // thumbnail width height : 50, // thumbnail height position : 'bottom', // 'top' or 'bottom' source : function ( item ) { // function to obtain the URL of the thumbnail image var href; if (item.element) { href = $(item.element).find('img').attr('src'); } if (!href && item.type === 'image' && item.href) { href = item.href; } return href; } }, wrap : null, list : null, width : 0, init: function (opts, obj) { var that = this, list, thumbWidth = opts.width, thumbHeight = opts.height, thumbSource = opts.source; //Build list structure list = ''; for (var n = 0; n < obj.group.length; n++) { list += '<li><a style="width:' + thumbWidth + 'px;height:' + thumbHeight + 'px;" href="javascript:jQuery.fancybox.jumpto(' + n + ');"></a></li>'; } this.wrap = $('<div id="fancybox-thumbs"></div>').addClass(opts.position).appendTo('body'); this.list = $('<ul>' + list + '</ul>').appendTo(this.wrap); //Load each thumbnail $.each(obj.group, function (i) { var href = thumbSource( obj.group[ i ] ); if (!href) { return; } $("<img />").load(function () { var width = this.width, height = this.height, widthRatio, heightRatio, parent; if (!that.list || !width || !height) { return; } //Calculate thumbnail width/height and center it widthRatio = width / thumbWidth; heightRatio = height / thumbHeight; parent = that.list.children().eq(i).find('a'); if (widthRatio >= 1 && heightRatio >= 1) { if (widthRatio > heightRatio) { width = Math.floor(width / heightRatio); height = thumbHeight; } else { width = thumbWidth; height = Math.floor(height / widthRatio); } } $(this).css({ width : width, height : height, top : Math.floor(thumbHeight / 2 - height / 2), left : Math.floor(thumbWidth / 2 - width / 2) }); parent.width(thumbWidth).height(thumbHeight); $(this).hide().appendTo(parent).fadeIn(300); }).attr('src', href); }); //Set initial width this.width = this.list.children().eq(0).outerWidth(true); this.list.width(this.width * (obj.group.length + 1)).css('left', Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5))); }, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (obj.group.length < 2) { obj.helpers.thumbs = false; return; } //Increase bottom margin to give space for thumbs obj.margin[ opts.position === 'top' ? 0 : 2 ] += ((opts.height) + 15); }, afterShow: function (opts, obj) { //Check if exists and create or update list if (this.list) { this.onUpdate(opts, obj); } else { this.init(opts, obj); } //Set active element this.list.children().removeClass('active').eq(obj.index).addClass('active'); }, //Center list onUpdate: function (opts, obj) { if (this.list) { this.list.stop(true).animate({ 'left': Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5)) }, 150); } }, beforeClose: function () { if (this.wrap) { this.wrap.remove(); } this.wrap = null; this.list = null; this.width = 0; } } }(jQuery));
JavaScript
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;b.axis!==void 0&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);b.wheelDeltaY!==void 0&&(g=b.wheelDeltaY/120);b.wheelDeltaX!==void 0&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]= d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,false);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
JavaScript
/*! * Nestable jQuery Plugin - Copyright (c) 2012 David Bushell - http://dbushell.com/ * Dual-licensed under the BSD or MIT licenses */ ;(function($, window, document, undefined) { var hasTouch = 'ontouchstart' in window; /** * Detect CSS pointer-events property * events are normally disabled on the dragging element to avoid conflicts * https://github.com/ausi/Feature-detection-technique-for-pointer-events/blob/master/modernizr-pointerevents.js */ var hasPointerEvents = (function() { var el = document.createElement('div'), docEl = document.documentElement; if (!('pointerEvents' in el.style)) { return false; } el.style.pointerEvents = 'auto'; el.style.pointerEvents = 'x'; docEl.appendChild(el); var supports = window.getComputedStyle && window.getComputedStyle(el, '').pointerEvents === 'auto'; docEl.removeChild(el); return !!supports; })(); var eStart = hasTouch ? 'touchstart' : 'mousedown', eMove = hasTouch ? 'touchmove' : 'mousemove', eEnd = hasTouch ? 'touchend' : 'mouseup'; eCancel = hasTouch ? 'touchcancel' : 'mouseup'; var defaults = { listNodeName : 'ol', itemNodeName : 'li', rootClass : 'dd', listClass : 'dd-list', itemClass : 'dd-item', dragClass : 'dd-dragel', handleClass : 'dd-handle', collapsedClass : 'dd-collapsed', placeClass : 'dd-placeholder', noDragClass : 'dd-nodrag', emptyClass : 'dd-empty', expandBtnHTML : '<button data-action="expand" type="button">Expand</button>', collapseBtnHTML : '<button data-action="collapse" type="button">Collapse</button>', group : 0, maxDepth : 5, threshold : 20 }; function Plugin(element, options) { this.w = $(window); this.el = $(element); this.options = $.extend({}, defaults, options); this.init(); } Plugin.prototype = { init: function() { var list = this; list.reset(); list.el.data('nestable-group', this.options.group); list.placeEl = $('<div class="' + list.options.placeClass + '"/>'); $.each(this.el.find(list.options.itemNodeName), function(k, el) { list.setParent($(el)); }); list.el.on('click', 'button', function(e) { if (list.dragEl || (!hasTouch && e.button !== 0)) { return; } var target = $(e.currentTarget), action = target.data('action'), item = target.parent(list.options.itemNodeName); if (action === 'collapse') { list.collapseItem(item); } if (action === 'expand') { list.expandItem(item); } }); var onStartEvent = function(e) { var handle = $(e.target); if (!handle.hasClass(list.options.handleClass)) { if (handle.closest('.' + list.options.noDragClass).length) { return; } handle = handle.closest('.' + list.options.handleClass); } if (!handle.length || list.dragEl || (!hasTouch && e.button !== 0) || (hasTouch && e.touches.length !== 1)) { return; } e.preventDefault(); list.dragStart(hasTouch ? e.touches[0] : e); }; var onMoveEvent = function(e) { if (list.dragEl) { e.preventDefault(); list.dragMove(hasTouch ? e.touches[0] : e); } }; var onEndEvent = function(e) { if (list.dragEl) { e.preventDefault(); list.dragStop(hasTouch ? e.touches[0] : e); } }; if (hasTouch) { list.el[0].addEventListener(eStart, onStartEvent, false); window.addEventListener(eMove, onMoveEvent, false); window.addEventListener(eEnd, onEndEvent, false); window.addEventListener(eCancel, onEndEvent, false); } else { list.el.on(eStart, onStartEvent); list.w.on(eMove, onMoveEvent); list.w.on(eEnd, onEndEvent); } }, serialize: function() { var data, depth = 0, list = this; step = function(level, depth) { var array = [ ], items = level.children(list.options.itemNodeName); items.each(function() { var li = $(this), item = $.extend({}, li.data()), sub = li.children(list.options.listNodeName); if (sub.length) { item.children = step(sub, depth + 1); } array.push(item); }); return array; }; data = step(list.el.find(list.options.listNodeName).first(), depth); return data; }, serialise: function() { return this.serialize(); }, reset: function() { this.mouse = { offsetX : 0, offsetY : 0, startX : 0, startY : 0, lastX : 0, lastY : 0, nowX : 0, nowY : 0, distX : 0, distY : 0, dirAx : 0, dirX : 0, dirY : 0, lastDirX : 0, lastDirY : 0, distAxX : 0, distAxY : 0 }; this.moving = false; this.dragEl = null; this.dragRootEl = null; this.dragDepth = 0; this.hasNewRoot = false; this.pointEl = null; }, expandItem: function(li) { li.removeClass(this.options.collapsedClass); li.children('[data-action="expand"]').hide(); li.children('[data-action="collapse"]').show(); li.children(this.options.listNodeName).show(); }, collapseItem: function(li) { var lists = li.children(this.options.listNodeName); if (lists.length) { li.addClass(this.options.collapsedClass); li.children('[data-action="collapse"]').hide(); li.children('[data-action="expand"]').show(); li.children(this.options.listNodeName).hide(); } }, expandAll: function() { var list = this; list.el.find(list.options.itemNodeName).each(function() { list.expandItem($(this)); }); }, collapseAll: function() { var list = this; list.el.find(list.options.itemNodeName).each(function() { list.collapseItem($(this)); }); }, setParent: function(li) { if (li.children(this.options.listNodeName).length) { li.prepend($(this.options.expandBtnHTML)); li.prepend($(this.options.collapseBtnHTML)); } li.children('[data-action="expand"]').hide(); }, unsetParent: function(li) { li.removeClass(this.options.collapsedClass); li.children('[data-action]').remove(); li.children(this.options.listNodeName).remove(); }, dragStart: function(e) { var mouse = this.mouse, target = $(e.target), dragItem = target.closest(this.options.itemNodeName); this.placeEl.css('height', dragItem.height()); mouse.offsetX = e.offsetX !== undefined ? e.offsetX : e.pageX - target.offset().left; mouse.offsetY = e.offsetY !== undefined ? e.offsetY : e.pageY - target.offset().top; mouse.startX = mouse.lastX = e.pageX; mouse.startY = mouse.lastY = e.pageY; this.dragRootEl = this.el; this.dragEl = $(document.createElement(this.options.listNodeName)).addClass(this.options.listClass + ' ' + this.options.dragClass); this.dragEl.css('width', dragItem.width()); // fix for zepto.js //dragItem.after(this.placeEl).detach().appendTo(this.dragEl); dragItem.after(this.placeEl); dragItem[0].parentNode.removeChild(dragItem[0]); dragItem.appendTo(this.dragEl); $(document.body).append(this.dragEl); this.dragEl.css({ 'left' : e.pageX - mouse.offsetX, 'top' : e.pageY - mouse.offsetY }); // total depth of dragging item var i, depth, items = this.dragEl.find(this.options.itemNodeName); for (i = 0; i < items.length; i++) { depth = $(items[i]).parents(this.options.listNodeName).length; if (depth > this.dragDepth) { this.dragDepth = depth; } } }, dragStop: function(e) { // fix for zepto.js //this.placeEl.replaceWith(this.dragEl.children(this.options.itemNodeName + ':first').detach()); var el = this.dragEl.children(this.options.itemNodeName).first(); el[0].parentNode.removeChild(el[0]); this.placeEl.replaceWith(el); this.dragEl.remove(); this.el.trigger('change'); if (this.hasNewRoot) { this.dragRootEl.trigger('change'); } this.reset(); }, dragMove: function(e) { var list, parent, prev, next, depth, opt = this.options, mouse = this.mouse; this.dragEl.css({ 'left' : e.pageX - mouse.offsetX, 'top' : e.pageY - mouse.offsetY }); // mouse position last events mouse.lastX = mouse.nowX; mouse.lastY = mouse.nowY; // mouse position this events mouse.nowX = e.pageX; mouse.nowY = e.pageY; // distance mouse moved between events mouse.distX = mouse.nowX - mouse.lastX; mouse.distY = mouse.nowY - mouse.lastY; // direction mouse was moving mouse.lastDirX = mouse.dirX; mouse.lastDirY = mouse.dirY; // direction mouse is now moving (on both axis) mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1; mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1; // axis mouse is now moving on var newAx = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0; // do nothing on first move if (!mouse.moving) { mouse.dirAx = newAx; mouse.moving = true; return; } // calc distance moved on this axis (and direction) if (mouse.dirAx !== newAx) { mouse.distAxX = 0; mouse.distAxY = 0; } else { mouse.distAxX += Math.abs(mouse.distX); if (mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) { mouse.distAxX = 0; } mouse.distAxY += Math.abs(mouse.distY); if (mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) { mouse.distAxY = 0; } } mouse.dirAx = newAx; /** * move horizontal */ if (mouse.dirAx && mouse.distAxX >= opt.threshold) { // reset move distance on x-axis for new phase mouse.distAxX = 0; prev = this.placeEl.prev(opt.itemNodeName); // increase horizontal level if previous sibling exists and is not collapsed if (mouse.distX > 0 && prev.length && !prev.hasClass(opt.collapsedClass)) { // cannot increase level when item above is collapsed list = prev.find(opt.listNodeName).last(); // check if depth limit has reached depth = this.placeEl.parents(opt.listNodeName).length; if (depth + this.dragDepth <= opt.maxDepth) { // create new sub-level if one doesn't exist if (!list.length) { list = $('<' + opt.listNodeName + '/>').addClass(opt.listClass); list.append(this.placeEl); prev.append(list); this.setParent(prev); } else { // else append to next level up list = prev.children(opt.listNodeName).last(); list.append(this.placeEl); } } } // decrease horizontal level if (mouse.distX < 0) { // we can't decrease a level if an item preceeds the current one next = this.placeEl.next(opt.itemNodeName); if (!next.length) { parent = this.placeEl.parent(); this.placeEl.closest(opt.itemNodeName).after(this.placeEl); if (!parent.children().length) { this.unsetParent(parent.parent()); } } } } var isEmpty = false; // find list item under cursor if (!hasPointerEvents) { this.dragEl[0].style.visibility = 'hidden'; } this.pointEl = $(document.elementFromPoint(e.pageX - document.body.scrollLeft, e.pageY - (window.pageYOffset || document.documentElement.scrollTop))); if (!hasPointerEvents) { this.dragEl[0].style.visibility = 'visible'; } if (this.pointEl.hasClass(opt.handleClass)) { this.pointEl = this.pointEl.parent(opt.itemNodeName); } if (this.pointEl.hasClass(opt.emptyClass)) { isEmpty = true; } else if (!this.pointEl.length || !this.pointEl.hasClass(opt.itemClass)) { return; } // find parent list of item under cursor var pointElRoot = this.pointEl.closest('.' + opt.rootClass), isNewRoot = this.dragRootEl.data('nestable-id') !== pointElRoot.data('nestable-id'); /** * move vertical */ if (!mouse.dirAx || isNewRoot || isEmpty) { // check if groups match if dragging over new root if (isNewRoot && opt.group !== pointElRoot.data('nestable-group')) { return; } // check depth limit depth = this.dragDepth - 1 + this.pointEl.parents(opt.listNodeName).length; if (depth > opt.maxDepth) { return; } var before = e.pageY < (this.pointEl.offset().top + this.pointEl.height() / 2); parent = this.placeEl.parent(); // if empty create new list to replace empty placeholder if (isEmpty) { list = $(document.createElement(opt.listNodeName)).addClass(opt.listClass); list.append(this.placeEl); this.pointEl.replaceWith(list); } else if (before) { this.pointEl.before(this.placeEl); } else { this.pointEl.after(this.placeEl); } if (!parent.children().length) { this.unsetParent(parent.parent()); } if (!this.dragRootEl.find(opt.itemNodeName).length) { this.dragRootEl.append('<div class="' + opt.emptyClass + '"/>'); } // parent root list has changed if (isNewRoot) { this.dragRootEl = pointElRoot; this.hasNewRoot = this.el[0] !== this.dragRootEl[0]; } } } }; $.fn.nestable = function(params) { var lists = this, retval = this; lists.each(function() { var plugin = $(this).data("nestable"); if (!plugin) { $(this).data("nestable", new Plugin(this, params)); $(this).data("nestable-id", new Date().getTime()); } else { if (typeof params === 'string' && typeof plugin[params] === 'function') { retval = plugin[params](); } } }); return retval || lists; }; })(window.jQuery || window.Zepto, window, document);
JavaScript
/** * jquery.Jcrop.js v0.9.12 * jQuery Image Cropping Plugin - released under MIT License * Author: Kelly Hallman <khallman@gmail.com> * http://github.com/tapmodo/Jcrop * Copyright (c) 2008-2013 Tapmodo Interactive LLC {{{ * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * }}} */ (function ($) { $.Jcrop = function (obj, opt) { var options = $.extend({}, $.Jcrop.defaults), docOffset, _ua = navigator.userAgent.toLowerCase(), is_msie = /msie/.test(_ua), ie6mode = /msie [1-6]\./.test(_ua); // Internal Methods {{{ function px(n) { return Math.round(n) + 'px'; } function cssClass(cl) { return options.baseClass + '-' + cl; } function supportsColorFade() { return $.fx.step.hasOwnProperty('backgroundColor'); } function getPos(obj) //{{{ { var pos = $(obj).offset(); return [pos.left, pos.top]; } //}}} function mouseAbs(e) //{{{ { return [(e.pageX - docOffset[0]), (e.pageY - docOffset[1])]; } //}}} function setOptions(opt) //{{{ { if (typeof(opt) !== 'object') opt = {}; options = $.extend(options, opt); $.each(['onChange','onSelect','onRelease','onDblClick'],function(i,e) { if (typeof(options[e]) !== 'function') options[e] = function () {}; }); } //}}} function startDragMode(mode, pos, touch) //{{{ { docOffset = getPos($img); Tracker.setCursor(mode === 'move' ? mode : mode + '-resize'); if (mode === 'move') { return Tracker.activateHandlers(createMover(pos), doneSelect, touch); } var fc = Coords.getFixed(); var opp = oppLockCorner(mode); var opc = Coords.getCorner(oppLockCorner(opp)); Coords.setPressed(Coords.getCorner(opp)); Coords.setCurrent(opc); Tracker.activateHandlers(dragmodeHandler(mode, fc), doneSelect, touch); } //}}} function dragmodeHandler(mode, f) //{{{ { return function (pos) { if (!options.aspectRatio) { switch (mode) { case 'e': pos[1] = f.y2; break; case 'w': pos[1] = f.y2; break; case 'n': pos[0] = f.x2; break; case 's': pos[0] = f.x2; break; } } else { switch (mode) { case 'e': pos[1] = f.y + 1; break; case 'w': pos[1] = f.y + 1; break; case 'n': pos[0] = f.x + 1; break; case 's': pos[0] = f.x + 1; break; } } Coords.setCurrent(pos); Selection.update(); }; } //}}} function createMover(pos) //{{{ { var lloc = pos; KeyManager.watchKeys(); return function (pos) { Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]); lloc = pos; Selection.update(); }; } //}}} function oppLockCorner(ord) //{{{ { switch (ord) { case 'n': return 'sw'; case 's': return 'nw'; case 'e': return 'nw'; case 'w': return 'ne'; case 'ne': return 'sw'; case 'nw': return 'se'; case 'se': return 'nw'; case 'sw': return 'ne'; } } //}}} function createDragger(ord) //{{{ { return function (e) { if (options.disabled) { return false; } if ((ord === 'move') && !options.allowMove) { return false; } // Fix position of crop area when dragged the very first time. // Necessary when crop image is in a hidden element when page is loaded. docOffset = getPos($img); btndown = true; startDragMode(ord, mouseAbs(e)); e.stopPropagation(); e.preventDefault(); return false; }; } //}}} function presize($obj, w, h) //{{{ { var nw = $obj.width(), nh = $obj.height(); if ((nw > w) && w > 0) { nw = w; nh = (w / $obj.width()) * $obj.height(); } if ((nh > h) && h > 0) { nh = h; nw = (h / $obj.height()) * $obj.width(); } xscale = $obj.width() / nw; yscale = $obj.height() / nh; $obj.width(nw).height(nh); } //}}} function unscale(c) //{{{ { return { x: c.x * xscale, y: c.y * yscale, x2: c.x2 * xscale, y2: c.y2 * yscale, w: c.w * xscale, h: c.h * yscale }; } //}}} function doneSelect(pos) //{{{ { var c = Coords.getFixed(); if ((c.w > options.minSelect[0]) && (c.h > options.minSelect[1])) { Selection.enableHandles(); Selection.done(); } else { Selection.release(); } Tracker.setCursor(options.allowSelect ? 'crosshair' : 'default'); } //}}} function newSelection(e) //{{{ { if (options.disabled) { return false; } if (!options.allowSelect) { return false; } btndown = true; docOffset = getPos($img); Selection.disableHandles(); Tracker.setCursor('crosshair'); var pos = mouseAbs(e); Coords.setPressed(pos); Selection.update(); Tracker.activateHandlers(selectDrag, doneSelect, e.type.substring(0,5)==='touch'); KeyManager.watchKeys(); e.stopPropagation(); e.preventDefault(); return false; } //}}} function selectDrag(pos) //{{{ { Coords.setCurrent(pos); Selection.update(); } //}}} function newTracker() //{{{ { var trk = $('<div></div>').addClass(cssClass('tracker')); if (is_msie) { trk.css({ opacity: 0, backgroundColor: 'white' }); } return trk; } //}}} // }}} // Initialization {{{ // Sanitize some options {{{ if (typeof(obj) !== 'object') { obj = $(obj)[0]; } if (typeof(opt) !== 'object') { opt = {}; } // }}} setOptions(opt); // Initialize some jQuery objects {{{ // The values are SET on the image(s) for the interface // If the original image has any of these set, they will be reset // However, if you destroy() the Jcrop instance the original image's // character in the DOM will be as you left it. var img_css = { border: 'none', visibility: 'visible', margin: 0, padding: 0, position: 'absolute', top: 0, left: 0 }; var $origimg = $(obj), img_mode = true; if (obj.tagName == 'IMG') { // Fix size of crop image. // Necessary when crop image is within a hidden element when page is loaded. if ($origimg[0].width != 0 && $origimg[0].height != 0) { // Obtain dimensions from contained img element. $origimg.width($origimg[0].width); $origimg.height($origimg[0].height); } else { // Obtain dimensions from temporary image in case the original is not loaded yet (e.g. IE 7.0). var tempImage = new Image(); tempImage.src = $origimg[0].src; $origimg.width(tempImage.width); $origimg.height(tempImage.height); } var $img = $origimg.clone().removeAttr('id').css(img_css).show(); $img.width($origimg.width()); $img.height($origimg.height()); $origimg.after($img).hide(); } else { $img = $origimg.css(img_css).show(); img_mode = false; if (options.shade === null) { options.shade = true; } } presize($img, options.boxWidth, options.boxHeight); var boundx = $img.width(), boundy = $img.height(), $div = $('<div />').width(boundx).height(boundy).addClass(cssClass('holder')).css({ position: 'relative', backgroundColor: options.bgColor }).insertAfter($origimg).append($img); if (options.addClass) { $div.addClass(options.addClass); } var $img2 = $('<div />'), $img_holder = $('<div />') .width('100%').height('100%').css({ zIndex: 310, position: 'absolute', overflow: 'hidden' }), $hdl_holder = $('<div />') .width('100%').height('100%').css('zIndex', 320), $sel = $('<div />') .css({ position: 'absolute', zIndex: 600 }).dblclick(function(){ var c = Coords.getFixed(); options.onDblClick.call(api,c); }).insertBefore($img).append($img_holder, $hdl_holder); if (img_mode) { $img2 = $('<img />') .attr('src', $img.attr('src')).css(img_css).width(boundx).height(boundy), $img_holder.append($img2); } if (ie6mode) { $sel.css({ overflowY: 'hidden' }); } var bound = options.boundary; var $trk = newTracker().width(boundx + (bound * 2)).height(boundy + (bound * 2)).css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 }).mousedown(newSelection); /* }}} */ // Set more variables {{{ var bgcolor = options.bgColor, bgopacity = options.bgOpacity, xlimit, ylimit, xmin, ymin, xscale, yscale, enabled = true, btndown, animating, shift_down; docOffset = getPos($img); // }}} // }}} // Internal Modules {{{ // Touch Module {{{ var Touch = (function () { // Touch support detection function adapted (under MIT License) // from code by Jeffrey Sambells - http://github.com/iamamused/ function hasTouchSupport() { var support = {}, events = ['touchstart', 'touchmove', 'touchend'], el = document.createElement('div'), i; try { for(i=0; i<events.length; i++) { var eventName = events[i]; eventName = 'on' + eventName; var isSupported = (eventName in el); if (!isSupported) { el.setAttribute(eventName, 'return;'); isSupported = typeof el[eventName] == 'function'; } support[events[i]] = isSupported; } return support.touchstart && support.touchend && support.touchmove; } catch(err) { return false; } } function detectSupport() { if ((options.touchSupport === true) || (options.touchSupport === false)) return options.touchSupport; else return hasTouchSupport(); } return { createDragger: function (ord) { return function (e) { if (options.disabled) { return false; } if ((ord === 'move') && !options.allowMove) { return false; } docOffset = getPos($img); btndown = true; startDragMode(ord, mouseAbs(Touch.cfilter(e)), true); e.stopPropagation(); e.preventDefault(); return false; }; }, newSelection: function (e) { return newSelection(Touch.cfilter(e)); }, cfilter: function (e){ e.pageX = e.originalEvent.changedTouches[0].pageX; e.pageY = e.originalEvent.changedTouches[0].pageY; return e; }, isSupported: hasTouchSupport, support: detectSupport() }; }()); // }}} // Coords Module {{{ var Coords = (function () { var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy; function setPressed(pos) //{{{ { pos = rebound(pos); x2 = x1 = pos[0]; y2 = y1 = pos[1]; } //}}} function setCurrent(pos) //{{{ { pos = rebound(pos); ox = pos[0] - x2; oy = pos[1] - y2; x2 = pos[0]; y2 = pos[1]; } //}}} function getOffset() //{{{ { return [ox, oy]; } //}}} function moveOffset(offset) //{{{ { var ox = offset[0], oy = offset[1]; if (0 > x1 + ox) { ox -= ox + x1; } if (0 > y1 + oy) { oy -= oy + y1; } if (boundy < y2 + oy) { oy += boundy - (y2 + oy); } if (boundx < x2 + ox) { ox += boundx - (x2 + ox); } x1 += ox; x2 += ox; y1 += oy; y2 += oy; } //}}} function getCorner(ord) //{{{ { var c = getFixed(); switch (ord) { case 'ne': return [c.x2, c.y]; case 'nw': return [c.x, c.y]; case 'se': return [c.x2, c.y2]; case 'sw': return [c.x, c.y2]; } } //}}} function getFixed() //{{{ { if (!options.aspectRatio) { return getRect(); } // This function could use some optimization I think... var aspect = options.aspectRatio, min_x = options.minSize[0] / xscale, //min_y = options.minSize[1]/yscale, max_x = options.maxSize[0] / xscale, max_y = options.maxSize[1] / yscale, rw = x2 - x1, rh = y2 - y1, rwa = Math.abs(rw), rha = Math.abs(rh), real_ratio = rwa / rha, xx, yy, w, h; if (max_x === 0) { max_x = boundx * 10; } if (max_y === 0) { max_y = boundy * 10; } if (real_ratio < aspect) { yy = y2; w = rha * aspect; xx = rw < 0 ? x1 - w : w + x1; if (xx < 0) { xx = 0; h = Math.abs((xx - x1) / aspect); yy = rh < 0 ? y1 - h : h + y1; } else if (xx > boundx) { xx = boundx; h = Math.abs((xx - x1) / aspect); yy = rh < 0 ? y1 - h : h + y1; } } else { xx = x2; h = rwa / aspect; yy = rh < 0 ? y1 - h : y1 + h; if (yy < 0) { yy = 0; w = Math.abs((yy - y1) * aspect); xx = rw < 0 ? x1 - w : w + x1; } else if (yy > boundy) { yy = boundy; w = Math.abs(yy - y1) * aspect; xx = rw < 0 ? x1 - w : w + x1; } } // Magic %-) if (xx > x1) { // right side if (xx - x1 < min_x) { xx = x1 + min_x; } else if (xx - x1 > max_x) { xx = x1 + max_x; } if (yy > y1) { yy = y1 + (xx - x1) / aspect; } else { yy = y1 - (xx - x1) / aspect; } } else if (xx < x1) { // left side if (x1 - xx < min_x) { xx = x1 - min_x; } else if (x1 - xx > max_x) { xx = x1 - max_x; } if (yy > y1) { yy = y1 + (x1 - xx) / aspect; } else { yy = y1 - (x1 - xx) / aspect; } } if (xx < 0) { x1 -= xx; xx = 0; } else if (xx > boundx) { x1 -= xx - boundx; xx = boundx; } if (yy < 0) { y1 -= yy; yy = 0; } else if (yy > boundy) { y1 -= yy - boundy; yy = boundy; } return makeObj(flipCoords(x1, y1, xx, yy)); } //}}} function rebound(p) //{{{ { if (p[0] < 0) p[0] = 0; if (p[1] < 0) p[1] = 0; if (p[0] > boundx) p[0] = boundx; if (p[1] > boundy) p[1] = boundy; return [Math.round(p[0]), Math.round(p[1])]; } //}}} function flipCoords(x1, y1, x2, y2) //{{{ { var xa = x1, xb = x2, ya = y1, yb = y2; if (x2 < x1) { xa = x2; xb = x1; } if (y2 < y1) { ya = y2; yb = y1; } return [xa, ya, xb, yb]; } //}}} function getRect() //{{{ { var xsize = x2 - x1, ysize = y2 - y1, delta; if (xlimit && (Math.abs(xsize) > xlimit)) { x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit); } if (ylimit && (Math.abs(ysize) > ylimit)) { y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit); } if (ymin / yscale && (Math.abs(ysize) < ymin / yscale)) { y2 = (ysize > 0) ? (y1 + ymin / yscale) : (y1 - ymin / yscale); } if (xmin / xscale && (Math.abs(xsize) < xmin / xscale)) { x2 = (xsize > 0) ? (x1 + xmin / xscale) : (x1 - xmin / xscale); } if (x1 < 0) { x2 -= x1; x1 -= x1; } if (y1 < 0) { y2 -= y1; y1 -= y1; } if (x2 < 0) { x1 -= x2; x2 -= x2; } if (y2 < 0) { y1 -= y2; y2 -= y2; } if (x2 > boundx) { delta = x2 - boundx; x1 -= delta; x2 -= delta; } if (y2 > boundy) { delta = y2 - boundy; y1 -= delta; y2 -= delta; } if (x1 > boundx) { delta = x1 - boundy; y2 -= delta; y1 -= delta; } if (y1 > boundy) { delta = y1 - boundy; y2 -= delta; y1 -= delta; } return makeObj(flipCoords(x1, y1, x2, y2)); } //}}} function makeObj(a) //{{{ { return { x: a[0], y: a[1], x2: a[2], y2: a[3], w: a[2] - a[0], h: a[3] - a[1] }; } //}}} return { flipCoords: flipCoords, setPressed: setPressed, setCurrent: setCurrent, getOffset: getOffset, moveOffset: moveOffset, getCorner: getCorner, getFixed: getFixed }; }()); //}}} // Shade Module {{{ var Shade = (function() { var enabled = false, holder = $('<div />').css({ position: 'absolute', zIndex: 240, opacity: 0 }), shades = { top: createShade(), left: createShade().height(boundy), right: createShade().height(boundy), bottom: createShade() }; function resizeShades(w,h) { shades.left.css({ height: px(h) }); shades.right.css({ height: px(h) }); } function updateAuto() { return updateShade(Coords.getFixed()); } function updateShade(c) { shades.top.css({ left: px(c.x), width: px(c.w), height: px(c.y) }); shades.bottom.css({ top: px(c.y2), left: px(c.x), width: px(c.w), height: px(boundy-c.y2) }); shades.right.css({ left: px(c.x2), width: px(boundx-c.x2) }); shades.left.css({ width: px(c.x) }); } function createShade() { return $('<div />').css({ position: 'absolute', backgroundColor: options.shadeColor||options.bgColor }).appendTo(holder); } function enableShade() { if (!enabled) { enabled = true; holder.insertBefore($img); updateAuto(); Selection.setBgOpacity(1,0,1); $img2.hide(); setBgColor(options.shadeColor||options.bgColor,1); if (Selection.isAwake()) { setOpacity(options.bgOpacity,1); } else setOpacity(1,1); } } function setBgColor(color,now) { colorChangeMacro(getShades(),color,now); } function disableShade() { if (enabled) { holder.remove(); $img2.show(); enabled = false; if (Selection.isAwake()) { Selection.setBgOpacity(options.bgOpacity,1,1); } else { Selection.setBgOpacity(1,1,1); Selection.disableHandles(); } colorChangeMacro($div,0,1); } } function setOpacity(opacity,now) { if (enabled) { if (options.bgFade && !now) { holder.animate({ opacity: 1-opacity },{ queue: false, duration: options.fadeTime }); } else holder.css({opacity:1-opacity}); } } function refreshAll() { options.shade ? enableShade() : disableShade(); if (Selection.isAwake()) setOpacity(options.bgOpacity); } function getShades() { return holder.children(); } return { update: updateAuto, updateRaw: updateShade, getShades: getShades, setBgColor: setBgColor, enable: enableShade, disable: disableShade, resize: resizeShades, refresh: refreshAll, opacity: setOpacity }; }()); // }}} // Selection Module {{{ var Selection = (function () { var awake, hdep = 370, borders = {}, handle = {}, dragbar = {}, seehandles = false; // Private Methods function insertBorder(type) //{{{ { var jq = $('<div />').css({ position: 'absolute', opacity: options.borderOpacity }).addClass(cssClass(type)); $img_holder.append(jq); return jq; } //}}} function dragDiv(ord, zi) //{{{ { var jq = $('<div />').mousedown(createDragger(ord)).css({ cursor: ord + '-resize', position: 'absolute', zIndex: zi }).addClass('ord-'+ord); if (Touch.support) { jq.bind('touchstart.jcrop', Touch.createDragger(ord)); } $hdl_holder.append(jq); return jq; } //}}} function insertHandle(ord) //{{{ { var hs = options.handleSize, div = dragDiv(ord, hdep++).css({ opacity: options.handleOpacity }).addClass(cssClass('handle')); if (hs) { div.width(hs).height(hs); } return div; } //}}} function insertDragbar(ord) //{{{ { return dragDiv(ord, hdep++).addClass('jcrop-dragbar'); } //}}} function createDragbars(li) //{{{ { var i; for (i = 0; i < li.length; i++) { dragbar[li[i]] = insertDragbar(li[i]); } } //}}} function createBorders(li) //{{{ { var cl,i; for (i = 0; i < li.length; i++) { switch(li[i]){ case'n': cl='hline'; break; case's': cl='hline bottom'; break; case'e': cl='vline right'; break; case'w': cl='vline'; break; } borders[li[i]] = insertBorder(cl); } } //}}} function createHandles(li) //{{{ { var i; for (i = 0; i < li.length; i++) { handle[li[i]] = insertHandle(li[i]); } } //}}} function moveto(x, y) //{{{ { if (!options.shade) { $img2.css({ top: px(-y), left: px(-x) }); } $sel.css({ top: px(y), left: px(x) }); } //}}} function resize(w, h) //{{{ { $sel.width(Math.round(w)).height(Math.round(h)); } //}}} function refresh() //{{{ { var c = Coords.getFixed(); Coords.setPressed([c.x, c.y]); Coords.setCurrent([c.x2, c.y2]); updateVisible(); } //}}} // Internal Methods function updateVisible(select) //{{{ { if (awake) { return update(select); } } //}}} function update(select) //{{{ { var c = Coords.getFixed(); resize(c.w, c.h); moveto(c.x, c.y); if (options.shade) Shade.updateRaw(c); awake || show(); if (select) { options.onSelect.call(api, unscale(c)); } else { options.onChange.call(api, unscale(c)); } } //}}} function setBgOpacity(opacity,force,now) //{{{ { if (!awake && !force) return; if (options.bgFade && !now) { $img.animate({ opacity: opacity },{ queue: false, duration: options.fadeTime }); } else { $img.css('opacity', opacity); } } //}}} function show() //{{{ { $sel.show(); if (options.shade) Shade.opacity(bgopacity); else setBgOpacity(bgopacity,true); awake = true; } //}}} function release() //{{{ { disableHandles(); $sel.hide(); if (options.shade) Shade.opacity(1); else setBgOpacity(1); awake = false; options.onRelease.call(api); } //}}} function showHandles() //{{{ { if (seehandles) { $hdl_holder.show(); } } //}}} function enableHandles() //{{{ { seehandles = true; if (options.allowResize) { $hdl_holder.show(); return true; } } //}}} function disableHandles() //{{{ { seehandles = false; $hdl_holder.hide(); } //}}} function animMode(v) //{{{ { if (v) { animating = true; disableHandles(); } else { animating = false; enableHandles(); } } //}}} function done() //{{{ { animMode(false); refresh(); } //}}} // Insert draggable elements {{{ // Insert border divs for outline if (options.dragEdges && $.isArray(options.createDragbars)) createDragbars(options.createDragbars); if ($.isArray(options.createHandles)) createHandles(options.createHandles); if (options.drawBorders && $.isArray(options.createBorders)) createBorders(options.createBorders); //}}} // This is a hack for iOS5 to support drag/move touch functionality $(document).bind('touchstart.jcrop-ios',function(e) { if ($(e.currentTarget).hasClass('jcrop-tracker')) e.stopPropagation(); }); var $track = newTracker().mousedown(createDragger('move')).css({ cursor: 'move', position: 'absolute', zIndex: 360 }); if (Touch.support) { $track.bind('touchstart.jcrop', Touch.createDragger('move')); } $img_holder.append($track); disableHandles(); return { updateVisible: updateVisible, update: update, release: release, refresh: refresh, isAwake: function () { return awake; }, setCursor: function (cursor) { $track.css('cursor', cursor); }, enableHandles: enableHandles, enableOnly: function () { seehandles = true; }, showHandles: showHandles, disableHandles: disableHandles, animMode: animMode, setBgOpacity: setBgOpacity, done: done }; }()); //}}} // Tracker Module {{{ var Tracker = (function () { var onMove = function () {}, onDone = function () {}, trackDoc = options.trackDocument; function toFront(touch) //{{{ { $trk.css({ zIndex: 450 }); if (touch) $(document) .bind('touchmove.jcrop', trackTouchMove) .bind('touchend.jcrop', trackTouchEnd); else if (trackDoc) $(document) .bind('mousemove.jcrop',trackMove) .bind('mouseup.jcrop',trackUp); } //}}} function toBack() //{{{ { $trk.css({ zIndex: 290 }); $(document).unbind('.jcrop'); } //}}} function trackMove(e) //{{{ { onMove(mouseAbs(e)); return false; } //}}} function trackUp(e) //{{{ { e.preventDefault(); e.stopPropagation(); if (btndown) { btndown = false; onDone(mouseAbs(e)); if (Selection.isAwake()) { options.onSelect.call(api, unscale(Coords.getFixed())); } toBack(); onMove = function () {}; onDone = function () {}; } return false; } //}}} function activateHandlers(move, done, touch) //{{{ { btndown = true; onMove = move; onDone = done; toFront(touch); return false; } //}}} function trackTouchMove(e) //{{{ { onMove(mouseAbs(Touch.cfilter(e))); return false; } //}}} function trackTouchEnd(e) //{{{ { return trackUp(Touch.cfilter(e)); } //}}} function setCursor(t) //{{{ { $trk.css('cursor', t); } //}}} if (!trackDoc) { $trk.mousemove(trackMove).mouseup(trackUp).mouseout(trackUp); } $img.before($trk); return { activateHandlers: activateHandlers, setCursor: setCursor }; }()); //}}} // KeyManager Module {{{ var KeyManager = (function () { var $keymgr = $('<input type="radio" />').css({ position: 'fixed', left: '-120px', width: '12px' }).addClass('jcrop-keymgr'), $keywrap = $('<div />').css({ position: 'absolute', overflow: 'hidden' }).append($keymgr); function watchKeys() //{{{ { if (options.keySupport) { $keymgr.show(); $keymgr.focus(); } } //}}} function onBlur(e) //{{{ { $keymgr.hide(); } //}}} function doNudge(e, x, y) //{{{ { if (options.allowMove) { Coords.moveOffset([x, y]); Selection.updateVisible(true); } e.preventDefault(); e.stopPropagation(); } //}}} function parseKey(e) //{{{ { if (e.ctrlKey || e.metaKey) { return true; } shift_down = e.shiftKey ? true : false; var nudge = shift_down ? 10 : 1; switch (e.keyCode) { case 37: doNudge(e, -nudge, 0); break; case 39: doNudge(e, nudge, 0); break; case 38: doNudge(e, 0, -nudge); break; case 40: doNudge(e, 0, nudge); break; case 27: if (options.allowSelect) Selection.release(); break; case 9: return true; } return false; } //}}} if (options.keySupport) { $keymgr.keydown(parseKey).blur(onBlur); if (ie6mode || !options.fixedSupport) { $keymgr.css({ position: 'absolute', left: '-20px' }); $keywrap.append($keymgr).insertBefore($img); } else { $keymgr.insertBefore($img); } } return { watchKeys: watchKeys }; }()); //}}} // }}} // API methods {{{ function setClass(cname) //{{{ { $div.removeClass().addClass(cssClass('holder')).addClass(cname); } //}}} function animateTo(a, callback) //{{{ { var x1 = a[0] / xscale, y1 = a[1] / yscale, x2 = a[2] / xscale, y2 = a[3] / yscale; if (animating) { return; } var animto = Coords.flipCoords(x1, y1, x2, y2), c = Coords.getFixed(), initcr = [c.x, c.y, c.x2, c.y2], animat = initcr, interv = options.animationDelay, ix1 = animto[0] - initcr[0], iy1 = animto[1] - initcr[1], ix2 = animto[2] - initcr[2], iy2 = animto[3] - initcr[3], pcent = 0, velocity = options.swingSpeed; x1 = animat[0]; y1 = animat[1]; x2 = animat[2]; y2 = animat[3]; Selection.animMode(true); var anim_timer; function queueAnimator() { window.setTimeout(animator, interv); } var animator = (function () { return function () { pcent += (100 - pcent) / velocity; animat[0] = Math.round(x1 + ((pcent / 100) * ix1)); animat[1] = Math.round(y1 + ((pcent / 100) * iy1)); animat[2] = Math.round(x2 + ((pcent / 100) * ix2)); animat[3] = Math.round(y2 + ((pcent / 100) * iy2)); if (pcent >= 99.8) { pcent = 100; } if (pcent < 100) { setSelectRaw(animat); queueAnimator(); } else { Selection.done(); Selection.animMode(false); if (typeof(callback) === 'function') { callback.call(api); } } }; }()); queueAnimator(); } //}}} function setSelect(rect) //{{{ { setSelectRaw([rect[0] / xscale, rect[1] / yscale, rect[2] / xscale, rect[3] / yscale]); options.onSelect.call(api, unscale(Coords.getFixed())); Selection.enableHandles(); } //}}} function setSelectRaw(l) //{{{ { Coords.setPressed([l[0], l[1]]); Coords.setCurrent([l[2], l[3]]); Selection.update(); } //}}} function tellSelect() //{{{ { return unscale(Coords.getFixed()); } //}}} function tellScaled() //{{{ { return Coords.getFixed(); } //}}} function setOptionsNew(opt) //{{{ { setOptions(opt); interfaceUpdate(); } //}}} function disableCrop() //{{{ { options.disabled = true; Selection.disableHandles(); Selection.setCursor('default'); Tracker.setCursor('default'); } //}}} function enableCrop() //{{{ { options.disabled = false; interfaceUpdate(); } //}}} function cancelCrop() //{{{ { Selection.done(); Tracker.activateHandlers(null, null); } //}}} function destroy() //{{{ { $div.remove(); $origimg.show(); $origimg.css('visibility','visible'); $(obj).removeData('Jcrop'); } //}}} function setImage(src, callback) //{{{ { Selection.release(); disableCrop(); var img = new Image(); img.onload = function () { var iw = img.width; var ih = img.height; var bw = options.boxWidth; var bh = options.boxHeight; $img.width(iw).height(ih); $img.attr('src', src); $img2.attr('src', src); presize($img, bw, bh); boundx = $img.width(); boundy = $img.height(); $img2.width(boundx).height(boundy); $trk.width(boundx + (bound * 2)).height(boundy + (bound * 2)); $div.width(boundx).height(boundy); Shade.resize(boundx,boundy); enableCrop(); if (typeof(callback) === 'function') { callback.call(api); } }; img.src = src; } //}}} function colorChangeMacro($obj,color,now) { var mycolor = color || options.bgColor; if (options.bgFade && supportsColorFade() && options.fadeTime && !now) { $obj.animate({ backgroundColor: mycolor }, { queue: false, duration: options.fadeTime }); } else { $obj.css('backgroundColor', mycolor); } } function interfaceUpdate(alt) //{{{ // This method tweaks the interface based on options object. // Called when options are changed and at end of initialization. { if (options.allowResize) { if (alt) { Selection.enableOnly(); } else { Selection.enableHandles(); } } else { Selection.disableHandles(); } Tracker.setCursor(options.allowSelect ? 'crosshair' : 'default'); Selection.setCursor(options.allowMove ? 'move' : 'default'); if (options.hasOwnProperty('trueSize')) { xscale = options.trueSize[0] / boundx; yscale = options.trueSize[1] / boundy; } if (options.hasOwnProperty('setSelect')) { setSelect(options.setSelect); Selection.done(); delete(options.setSelect); } Shade.refresh(); if (options.bgColor != bgcolor) { colorChangeMacro( options.shade? Shade.getShades(): $div, options.shade? (options.shadeColor || options.bgColor): options.bgColor ); bgcolor = options.bgColor; } if (bgopacity != options.bgOpacity) { bgopacity = options.bgOpacity; if (options.shade) Shade.refresh(); else Selection.setBgOpacity(bgopacity); } xlimit = options.maxSize[0] || 0; ylimit = options.maxSize[1] || 0; xmin = options.minSize[0] || 0; ymin = options.minSize[1] || 0; if (options.hasOwnProperty('outerImage')) { $img.attr('src', options.outerImage); delete(options.outerImage); } Selection.refresh(); } //}}} //}}} if (Touch.support) $trk.bind('touchstart.jcrop', Touch.newSelection); $hdl_holder.hide(); interfaceUpdate(true); var api = { setImage: setImage, animateTo: animateTo, setSelect: setSelect, setOptions: setOptionsNew, tellSelect: tellSelect, tellScaled: tellScaled, setClass: setClass, disable: disableCrop, enable: enableCrop, cancel: cancelCrop, release: Selection.release, destroy: destroy, focus: KeyManager.watchKeys, getBounds: function () { return [boundx * xscale, boundy * yscale]; }, getWidgetSize: function () { return [boundx, boundy]; }, getScaleFactor: function () { return [xscale, yscale]; }, getOptions: function() { // careful: internal values are returned return options; }, ui: { holder: $div, selection: $sel } }; if (is_msie) $div.bind('selectstart', function () { return false; }); $origimg.data('Jcrop', api); return api; }; $.fn.Jcrop = function (options, callback) //{{{ { var api; // Iterate over each object, attach Jcrop this.each(function () { // If we've already attached to this object if ($(this).data('Jcrop')) { // The API can be requested this way (undocumented) if (options === 'api') return $(this).data('Jcrop'); // Otherwise, we just reset the options... else $(this).data('Jcrop').setOptions(options); } // If we haven't been attached, preload and attach else { if (this.tagName == 'IMG') $.Jcrop.Loader(this,function(){ $(this).css({display:'block',visibility:'hidden'}); api = $.Jcrop(this, options); if ($.isFunction(callback)) callback.call(api); }); else { $(this).css({display:'block',visibility:'hidden'}); api = $.Jcrop(this, options); if ($.isFunction(callback)) callback.call(api); } } }); // Return "this" so the object is chainable (jQuery-style) return this; }; //}}} // $.Jcrop.Loader - basic image loader {{{ $.Jcrop.Loader = function(imgobj,success,error){ var $img = $(imgobj), img = $img[0]; function completeCheck(){ if (img.complete) { $img.unbind('.jcloader'); if ($.isFunction(success)) success.call(img); } else window.setTimeout(completeCheck,50); } $img .bind('load.jcloader',completeCheck) .bind('error.jcloader',function(e){ $img.unbind('.jcloader'); if ($.isFunction(error)) error.call(img); }); if (img.complete && $.isFunction(success)){ $img.unbind('.jcloader'); success.call(img); } }; //}}} // Global Defaults {{{ $.Jcrop.defaults = { // Basic Settings allowSelect: true, allowMove: true, allowResize: true, trackDocument: true, // Styling Options baseClass: 'jcrop', addClass: null, bgColor: 'black', bgOpacity: 0.6, bgFade: false, borderOpacity: 0.4, handleOpacity: 0.5, handleSize: null, aspectRatio: 0, keySupport: true, createHandles: ['n','s','e','w','nw','ne','se','sw'], createDragbars: ['n','s','e','w'], createBorders: ['n','s','e','w'], drawBorders: true, dragEdges: true, fixedSupport: true, touchSupport: null, shade: null, boxWidth: 0, boxHeight: 0, boundary: 2, fadeTime: 400, animationDelay: 20, swingSpeed: 3, minSelect: [0, 0], maxSize: [0, 0], minSize: [0, 0], // Callbacks / Event Handlers onChange: function () {}, onSelect: function () {}, onDblClick: function () {}, onRelease: function () {} }; // }}} }(jQuery));
JavaScript
/*! * jQuery Color Animations v2.0pre * http://jquery.org/ * * Copyright 2011 John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( jQuery, undefined ){ var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color outlineColor".split(" "), // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [{ re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ 2.55 * execResult[1], 2.55 * execResult[2], 2.55 * execResult[3], execResult[ 4 ] ]; } }, { re: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { re: /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[1], execResult[2] / 100, execResult[3] / 100, execResult[4] ]; } }], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { cache: "_rgba", props: { red: { idx: 0, type: "byte", empty: true }, green: { idx: 1, type: "byte", empty: true }, blue: { idx: 2, type: "byte", empty: true }, alpha: { idx: 3, type: "percent", def: 1 } } }, hsla: { cache: "_hsla", props: { hue: { idx: 0, type: "degrees", empty: true }, saturation: { idx: 1, type: "percent", empty: true }, lightness: { idx: 2, type: "percent", empty: true } } } }, propTypes = { "byte": { floor: true, min: 0, max: 255 }, "percent": { min: 0, max: 1 }, "degrees": { mod: 360, floor: true } }, rgbaspace = spaces.rgba.props, support = color.support = {}, // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; spaces.hsla.props.alpha = rgbaspace.alpha; function clamp( value, prop, alwaysAllowEmpty ) { var type = propTypes[ prop.type ] || {}, allowEmpty = prop.empty || alwaysAllowEmpty; if ( allowEmpty && value == null ) { return null; } if ( prop.def && value == null ) { return prop.def; } if ( type.floor ) { value = ~~value; } else { value = parseFloat( value ); } if ( value == null || isNaN( value ) ) { return prop.def; } if ( type.mod ) { value = value % type.mod; // -10 -> 350 return value < 0 ? type.mod + value : value; } // for now all property types without mod have min and max return type.min > value ? type.min : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var match = parser.re.exec( string ), values = match && parser.parse( match ), parsed, spaceName = parser.space || "rgba", cache = spaces[ spaceName ].cache; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ cache ] = parsed[ cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length !== 0 ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( Math.max.apply( Math, rgba ) === 0 ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors / default - filter back through parse function if ( string = colors[ string ] ) { return string; } } color.fn = color.prototype = { constructor: color, parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red instanceof jQuery || red.nodeType ) { red = red instanceof jQuery ? red.css( green ) : jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = [], source; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( rgbaspace, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { each( space.props, function( key, prop ) { var cache = space.cache; // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( red[ key ] == null || key === "alpha") { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, myself = this; each( spaces, function( _, space ) { var isCache = is[ space.cache ], localCache; if (isCache) { localCache = myself[ space.cache ] || space.to && space.to( myself._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], start = this[ space.cache ] || space.to( this._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ prop.idx ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join(",") + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join(",") + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v, i ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }; color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // http://www.google.com/codesearch/p#OAMlx_jo-ck/src/third_party/WebKit/Source/WebCore/inspector/front-end/Color.js&d=7&l=193 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + (q - p) * 6 * h; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + (q - p) * ((2/3) - h) * 6; } return p; } spaces.hsla.to = function ( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } if ( l === 0 || l === 1 ) { s = l; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function ( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q, r, g, b; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(), ret; each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === 'alpha' ? ( this._hsla ? 'hsla' : 'rgba' ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add .fx.step functions each( stepHooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, backgroundColor, curElem; if ( jQuery.type( value ) !== 'string' || ( parsed = stringParse( value ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; do { backgroundColor = jQuery.curCSS( curElem, "backgroundColor" ); } while ( ( backgroundColor === "" || backgroundColor === "transparent" ) && ( curElem = curElem.parentNode ) && curElem.style ); value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } elem.style[ hook ] = value; } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); // detect rgba support jQuery(function() { var div = document.createElement( "div" ), div_style = div.style; div_style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = div_style.backgroundColor.indexOf( "rgba" ) > -1; }); // Some named colors to work with // From Interface by Stefan Petre // http://interface.eyecon.ro/ colors = jQuery.Color.names = { aqua: "#00ffff", azure: "#f0ffff", beige: "#f5f5dc", black: "#000000", blue: "#0000ff", brown: "#a52a2a", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgrey: "#a9a9a9", darkgreen: "#006400", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkviolet: "#9400d3", fuchsia: "#ff00ff", gold: "#ffd700", green: "#008000", indigo: "#4b0082", khaki: "#f0e68c", lightblue: "#add8e6", lightcyan: "#e0ffff", lightgreen: "#90ee90", lightgrey: "#d3d3d3", lightpink: "#ffb6c1", lightyellow: "#ffffe0", lime: "#00ff00", magenta: "#ff00ff", maroon: "#800000", navy: "#000080", olive: "#808000", orange: "#ffa500", pink: "#ffc0cb", purple: "#800080", violet: "#800080", red: "#ff0000", silver: "#c0c0c0", white: "#ffffff", yellow: "#ffff00", transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery );
JavaScript
/** Address editable input. Internally value stored as {city: "Moscow", street: "Lenina", building: "15"} @class address @extends abstractinput @final @example <a href="#" id="address" data-type="address" data-pk="1">awesome</a> <script> $(function(){ $('#address').editable({ url: '/post', title: 'Enter city, street and building #', value: { city: "Moscow", street: "Lenina", building: "15" } }); }); </script> **/ (function ($) { "use strict"; var Address = function (options) { this.init('address', options, Address.defaults); }; //inherit from Abstract input $.fn.editableutils.inherit(Address, $.fn.editabletypes.abstractinput); $.extend(Address.prototype, { /** Renders input from tpl @method render() **/ render: function() { this.$input = this.$tpl.find('input'); }, /** Default method to show value in element. Can be overwritten by display option. @method value2html(value, element) **/ value2html: function(value, element) { if(!value) { $(element).empty(); return; } var html = $('<div>').text(value.city).html() + ', ' + $('<div>').text(value.street).html() + ' st., bld. ' + $('<div>').text(value.building).html(); $(element).html(html); }, /** Gets value from element's html @method html2value(html) **/ html2value: function(html) { /* you may write parsing method to get value by element's html e.g. "Moscow, st. Lenina, bld. 15" => {city: "Moscow", street: "Lenina", building: "15"} but for complex structures it's not recommended. Better set value directly via javascript, e.g. editable({ value: { city: "Moscow", street: "Lenina", building: "15" } }); */ return null; }, /** Converts value to string. It is used in internal comparing (not for sending to server). @method value2str(value) **/ value2str: function(value) { var str = ''; if(value) { for(var k in value) { str = str + k + ':' + value[k] + ';'; } } return str; }, /* Converts string to value. Used for reading value from 'data-value' attribute. @method str2value(str) */ str2value: function(str) { /* this is mainly for parsing value defined in data-value attribute. If you will always set value by javascript, no need to overwrite it */ return str; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function(value) { if(!value) { return; } this.$input.filter('[name="city"]').val(value.city); this.$input.filter('[name="street"]').val(value.street); this.$input.filter('[name="building"]').val(value.building); }, /** Returns value of input. @method input2value() **/ input2value: function() { return { city: this.$input.filter('[name="city"]').val(), street: this.$input.filter('[name="street"]').val(), building: this.$input.filter('[name="building"]').val() }; }, /** Activates input: sets focus on the first field. @method activate() **/ activate: function() { this.$input.filter('[name="city"]').focus(); }, /** Attaches handler to submit form in case of 'showbuttons=false' mode @method autosubmit() **/ autosubmit: function() { this.$input.keydown(function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); } }); Address.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { tpl: '<div class="editable-address"><label><span>City: </span><input type="text" name="city" class="form-control input-small"></label></div>'+ '<div class="editable-address"><label><span>Street: </span><input type="text" name="street" class="form-control input-small"></label></div>'+ '<div class="editable-address"><label><span>Building: </span><input type="text" name="building" class="form-control input-small"></label></div>', inputclass: '' }); $.fn.editabletypes.address = Address; }(window.jQuery));
JavaScript
/** Bootstrap wysihtml5 editor. Based on [bootstrap-wysihtml5](https://github.com/jhollingworth/bootstrap-wysihtml5). You should include **manually** distributives of `wysihtml5` and `bootstrap-wysihtml5`: <link href="js/inputs-ext/wysihtml5/bootstrap-wysihtml5-0.0.2/bootstrap-wysihtml5-0.0.2.css" rel="stylesheet" type="text/css"></link> <script src="js/inputs-ext/wysihtml5/bootstrap-wysihtml5-0.0.2/wysihtml5-0.3.0.min.js"></script> <script src="js/inputs-ext/wysihtml5/bootstrap-wysihtml5-0.0.2/bootstrap-wysihtml5-0.0.2.min.js"></script> And also include `wysihtml5.js` from `inputs-ext` directory of x-editable: <script src="js/inputs-ext/wysihtml5/wysihtml5.js"></script> **Note:** It's better to use fresh bootstrap-wysihtml5 from it's [master branch](https://github.com/jhollingworth/bootstrap-wysihtml5/tree/master/src) as there is update for correct image insertion. @class wysihtml5 @extends abstractinput @final @since 1.4.0 @example <div id="comments" data-type="wysihtml5" data-pk="1"><h2>awesome</h2> comment!</div> <script> $(function(){ $('#comments').editable({ url: '/post', title: 'Enter comments' }); }); </script> **/ (function ($) { "use strict"; var Wysihtml5 = function (options) { this.init('wysihtml5', options, Wysihtml5.defaults); //extend wysihtml5 manually as $.extend not recursive this.options.wysihtml5 = $.extend({}, Wysihtml5.defaults.wysihtml5, options.wysihtml5); }; $.fn.editableutils.inherit(Wysihtml5, $.fn.editabletypes.abstractinput); $.extend(Wysihtml5.prototype, { render: function () { var deferred = $.Deferred(), msieOld; //generate unique id as it required for wysihtml5 this.$input.attr('id', 'textarea_'+(new Date()).getTime()); this.setClass(); this.setAttr('placeholder'); //resolve deffered when widget loaded $.extend(this.options.wysihtml5, { events: { load: function() { deferred.resolve(); } } }); this.$input.wysihtml5(this.options.wysihtml5); /* In IE8 wysihtml5 iframe stays on the same line with buttons toolbar (inside popover). The only solution I found is to add <br>. If you fine better way, please send PR. */ msieOld = /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase()); if(msieOld) { this.$input.before('<br><br>'); } return deferred.promise(); }, value2html: function(value, element) { $(element).html(value); }, html2value: function(html) { return html; }, value2input: function(value) { this.$input.data("wysihtml5").editor.setValue(value, true); }, activate: function() { this.$input.data("wysihtml5").editor.focus(); } }); Wysihtml5.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <textarea></textarea> **/ tpl:'<textarea></textarea>', /** @property inputclass @default editable-wysihtml5 **/ inputclass: 'editable-wysihtml5', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Wysihtml5 default options. See https://github.com/jhollingworth/bootstrap-wysihtml5#options @property wysihtml5 @type object @default {stylesheets: false} **/ wysihtml5: { stylesheets: false //see https://github.com/jhollingworth/bootstrap-wysihtml5/issues/183 } }); $.fn.editabletypes.wysihtml5 = Wysihtml5; }(window.jQuery));
JavaScript
/*! * FullCalendar v1.6.1 Google Calendar Plugin * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function($) { var fc = $.fullCalendar; var formatDate = fc.formatDate; var parseISO8601 = fc.parseISO8601; var addDays = fc.addDays; var applyAll = fc.applyAll; fc.sourceNormalizers.push(function(sourceOptions) { if (sourceOptions.dataType == 'gcal' || sourceOptions.dataType === undefined && (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) { sourceOptions.dataType = 'gcal'; if (sourceOptions.editable === undefined) { sourceOptions.editable = false; } } }); fc.sourceFetchers.push(function(sourceOptions, start, end) { if (sourceOptions.dataType == 'gcal') { return transformOptions(sourceOptions, start, end); } }); function transformOptions(sourceOptions, start, end) { var success = sourceOptions.success; var data = $.extend({}, sourceOptions.data || {}, { 'start-min': formatDate(start, 'u'), 'start-max': formatDate(end, 'u'), 'singleevents': true, 'max-results': 9999 }); var ctz = sourceOptions.currentTimezone; if (ctz) { data.ctz = ctz = ctz.replace(' ', '_'); } return $.extend({}, sourceOptions, { url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?', dataType: 'jsonp', data: data, startParam: false, endParam: false, success: function(data) { var events = []; if (data.feed.entry) { $.each(data.feed.entry, function(i, entry) { var startStr = entry['gd$when'][0]['startTime']; var start = parseISO8601(startStr, true); var end = parseISO8601(entry['gd$when'][0]['endTime'], true); var allDay = startStr.indexOf('T') == -1; var url; $.each(entry.link, function(i, link) { if (link.type == 'text/html') { url = link.href; if (ctz) { url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz; } } }); if (allDay) { addDays(end, -1); // make inclusive } events.push({ id: entry['gCal$uid']['value'], title: entry['title']['$t'], url: url, start: start, end: end, allDay: allDay, location: entry['gd$where'][0]['valueString'], description: entry['content']['$t'] }); }); } var args = [events].concat(Array.prototype.slice.call(arguments, 1)); var res = applyAll(success, this, args); if ($.isArray(res)) { return res; } return events; } }); } // legacy fc.gcalFeed = function(url, sourceOptions) { return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); }; })(jQuery);
JavaScript
/*! * FullCalendar v1.6.1 * 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]{ '&#8212;'[ 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'>&lsaquo;</span>", next: "<span class='fc-text-arrow'>&rsaquo;</span>", prevYear: "<span class='fc-text-arrow'>&laquo;</span>", nextYear: "<span class='fc-text-arrow'>&raquo;</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: '*' }; // right-to-left defaults var rtlDefaults = { header: { left: 'next,prev today', center: '', right: 'title' }, buttonText: { prev: "<span class='fc-text-arrow'>&rsaquo;</span>", next: "<span class='fc-text-arrow'>&lsaquo;</span>", prevYear: "<span class='fc-text-arrow'>&raquo;</span>", nextYear: "<span class='fc-text-arrow'>&laquo;</span>" }, buttonIcons: { prev: 'circle-triangle-e', next: 'circle-triangle-w' } }; ;; var fc = $.fullCalendar = { version: "1.6.1" }; 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; } // 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 viewInstances = {}; var elementOuterWidth; var suggestedViewHeight; var absoluteViewElement; 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{ calcSize(); markSizesDirty(); markEventsDirty(); 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); $(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() { $(window).unbind('resize', windowResize); header.destroy(); content.remove(); element.removeClass('fc fc-rtl ui-widget'); } function elementVisible() { return _element.offsetWidth !== 0; } function bodyVisible() { return $('body')[0].offsetWidth !== 0; } /* View Rendering -----------------------------------------------------------------------------*/ // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) function changeView(newViewName) { if (!currentView || newViewName != currentView.name) { ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached unselect(); var oldView = currentView; var newViewElement; if (oldView) { (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) setMinHeight(content, content.height()); oldView.element.hide(); }else{ setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated } content.css('overflow', 'hidden'); currentView = viewInstances[newViewName]; if (currentView) { currentView.element.show(); }else{ currentView = viewInstances[newViewName] = new fcViews[newViewName]( newViewElement = absoluteViewElement = $("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>") .appendTo(content), t // the calendar object ); } if (oldView) { header.deactivateButton(oldView.name); } header.activateButton(newViewName); renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null content.css('overflow', ''); if (oldView) { setMinHeight(content, 1); } if (!newViewElement) { (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) } ignoreWindowResize--; } } function renderView(inc) { if (elementVisible()) { ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached unselect(); if (suggestedViewHeight === undefined) { calcSize(); } var forceEventRender = false; if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { // view must render an entire new date range (and refetch/render events) currentView.render(date, inc || 0); // responsible for clearing events setSize(true); forceEventRender = true; } else if (currentView.sizeDirty) { // view must resize (and rerender events) currentView.clearEvents(); setSize(); forceEventRender = true; } else if (currentView.eventsDirty) { currentView.clearEvents(); forceEventRender = true; } currentView.sizeDirty = false; currentView.eventsDirty = false; updateEvents(forceEventRender); elementOuterWidth = element.outerWidth(); header.updateTitle(currentView.title); var today = new Date(); if (today >= currentView.start && today < currentView.end) { header.disableButton('today'); }else{ header.enableButton('today'); } ignoreWindowResize--; currentView.trigger('viewDisplay', _element); } } /* Resizing -----------------------------------------------------------------------------*/ function updateSize() { markSizesDirty(); if (elementVisible()) { calcSize(); setSize(); unselect(); currentView.clearEvents(); currentView.renderEvents(events); currentView.sizeDirty = false; } } function markSizesDirty() { $.each(viewInstances, function(i, inst) { inst.sizeDirty = true; }); } function calcSize() { 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(dateChanged) { // todo: dateChanged? ignoreWindowResize++; currentView.setHeight(suggestedViewHeight, dateChanged); if (absoluteViewElement) { absoluteViewElement.css('position', 'relative'); absoluteViewElement = null; } currentView.setWidth(content.width(), dateChanged); ignoreWindowResize--; } 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 -----------------------------------------------------------------------------*/ // fetches events if necessary, rerenders events if necessary (or if forced) function updateEvents(forceRender) { if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { refetchEvents(); } else if (forceRender) { rerenderEvents(); } } function refetchEvents() { fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents } // called when event data arrives function reportEvents(_events) { events = _events; rerenderEvents(); } // called when a single event's data has been changed function reportEventChange(eventID) { rerenderEvents(eventID); } // attempts to rerenderEvents function rerenderEvents(modifiedEventID) { markEventsDirty(); if (elementVisible()) { currentView.clearEvents(); currentView.renderEvents(events, modifiedEventID); currentView.eventsDirty = false; } } function markEventsDirty() { $.each(viewInstances, function(i, inst) { inst.eventsDirty = true; }); } /* 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); } /* 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>&nbsp;</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; // 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; var data = $.extend({}, source.data || {}); 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.backgroudColor = event.backgroudColor; 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); } } function popLoading() { if (!--loadingLevel) { trigger('loading', null, false); } } /* 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.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; } } ;; 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 skipWeekend(date, inc, excl) { inc = inc || 1; while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) { addDays(date, inc); } return date; } 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. * @param date Date - the date to get the week for * @return 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); } function segCmp(a, b) { return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start); } function segsCollide(seg1, seg2) { return seg1.end > seg2.start && seg1.start < seg2.end; } /* Event Sorting -----------------------------------------------------------------------------*/ // event rendering utilities function sliceSegs(events, visEventEnds, start, end) { 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]; if (eventEnd > start && eventStart < end) { 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, msLength: segEnd - segStart }); } } return segs.sort(segCmp); } // event rendering calculation utilities function stackSegs(segs) { var levels = [], i, len = segs.length, seg, j, collide, k; for (i=0; i<len; i++) { seg = segs[i]; j = 0; // the level index where seg should belong while (true) { collide = false; if (levels[j]) { for (k=0; k<levels[j].length; k++) { if (segsCollide(levels[j][k], seg)) { collide = true; break; } } } if (collide) { j++; }else{ break; } } if (levels[j]) { levels[j].push(seg); }else{ levels[j] = [seg]; } } return levels; } /* 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); } function setMinHeight(element, height) { height = (typeof height == 'number' ? height + 'px' : height); element.each(function(i, _element) { _element.style.cssText += ';min-height:' + height + ';_height:' + height; // why can't we just use .css() ? i forget }); } /* Misc Utils -----------------------------------------------------------------------------*/ //TODO: arraySlice //TODO: isFunction, grep ? function noop() { } function cmp(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, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/'/g, '&#039;') .replace(/"/g, '&quot;') .replace(/\n/g, '<br />'); } function cssKey(_element) { return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, ''); } 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 formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addMonths(date, delta); date.setDate(1); } var start = cloneDate(date, true); start.setDate(1); var end = addMonths(cloneDate(start), 1); var visStart = cloneDate(start); var visEnd = cloneDate(end); var firstDay = opt('firstDay'); var nwe = opt('weekends') ? 0 : 1; if (nwe) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } addDays(visStart, -((visStart.getDay() - Math.max(firstDay, nwe) + 7) % 7)); addDays(visEnd, (7 - visEnd.getDay() + Math.max(firstDay, nwe)) % 7); var rowCnt = Math.round((visEnd - visStart) / (DAY_MS * 7)); if (opt('weekMode') == 'fixed') { addDays(visEnd, (6 - rowCnt) * 7); rowCnt = 6; } t.title = formatDate(start, opt('titleFormat')); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderBasic(rowCnt, nwe ? 5 : 7, 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 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); var visEnd = cloneDate(end); var weekends = opt('weekends'); if (!weekends) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } t.title = formatDates( visStart, addDays(cloneDate(visEnd), -1), opt('titleFormat') ); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderBasic(1, weekends ? 7 : 5, false); } } ;; fcViews.basicDay = BasicDayView; //TODO: when calendar's date starts out on a weekend, shouldn't happen 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 formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addDays(date, delta); if (!opt('weekends')) { skipWeekend(date, delta < 0 ? -1 : 1); } } t.title = formatDate(date, opt('titleFormat')); t.start = t.visStart = cloneDate(date, true); t.end = t.visEnd = addDays(cloneDate(t.start), 1); 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.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.dayOfWeekCol = dayOfWeekCol; t.dateCell = dateCell; t.cellDate = cellDate; t.cellIsAllDay = function() { return true }; t.allDayRow = allDayRow; t.allDayBounds = allDayBounds; 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 clearEvents = t.clearEvents; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var daySelectionMousedown = t.daySelectionMousedown; var formatDate = calendar.formatDate; // locals var table; var head; var headCells; var body; var bodyRows; var bodyCells; var bodyFirstCells; var bodyCellTopInners; var daySegmentContainer; var viewWidth; var viewHeight; var colWidth; var weekNumberWidth; var rowCnt, colCnt; var coordinateGrid; var hoverListener; var colContentPositions; var rtl, dis, dit; var firstDay; var nwe; // no weekends? a 0 or 1 for easy computations var tm; var colFormat; var showWeekNumbers; var weekNumberTitle; var weekNumberFormat; /* Rendering ------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-grid')); function renderBasic(r, c, showNumbers) { rowCnt = r; colCnt = c; updateOptions(); var firstTime = !body; if (firstTime) { buildEventContainer(); }else{ clearEvents(); } buildTable(showNumbers); } function updateOptions() { rtl = opt('isRTL'); if (rtl) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } firstDay = opt('firstDay'); nwe = opt('weekends') ? 0 : 1; 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 style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(element); } function buildTable(showNumbers) { var html = ''; var i, j; var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var month = t.start.getMonth(); var today = clearTime(new Date()); var cellDate; // not to be confused with local function. TODO: better names var cellClasses; var cell; html += "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" + "<thead>" + "<tr>"; if (showWeekNumbers) { html += "<th class='fc-week-number " + headerClass + "'/>"; } for (i=0; i<colCnt; i++) { cellDate = _cellDate(0, i); // a little confusing. cellDate is local variable. _cellDate is private function html += "<th class='fc-day-header fc-" + dayIDs[cellDate.getDay()] + " " + headerClass + "'/>"; } html += "</tr>" + "</thead>" + "<tbody>"; for (i=0; i<rowCnt; i++) { html += "<tr class='fc-week'>"; if (showWeekNumbers) { html += "<td class='fc-week-number " + contentClass + "'>" + "<div/>" + "</td>"; } for (j=0; j<colCnt; j++) { cellDate = _cellDate(i, j); // a little confusing. cellDate is local variable. _cellDate is private function cellClasses = [ 'fc-day', 'fc-' + dayIDs[cellDate.getDay()], contentClass ]; if (cellDate.getMonth() != month) { cellClasses.push('fc-other-month'); } if (+cellDate == +today) { cellClasses.push('fc-today'); cellClasses.push(tm + '-state-highlight'); } html += "<td" + " class='" + cellClasses.join(' ') + "'" + " data-date='" + formatDate(cellDate, 'yyyy-MM-dd') + "'" + ">" + "<div>"; if (showNumbers) { html += "<div class='fc-day-number'>" + cellDate.getDate() + "</div>"; } html += "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; } html += "</tr>"; } html += "</tbody>" + "</table>"; lockHeight(); // the unlock happens later, in setHeight()... 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'); bodyCellTopInners = 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'); if (showWeekNumbers) { head.find('.fc-week-number').text(weekNumberTitle); } headCells.each(function(i, _cell) { var date = indexDate(i); $(_cell).text(formatDate(date, colFormat)); }); if (showWeekNumbers) { body.find('.fc-week-number > div').each(function(i, _cell) { var weekStart = _cellDate(i, 0); $(_cell).text(formatDate(weekStart, weekNumberFormat)); }); } bodyCells.each(function(i, _cell) { var date = indexDate(i); trigger('dayRender', t, date, $(_cell)); }); dayBind(bodyCells); } 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); setMinHeight( cell.find('> div'), (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) ); } }); unlockHeight(); } function setWidth(width) { viewWidth = width; 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 ------------------------------------------------------*/ function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var rowStart = cloneDate(t.visStart); var rowEnd = addDays(cloneDate(rowStart), colCnt); for (var i=0; i<rowCnt; i++) { var stretchStart = new Date(Math.max(rowStart, overlayStart)); var stretchEnd = new Date(Math.min(rowEnd, overlayEnd)); if (stretchStart < stretchEnd) { var colStart, colEnd; if (rtl) { colStart = dayDiff(stretchEnd, rowStart)*dis+dit+1; colEnd = dayDiff(stretchStart, rowStart)*dis+dit+1; }else{ colStart = dayDiff(stretchStart, rowStart); colEnd = dayDiff(stretchEnd, rowStart); } dayBind( renderCellOverlay(i, colStart, i, colEnd-1) ); } addDays(rowStart, 7); addDays(rowEnd, 7); } } 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 = dateCell(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 = cellDate(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); colContentPositions = new HorizontalPositionCache(function(col) { return bodyCellTopInners.eq(col); }); function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function dateCell(date) { return { row: Math.floor(dayDiff(date, t.visStart) / 7), col: dayOfWeekCol(date.getDay()) }; } function cellDate(cell) { return _cellDate(cell.row, cell.col); } function _cellDate(row, col) { return addDays(cloneDate(t.visStart), row*7 + col*dis+dit); // what about weekends in middle of week? } function indexDate(index) { return _cellDate(Math.floor(index/colCnt), index%colCnt); } function dayOfWeekCol(dayOfWeek) { return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt) * dis + dit; } function allDayRow(i) { return bodyRows.eq(i); } function allDayBounds(i) { var left = 0; if (showWeekNumbers) { left += weekNumberWidth; } return { left: left, right: viewWidth }; } // makes sure height doesn't collapse while we destroy/render new cells // (this causes a bad end-user scrollbar jump) // TODO: generalize this for all view rendering. (also in Calendar.js) function lockHeight() { setMinHeight(element, element.height()); } function unlockHeight() { setMinHeight(element, 1); } } ;; function BasicEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.compileDaySegs = compileSegs; // for DayEventRenderer t.clearEvents = clearEvents; t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var reportEvents = t.reportEvents; var reportEventClear = t.reportEventClear; var eventElementHandlers = t.eventElementHandlers; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var getDaySegmentContainer = t.getDaySegmentContainer; var getHoverListener = t.getHoverListener; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var renderDaySegs = t.renderDaySegs; var resizableDayEvent = t.resizableDayEvent; /* Rendering --------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { reportEvents(events); renderDaySegs(compileSegs(events), modifiedEventId); trigger('eventAfterAllRender'); } function clearEvents() { reportEventClear(); getDaySegmentContainer().empty(); } function compileSegs(events) { var rowCnt = getRowCnt(), colCnt = getColCnt(), d1 = cloneDate(t.visStart), d2 = addDays(cloneDate(d1), colCnt), visEventsEnds = $.map(events, exclEndDay), i, row, j, level, k, seg, segs=[]; for (i=0; i<rowCnt; i++) { row = stackSegs(sliceSegs(events, visEventsEnds, d1, d2)); for (j=0; j<row.length; j++) { level = row[j]; for (k=0; k<level.length; k++) { seg = level[k]; seg.row = i; seg.level = j; // not needed anymore segs.push(seg); } } addDays(d1, 7); addDays(d2, 7); } return segs; } function bindDaySeg(event, eventElement, seg) { if (isEventDraggable(event)) { draggableDayEvent(event, eventElement); } if (seg.isEnd && isEventResizable(event)) { resizableDayEvent(event, eventElement, seg); } eventElementHandlers(event, eventElement); // needs to be after, because resizableDayEvent might stopImmediatePropagation on click } /* Dragging ----------------------------------------------------------------------------*/ function draggableDayEvent(event, eventElement) { var hoverListener = getHoverListener(); var dayDelta; eventElement.draggable({ zIndex: 9, 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) { //setOverflowHidden(true); dayDelta = rowDelta*7 + colDelta * (opt('isRTL') ? -1 : 1); renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); }else{ //setOverflowHidden(false); 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); } //setOverflowHidden(false); } }); } } ;; 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 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); var visEnd = cloneDate(end); var weekends = opt('weekends'); if (!weekends) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } t.title = formatDates( visStart, addDays(cloneDate(visEnd), -1), opt('titleFormat') ); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderAgenda(weekends ? 7 : 5); } } ;; 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 formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addDays(date, delta); if (!opt('weekends')) { skipWeekend(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 }); // 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.beforeHide = beforeHide; t.afterShow = afterShow; t.defaultEventEnd = defaultEventEnd; t.timePosition = timePosition; t.dayOfWeekCol = dayOfWeekCol; t.dateCell = dateCell; t.cellDate = cellDate; t.cellIsAllDay = cellIsAllDay; t.allDayRow = getAllDayRow; t.allDayBounds = allDayBounds; t.getHoverListener = function() { return hoverListener }; 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.getBodyContent = function() { return slotContent }; // !!?? t.getRowCnt = function() { return 1 }; t.getColCnt = function() { return colCnt }; t.getColWidth = function() { return colWidth }; 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 clearEvents = t.clearEvents; 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 formatDate = calendar.formatDate; // locals var dayTable; var dayHead; var dayHeadCells; var dayBody; var dayBodyCells; var dayBodyCellInners; var dayBodyFirstCell; var dayBodyFirstCellStretcher; var slotLayer; var daySegmentContainer; var allDayTable; var allDayRow; var slotScroller; var slotContent; var slotSegmentContainer; var slotTable; var slotTableFirstInner; var axisFirstCells; var gutterCells; var selectionHelper; var viewWidth; var viewHeight; var axisWidth; var colWidth; 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 colContentPositions; var slotTopCache = {}; var savedScrollTop; var tm; var firstDay; var nwe; // no weekends (int) var rtl, dis, dit; // day index sign / translate var minMinute, maxMinute; var colFormat; var showWeekNumbers; var weekNumberTitle; var weekNumberFormat; /* Rendering -----------------------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-agenda')); function renderAgenda(c) { colCnt = c; updateOptions(); if (!dayTable) { buildSkeleton(); }else{ clearEvents(); } updateCells(); } function updateOptions() { tm = opt('theme') ? 'ui' : 'fc'; nwe = opt('weekends') ? 0 : 1; firstDay = opt('firstDay'); if (rtl = opt('isRTL')) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } 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'); if (opt('weekNumberCalculation') != 'iso') { weekNumberFormat = "w"; } else { weekNumberFormat = "W"; } snapMinutes = opt('snapMinutes') || opt('slotMinutes'); } function buildSkeleton() { var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var s; var i; var d; var maxd; var minutes; var slotNormal = opt('slotMinutes') % 15 == 0; s = "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" + "<thead>" + "<tr>"; if (showWeekNumbers) { s += "<th class='fc-agenda-axis fc-week-number " + headerClass + "'/>"; } else { s += "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; } for (i=0; i<colCnt; i++) { s += "<th class='fc- fc-col" + i + ' ' + headerClass + "'/>"; // fc- needed for setDayID } s += "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" + "</tr>" + "</thead>" + "<tbody>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; for (i=0; i<colCnt; i++) { s += "<td class='fc- fc-col" + i + ' ' + contentClass + "'>" + // fc- needed for setDayID "<div>" + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; } s += "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" + "</tr>" + "</tbody>" + "</table>"; dayTable = $(s).appendTo(element); dayHead = dayTable.find('thead'); dayHeadCells = dayHead.find('th').slice(1, -1); dayBody = dayTable.find('tbody'); dayBodyCells = dayBody.find('td').slice(0, -1); dayBodyCellInners = dayBodyCells.find('div.fc-day-content div'); dayBodyFirstCell = dayBodyCells.eq(0); dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div'); markFirstLast(dayHead.add(dayHead.find('tr'))); markFirstLast(dayBody.add(dayBody.find('tr'))); axisFirstCells = dayHead.find('th:first'); gutterCells = dayTable.find('.fc-agenda-gutter'); slotLayer = $("<div style='position:absolute;z-index:2;left:0;width:100%'/>") .appendTo(element); if (opt('allDaySlot')) { daySegmentContainer = $("<div 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'>&nbsp;</th>" + "</tr>" + "</table>"; allDayTable = $(s).appendTo(slotLayer); allDayRow = allDayTable.find('tr'); dayBind(allDayRow.find('td')); axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); 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); slotContent = $("<div style='position:relative;width:100%;overflow:hidden'/>") .appendTo(slotScroller); slotSegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotContent); 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')) : '&nbsp;') + "</th>" + "<td class='" + contentClass + "'>" + "<div style='position:relative'>&nbsp;</div>" + "</td>" + "</tr>"; addMinutes(d, opt('slotMinutes')); slotCnt++; } s += "</tbody>" + "</table>"; slotTable = $(s).appendTo(slotContent); slotTableFirstInner = slotTable.find('div:first'); slotBind(slotTable.find('td')); axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); } function updateCells() { var i; var headCell; var bodyCell; var date; var today = clearTime(new Date()); if (showWeekNumbers) { var weekText = formatDate(colDate(0), weekNumberFormat); if (rtl) { weekText = weekText + weekNumberTitle; } else { weekText = weekNumberTitle + weekText; } dayHead.find('.fc-week-number').text(weekText); } for (i=0; i<colCnt; i++) { date = colDate(i); headCell = dayHeadCells.eq(i); headCell.html(formatDate(date, colFormat)); bodyCell = dayBodyCells.eq(i); if (+date == +today) { bodyCell.addClass(tm + '-state-highlight fc-today'); }else{ bodyCell.removeClass(tm + '-state-highlight fc-today'); } setDayID(headCell.add(bodyCell), date); } } function setHeight(height, dateChanged) { 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); slotHeight = slotTableFirstInner.height() + 1; // +1 for border snapRatio = opt('slotMinutes') / snapMinutes; snapHeight = slotHeight / snapRatio; if (dateChanged) { resetScroll(); } } function setWidth(width) { viewWidth = width; colContentPositions.clear(); axisWidth = 0; setOuterWidth( axisFirstCells .width('') .each(function(i, _cell) { axisWidth = Math.max(axisWidth, $(_cell).outerWidth()); }), axisWidth ); var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7) //slotTable.width(slotTableWidth); 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); setOuterWidth(dayHeadCells.slice(0, -1), colWidth); } 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 beforeHide() { savedScrollTop = slotScroller.scrollTop(); } function afterShow() { slotScroller.scrollTop(savedScrollTop); } /* 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 = colDate(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 -----------------------------------------------------*/ function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var visStart = cloneDate(t.visStart); var startCol, endCol; if (rtl) { startCol = dayDiff(endDate, visStart)*dis+dit+1; endCol = dayDiff(startDate, visStart)*dis+dit+1; }else{ startCol = dayDiff(startDate, visStart); endCol = dayDiff(endDate, visStart); } startCol = Math.max(0, startCol); endCol = Math.min(colCnt, endCol); if (startCol < endCol) { dayBind( renderCellOverlay(0, startCol, 0, endCol-1) ); } } 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) { var dayStart = cloneDate(t.visStart); var dayEnd = addDays(cloneDate(dayStart), 1); for (var i=0; i<colCnt; i++) { var stretchStart = new Date(Math.max(dayStart, overlayStart)); var stretchEnd = new Date(Math.min(dayEnd, overlayEnd)); if (stretchStart < stretchEnd) { var col = i*dis+dit; var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // 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, slotContent) ); } addDays(dayStart, 1); addDays(dayEnd, 1); } } /* Coordinate Utilities -----------------------------------------------------------------------------*/ coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; 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(); if (opt('allDaySlot')) { e = allDayRow; n = e.offset().top; rows[0] = [n, n+e.outerHeight()]; } var slotTableTop = slotContent.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); colContentPositions = new HorizontalPositionCache(function(col) { return dayBodyCellInners.eq(col); }); function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function dateCell(date) { // "cell" terminology is now confusing return { row: Math.floor(dayDiff(date, t.visStart) / 7), col: dayOfWeekCol(date.getDay()) }; } function cellDate(cell) { var d = colDate(cell.col); var slotIndex = cell.row; if (opt('allDaySlot')) { slotIndex--; } if (slotIndex >= 0) { addMinutes(d, minMinute + slotIndex * snapMinutes); } return d; } function colDate(col) { // returns dates with 00:00:00 return addDays(cloneDate(t.visStart), col*dis+dit); } function cellIsAllDay(cell) { return opt('allDaySlot') && !cell.row; } function dayOfWeekCol(dayOfWeek) { return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit; } // 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 + ') td div')[0].offsetTop; //.position().top; // need this optimization??? } return Math.max(0, Math.round( slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes) )); } function allDayBounds() { return { left: axisWidth, right: viewWidth - gutterWidth } } 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) { var helperOption = opt('selectHelper'); coordinateGrid.build(); if (helperOption) { var col = dayDiff(startDate, t.visStart) * dis + dit; if (col >= 0 && col < colCnt) { // only works when times are on same day var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // 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'; rect.zIndex = 8; selectionHelper = $(helperRes) .css(rect) .appendTo(slotContent); } }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); slotContent.append(selectionHelper); setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended setOuterHeight(selectionHelper, rect.height, true); } } } }else{ renderSlotOverlay(startDate, endDate); } } 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; hoverListener.start(function(cell, origCell) { clearSelection(); if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) { var d1 = cellDate(origCell); var d2 = cellDate(cell); dates = [ d1, addMinutes(cloneDate(d1), snapMinutes), // calculate minutes depending on selection slot minutes d2, addMinutes(cloneDate(d2), snapMinutes) ].sort(cmp); renderSlotSelection(dates[0], dates[3]); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], false, ev); } reportSelection(dates[0], dates[3], false, ev); } }); } } function reportDayClick(date, allDay, ev) { trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev); } /* External Dragging --------------------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { if (cellIsAllDay(cell)) { renderCellOverlay(cell.row, cell.col, cell.row, cell.col); }else{ var d1 = cellDate(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, cellDate(cell), cellIsAllDay(cell), ev, ui); } } } ;; function AgendaEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.compileDaySegs = compileDaySegs; // for DayEventRenderer t.clearEvents = clearEvents; t.slotSegHtml = slotSegHtml; t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventEnd = t.eventEnd; var reportEvents = t.reportEvents; var reportEventClear = t.reportEventClear; 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 colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var renderDaySegs = t.renderDaySegs; var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var getSnapHeight = t.getSnapHeight; var getSnapMinutes = t.getSnapMinutes; var getBodyContent = t.getBodyContent; 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 calendar = t.calendar; var formatDate = calendar.formatDate; var formatDates = calendar.formatDates; /* Rendering ----------------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { reportEvents(events); 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')) { renderDaySegs(compileDaySegs(dayEvents), modifiedEventId); setHeight(); // no params means set to viewHeight } renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId); trigger('eventAfterAllRender'); } function clearEvents() { reportEventClear(); getDaySegmentContainer().empty(); getSlotSegmentContainer().empty(); } function compileDaySegs(events) { var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)), i, levelCnt=levels.length, level, j, seg, segs=[]; for (i=0; i<levelCnt; i++) { level = levels[i]; for (j=0; j<level.length; j++) { seg = level[j]; seg.row = 0; seg.level = i; // not needed anymore segs.push(seg); } } return segs; } function compileSlotSegs(events) { var colCnt = getColCnt(), minMinute = getMinMinute(), maxMinute = getMaxMinute(), d = addMinutes(cloneDate(t.visStart), minMinute), visEventEnds = $.map(events, slotEventEnd), i, col, j, level, k, seg, segs=[]; for (i=0; i<colCnt; i++) { col = stackSegs(sliceSegs(events, visEventEnds, d, addMinutes(cloneDate(d), maxMinute-minMinute))); countForwardSegs(col); for (j=0; j<col.length; j++) { level = col[j]; for (k=0; k<level.length; k++) { seg = level[k]; seg.col = i; seg.level = j; segs.push(seg); } } addDays(d, 1, true); } return segs; } 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 function renderSlotSegs(segs, modifiedEventId) { var i, segCnt=segs.length, seg, event, classes, top, bottom, colI, levelI, forward, leftmost, availWidth, outerWidth, left, html='', eventElements, eventElement, triggerRes, vsideCache={}, hsideCache={}, key, val, titleElement, height, slotSegmentContainer = getSlotSegmentContainer(), rtl, dis, dit, colCnt = getColCnt(); if (rtl = opt('isRTL')) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } // 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); colI = seg.col; levelI = seg.level; forward = seg.forward || 0; leftmost = colContentLeft(colI*dis + dit); availWidth = colContentRight(colI*dis + dit) - leftmost; availWidth = Math.min(availWidth-6, availWidth*.95); // TODO: move this to CSS if (levelI) { // indented and thin outerWidth = availWidth / (levelI + forward + 1); }else{ if (forward) { // moderately wide, aligned left still outerWidth = ((availWidth / (forward + 1)) - (12/2)) * 2; // 12 is the predicted width of resizer = }else{ // can be entire width, aligned left outerWidth = availWidth; } } left = leftmost + // leftmost possible (availWidth / (levelI + forward + 1) * levelI) // indentation * dis + (rtl ? availWidth - outerWidth : 0); // rtl seg.top = top; seg.left = left; seg.outerWidth = outerWidth; 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) { val = vsideCache[key = seg.key = cssKey(eventElement[0])]; seg.vsides = val === undefined ? (vsideCache[key] = vsides(eventElement, true)) : val; val = hsideCache[key]; seg.hsides = val === undefined ? (hsideCache[key] = hsides(eventElement, true)) : val; 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'); } 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;z-index:8;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 bindDaySeg(event, eventElement, seg) { if (isEventDraggable(event)) { draggableDayEvent(event, eventElement, seg.isStart); } if (seg.isEnd && isEventResizable(event)) { resizableDayEvent(event, eventElement, seg); } eventElementHandlers(event, eventElement); // needs to be after, because resizableDayEvent might stopImmediatePropagation on click } 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 function draggableDayEvent(event, eventElement, isStart) { var origWidth; var revert; var allDay=true; var dayDelta; var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colWidth = getColWidth(); var snapHeight = getSnapHeight(); var snapMinutes = getSnapMinutes(); var minMinute = getMinMinute(); eventElement.draggable({ zIndex: 9, 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 = .width(); hoverListener.start(function(cell, origCell, rowDelta, colDelta) { clearOverlays(); if (cell) { //setOverflowHidden(true); revert = false; dayDelta = colDelta * dis; 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(); //setOverflowHidden(false); 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 - getBodyContent().offset().top) / snapHeight) * snapMinutes + minMinute - (event.start.getHours() * 60 + event.start.getMinutes()); } eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui); } //setOverflowHidden(false); } }); 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 origPosition; var allDay=false; var dayDelta; var minuteDelta; var prevMinuteDelta; var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colCnt = getColCnt(); var colWidth = getColWidth(); var snapHeight = getSnapHeight(); var snapMinutes = getSnapMinutes(); eventElement.draggable({ zIndex: 9, scroll: false, grid: [colWidth, snapHeight], axis: colCnt==1 ? 'y' : false, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origPosition = eventElement.position(); minuteDelta = prevMinuteDelta = 0; hoverListener.start(function(cell, origCell, rowDelta, colDelta) { eventElement.draggable('option', 'revert', !cell); clearOverlays(); if (cell) { dayDelta = colDelta * dis; if (opt('allDaySlot') && !cell.row) { // over full days if (!allDay) { // convert to temporary all-day event allDay = true; timeElement.hide(); eventElement.draggable('option', 'grid', null); } renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); }else{ // on slots resetElement(); } } }, ev, 'drag'); }, drag: function(ev, ui) { minuteDelta = Math.round((ui.position.top - origPosition.top) / snapHeight) * snapMinutes; if (minuteDelta != prevMinuteDelta) { if (!allDay) { updateTimeText(minuteDelta); } prevMinuteDelta = minuteDelta; } }, stop: function(ev, ui) { var cell = hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (cell && (dayDelta || minuteDelta || allDay)) { // changed! eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui); }else{ // either no change or out-of-bounds (draggable has already reverted) resetElement(); eventElement.css('filter', ''); // clear IE opacity side-effects eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position updateTimeText(0); showEvents(event, eventElement); } } }); 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'))); } function resetElement() { // convert back to original slot-event if (allDay) { timeElement.css('display', ''); // show() was causing display=inline eventElement.draggable('option', 'grid', [colWidth, snapHeight]); allDay = false; } } } /* 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); eventElement.css('z-index', 9); 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{ eventElement.css('z-index', 8); showEvents(event, eventElement); // BUG: if event was really short, need to put title back in span } } }); } } function countForwardSegs(levels) { var i, j, k, level, segForward, segBack; for (i=levels.length-1; i>0; i--) { level = levels[i]; for (j=0; j<level.length; j++) { segForward = level[j]; for (k=0; k<levels[i-1].length; k++) { segBack = levels[i-1][k]; if (segsCollide(segForward, segBack)) { segBack.forward = Math.max(segBack.forward||0, (segForward.forward||0)+1); } } } } } ;; 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.setOverflowHidden = setOverflowHidden; t.isEventDraggable = isEventDraggable; t.isEventResizable = isEventResizable; t.reportEvents = reportEvents; t.eventEnd = eventEnd; t.reportEventElement = reportEventElement; t.reportEventClear = reportEventClear; 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 = {}; var eventElements = []; var eventElementsByID = {}; var options = calendar.options; function opt(name, viewNameOverride) { var v = options[name]; if (typeof v == 'object') { 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]) ); } /* function setOverflowHidden(bool) { element.css('overflow', bool ? 'hidden' : ''); } */ function isEventDraggable(event) { return isEventEditable(event) && !opt('disableDragging'); } function isEventResizable(event) { // but also need to make sure the seg.isEnd == true return isEventEditable(event) && !opt('disableResizing'); } function isEventEditable(event) { return firstDefined(event.editable, (event.source || {}).editable, opt('editable')); } /* Event Data ------------------------------------------------------------------------------*/ // report when view receives new events function reportEvents(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]; } } } // 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) { eventElements.push(element); if (eventElementsByID[event._id]) { eventElementsByID[event._id].push(element); }else{ eventElementsByID[event._id] = [element]; } } function reportEventClear() { eventElements = []; eventElementsByID = {}; } // 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) { 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) { 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 ); 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); } } } ;; function DayEventRenderer() { var t = this; // exports t.renderDaySegs = renderDaySegs; 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 showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventResize = t.eventResize; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var allDayRow = t.allDayRow; var allDayBounds = t.allDayBounds; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var dayOfWeekCol = t.dayOfWeekCol; var dateCell = t.dateCell; var compileDaySegs = t.compileDaySegs; var getDaySegmentContainer = t.getDaySegmentContainer; var bindDaySeg = t.bindDaySeg; //TODO: streamline this var formatDates = t.calendar.formatDates; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var clearSelection = t.clearSelection; /* Rendering -----------------------------------------------------------------------------*/ function renderDaySegs(segs, modifiedEventId) { var segmentContainer = getDaySegmentContainer(); var rowDivs; var rowCnt = getRowCnt(); var colCnt = getColCnt(); var i = 0; var rowI; var levelI; var colHeights; var j; var segCnt = segs.length; var seg; var top; var k; segmentContainer[0].innerHTML = daySegHTML(segs); // faster than .html() daySegElementResolve(segs, segmentContainer.children()); daySegElementReport(segs); daySegHandlers(segs, segmentContainer, modifiedEventId); daySegCalcHSides(segs); daySegSetWidths(segs); daySegCalcHeights(segs); rowDivs = getRowDivs(); // set row heights, calculate event tops (in relation to row top) for (rowI=0; rowI<rowCnt; rowI++) { levelI = 0; colHeights = []; for (j=0; j<colCnt; j++) { colHeights[j] = 0; } while (i<segCnt && (seg = segs[i]).row == rowI) { // loop through segs in a row top = arrayMax(colHeights.slice(seg.startCol, seg.endCol)); seg.top = top; top += seg.outerHeight; for (k=seg.startCol; k<seg.endCol; k++) { colHeights[k] = top; } i++; } rowDivs[rowI].height(arrayMax(colHeights)); } daySegSetTops(segs, getRowTops(rowDivs)); } function renderTempDaySegs(segs, adjustRow, adjustTop) { var tempContainer = $("<div/>"); var elements; var segmentContainer = getDaySegmentContainer(); var i; var segCnt = segs.length; var element; tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html() elements = tempContainer.children(); segmentContainer.append(elements); daySegElementResolve(segs, elements); daySegCalcHSides(segs); daySegSetWidths(segs); daySegCalcHeights(segs); daySegSetTops(segs, getRowTops(getRowDivs())); elements = []; for (i=0; i<segCnt; i++) { element = segs[i].element; if (element) { if (segs[i].row === adjustRow) { element.css('top', adjustTop); } elements.push(element[0]); } } return $(elements); } function daySegHTML(segs) { // also sets seg.left and seg.outerWidth var rtl = opt('isRTL'); var i; var segCnt=segs.length; var seg; var event; var url; var classes; var bounds = allDayBounds(); var minLeft = bounds.left; var maxLeft = bounds.right; var leftCol; var rightCol; var left; var right; var skinCss; var html = ''; // calculate desired position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; classes = ['fc-event', 'fc-event-hori']; 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 (rtl) { leftCol = dayOfWeekCol(seg.end.getDay()-1); rightCol = dayOfWeekCol(seg.start.getDay()); left = seg.isEnd ? colContentLeft(leftCol) : minLeft; right = seg.isStart ? colContentRight(rightCol) : maxLeft; }else{ leftCol = dayOfWeekCol(seg.start.getDay()); rightCol = dayOfWeekCol(seg.end.getDay()-1); left = seg.isStart ? colContentLeft(leftCol) : minLeft; right = seg.isEnd ? colContentRight(rightCol) : maxLeft; } classes = classes.concat(event.className); if (event.source) { classes = classes.concat(event.source.className || []); } url = event.url; skinCss = getSkinCss(event, opt); if (url) { html += "<a href='" + htmlEscape(url) + "'"; }else{ html += "<div"; } html += " class='" + classes.join(' ') + "'" + " style='position:absolute;z-index:8;left:"+left+"px;" + skinCss + "'" + ">" + "<div class='fc-event-inner'>"; if (!event.allDay && seg.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 (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-" + (rtl ? 'w' : 'e') + "'>" + "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7 "</div>"; } html += "</" + (url ? "a" : "div" ) + ">"; seg.left = left; seg.outerWidth = right - left; seg.startCol = leftCol; seg.endCol = rightCol + 1; // needs to be exclusive } return html; } function daySegElementResolve(segs, elements) { // sets seg.element var i; var segCnt = segs.length; var seg; var event; var element; var triggerRes; for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; element = $(elements[i]); // faster than .eq() triggerRes = trigger('eventRender', event, event, element); if (triggerRes === false) { element.remove(); }else{ if (triggerRes && triggerRes !== true) { triggerRes = $(triggerRes) .css({ position: 'absolute', left: seg.left }); element.replaceWith(triggerRes); element = triggerRes; } seg.element = element; } } } function daySegElementReport(segs) { var i; var segCnt = segs.length; var seg; var element; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { reportEventElement(seg.event, element); } } } function daySegHandlers(segs, segmentContainer, modifiedEventId) { var i; var segCnt = segs.length; var seg; var element; var event; // retrieve elements, run through eventRender callback, bind handlers for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { event = seg.event; if (event._id === modifiedEventId) { bindDaySeg(event, element, seg); }else{ element[0]._fci = i; // for lazySegBind } } } lazySegBind(segmentContainer, segs, bindDaySeg); } function daySegCalcHSides(segs) { // also sets seg.key var i; var segCnt = segs.length; var seg; var element; var key, val; var hsideCache = {}; // record event horizontal sides for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { key = seg.key = cssKey(element[0]); val = hsideCache[key]; if (val === undefined) { val = hsideCache[key] = hsides(element, true); } seg.hsides = val; } } } function daySegSetWidths(segs) { var i; var segCnt = segs.length; var seg; var element; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { element[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; } } } function daySegCalcHeights(segs) { var i; var segCnt = segs.length; var seg; var element; var key, val; var vmarginCache = {}; // record event heights for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { key = seg.key; // created in daySegCalcHSides val = vmarginCache[key]; if (val === undefined) { val = vmarginCache[key] = vmargins(element); } seg.outerHeight = element[0].offsetHeight + val; } } } function getRowDivs() { var i; var rowCnt = getRowCnt(); var rowDivs = []; for (i=0; i<rowCnt; i++) { rowDivs[i] = allDayRow(i) .find('div.fc-day-content > div'); // optimal selector? } return rowDivs; } function getRowTops(rowDivs) { var i; var rowCnt = rowDivs.length; var tops = []; for (i=0; i<rowCnt; i++) { tops[i] = rowDivs[i][0].offsetTop; // !!?? but this means the element needs position:relative if in a table cell!!!! } return tops; } function daySegSetTops(segs, rowTops) { // also triggers eventAfterRender var i; var segCnt = segs.length; var seg; var element; var event; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { element[0].style.top = rowTops[seg.row] + (seg.top||0) + 'px'; event = seg.event; trigger('eventAfterRender', event, event, element); } } } /* Resizing -----------------------------------------------------------------------------------*/ function resizableDayEvent(event, element, seg) { var rtl = opt('isRTL'); var direction = rtl ? '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 = t.getHoverListener(); var rowCnt = getRowCnt(); var colCnt = getColCnt(); var dis = rtl ? -1 : 1; var dit = rtl ? colCnt-1 : 0; var elementTop = element.css('top'); var dayDelta; var helpers; var eventCopy = $.extend({}, event); var minCell = dateCell(event.start); clearSelection(); $('body') .css('cursor', direction + '-resize') .one('mouseup', mouseup); trigger('eventResizeStart', this, event, ev); hoverListener.start(function(cell, origCell) { if (cell) { var r = Math.max(minCell.row, cell.row); var c = cell.col; if (rowCnt == 1) { r = 0; // hack for all-day area in agenda views } if (r == minCell.row) { if (rtl) { c = Math.min(minCell.col, c); }else{ c = Math.max(minCell.col, c); } } dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit); var newEnd = addDays(eventEnd(event), dayDelta, true); if (dayDelta) { eventCopy.end = newEnd; var oldHelpers = helpers; helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop); helpers.find('*').css('cursor', direction + '-resize'); if (oldHelpers) { oldHelpers.remove(); } hideEvents(event); }else{ if (helpers) { showEvents(event); helpers.remove(); helpers = null; } } clearOverlays(); renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start } }, 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); } }); } } ;; //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) { selected = true; trigger('select', null, startDate, endDate, allDay, ev); } function daySelectionMousedown(ev) { // not really a generic manager method, oh well var cellDate = t.cellDate; var cellIsAllDay = t.cellIsAllDay; 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 cellDate/cellIsAllDay info in cell clearSelection(); if (cell && cellIsAllDay(cell)) { dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp); 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; t.build = function() { rows = []; cols = []; buildFunc(rows, cols); }; t.cell = function(x, y) { var rowCnt = rows.length; var colCnt = cols.length; var i, r=-1, c=-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; } } return (r>=0 && c>=0) ? { row:r, col:c } : null; }; t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive var origin = originElement.offset(); return { top: rows[row0][0] - origin.top, left: cols[col0][0] - origin.left, width: cols[col1][1] - cols[col0][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)) { if (newCell) { if (!firstCell) { firstCell = newCell; } change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col); }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);
JavaScript
// moment.js // version : 2.1.0 // author : Tim Wood // license : MIT // momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.1.0", round = Math.round, i, // internal storage for language config files languages = {}, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(\d*)?\.?(\d+)\:(\d+)\:(\d+)\.?(\d{3})?/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO seperator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 // preliminary iso regex // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', // iso time formats and regexes isoTimes = [ ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', w : 'week', M : 'month', y : 'year' }, // format function strings formatFunctions = {}, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.lang().monthsShort(this, format); }, MMMM : function (format) { return this.lang().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.lang().weekdaysMin(this, format); }, ddd : function (format) { return this.lang().weekdaysShort(this, format); }, dddd : function (format) { return this.lang().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return this.weekYear(); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return this.isoWeekYear(); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.lang().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.lang().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return ~~(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(~~(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(~~(10 * a / 6), 4); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); } }; function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.lang().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Language() { } // Moment prototype object function Moment(config) { extend(this, config); } // Duration Constructor function Duration(duration) { var years = duration.years || duration.year || duration.y || 0, months = duration.months || duration.month || duration.M || 0, weeks = duration.weeks || duration.week || duration.w || 0, days = duration.days || duration.day || duration.d || 0, hours = duration.hours || duration.hour || duration.h || 0, minutes = duration.minutes || duration.minute || duration.m || 0, seconds = duration.seconds || duration.second || duration.s || 0, milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0; // store reference to input for deterministic cloning this._input = duration; // representation for dateAddRemove this._milliseconds = milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = months + years * 12; this._data = {}; this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } return a; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength) { var output = number + ''; while (output.length < targetLength) { output = '0' + output; } return output; } // helper function for _.addTime and _.subtractTime function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months, minutes, hours, currentDate; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } // store the minutes and hours so we can restore them if (days || months) { minutes = mom.minute(); hours = mom.hour(); } if (days) { mom.date(mom.date() + days * isAdding); } if (months) { mom.month(mom.month() + months * isAdding); } if (milliseconds && !ignoreUpdateOffset) { moment.updateOffset(mom); } // restore the minutes and hours after possibly changing dst if (days || months) { mom.minute(minutes); mom.hour(hours); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } // compare two arrays, return the number of differences function compareArrays(array1, array2) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if (~~array1[i] !== ~~array2[i]) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { return units ? unitAliases[units] || units.toLowerCase().replace(/(.)s$/, '$1') : units; } /************************************ Languages ************************************/ Language.prototype = { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), months : function (m) { return this._months[m.month()]; }, _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : "h:mm A", L : "MM/DD/YYYY", LL : "MMMM D YYYY", LLL : "MMMM D YYYY LT", LLLL : "dddd, MMMM D YYYY LT" }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { return ((input + '').toLowerCase()[0] === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace("%d", number); }, _ordinal : "%d", preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }; // Loads a language definition into the `languages` cache. The function // takes a key and optionally values. If not in the browser and no values // are provided, it will load the language file module. As a convenience, // this function also returns the language values. function loadLang(key, values) { values.abbr = key; if (!languages[key]) { languages[key] = new Language(); } languages[key].set(values); return languages[key]; } // Determines which language definition to use and returns it. // // With no parameters, it will return the global language. If you // pass in a language key, such as 'en', it will return the // definition for 'en', so long as 'en' has already been loaded using // moment.lang. function getLangDefinition(key) { if (!key) { return moment.fn._lang; } if (!languages[key] && hasModule) { try { require('./lang/' + key); } catch (e) { // call with no params to set to default return moment.fn._lang; } } return languages[key]; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[.*\]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ""; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { var i = 5; function replaceLongDateFormatTokens(input) { return m.lang().longDateFormat(input) || input; } while (i-- && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); } if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { switch (token) { case 'DDDD': return parseTokenThreeDigits; case 'YYYY': return parseTokenFourDigits; case 'YYYYY': return parseTokenSixDigits; case 'S': case 'SS': case 'SSS': case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return getLangDefinition(config._l)._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'MM': case 'DD': case 'YY': case 'HH': case 'hh': case 'mm': case 'ss': case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': return parseTokenOneOrTwoDigits; default : return new RegExp(token.replace('\\', '')); } } function timezoneMinutesFromString(string) { var tzchunk = (parseTokenTimezone.exec(string) || [])[0], parts = (tzchunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + ~~parts[2]; return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // MONTH case 'M' : // fall through to MM case 'MM' : datePartArray[1] = (input == null) ? 0 : ~~input - 1; break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = getLangDefinition(config._l).monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[1] = a; } else { config._isValid = false; } break; // DAY OF MONTH case 'D' : // fall through to DDDD case 'DD' : // fall through to DDDD case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { datePartArray[2] = ~~input; } break; // YEAR case 'YY' : datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000); break; case 'YYYY' : case 'YYYYY' : datePartArray[0] = ~~input; break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = getLangDefinition(config._l).isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[3] = ~~input; break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[4] = ~~input; break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[5] = ~~input; break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : datePartArray[6] = ~~ (('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; } // if the input is null, the date is not valid if (input == null) { config._isValid = false; } } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromArray(config) { var i, date, input = []; if (config._d) { return; } for (i = 0; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // add the offsets to the time to be parsed so that we can have a clean array for checking isValid input[3] += ~~((config._tzm || 0) / 60); input[4] += ~~((config._tzm || 0) % 60); date = new Date(0); if (config._useUTC) { date.setUTCFullYear(input[0], input[1], input[2]); date.setUTCHours(input[3], input[4], input[5], input[6]); } else { date.setFullYear(input[0], input[1], input[2]); date.setHours(input[3], input[4], input[5], input[6]); } config._d = date; } // date from string and format string function makeDateFromStringAndFormat(config) { // This array is used to make a Date, either with `new Date` or `Date.UTC` var tokens = config._f.match(formattingTokens), string = config._i, i, parsedInput; config._a = []; for (i = 0; i < tokens.length; i++) { parsedInput = (getParseRegexForToken(tokens[i], config).exec(string) || [])[0]; if (parsedInput) { string = string.slice(string.indexOf(parsedInput) + parsedInput.length); } // don't parse if its not a known token if (formatTokenFunctions[tokens[i]]) { addTimeToArrayFromToken(tokens[i], parsedInput, config); } } // add remaining unparsed input to the string if (string) { config._il = string; } // handle am pm if (config._isPm && config._a[3] < 12) { config._a[3] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[3] === 12) { config._a[3] = 0; } // return dateFromArray(config); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, tempMoment, bestMoment, scoreToBeat = 99, i, currentScore; for (i = 0; i < config._f.length; i++) { tempConfig = extend({}, config); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); tempMoment = new Moment(tempConfig); currentScore = compareArrays(tempConfig._a, tempMoment.toArray()); // if there is any input that was not parsed // add a penalty for that format if (tempMoment._il) { currentScore += tempMoment._il.length; } if (currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempMoment; } } extend(config, bestMoment); } // date from iso format function makeDateFromString(config) { var i, string = config._i, match = isoRegex.exec(string); if (match) { // match[2] should be "T" or undefined config._f = 'YYYY-MM-DD' + (match[2] || " "); for (i = 0; i < 4; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (parseTokenTimezone.exec(string)) { config._f += " Z"; } makeDateFromStringAndFormat(config); } else { config._d = new Date(string); } } function makeDateFromInput(config) { var input = config._i, matched = aspNetJsonRegex.exec(input); if (input === undefined) { config._d = new Date(); } else if (matched) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromArray(config); } else { config._d = input instanceof Date ? new Date(+input) : new Date(input); } } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) { return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(milliseconds, withoutSuffix, lang) { var seconds = round(Math.abs(milliseconds) / 1000), minutes = round(seconds / 60), hours = round(minutes / 60), days = round(hours / 24), years = round(days / 365), args = seconds < 45 && ['s', seconds] || minutes === 1 && ['m'] || minutes < 45 && ['mm', minutes] || hours === 1 && ['h'] || hours < 22 && ['hh', hours] || days === 1 && ['d'] || days <= 25 && ['dd', days] || days <= 45 && ['M'] || days < 345 && ['MM', round(days / 30)] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = milliseconds > 0; args[4] = lang; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add('d', daysToDayOfWeek); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; if (input === null || input === '') { return null; } if (typeof input === 'string') { config._i = input = getLangDefinition().preparse(input); } if (moment.isMoment(input)) { config = extend({}, input); config._d = new Date(+input._d); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, lang) { return makeMoment({ _i : input, _f : format, _l : lang, _isUTC : false }); }; // creating with utc moment.utc = function (input, format, lang) { return makeMoment({ _useUTC : true, _isUTC : true, _l : lang, _i : input, _f : format }); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var isDuration = moment.isDuration(input), isNumber = (typeof input === 'number'), duration = (isDuration ? input._input : (isNumber ? {} : input)), matched = aspNetTimeSpanJsonRegex.exec(input), sign, ret; if (isNumber) { if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (matched) { sign = (matched[1] === "-") ? -1 : 1; duration = { y: 0, d: ~~matched[2] * sign, h: ~~matched[3] * sign, m: ~~matched[4] * sign, s: ~~matched[5] * sign, ms: ~~matched[6] * sign }; } ret = new Duration(duration); if (isDuration && input.hasOwnProperty('_lang')) { ret._lang = input._lang; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. moment.lang = function (key, values) { if (!key) { return moment.fn._lang._abbr; } if (values) { loadLang(key, values); } else if (!languages[key]) { getLangDefinition(key); } moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key); }; // returns language data moment.langData = function (key) { if (key && key._lang && key._lang._abbr) { key = key._lang._abbr; } return getLangDefinition(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment; }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; /************************************ Moment Prototype ************************************/ moment.fn = Moment.prototype = { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { return formatMoment(moment(this).utc(), 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { if (this._isValid == null) { if (this._a) { this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()); } else { this._isValid = !isNaN(this._d.getTime()); } } return !!this._isValid; }, utc : function () { return this.zone(0); }, local : function () { this.zone(0); this._isUTC = false; return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.lang().postformat(output); }, add : function (input, val) { var dur; // switch args to support add('s', 1) and add(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, 1); return this; }, subtract : function (input, val) { var dur; // switch args to support subtract('s', 1) and subtract(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, -1); return this; }, diff : function (input, units, asFloat) { var that = this._isUTC ? moment(input).zone(this._offset || 0) : moment(input).local(), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function () { var diff = this.diff(moment().startOf('day'), 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.lang().calendar(format, this)); }, isLeapYear : function () { var year = this.year(); return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { if (typeof input === 'string') { input = this.lang().weekdaysParse(input); if (typeof input !== 'number') { return this; } } return this.add({ d : input - day }); } else { return day; } }, month : function (input) { var utc = this._isUTC ? 'UTC' : '', dayOfMonth, daysInMonth; if (input != null) { if (typeof input === 'string') { input = this.lang().monthsParse(input); if (typeof input !== 'number') { return this; } } dayOfMonth = this.date(); this.date(1); this._d['set' + utc + 'Month'](input); this.date(Math.min(dayOfMonth, this.daysInMonth())); moment.updateOffset(this); return this; } else { return this._d['get' + utc + 'Month'](); } }, startOf: function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'month': this.date(1); /* falls through */ case 'week': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } return this; }, endOf: function (units) { return this.startOf(units).add(units, 1).subtract('ms', 1); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) === +moment(input).startOf(units); }, min: function (other) { other = moment.apply(null, arguments); return other < this ? this : other; }, max: function (other) { other = moment.apply(null, arguments); return other > this ? this : other; }, zone : function (input) { var offset = this._offset || 0; if (input != null) { if (typeof input === "string") { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } this._offset = input; this._isUTC = true; if (offset !== input) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true); } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? "UTC" : ""; }, zoneName : function () { return this._isUTC ? "Coordinated Universal Time" : ""; }, daysInMonth : function () { return moment.utc([this.year(), this.month() + 1, 0]).date(); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add("d", (input - dayOfYear)); }, weekYear : function (input) { var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year; return input == null ? year : this.add("y", (input - year)); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add("y", (input - year)); }, week : function (input) { var week = this.lang().week(this); return input == null ? week : this.add("d", (input - week) * 7); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add("d", (input - week) * 7); }, weekday : function (input) { var weekday = (this._d.getDay() + 7 - this.lang()._week.dow) % 7; return input == null ? weekday : this.add("d", input - weekday); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, // If passed a language key, it will set the language for this // instance. Otherwise, it will return the language configuration // variables for this instance. lang : function (key) { if (key === undefined) { return this._lang; } else { this._lang = getLangDefinition(key); return this; } } }; // helper for adding shortcuts function makeGetterAndSetter(name, key) { moment.fn[name] = moment.fn[name + 's'] = function (input) { var utc = this._isUTC ? 'UTC' : ''; if (input != null) { this._d['set' + utc + key](input); moment.updateOffset(this); return this; } else { return this._d['get' + utc + key](); } }; } // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds) for (i = 0; i < proxyGettersAndSetters.length; i ++) { makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]); } // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear') makeGetterAndSetter('year', 'FullYear'); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ moment.duration.fn = Duration.prototype = { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); data.days = days % 30; months += absRound(days / 30); data.months = months % 12; years = absRound(months / 12); data.years = years; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + ~~(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var difference = +this, output = relativeTime(difference, !withSuffix, this.lang()); if (withSuffix) { output = this.lang().pastFuture(difference, output); } return this.lang().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { units = normalizeUnits(units); return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's'](); }, lang : moment.fn.lang }; function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } function makeDurationAsGetter(name, factor) { moment.duration.fn['as' + name] = function () { return +this / factor; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationAsGetter(i, unitMillisecondFactors[i]); makeDurationGetter(i.toLowerCase()); } } makeDurationAsGetter('Weeks', 6048e5); moment.duration.fn.asMonths = function () { return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12; }; /************************************ Default Lang ************************************/ // Set default language, other languages will inherit from English. moment.lang('en', { ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /************************************ Exposing Moment ************************************/ // CommonJS module is defined if (hasModule) { module.exports = moment; } /*global ender:false */ if (typeof ender === 'undefined') { // here, `this` means `window` in the browser, or `global` on the server // add `moment` as a global object via a string identifier, // for Closure Compiler "advanced" mode this['moment'] = moment; } /*global define:false */ if (typeof define === "function" && define.amd) { define("moment", [], function () { return moment; }); } }).call(this);
JavaScript
/** * @version: 1.3 * @author: Dan Grossman http://www.dangrossman.info/ * @date: 2014-01-14 * @copyright: Copyright (c) 2012-2014 Dan Grossman. All rights reserved. * @license: Licensed under Apache License v2.0. See http://www.apache.org/licenses/LICENSE-2.0 * @website: http://www.improvely.com/ */ !function ($) { var DateRangePicker = function (element, options, cb) { // by default, the daterangepicker element is placed at the bottom of HTML body this.parentEl = 'body'; //element that triggered the date range picker this.element = $(element); //create the picker HTML object var DRPTemplate = '<div class="daterangepicker dropdown-menu">' + '<div class="calendar left"></div>' + '<div class="calendar right"></div>' + '<div class="ranges">' + '<div class="range_inputs">' + '<div class="daterangepicker_start_input" style="float: left">' + '<label for="daterangepicker_start"></label>' + '<input class="input-mini" type="text" name="daterangepicker_start" value="" disabled="disabled" />' + '</div>' + '<div class="daterangepicker_end_input" style="float: left; padding-left: 11px">' + '<label for="daterangepicker_end"></label>' + '<input class="input-mini" type="text" name="daterangepicker_end" value="" disabled="disabled" />' + '</div>' + '<button class="applyBtn" disabled="disabled"></button>&nbsp;' + '<button class="cancelBtn"></button>' + '</div>' + '</div>' + '</div>'; this.parentEl = (typeof options == 'object' && options.parentEl && $(options.parentEl)) || $(this.parentEl); this.container = $(DRPTemplate).appendTo(this.parentEl); //custom options if (typeof options != 'object') options = {}; this.setOptions(options, cb); //apply CSS classes and labels to buttons var c = this.container; $.each(this.buttonClasses, function (idx, val) { c.find('button').addClass(val); }); this.container.find('.daterangepicker_start_input label').html(this.locale.fromLabel); this.container.find('.daterangepicker_end_input label').html(this.locale.toLabel); if (this.applyClass.length) this.container.find('.applyBtn').addClass(this.applyClass); if (this.cancelClass.length) this.container.find('.cancelBtn').addClass(this.cancelClass); this.container.find('.applyBtn').html(this.locale.applyLabel); this.container.find('.cancelBtn').html(this.locale.cancelLabel); //event listeners this.container.on('mousedown', $.proxy(this.mousedown, this)); this.container.find('.calendar') .on('click', '.prev', $.proxy(this.clickPrev, this)) .on('click', '.next', $.proxy(this.clickNext, this)) .on('click', 'td.available', $.proxy(this.clickDate, this)) .on('mouseenter', 'td.available', $.proxy(this.enterDate, this)) .on('mouseleave', 'td.available', $.proxy(this.updateFormInputs, this)) .on('change', 'select.yearselect', $.proxy(this.updateMonthYear, this)) .on('change', 'select.monthselect', $.proxy(this.updateMonthYear, this)) .on('change', 'select.hourselect,select.minuteselect,select.ampmselect', $.proxy(this.updateTime, this)); this.container.find('.ranges') .on('click', 'button.applyBtn', $.proxy(this.clickApply, this)) .on('click', 'button.cancelBtn', $.proxy(this.clickCancel, this)) .on('click', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.showCalendars, this)) .on('click', 'li', $.proxy(this.clickRange, this)) .on('mouseenter', 'li', $.proxy(this.enterRange, this)) .on('mouseleave', 'li', $.proxy(this.updateFormInputs, this)); if (this.element.is('input')) { this.element.on({ 'click.daterangepicker': $.proxy(this.show, this), 'focus.daterangepicker': $.proxy(this.show, this), 'keyup.daterangepicker': $.proxy(this.updateFromControl, this) }); } else { this.element.on('click.daterangepicker', $.proxy(this.show, this)); } }; DateRangePicker.prototype = { constructor: DateRangePicker, setOptions: function(options, callback) { this.startDate = moment().startOf('day'); this.endDate = moment().startOf('day'); this.minDate = false; this.maxDate = false; this.dateLimit = false; this.showDropdowns = false; this.showWeekNumbers = false; this.timePicker = false; this.timePickerIncrement = 30; this.timePicker12Hour = true; this.singleDatePicker = false; this.ranges = {}; this.opens = 'right'; if (this.element.hasClass('pull-right')) this.opens = 'left'; this.buttonClasses = ['btn', 'btn-small']; this.applyClass = 'btn-success'; this.cancelClass = 'btn-default'; this.format = 'MM/DD/YYYY'; this.separator = ' - '; this.locale = { applyLabel: 'Apply', cancelLabel: 'Cancel', fromLabel: 'From', toLabel: 'To', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: moment()._lang._weekdaysMin.slice(), monthNames: moment()._lang._monthsShort.slice(), firstDay: 0 }; this.cb = function () { }; if (typeof options.format == 'string') this.format = options.format; if (typeof options.separator == 'string') this.separator = options.separator; if (typeof options.startDate == 'string') this.startDate = moment(options.startDate, this.format); if (typeof options.endDate == 'string') this.endDate = moment(options.endDate, this.format); if (typeof options.minDate == 'string') this.minDate = moment(options.minDate, this.format); if (typeof options.maxDate == 'string') this.maxDate = moment(options.maxDate, this.format); if (typeof options.startDate == 'object') this.startDate = moment(options.startDate); if (typeof options.endDate == 'object') this.endDate = moment(options.endDate); if (typeof options.minDate == 'object') this.minDate = moment(options.minDate); if (typeof options.maxDate == 'object') this.maxDate = moment(options.maxDate); if (typeof options.applyClass == 'string') this.applyClass = options.applyClass; if (typeof options.cancelClass == 'string') this.cancelClass = options.cancelClass; if (typeof options.ranges == 'object') { for (var range in options.ranges) { var start = moment(options.ranges[range][0]); var end = moment(options.ranges[range][1]); // If we have a min/max date set, bound this range // to it, but only if it would otherwise fall // outside of the min/max. if (this.minDate && start.isBefore(this.minDate)) start = moment(this.minDate); if (this.maxDate && end.isAfter(this.maxDate)) end = moment(this.maxDate); // If the end of the range is before the minimum (if min is set) OR // the start of the range is after the max (also if set) don't display this // range option. if ((this.minDate && end.isBefore(this.minDate)) || (this.maxDate && start.isAfter(this.maxDate))) { continue; } this.ranges[range] = [start, end]; } var list = '<ul>'; for (var range in this.ranges) { list += '<li>' + range + '</li>'; } list += '<li>' + this.locale.customRangeLabel + '</li>'; list += '</ul>'; this.container.find('.ranges ul').remove(); this.container.find('.ranges').prepend(list); } if (typeof options.dateLimit == 'object') this.dateLimit = options.dateLimit; // update day names order to firstDay if (typeof options.locale == 'object') { if (typeof options.locale.daysOfWeek == 'object') { // Create a copy of daysOfWeek to avoid modification of original // options object for reusability in multiple daterangepicker instances this.locale.daysOfWeek = options.locale.daysOfWeek.slice(); } if (typeof options.locale.firstDay == 'number') { this.locale.firstDay = options.locale.firstDay; var iterator = options.locale.firstDay; while (iterator > 0) { this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()); iterator--; } } } if (typeof options.opens == 'string') this.opens = options.opens; if (typeof options.showWeekNumbers == 'boolean') { this.showWeekNumbers = options.showWeekNumbers; } if (typeof options.buttonClasses == 'string') { this.buttonClasses = [options.buttonClasses]; } if (typeof options.buttonClasses == 'object') { this.buttonClasses = options.buttonClasses; } if (typeof options.showDropdowns == 'boolean') { this.showDropdowns = options.showDropdowns; } if (typeof options.singleDatePicker == 'boolean') { this.singleDatePicker = options.singleDatePicker; } if (typeof options.timePicker == 'boolean') { this.timePicker = options.timePicker; } if (typeof options.timePickerIncrement == 'number') { this.timePickerIncrement = options.timePickerIncrement; } if (typeof options.timePicker12Hour == 'boolean') { this.timePicker12Hour = options.timePicker12Hour; } //if no start/end dates set, check if an input element contains initial values if (typeof options.startDate == 'undefined' && typeof options.endDate == 'undefined') { if ($(this.element).is('input[type=text]')) { var val = $(this.element).val(); var split = val.split(this.separator); var start, end; if (split.length == 2) { start = moment(split[0], this.format); end = moment(split[1], this.format); } else if (this.singleDatePicker) { start = moment(val, this.format); end = moment(val, this.format); } if (start != null && end != null) { this.startDate = start; this.endDate = end; } } } if (typeof callback == 'function') { this.cb = callback; } if (!this.timePicker) { this.startDate = this.startDate.startOf('day'); this.endDate = this.endDate.startOf('day'); } if (this.singleDatePicker) { this.opens = 'right'; this.container.find('.calendar.right').show(); this.container.find('.calendar.left').hide(); this.container.find('.ranges').hide(); if (!this.container.find('.calendar.right').hasClass('single')) this.container.find('.calendar.right').addClass('single'); } else { this.container.find('.calendar.right').removeClass('single'); this.container.find('.ranges').show(); } this.oldStartDate = this.startDate.clone(); this.oldEndDate = this.endDate.clone(); this.leftCalendar = { month: moment([this.startDate.year(), this.startDate.month(), 1, this.startDate.hour(), this.startDate.minute()]), calendar: [] }; this.rightCalendar = { month: moment([this.endDate.year(), this.endDate.month(), 1, this.endDate.hour(), this.endDate.minute()]), calendar: [] }; if (this.opens == 'right') { //swap calendar positions var left = this.container.find('.calendar.left'); var right = this.container.find('.calendar.right'); left.removeClass('left').addClass('right'); right.removeClass('right').addClass('left'); } if (typeof options.ranges == 'undefined' && !this.singleDatePicker) { this.container.find('.calendar').show(); } this.container.addClass('opens' + this.opens); this.updateView(); this.updateCalendars() }, setStartDate: function(startDate) { if (typeof startDate == 'string') this.startDate = moment(startDate, this.format); if (typeof startDate == 'object') this.startDate = moment(startDate); if (!this.timePicker) this.startDate = this.startDate.startOf('day'); this.oldStartDate = this.startDate.clone(); this.updateView(); this.updateCalendars(); }, setEndDate: function(endDate) { if (typeof endDate == 'string') this.endDate = moment(endDate, this.format); if (typeof endDate == 'object') this.endDate = moment(endDate); if (!this.timePicker) this.endDate = this.endDate.startOf('day'); this.endDate = this.endDate.clone(); this.updateView(); this.updateCalendars(); }, mousedown: function (e) { e.stopPropagation(); }, updateView: function () { this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()); this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()); this.updateFormInputs(); }, updateFormInputs: function () { this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.format)); this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.format)); if (this.startDate.isSame(this.endDate) || this.startDate.isBefore(this.endDate)) { this.container.find('button.applyBtn').removeAttr('disabled'); } else { this.container.find('button.applyBtn').attr('disabled', 'disabled'); } }, updateFromControl: function () { if (!this.element.is('input')) return; if (!this.element.val().length) return; var dateString = this.element.val().split(this.separator); var start = moment(dateString[0], this.format); var end = moment(dateString[1], this.format); if (start == null || end == null) return; if (end.isBefore(start)) return; this.oldStartDate = this.startDate.clone(); this.oldEndDate = this.endDate.clone(); this.startDate = start; this.endDate = end; if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate)) this.notify(); this.updateCalendars(); }, notify: function () { this.updateView(); this.cb(this.startDate, this.endDate); }, move: function () { var parentOffset = { top: this.parentEl.offset().top - (this.parentEl.is('body') ? 0 : this.parentEl.scrollTop()), left: this.parentEl.offset().left - (this.parentEl.is('body') ? 0 : this.parentEl.scrollLeft()) }; if (this.opens == 'left') { this.container.css({ top: this.element.offset().top + this.element.outerHeight() - parentOffset.top, right: $(window).width() - this.element.offset().left - this.element.outerWidth() - parentOffset.left, left: 'auto' }); if (this.container.offset().left < 0) { this.container.css({ right: 'auto', left: 9 }); } } else { this.container.css({ top: this.element.offset().top + this.element.outerHeight() - parentOffset.top, left: this.element.offset().left - parentOffset.left, right: 'auto' }); if (this.container.offset().left + this.container.outerWidth() > $(window).width()) { this.container.css({ left: 'auto', right: 0 }); } } }, show: function (e) { this.container.show(); this.move(); if (e) { e.stopPropagation(); e.preventDefault(); } $(document).on('mousedown', $.proxy(this.hide, this)); this.element.trigger('show', this); }, hide: function (e) { this.container.hide(); if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate)) this.notify(); this.oldStartDate = this.startDate.clone(); this.oldEndDate = this.endDate.clone(); $(document).off('mousedown', this.hide); this.element.trigger('hide', this); }, enterRange: function (e) { var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.updateView(); } else { var dates = this.ranges[label]; this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.format)); this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.format)); } }, showCalendars: function() { this.container.find('.calendar').show(); this.move(); }, updateInputText: function() { if (this.element.is('input') && !this.singleDatePicker) { this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format)); } else if (this.element.is('input')) { this.element.val(this.startDate.format(this.format)); } }, clickRange: function (e) { var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.showCalendars(); } else { var dates = this.ranges[label]; this.startDate = dates[0]; this.endDate = dates[1]; if (!this.timePicker) { this.startDate.startOf('day'); this.endDate.startOf('day'); } this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute()); this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute()); this.updateCalendars(); this.updateInputText(); this.container.find('.calendar').hide(); this.hide(); this.element.trigger('apply', this); } }, clickPrev: function (e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.subtract('month', 1); } else { this.rightCalendar.month.subtract('month', 1); } this.updateCalendars(); }, clickNext: function (e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add('month', 1); } else { this.rightCalendar.month.add('month', 1); } this.updateCalendars(); }, enterDate: function (e) { var title = $(e.target).attr('data-title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].format(this.format)); } else { this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].format(this.format)); } }, clickDate: function (e) { var title = $(e.target).attr('data-title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { var startDate = this.leftCalendar.calendar[row][col]; var endDate = this.endDate; if (typeof this.dateLimit == 'object') { var maxDate = moment(startDate).add(this.dateLimit).startOf('day'); if (endDate.isAfter(maxDate)) { endDate = maxDate; } } } else { var startDate = this.startDate; var endDate = this.rightCalendar.calendar[row][col]; if (typeof this.dateLimit == 'object') { var minDate = moment(endDate).subtract(this.dateLimit).startOf('day'); if (startDate.isBefore(minDate)) { startDate = minDate; } } } if (this.singleDatePicker && cal.hasClass('left')) { endDate = startDate; } else if (this.singleDatePicker && cal.hasClass('right')) { startDate = endDate; } cal.find('td').removeClass('active'); if (startDate.isSame(endDate) || startDate.isBefore(endDate)) { $(e.target).addClass('active'); this.startDate = startDate; this.endDate = endDate; } else if (startDate.isAfter(endDate)) { $(e.target).addClass('active'); this.startDate = startDate; this.endDate = moment(startDate).add('day', 1).startOf('day'); } this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()); this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()); this.updateCalendars(); if (this.singleDatePicker) this.clickApply(); }, clickApply: function (e) { this.updateInputText(); this.hide(); this.element.trigger('apply', this); }, clickCancel: function (e) { this.startDate = this.oldStartDate; this.endDate = this.oldEndDate; this.updateView(); this.updateCalendars(); this.hide(); this.element.trigger('cancel', this); }, updateMonthYear: function (e) { var isLeft = $(e.target).closest('.calendar').hasClass('left'); var cal = this.container.find('.calendar.left'); if (!isLeft) cal = this.container.find('.calendar.right'); // Month must be Number for new moment versions var month = parseInt(cal.find('.monthselect').val(), 10); var year = cal.find('.yearselect').val(); if (isLeft) { this.leftCalendar.month.month(month).year(year); } else { this.rightCalendar.month.month(month).year(year); } this.updateCalendars(); }, updateTime: function(e) { var isLeft = $(e.target).closest('.calendar').hasClass('left'); var cal = this.container.find('.calendar.left'); if (!isLeft) cal = this.container.find('.calendar.right'); var hour = parseInt(cal.find('.hourselect').val()); var minute = parseInt(cal.find('.minuteselect').val()); if (this.timePicker12Hour) { var ampm = cal.find('.ampmselect').val(); if (ampm == 'PM' && hour < 12) hour += 12; if (ampm == 'AM' && hour == 12) hour = 0; } if (isLeft) { var start = this.startDate.clone(); start.hour(hour); start.minute(minute); this.startDate = start; this.leftCalendar.month.hour(hour).minute(minute); } else { var end = this.endDate.clone(); end.hour(hour); end.minute(minute); this.endDate = end; this.rightCalendar.month.hour(hour).minute(minute); } this.updateCalendars(); }, updateCalendars: function () { this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.month(), this.leftCalendar.month.year(), this.leftCalendar.month.hour(), this.leftCalendar.month.minute(), 'left'); this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.month(), this.rightCalendar.month.year(), this.rightCalendar.month.hour(), this.rightCalendar.month.minute(), 'right'); this.container.find('.calendar.left').html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.maxDate)); this.container.find('.calendar.right').html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.startDate, this.maxDate)); this.container.find('.ranges li').removeClass('active'); var customRange = true; var i = 0; for (var range in this.ranges) { if (this.timePicker) { if (this.startDate.isSame(this.ranges[range][0]) && this.endDate.isSame(this.ranges[range][1])) { customRange = false; this.container.find('.ranges li:eq(' + i + ')').addClass('active'); } } else { //ignore times when comparing dates if time picker is not enabled if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) { customRange = false; this.container.find('.ranges li:eq(' + i + ')').addClass('active'); } } i++; } if (customRange) this.container.find('.ranges li:last').addClass('active'); }, buildCalendar: function (month, year, hour, minute, side) { var firstDay = moment([year, month, 1]); var lastMonth = moment(firstDay).subtract('month', 1).month(); var lastYear = moment(firstDay).subtract('month', 1).year(); var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth(); var dayOfWeek = firstDay.day(); //initialize a 6 rows x 7 columns array for the calendar var calendar = []; for (var i = 0; i < 6; i++) { calendar[i] = []; } //populate the calendar with date objects var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1; if (startDay > daysInLastMonth) startDay -= 7; if (dayOfWeek == this.locale.firstDay) startDay = daysInLastMonth - 6; var curDate = moment([lastYear, lastMonth, startDay, 12, minute]); for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add('hour', 24)) { if (i > 0 && col % 7 == 0) { col = 0; row++; } calendar[row][col] = curDate.clone().hour(hour); curDate.hour(12); } return calendar; }, renderDropdowns: function (selected, minDate, maxDate) { var currentMonth = selected.month(); var monthHtml = '<select class="monthselect">'; var inMinYear = false; var inMaxYear = false; for (var m = 0; m < 12; m++) { if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) { monthHtml += "<option value='" + m + "'" + (m === currentMonth ? " selected='selected'" : "") + ">" + this.locale.monthNames[m] + "</option>"; } } monthHtml += "</select>"; var currentYear = selected.year(); var maxYear = (maxDate && maxDate.year()) || (currentYear + 5); var minYear = (minDate && minDate.year()) || (currentYear - 50); var yearHtml = '<select class="yearselect">'; for (var y = minYear; y <= maxYear; y++) { yearHtml += '<option value="' + y + '"' + (y === currentYear ? ' selected="selected"' : '') + '>' + y + '</option>'; } yearHtml += '</select>'; return monthHtml + yearHtml; }, renderCalendar: function (calendar, selected, minDate, maxDate) { var html = '<div class="calendar-date">'; html += '<table class="table-condensed">'; html += '<thead>'; html += '<tr>'; // add empty cell for week number if (this.showWeekNumbers) html += '<th></th>'; if (!minDate || minDate.isBefore(calendar[1][1])) { html += '<th class="prev available"><i class="fa fa-angle-left icon-arrow-left"></i></th>'; } else { html += '<th></th>'; } var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY"); if (this.showDropdowns) { dateHtml = this.renderDropdowns(calendar[1][1], minDate, maxDate); } html += '<th colspan="5" style="width: auto">' + dateHtml + '</th>'; if (!maxDate || maxDate.isAfter(calendar[1][1])) { html += '<th class="next available"><i class="fa fa-angle-right icon-arrow-right"></i></th>'; } else { html += '<th></th>'; } html += '</tr>'; html += '<tr>'; // add week number label if (this.showWeekNumbers) html += '<th class="week">' + this.locale.weekLabel + '</th>'; $.each(this.locale.daysOfWeek, function (index, dayOfWeek) { html += '<th>' + dayOfWeek + '</th>'; }); html += '</tr>'; html += '</thead>'; html += '<tbody>'; for (var row = 0; row < 6; row++) { html += '<tr>'; // add week number if (this.showWeekNumbers) html += '<td class="week">' + calendar[row][0].week() + '</td>'; for (var col = 0; col < 7; col++) { var cname = 'available '; cname += (calendar[row][col].month() == calendar[1][1].month()) ? '' : 'off'; if ((minDate && calendar[row][col].isBefore(minDate)) || (maxDate && calendar[row][col].isAfter(maxDate))) { cname = ' off disabled '; } else if (calendar[row][col].format('YYYY-MM-DD') == selected.format('YYYY-MM-DD')) { cname += ' active '; if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD')) { cname += ' start-date '; } if (calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD')) { cname += ' end-date '; } } else if (calendar[row][col] >= this.startDate && calendar[row][col] <= this.endDate) { cname += ' in-range '; if (calendar[row][col].isSame(this.startDate)) { cname += ' start-date '; } if (calendar[row][col].isSame(this.endDate)) { cname += ' end-date '; } } var title = 'r' + row + 'c' + col; html += '<td class="' + cname.replace(/\s+/g, ' ').replace(/^\s?(.*?)\s?$/, '$1') + '" data-title="' + title + '">' + calendar[row][col].date() + '</td>'; } html += '</tr>'; } html += '</tbody>'; html += '</table>'; html += '</div>'; if (this.timePicker) { html += '<div class="calendar-time">'; html += '<select class="hourselect">'; var start = 0; var end = 23; var selected_hour = selected.hour(); if (this.timePicker12Hour) { start = 1; end = 12; if (selected_hour >= 12) selected_hour -= 12; if (selected_hour == 0) selected_hour = 12; } for (var i = start; i <= end; i++) { if (i == selected_hour) { html += '<option value="' + i + '" selected="selected">' + i + '</option>'; } else { html += '<option value="' + i + '">' + i + '</option>'; } } html += '</select> : '; html += '<select class="minuteselect">'; for (var i = 0; i < 60; i += this.timePickerIncrement) { var num = i; if (num < 10) num = '0' + num; if (i == selected.minute()) { html += '<option value="' + i + '" selected="selected">' + num + '</option>'; } else { html += '<option value="' + i + '">' + num + '</option>'; } } html += '</select> '; if (this.timePicker12Hour) { html += '<select class="ampmselect">'; if (selected.hour() >= 12) { html += '<option value="AM">AM</option><option value="PM" selected="selected">PM</option>'; } else { html += '<option value="AM" selected="selected">AM</option><option value="PM">PM</option>'; } html += '</select>'; } html += '</div>'; } return html; }, remove: function() { this.container.remove(); this.element.off('.daterangepicker'); this.element.removeData('daterangepicker'); } }; $.fn.daterangepicker = function (options, cb) { this.each(function () { var el = $(this); if (el.data('daterangepicker')) el.data('daterangepicker').remove(); el.data('daterangepicker', new DateRangePicker(el, options, cb)); }); return this; }; }(window.jQuery);
JavaScript
/* noUiSlider - refreshless.com/nouislider/ */ (function($, UNDEF){ $.fn.noUiSlider = function( options ){ var namespace = '.nui' // Create a shorthand for document event binding ,all = $(document) // Create a map of touch and mouse actions ,actions = { start: 'mousedown' + namespace + ' touchstart' + namespace ,move: 'mousemove' + namespace + ' touchmove' + namespace ,end: 'mouseup' + namespace + ' touchend' + namespace } // Make a copy of the current val function. ,$VAL = $.fn.val // Define a set of standard HTML classes for // the various structures noUiSlider uses. ,clsList = [ 'noUi-base' // 0 ,'noUi-origin' // 1 ,'noUi-handle' // 2 ,'noUi-input' // 3 ,'noUi-active' // 4 ,'noUi-state-tap' // 5 ,'noUi-target' // 6 ,'-lower' // 7 ,'-upper' // 8 ,'noUi-connect' // 9 ,'noUi-vertical' // 10 ,'noUi-horizontal' // 11 ,'handles' // 12 ,'noUi-background' // 13 ,'noUi-z-index' // 14 ] // Define an extendible object with base classes for the various // structure elements in the slider. These can be extended by simply // pushing to the array, which reduces '.addClass()' calls. ,stdCls = { base: [clsList[0], clsList[13]] ,origin: [clsList[1]] ,handle: [clsList[2]] } // The percentage object contains some well tested math to turn values // to and from percentages. It can be a bit strange to wrap your head // around the individual calls, but they'll do their job with all positive // and negative input values. ,percentage = { to: function ( range, value ) { value = range[0] < 0 ? value + Math.abs(range[0]) : value - range[0]; return (value * 100) / this.len(range); } ,from: function ( range, value ) { return (value * 100) / this.len(range); } ,is: function ( range, value ) { return ((value * this.len(range)) / 100) + range[0]; } ,len: function ( range ) { return (range[0] > range[1] ? range[0] - range[1] : range[1] - range[0]); } }; // When the browser supports MsPointerEvents, // Don't bind touch or mouse events. The touch events are // currently only implemented by IE(10), but they are stable // and convenient to use. if ( window.navigator.msPointerEnabled ) { actions = { start: 'MSPointerDown' + namespace ,move: 'MSPointerMove' + namespace ,end: 'MSPointerUp' + namespace }; } // Shorthand for stopping propagation on an object. // Calling a function prevents having to define one inline. function stopPropagation ( e ) { e.stopPropagation(); } // Test an array of objects, and calls them if they are a function. function call ( f, scope, args ) { $.each(f,function(i,q){ if (typeof q === "function") { q.call(scope, args); } }); } // Test if there is anything that should prevent an event from being // handled, such as a disabled state of a slider moving in the 'tap' event. function blocked ( e ) { return ( e.data.base.data('target').is('[class*="noUi-state-"], [disabled]') ); } function fixEvent ( e, preventDefault ) { // Required (in at the very least Chrome) to prevent // scrolling and panning while attempting to slide. // The tap event also depends on this. if( preventDefault ) { e.preventDefault(); } // Filter the event to register the type, // which can be touch, mouse or pointer. Since noUiSlider 4 // so longer binds touch OR mouse, but rather touch AND mouse, // offset changes need to be made on an event specific basis. var jQueryEvent = e ,touch = e.type.indexOf('touch') === 0 ,mouse = e.type.indexOf('mouse') === 0 ,pointer = e.type.indexOf('MSPointer') === 0 ,x,y; // Fetch the event where jQuery didn't make any modifications. e = e.originalEvent; if (touch) { // noUiSlider supports one movement at a time, for now. // It is therefore safe to select the first 'changedTouch'. x = e.changedTouches[0].pageX; y = e.changedTouches[0].pageY; } if (mouse) { // Polyfill the pageXOffset and pageYOffset // variables for IE7 and IE8; if(window.pageXOffset === UNDEF){ window.pageXOffset = document.documentElement.scrollLeft; window.pageYOffset = document.documentElement.scrollTop; } x = e.clientX + window.pageXOffset; y = e.clientY + window.pageYOffset; } if (pointer) { x = e.pageX; y = e.pageY; } return { pass: jQueryEvent.data, e:e, x:x, y:y, t: [touch, mouse, pointer] }; } function getPercentage( a ){ return parseFloat(this.style[a]); } function test ( o, set ){ // Checks whether a variable is numerical. function num(e){ return !isNaN(e) && isFinite(e); } // Checks whether a variable is a candidate to be a // valid serialization target. function ser(r){ return ( r instanceof $ || typeof r === 'string' || r === false ); } /** These tests are structured with an item for every option available. Every item contains an 'r' flag, which marks a required option, and a 't' function, which in turn takes some arguments: - a reference to options object - the value for the option - the option name (optional); The testing function returns false when an error is detected, or true when everything is OK. Every test also has an 'init' method which appends the parent object to all children. **/ var TESTS = { /* Handles. Has default, can be 1 or 2; */ "handles": { r: true ,t: function(o,q){ q = parseInt(q, 10); return ( q === 1 || q === 2 ); } } /* Range. * Must be an array of two numerical floats, * which can't be identical. */ ,"range": { r: true ,t: function(o,q,w){ if(q.length!==2){ return false; } // Reset the array to floats q = [parseFloat(q[0]),parseFloat(q[1])]; // Test if those floats are numerical if(!num(q[0])||!num(q[1])){ return false; } // When this test is run for range, the values can't // be identical. if(w==="range" && q[0] === q[1]){ return false; } o[w]=q; return true; } } /* Start. * Must be an array of two numerical floats when handles = 2; * Uses 'range' test. * When handles = 1, a single float is also allowed. */ ,"start": { r: true ,t: function(o,q,w){ if(o.handles === 1){ if($.isArray(q)){ q=q[0]; } q = parseFloat(q); o.start = [q]; return num(q); } return this.parent.range.t(o,q,w); } } /* Connect. * Must be true or false when handles = 2; * Can use 'lower' and 'upper' when handles = 1. */ ,"connect": { t: function(o,q){ return ( q === true || q === false || ( q === 'lower' && o.handles === 1) || ( q === 'upper' && o.handles === 1)); } } /* Connect. * Will default to horizontal, not required. */ ,"orientation": { t: function(o,q){ return ( q === "horizontal" || q === "vertical" ); } } /* Margin. * Must be a float, has a default value. */ ,"margin": { r: true ,t: function(o,q,w){ q = parseFloat(q); o[w]=q; return num(q); } } /* Serialization. * Required, but has default. Resolution option can be missing, * 'to' can't. Must be an array when using two handles, can * be a singular value when using one handle. */ ,"serialization": { r: true ,t: function(o,q){ if(!q.resolution){ o.serialization.resolution = 0.01; } else { switch(q.resolution){ case 1: case 0.1: case 0.01: case 0.001: case 0.0001: case 0.00001: break; default: return false; } } if(q.to){ if(o.handles === 1){ // Wrap the value for one handle into an array; if(!$.isArray(q.to)){ q.to = [q.to]; } // Write back to the options object; o.serialization.to = q.to; // Run test for valid serialization target. return ser(q.to[0]); } return (q.to.length === 2 && ser(q.to[0]) && ser(q.to[1])); } // If no 'to' option is specified, // the serialization option is invalid. return false; } } /* Slide. * Not required. Must be a function. */ ,"slide": { t: function(o,q){ return typeof q === "function"; } } /* Slide. * Not required. Tested using the 'margin' function. */ ,"step": { t: function(o,q,w){ return this.parent.margin.t(o,q,w); } } /* [init] * Not an option test. Calling this method will return the * parent object with some cross references that allow crawling * the object upward, which normally isn't possible in Javascript. */ ,"init": function(){ var obj = this; $.each(obj,function(i,c){ c.parent = obj; }); delete this.init; return this; } }, // Prepare a set of tests, by adding some internal reference // values not available in native Javascript object implementation. a = TESTS.init(); // Loop all provided tests; // v is the option set, i is the index for the current test. $.each(a, function( i, v ){ // If the value is required but not set, // or if the test fails, throw an error. if((v.r && (!o[i] && o[i] !== 0)) || ((o[i] || o[i] === 0) && !v.t(o,o[i],i))){ // For debugging purposes it might be very useful // to know what option caused the trouble. if(console&&console.log){ console.log( "Slider:\t\t\t", set, "\nOption:\t\t\t", i, "\nValue:\t\t\t", o[i] ); } // Since 'error' will prevent further script execution, // log the error first. $.error("Error on noUiSlider initialisation."); return false; } }); } function closest( value, to ){ // Round a value to the closest 'to'. // Used with the 'step' option. return Math.round(value / to) * to; } function setHandle ( handle, to, forgive ) { var nui = handle.data('nui').options // Get the array of handles from the base. // Will be undefined at initialisation. ,handles = handle.data('nui').base.data(clsList[12]) // Get some settings from the handle; ,style = handle.data('nui').style ,dec = handle.data('nui').decimals ,hLimit; // Ignore the call if the handle won't move anyway. if(to === handle[0].getPercentage(style)) { return false; } // Limit 'to' to 0 - 100 to = to < 0 ? 0 : to > 100 ? 100 : to; // Handle the step option, or ignore it. if( nui.step && !forgive ){ to = closest( to, percentage.from(nui.range, nui.step)); } // Stop handling this call if the handle won't step to a new value. if(to === handle[0].getPercentage(style)) { return false; } // We're done if this is the only handle, // if the handle bounce is trusted to the user // or on initialisation when handles isn't defined yet. if( handle.siblings('.' + clsList[1]).length && !forgive && handles ){ // Otherwise, the handle should bounce, // and stop at the other handle. if ( handle.data('nui').number ) { hLimit = handles[0][0].getPercentage(style) + nui.margin; to = to < hLimit ? hLimit : to; } else { hLimit = handles[1][0].getPercentage(style) - nui.margin; to = to > hLimit ? hLimit : to; } // Stop handling this call if the handle can't move past another. if(to === handle[0].getPercentage(style)) { return false; } } // Fix for the z-index issue where the lower handle gets stuck // below the upper one. Since this function is called for every // movement, toggleClass cannot be used. if(handle.data('nui').number === 0 && to > 95){ handle.addClass(clsList[14]); } else { handle.removeClass(clsList[14]); } // Set handle to new location handle.css( style , to + '%'); // Write the value to the serialization object. handle.data('store').val(percentage.is(nui.range, to).toFixed(dec)); return true; } function store ( handle, S ) { var i = handle.data('nui').number; if( S.to[i] instanceof $ ) { // Attach a change event to the supplied jQuery object, // which will just trigger the val function on the parent. // In some cases, the change event will not fire on select elements, // so listen to 'blur' too. return S.to[i].on('change'+namespace+' blur'+namespace, function(){ var arr = [null, null]; arr[i] = $(this).val(); handle.data('nui').target.val(arr, true); }); } if ( typeof S.to[i] === "string" ) { // Append a new object to the noUiSlider base, // prevent change events flowing upward. return $('<input type="hidden" class="'+clsList[3]+'" name="' + S.to[i] + '">') .appendTo(handle).change(stopPropagation); } if ( S.to[i] === false ) { // Create an object capable of handling all jQuery calls. return { // The value will be stored a data on the handle. val : function(a) { // Value function provides a getter and a setter. // Can't just test for !a, as a might be 0. if ( a === UNDEF ) { // Either set... return this.handleElement.data('nui-val'); } // ... or return; this.handleElement.data('nui-val', a); } // The object could be mistaken for a jQuery object, // make sure that doesn't trigger any errors. ,hasClass: function(){ return false; } // The val function needs access to the handle. ,handleElement: handle }; } } function move( event ) { // This function is called often, keep it light. event = fixEvent( event, true ); if(!event) { return; } var base = event.pass.base ,style = base.data('style') // Subtract the initial movement from the current event, // while taking vertical sliders into account. ,proposal = event.x - event.pass.startEvent.x ,baseSize = style === 'left' ? base.width() : base.height(); // This loop prevents a long ternary for the proposal variable. if(style === 'top') { proposal = event.y - event.pass.startEvent.y; } proposal = event.pass.position + ( ( proposal * 100 ) / baseSize ); setHandle( event.pass.handle, proposal ); // Trigger the 'slide' event, pass the target so that it is 'this'. call( [ event.pass.base.data('options').slide ] ,event.pass.base.data('target') ); } function end ( event ) { if ( blocked( event ) ) { return; } // Handle is no longer active; event.data.handle.children().removeClass(clsList[4]); // Unbind move and end events, to prevent // them stacking up over and over; all.off(actions.move); all.off(actions.end); $('body').off(namespace); event.data.base.data('target').change(); } function start ( event ) { // When the slider is in a transitional state, stop. // Also prevents interaction with disabled sliders. if ( blocked( event ) ) { return; } event = fixEvent( event ); if(!event) { return; } var handle = event.pass.handle ,position = handle[0].getPercentage( handle.data('nui').style ); handle.children().addClass('noUi-active'); // Attach the move event handler, while // passing all relevant information along. all.on(actions.move, { startEvent: event ,position: position ,base: event.pass.base ,handle: handle }, move); all.on(actions.end, { base: event.pass.base, handle: handle }, end); // Prevent text selection when dragging the handles. // This doesn't prevent the browser defaulting to the I like cursor. $('body').on('selectstart' + namespace, function(){ return false; }); } function selfEnd( event ) { // Trigger the end handler. Supply correct data using a // fake object that contains all required information; end({ data: { base: event.data.base, handle: event.data.handle } }); // Stop propagation so that the tap handler doesn't interfere; event.stopPropagation(); } function tap ( event ) { if ( blocked( event ) || event.data.base.find('.' + clsList[4]).length ) { return; } event = fixEvent( event ); // The event handler might have rejected this event. if(!event) { return; } // Getting variables from the event is not required, but // shortens other expressions and is far more convenient; var i, handle, hCenter, base = event.pass.base ,handles = event.pass.handles ,style = base.data('style') ,eventXY = event[style === 'left' ? 'x' : 'y'] ,baseSize = style === 'left' ? base.width() : base.height() // Create a standard set off offsets compensated with the // scroll distance. When required, correct for scrolling. // This is a bug, as far as I can see, in IE(10?). ,correction = { x: ( event.t[2] ? window.pageXOffset : 0 ) } ,offset = { handles: [] ,base: { left: base.offset().left - correction.x ,top: base.offset().top } }; // Loop handles and add data to the offset list. for (i = 0; i < handles.length; i++ ) { offset.handles.push({ left: handles[i].offset().left - correction.x ,top: handles[i].offset().top }); } // Calculate the central point between the handles; hCenter = handles.length === 1 ? 0 : (( offset.handles[0][style] + offset.handles[1][style] ) / 2 ); // If there is just one handle, // or the lower handles in closest to the event, // select the first handle. Otherwise, pick the second. if ( handles.length === 1 || eventXY < hCenter ){ handle = handles[0]; } else { handle = handles[1]; } // Flag the slider as it is now in a transitional state. // Transition takes 300 ms, so re-enable the slider afterwards. base.addClass(clsList[5]); setTimeout(function(){ base.removeClass(clsList[5]); }, 300); // Calculate the new position for the handle and // trigger the movement. setHandle( handle ,(((eventXY - offset.base[style]) * 100) / baseSize) ); // Trigger the 'slide' event, pass the target so that it is 'this'. call( [ handle.data('nui').options.slide ] ,base.data('target') ); base.data('target').change(); } function create ( ) { return this.each(function( index, target ){ // Target is the wrapper that will receive all external // scripting interaction. It has no styling and serves no // other function. target = $(target); target.addClass(clsList[6]); // Base is the internal main 'bar'. var i, style, decimals, handle ,base = $('<div/>').appendTo(target) ,handles = [] ,cls = { base: stdCls.base ,origin: [ stdCls.origin.concat([clsList[1] + clsList[7]]) ,stdCls.origin.concat([clsList[1] + clsList[8]]) ] ,handle: [ stdCls.handle.concat([clsList[2] + clsList[7]]) ,stdCls.handle.concat([clsList[2] + clsList[8]]) ] }; // Set defaults where applicable; options = $.extend({ handles: 2 ,margin: 0 ,orientation: "horizontal" }, options) || {}; // Set a default for serialization; if(!options.serialization){ options.serialization = { to : [false, false] ,resolution : 0.01 }; } // Run all options through a testing mechanism to ensure correct // input. The test function will throw errors, so there is // no need to capture the result of this call. It should be noted // that options might get modified to be handled properly. E.g. // wrapping integers in arrays. test(options, target); // I can't type serialization any more, and it doesn't compress // very well, so shorten it. options.S = options.serialization; // INCOMPLETE if( options.connect ) { cls.origin[0].push(clsList[9]); if( options.connect === "lower" ){ // Add some styling classes to the base; cls.base.push(clsList[9], clsList[9] + clsList[7]); // When using the option 'Lower', there is only one // handle, and thus only one origin. cls.origin[0].push(clsList[13]); } else { cls.base.push(clsList[9] + clsList[8]); } } // Parse the syntactic sugar that is the serialization // resolution option to a usable integer. style = options.orientation === 'vertical' ? 'top' : 'left'; decimals = options.S.resolution.toString().split('.'); // Checking for a string "1", since the resolution needs // to be cast to a string to split in on the period. decimals = decimals[0] === "1" ? 0 : decimals[1].length; // Add classes for horizontal and vertical sliders. // The horizontal class is provided for completeness, // as it isn't used in the default theme. if( options.orientation === "vertical" ){ cls.base.push(clsList[10]); } else { cls.base.push(clsList[11]); } // Merge base classes with default; base.addClass(cls.base.join(" ")).data('target', target); for (i = 0; i < options.handles; i++ ) { handle = $('<div><div/></i>').appendTo(base); // Add all default and option-specific classes to the // origins and handles. handle.addClass(cls.origin[i].join(" ")); handle.children().addClass(cls.handle[i].join(" ")); // These events are only bound to the visual handle element, // not the 'real' origin element. handle.children() .on(actions.start, { base: base, handle: handle }, start) .on(actions.end, { base: base, handle: handle }, selfEnd); // Make sure every handle has access to all primary // variables. Can't uses jQuery's .data( obj ) structure // here, as 'store' needs some values from the 'nui' object. handle.data('nui', { target: target ,decimals: decimals ,options: options ,base: base ,style: style ,number: i }).data('store', store ( handle ,options.S )); // Attach a function to the native DOM element, // since jQuery wont let me get the current value in percentages. handle[0].getPercentage = getPercentage; // Make handles loop-able handles.push(handle); // Set the handle to its initial position; setHandle(handle, percentage.to(options.range, options.start[i])); } // The base could use the handles too; base.data({ options: options ,handles: handles ,style: style }); // Add a downstream reference to the target as well. target.data({ base: base ,handles: handles }); // The tap event. base.on(actions.end, { base: base, handles: handles }, tap); }); } function val ( args, ignore ) { // Setter if( args !== UNDEF ){ // If the val is to be set to a number, which is valid // when using a one-handle slider, wrap it in an array. if(!$.isArray(args)){ args = [args]; } // Setting is handled properly for each slider in the data set. return this.each(function(){ $.each($(this).data(clsList[12]), function(i, handle){ // The set request might want to ignore this handle. if( args[i] === null ) { return; } // Calculate a new position for the handle. var value, current ,range = handle.data('nui').options.range ,to = percentage.to( range ,parseFloat(args[i]) ), // Set handle to new location, and make sure developer // input is always accepted. The ignore flag indicates // input from user facing elements. result = setHandle(handle, to, (ignore === true ? false : true)); // If the value of the input doesn't match the slider, // reset it. if(!result){ // Get the 'store' object, which can be an input element // or a wrapper arround a 'data' call. value = handle.data('store').val(); current = percentage.is(range, handle[0].getPercentage(handle.data('nui').style) ).toFixed(handle.data('nui').decimals); // Sometimes the input is changed to a value the slider // has rejected. This can occur when using 'select' or // 'input[type="number"]' elements. In this case, // set the value back to the input. if(value !== current){ handle.data('store').val(current); } } }); }); } // Or, if the function was called without arguments, // act as a 'getter'; var re = []; // Loop the handles, and get the value from the input // for every handle on its' own. $.each($(this).data(clsList[12]), function(i, handle){ re.push( handle.data('store').val() ); }); // If the slider has just one handle, return a single value. // Otherwise, return an array. return ( re.length === 1 ? re[0] : re) ; } // Overwrite the native jQuery val() function // with a simple handler. noUiSlider will use the internal // value method, anything else will use the standard method. $.fn.val = function(){ return this.hasClass(clsList[6]) ? val.apply(this, arguments) : $VAL.apply(this, arguments); }; return create.apply(this, arguments); }; }(jQuery));
JavaScript
;(function(){ /** * Require the given path. * * @param {String} path * @return {Object} exports * @api public */ function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module.exports) { module.exports = {}; module.client = module.component = true; module.call(this, module.exports, require.relative(resolved), module); } return module.exports; } /** * Registered modules. */ require.modules = {}; /** * Registered aliases. */ require.aliases = {}; /** * Resolve `path`. * * Lookup: * * - PATH/index.js * - PATH.js * - PATH * * @param {String} path * @return {String} path or null * @api private */ require.resolve = function(path) { if (path.charAt(0) === '/') path = path.slice(1); var paths = [ path, path + '.js', path + '.json', path + '/index.js', path + '/index.json' ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; } }; /** * Normalize `path` relative to the current path. * * @param {String} curr * @param {String} path * @return {String} * @api private */ require.normalize = function(curr, path) { var segs = []; if ('.' != path.charAt(0)) return path; curr = curr.split('/'); path = path.split('/'); for (var i = 0; i < path.length; ++i) { if ('..' == path[i]) { curr.pop(); } else if ('.' != path[i] && '' != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join('/'); }; /** * Register module at `path` with callback `definition`. * * @param {String} path * @param {Function} definition * @api private */ require.register = function(path, definition) { require.modules[path] = definition; }; /** * Alias a module definition. * * @param {String} from * @param {String} to * @api private */ require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; /** * Return a require function relative to the `parent` path. * * @param {String} parent * @return {Function} * @api private */ require.relative = function(parent) { var p = require.normalize(parent, '..'); /** * lastIndexOf helper. */ function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * The relative require() itself. */ function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } /** * Resolve relative to the parent. */ localRequire.resolve = function(path) { var c = path.charAt(0); if ('/' == c) return path.slice(1); if ('.' == c) return require.normalize(p, path); // resolve deps by returning // the dep in the nearest "deps" // directory var segs = parent.split('/'); var i = lastIndexOf(segs, 'deps') + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join('/') + '/deps/' + path; return path; }; /** * Check if module is defined at `path`. */ localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("component-emitter/index.js", function(exports, require, module){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = function(event, fn){ this._callbacks = this._callbacks || {}; var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = callbacks.indexOf(fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }); require.register("dropzone/index.js", function(exports, require, module){ /** * Exposing dropzone */ module.exports = require("./lib/dropzone.js"); }); require.register("dropzone/lib/dropzone.js", function(exports, require, module){ /* # # More info at [www.dropzonejs.com](http://www.dropzonejs.com) # # Copyright (c) 2012, Matias Meno # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # */ (function() { var Dropzone, Em, camelize, contentLoaded, noop, without, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __slice = [].slice; Em = typeof Emitter !== "undefined" && Emitter !== null ? Emitter : require("emitter"); noop = function() {}; Dropzone = (function(_super) { var extend; __extends(Dropzone, _super); /* This is a list of all available events you can register on a dropzone object. You can register an event handler like this: dropzone.on("dragEnter", function() { }); */ Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "selectedfiles", "addedfile", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded"]; Dropzone.prototype.defaultOptions = { url: null, method: "post", withCredentials: false, parallelUploads: 2, uploadMultiple: false, maxFilesize: 256, paramName: "file", createImageThumbnails: true, maxThumbnailFilesize: 10, thumbnailWidth: 100, thumbnailHeight: 100, maxFiles: null, params: {}, clickable: true, ignoreHiddenFiles: true, acceptedFiles: null, acceptedMimeTypes: null, autoProcessQueue: true, addRemoveLinks: false, previewsContainer: null, dictDefaultMessage: "Drop files here to upload", dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.", dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: {{maxFilesize}}MB.", dictInvalidFileType: "You can't upload files of this type.", dictResponseError: "Server responded with {{statusCode}} code.", dictCancelUpload: "Cancel upload", dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", dictRemoveFile: "Remove file", dictRemoveFileConfirmation: null, dictMaxFilesExceeded: "You can only upload {{maxFiles}} files.", accept: function(file, done) { return done(); }, init: function() { return noop; }, forceFallback: false, fallback: function() { var child, messageElement, span, _i, _len, _ref; this.element.className = "" + this.element.className + " dz-browser-not-supported"; _ref = this.element.getElementsByTagName("div"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; if (/(^| )dz-message($| )/.test(child.className)) { messageElement = child; child.className = "dz-message"; continue; } } if (!messageElement) { messageElement = Dropzone.createElement("<div class=\"dz-message\"><span></span></div>"); this.element.appendChild(messageElement); } span = messageElement.getElementsByTagName("span")[0]; if (span) { span.textContent = this.options.dictFallbackMessage; } return this.element.appendChild(this.getFallbackForm()); }, resize: function(file) { var info, srcRatio, trgRatio; info = { srcX: 0, srcY: 0, srcWidth: file.width, srcHeight: file.height }; srcRatio = file.width / file.height; trgRatio = this.options.thumbnailWidth / this.options.thumbnailHeight; if (file.height < this.options.thumbnailHeight || file.width < this.options.thumbnailWidth) { info.trgHeight = info.srcHeight; info.trgWidth = info.srcWidth; } else { if (srcRatio > trgRatio) { info.srcHeight = file.height; info.srcWidth = info.srcHeight * trgRatio; } else { info.srcWidth = file.width; info.srcHeight = info.srcWidth / trgRatio; } } info.srcX = (file.width - info.srcWidth) / 2; info.srcY = (file.height - info.srcHeight) / 2; return info; }, /* Those functions register themselves to the events on init and handle all the user interface specific stuff. Overwriting them won't break the upload but can break the way it's displayed. You can overwrite them if you don't like the default behavior. If you just want to add an additional event handler, register it on the dropzone object and don't overwrite those options. */ drop: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragstart: noop, dragend: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragenter: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragover: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragleave: function(e) { return this.element.classList.remove("dz-drag-hover"); }, selectedfiles: function(files) { if (this.element === this.previewsContainer) { return this.element.classList.add("dz-started"); } }, reset: function() { return this.element.classList.remove("dz-started"); }, addedfile: function(file) { var _this = this; file.previewElement = Dropzone.createElement(this.options.previewTemplate); file.previewTemplate = file.previewElement; this.previewsContainer.appendChild(file.previewElement); file.previewElement.querySelector("[data-dz-name]").textContent = file.name; file.previewElement.querySelector("[data-dz-size]").innerHTML = this.filesize(file.size); if (this.options.addRemoveLinks) { file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>"); file._removeLink.addEventListener("click", function(e) { e.preventDefault(); e.stopPropagation(); if (file.status === Dropzone.UPLOADING) { return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() { return _this.removeFile(file); }); } else { if (_this.options.dictRemoveFileConfirmation) { return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() { return _this.removeFile(file); }); } else { return _this.removeFile(file); } } }); file.previewElement.appendChild(file._removeLink); } return this._updateMaxFilesReachedClass(); }, removedfile: function(file) { var _ref; if ((_ref = file.previewElement) != null) { _ref.parentNode.removeChild(file.previewElement); } return this._updateMaxFilesReachedClass(); }, thumbnail: function(file, dataUrl) { var thumbnailElement; file.previewElement.classList.remove("dz-file-preview"); file.previewElement.classList.add("dz-image-preview"); thumbnailElement = file.previewElement.querySelector("[data-dz-thumbnail]"); thumbnailElement.alt = file.name; return thumbnailElement.src = dataUrl; }, error: function(file, message) { file.previewElement.classList.add("dz-error"); return file.previewElement.querySelector("[data-dz-errormessage]").textContent = message; }, errormultiple: noop, processing: function(file) { file.previewElement.classList.add("dz-processing"); if (file._removeLink) { return file._removeLink.textContent = this.options.dictCancelUpload; } }, processingmultiple: noop, uploadprogress: function(file, progress, bytesSent) { return file.previewElement.querySelector("[data-dz-uploadprogress]").style.width = "" + progress + "%"; }, totaluploadprogress: noop, sending: noop, sendingmultiple: noop, success: function(file) { return file.previewElement.classList.add("dz-success"); }, successmultiple: noop, canceled: function(file) { return this.emit("error", file, "Upload canceled."); }, canceledmultiple: noop, complete: function(file) { if (file._removeLink) { return file._removeLink.textContent = this.options.dictRemoveFile; } }, completemultiple: noop, maxfilesexceeded: noop, previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-success-mark\"><span>✔</span></div>\n <div class=\"dz-error-mark\"><span>✘</span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>" }; extend = function() { var key, object, objects, target, val, _i, _len; target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = objects.length; _i < _len; _i++) { object = objects[_i]; for (key in object) { val = object[key]; target[key] = val; } } return target; }; function Dropzone(element, options) { var elementOptions, fallback, _ref; this.element = element; this.version = Dropzone.version; this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, ""); this.clickableElements = []; this.listeners = []; this.files = []; if (typeof this.element === "string") { this.element = document.querySelector(this.element); } if (!(this.element && (this.element.nodeType != null))) { throw new Error("Invalid dropzone element."); } if (this.element.dropzone) { throw new Error("Dropzone already attached."); } Dropzone.instances.push(this); element.dropzone = this; elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {}; this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {}); if (this.options.forceFallback || !Dropzone.isBrowserSupported()) { return this.options.fallback.call(this); } if (this.options.url == null) { this.options.url = this.element.getAttribute("action"); } if (!this.options.url) { throw new Error("No URL provided."); } if (this.options.acceptedFiles && this.options.acceptedMimeTypes) { throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."); } if (this.options.acceptedMimeTypes) { this.options.acceptedFiles = this.options.acceptedMimeTypes; delete this.options.acceptedMimeTypes; } this.options.method = this.options.method.toUpperCase(); if ((fallback = this.getExistingFallback()) && fallback.parentNode) { fallback.parentNode.removeChild(fallback); } if (this.options.previewsContainer) { this.previewsContainer = Dropzone.getElement(this.options.previewsContainer, "previewsContainer"); } else { this.previewsContainer = this.element; } if (this.options.clickable) { if (this.options.clickable === true) { this.clickableElements = [this.element]; } else { this.clickableElements = Dropzone.getElements(this.options.clickable, "clickable"); } } this.init(); } Dropzone.prototype.getAcceptedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getRejectedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (!file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getQueuedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === Dropzone.QUEUED) { _results.push(file); } } return _results; }; Dropzone.prototype.getUploadingFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === Dropzone.UPLOADING) { _results.push(file); } } return _results; }; Dropzone.prototype.init = function() { var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1, _this = this; if (this.element.tagName === "form") { this.element.setAttribute("enctype", "multipart/form-data"); } if (this.element.classList.contains("dropzone") && !this.element.querySelector(".dz-message")) { this.element.appendChild(Dropzone.createElement("<div class=\"dz-default dz-message\"><span>" + this.options.dictDefaultMessage + "</span></div>")); } if (this.clickableElements.length) { setupHiddenFileInput = function() { if (_this.hiddenFileInput) { document.body.removeChild(_this.hiddenFileInput); } _this.hiddenFileInput = document.createElement("input"); _this.hiddenFileInput.setAttribute("type", "file"); _this.hiddenFileInput.setAttribute("multiple", "multiple"); if (_this.options.acceptedFiles != null) { _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles); } _this.hiddenFileInput.style.visibility = "hidden"; _this.hiddenFileInput.style.position = "absolute"; _this.hiddenFileInput.style.top = "0"; _this.hiddenFileInput.style.left = "0"; _this.hiddenFileInput.style.height = "0"; _this.hiddenFileInput.style.width = "0"; document.body.appendChild(_this.hiddenFileInput); return _this.hiddenFileInput.addEventListener("change", function() { var files; files = _this.hiddenFileInput.files; if (files.length) { _this.emit("selectedfiles", files); _this.handleFiles(files); } return setupHiddenFileInput(); }); }; setupHiddenFileInput(); } this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL; _ref1 = this.events; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { eventName = _ref1[_i]; this.on(eventName, this.options[eventName]); } this.on("uploadprogress", function() { return _this.updateTotalUploadProgress(); }); this.on("removedfile", function() { return _this.updateTotalUploadProgress(); }); this.on("canceled", function(file) { return _this.emit("complete", file); }); noPropagation = function(e) { e.stopPropagation(); if (e.preventDefault) { return e.preventDefault(); } else { return e.returnValue = false; } }; this.listeners = [ { element: this.element, events: { "dragstart": function(e) { return _this.emit("dragstart", e); }, "dragenter": function(e) { noPropagation(e); return _this.emit("dragenter", e); }, "dragover": function(e) { noPropagation(e); return _this.emit("dragover", e); }, "dragleave": function(e) { return _this.emit("dragleave", e); }, "drop": function(e) { noPropagation(e); return _this.drop(e); }, "dragend": function(e) { return _this.emit("dragend", e); } } } ]; this.clickableElements.forEach(function(clickableElement) { return _this.listeners.push({ element: clickableElement, events: { "click": function(evt) { if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) { return _this.hiddenFileInput.click(); } } } }); }); this.enable(); return this.options.init.call(this); }; Dropzone.prototype.destroy = function() { var _ref; this.disable(); this.removeAllFiles(true); if ((_ref = this.hiddenFileInput) != null ? _ref.parentNode : void 0) { this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput); this.hiddenFileInput = null; } return delete this.element.dropzone; }; Dropzone.prototype.updateTotalUploadProgress = function() { var acceptedFiles, file, totalBytes, totalBytesSent, totalUploadProgress, _i, _len, _ref; totalBytesSent = 0; totalBytes = 0; acceptedFiles = this.getAcceptedFiles(); if (acceptedFiles.length) { _ref = this.getAcceptedFiles(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; totalBytesSent += file.upload.bytesSent; totalBytes += file.upload.total; } totalUploadProgress = 100 * totalBytesSent / totalBytes; } else { totalUploadProgress = 100; } return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent); }; Dropzone.prototype.getFallbackForm = function() { var existingFallback, fields, fieldsString, form; if (existingFallback = this.getExistingFallback()) { return existingFallback; } fieldsString = "<div class=\"dz-fallback\">"; if (this.options.dictFallbackText) { fieldsString += "<p>" + this.options.dictFallbackText + "</p>"; } fieldsString += "<input type=\"file\" name=\"" + this.options.paramName + (this.options.uploadMultiple ? "[]" : "") + "\" " + (this.options.uploadMultiple ? 'multiple="multiple"' : void 0) + " /><button type=\"submit\">Upload!</button></div>"; fields = Dropzone.createElement(fieldsString); if (this.element.tagName !== "FORM") { form = Dropzone.createElement("<form action=\"" + this.options.url + "\" enctype=\"multipart/form-data\" method=\"" + this.options.method + "\"></form>"); form.appendChild(fields); } else { this.element.setAttribute("enctype", "multipart/form-data"); this.element.setAttribute("method", this.options.method); } return form != null ? form : fields; }; Dropzone.prototype.getExistingFallback = function() { var fallback, getFallback, tagName, _i, _len, _ref; getFallback = function(elements) { var el, _i, _len; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )fallback($| )/.test(el.className)) { return el; } } }; _ref = ["div", "form"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { tagName = _ref[_i]; if (fallback = getFallback(this.element.getElementsByTagName(tagName))) { return fallback; } } }; Dropzone.prototype.setupEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.addEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.removeEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.removeEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.disable = function() { var file, _i, _len, _ref, _results; this.clickableElements.forEach(function(element) { return element.classList.remove("dz-clickable"); }); this.removeEventListeners(); _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; _results.push(this.cancelUpload(file)); } return _results; }; Dropzone.prototype.enable = function() { this.clickableElements.forEach(function(element) { return element.classList.add("dz-clickable"); }); return this.setupEventListeners(); }; Dropzone.prototype.filesize = function(size) { var string; if (size >= 100000000000) { size = size / 100000000000; string = "TB"; } else if (size >= 100000000) { size = size / 100000000; string = "GB"; } else if (size >= 100000) { size = size / 100000; string = "MB"; } else if (size >= 100) { size = size / 100; string = "KB"; } else { size = size * 10; string = "b"; } return "<strong>" + (Math.round(size) / 10) + "</strong> " + string; }; Dropzone.prototype._updateMaxFilesReachedClass = function() { if (this.options.maxFiles && this.getAcceptedFiles().length >= this.options.maxFiles) { return this.element.classList.add("dz-max-files-reached"); } else { return this.element.classList.remove("dz-max-files-reached"); } }; Dropzone.prototype.drop = function(e) { var files, items; if (!e.dataTransfer) { return; } this.emit("drop", e); files = e.dataTransfer.files; this.emit("selectedfiles", files); if (files.length) { items = e.dataTransfer.items; if (items && items.length && ((items[0].webkitGetAsEntry != null) || (items[0].getAsEntry != null))) { this.handleItems(items); } else { this.handleFiles(files); } } }; Dropzone.prototype.handleFiles = function(files) { var file, _i, _len, _results; _results = []; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; _results.push(this.addFile(file)); } return _results; }; Dropzone.prototype.handleItems = function(items) { var entry, item, _i, _len; for (_i = 0, _len = items.length; _i < _len; _i++) { item = items[_i]; if (item.webkitGetAsEntry != null) { entry = item.webkitGetAsEntry(); if (entry.isFile) { this.addFile(item.getAsFile()); } else if (entry.isDirectory) { this.addDirectory(entry, entry.name); } } else { this.addFile(item.getAsFile()); } } }; Dropzone.prototype.accept = function(file, done) { if (file.size > this.options.maxFilesize * 1024 * 1024) { return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize)); } else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) { return done(this.options.dictInvalidFileType); } else if (this.options.maxFiles && this.getAcceptedFiles().length >= this.options.maxFiles) { done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles)); return this.emit("maxfilesexceeded", file); } else { return this.options.accept.call(this, file, done); } }; Dropzone.prototype.addFile = function(file) { var _this = this; file.upload = { progress: 0, total: file.size, bytesSent: 0 }; this.files.push(file); file.status = Dropzone.ADDED; this.emit("addedfile", file); if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) { this.createThumbnail(file); } return this.accept(file, function(error) { if (error) { file.accepted = false; return _this._errorProcessing([file], error); } else { return _this.enqueueFile(file); } }); }; Dropzone.prototype.enqueueFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; this.enqueueFile(file); } return null; }; Dropzone.prototype.enqueueFile = function(file) { var _this = this; file.accepted = true; if (file.status === Dropzone.ADDED) { file.status = Dropzone.QUEUED; if (this.options.autoProcessQueue) { return setTimeout((function() { return _this.processQueue(); }), 1); } } else { throw new Error("This file can't be queued because it has already been processed or was rejected."); } }; Dropzone.prototype.addDirectory = function(entry, path) { var dirReader, entriesReader, _this = this; dirReader = entry.createReader(); entriesReader = function(entries) { var _i, _len; for (_i = 0, _len = entries.length; _i < _len; _i++) { entry = entries[_i]; if (entry.isFile) { entry.file(function(file) { if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') { return; } file.fullPath = "" + path + "/" + file.name; return _this.addFile(file); }); } else if (entry.isDirectory) { _this.addDirectory(entry, "" + path + "/" + entry.name); } } }; return dirReader.readEntries(entriesReader, function(error) { return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0; }); }; Dropzone.prototype.removeFile = function(file) { if (file.status === Dropzone.UPLOADING) { this.cancelUpload(file); } this.files = without(this.files, file); this.emit("removedfile", file); if (this.files.length === 0) { return this.emit("reset"); } }; Dropzone.prototype.removeAllFiles = function(cancelIfNecessary) { var file, _i, _len, _ref; if (cancelIfNecessary == null) { cancelIfNecessary = false; } _ref = this.files.slice(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) { this.removeFile(file); } } return null; }; Dropzone.prototype.createThumbnail = function(file) { var fileReader, _this = this; fileReader = new FileReader; fileReader.onload = function() { var img; img = new Image; img.onload = function() { var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3; file.width = img.width; file.height = img.height; resizeInfo = _this.options.resize.call(_this, file); if (resizeInfo.trgWidth == null) { resizeInfo.trgWidth = _this.options.thumbnailWidth; } if (resizeInfo.trgHeight == null) { resizeInfo.trgHeight = _this.options.thumbnailHeight; } canvas = document.createElement("canvas"); ctx = canvas.getContext("2d"); canvas.width = resizeInfo.trgWidth; canvas.height = resizeInfo.trgHeight; ctx.drawImage(img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight); thumbnail = canvas.toDataURL("image/png"); return _this.emit("thumbnail", file, thumbnail); }; return img.src = fileReader.result; }; return fileReader.readAsDataURL(file); }; Dropzone.prototype.processQueue = function() { var i, parallelUploads, processingLength, queuedFiles; parallelUploads = this.options.parallelUploads; processingLength = this.getUploadingFiles().length; i = processingLength; if (processingLength >= parallelUploads) { return; } queuedFiles = this.getQueuedFiles(); if (!(queuedFiles.length > 0)) { return; } if (this.options.uploadMultiple) { return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength)); } else { while (i < parallelUploads) { if (!queuedFiles.length) { return; } this.processFile(queuedFiles.shift()); i++; } } }; Dropzone.prototype.processFile = function(file) { return this.processFiles([file]); }; Dropzone.prototype.processFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.processing = true; file.status = Dropzone.UPLOADING; this.emit("processing", file); } if (this.options.uploadMultiple) { this.emit("processingmultiple", files); } return this.uploadFiles(files); }; Dropzone.prototype._getFilesWithXhr = function(xhr) { var file, files; return files = (function() { var _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.xhr === xhr) { _results.push(file); } } return _results; }).call(this); }; Dropzone.prototype.cancelUpload = function(file) { var groupedFile, groupedFiles, _i, _j, _len, _len1, _ref; if (file.status === Dropzone.UPLOADING) { groupedFiles = this._getFilesWithXhr(file.xhr); for (_i = 0, _len = groupedFiles.length; _i < _len; _i++) { groupedFile = groupedFiles[_i]; groupedFile.status = Dropzone.CANCELED; } file.xhr.abort(); for (_j = 0, _len1 = groupedFiles.length; _j < _len1; _j++) { groupedFile = groupedFiles[_j]; this.emit("canceled", groupedFile); } if (this.options.uploadMultiple) { this.emit("canceledmultiple", groupedFiles); } } else if ((_ref = file.status) === Dropzone.ADDED || _ref === Dropzone.QUEUED) { file.status = Dropzone.CANCELED; this.emit("canceled", file); if (this.options.uploadMultiple) { this.emit("canceledmultiple", [file]); } } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype.uploadFile = function(file) { return this.uploadFiles([file]); }; Dropzone.prototype.uploadFiles = function(files) { var file, formData, handleError, headerName, headerValue, headers, input, inputName, inputType, key, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _this = this; xhr = new XMLHttpRequest(); for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.xhr = xhr; } xhr.open(this.options.method, this.options.url, true); xhr.withCredentials = !!this.options.withCredentials; response = null; handleError = function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr)); } return _results; }; updateProgress = function(e) { var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results; if (e != null) { progress = 100 * e.loaded / e.total; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; file.upload = { progress: progress, total: e.total, bytesSent: e.loaded }; } } else { allFilesFinished = true; progress = 100; for (_k = 0, _len2 = files.length; _k < _len2; _k++) { file = files[_k]; if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) { allFilesFinished = false; } file.upload.progress = progress; file.upload.bytesSent = file.upload.total; } if (allFilesFinished) { return; } } _results = []; for (_l = 0, _len3 = files.length; _l < _len3; _l++) { file = files[_l]; _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent)); } return _results; }; xhr.onload = function(e) { var _ref; if (files[0].status === Dropzone.CANCELED) { return; } if (xhr.readyState !== 4) { return; } response = xhr.responseText; if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) { try { response = JSON.parse(response); } catch (_error) { e = _error; response = "Invalid JSON response from server."; } } updateProgress(); if (!((200 <= (_ref = xhr.status) && _ref < 300))) { return handleError(); } else { return _this._finished(files, response, e); } }; xhr.onerror = function() { if (files[0].status === Dropzone.CANCELED) { return; } return handleError(); }; progressObj = (_ref = xhr.upload) != null ? _ref : xhr; progressObj.onprogress = updateProgress; headers = { "Accept": "application/json", "Cache-Control": "no-cache", "X-Requested-With": "XMLHttpRequest" }; if (this.options.headers) { extend(headers, this.options.headers); } for (headerName in headers) { headerValue = headers[headerName]; xhr.setRequestHeader(headerName, headerValue); } formData = new FormData(); if (this.options.params) { _ref1 = this.options.params; for (key in _ref1) { value = _ref1[key]; formData.append(key, value); } } for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; this.emit("sending", file, xhr, formData); } if (this.options.uploadMultiple) { this.emit("sendingmultiple", files, xhr, formData); } if (this.element.tagName === "FORM") { _ref2 = this.element.querySelectorAll("input, textarea, select, button"); for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { input = _ref2[_k]; inputName = input.getAttribute("name"); inputType = input.getAttribute("type"); if (!inputType || ((_ref3 = inputType.toLowerCase()) !== "checkbox" && _ref3 !== "radio") || input.checked) { formData.append(inputName, input.value); } } } for (_l = 0, _len3 = files.length; _l < _len3; _l++) { file = files[_l]; formData.append("" + this.options.paramName + (this.options.uploadMultiple ? "[]" : ""), file, file.name); } return xhr.send(formData); }; Dropzone.prototype._finished = function(files, responseText, e) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.SUCCESS; this.emit("success", file, responseText, e); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("successmultiple", files, responseText, e); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype._errorProcessing = function(files, message, xhr) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.ERROR; this.emit("error", file, message, xhr); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("errormultiple", files, message, xhr); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; return Dropzone; })(Em); Dropzone.version = "3.7.1"; Dropzone.options = {}; Dropzone.optionsForElement = function(element) { if (element.id) { return Dropzone.options[camelize(element.id)]; } else { return void 0; } }; Dropzone.instances = []; Dropzone.forElement = function(element) { if (typeof element === "string") { element = document.querySelector(element); } if ((element != null ? element.dropzone : void 0) == null) { throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."); } return element.dropzone; }; Dropzone.autoDiscover = true; Dropzone.discover = function() { var checkElements, dropzone, dropzones, _i, _len, _results; if (document.querySelectorAll) { dropzones = document.querySelectorAll(".dropzone"); } else { dropzones = []; checkElements = function(elements) { var el, _i, _len, _results; _results = []; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )dropzone($| )/.test(el.className)) { _results.push(dropzones.push(el)); } else { _results.push(void 0); } } return _results; }; checkElements(document.getElementsByTagName("div")); checkElements(document.getElementsByTagName("form")); } _results = []; for (_i = 0, _len = dropzones.length; _i < _len; _i++) { dropzone = dropzones[_i]; if (Dropzone.optionsForElement(dropzone) !== false) { _results.push(new Dropzone(dropzone)); } else { _results.push(void 0); } } return _results; }; Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i]; Dropzone.isBrowserSupported = function() { var capableBrowser, regex, _i, _len, _ref; capableBrowser = true; if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) { if (!("classList" in document.createElement("a"))) { capableBrowser = false; } else { _ref = Dropzone.blacklistedBrowsers; for (_i = 0, _len = _ref.length; _i < _len; _i++) { regex = _ref[_i]; if (regex.test(navigator.userAgent)) { capableBrowser = false; continue; } } } } else { capableBrowser = false; } return capableBrowser; }; without = function(list, rejectedItem) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { item = list[_i]; if (item !== rejectedItem) { _results.push(item); } } return _results; }; camelize = function(str) { return str.replace(/[\-_](\w)/g, function(match) { return match[1].toUpperCase(); }); }; Dropzone.createElement = function(string) { var div; div = document.createElement("div"); div.innerHTML = string; return div.childNodes[0]; }; Dropzone.elementInside = function(element, container) { if (element === container) { return true; } while (element = element.parentNode) { if (element === container) { return true; } } return false; }; Dropzone.getElement = function(el, name) { var element; if (typeof el === "string") { element = document.querySelector(el); } else if (el.nodeType != null) { element = el; } if (element == null) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element."); } return element; }; Dropzone.getElements = function(els, name) { var e, el, elements, _i, _j, _len, _len1, _ref; if (els instanceof Array) { elements = []; try { for (_i = 0, _len = els.length; _i < _len; _i++) { el = els[_i]; elements.push(this.getElement(el, name)); } } catch (_error) { e = _error; elements = null; } } else if (typeof els === "string") { elements = []; _ref = document.querySelectorAll(els); for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { el = _ref[_j]; elements.push(el); } } else if (els.nodeType != null) { elements = [els]; } if (!((elements != null) && elements.length)) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those."); } return elements; }; Dropzone.confirm = function(question, accepted, rejected) { if (window.confirm(question)) { return accepted(); } else if (rejected != null) { return rejected(); } }; Dropzone.isValidFile = function(file, acceptedFiles) { var baseMimeType, mimeType, validType, _i, _len; if (!acceptedFiles) { return true; } acceptedFiles = acceptedFiles.split(","); mimeType = file.type; baseMimeType = mimeType.replace(/\/.*$/, ""); for (_i = 0, _len = acceptedFiles.length; _i < _len; _i++) { validType = acceptedFiles[_i]; validType = validType.trim(); if (validType.charAt(0) === ".") { if (file.name.indexOf(validType, file.name.length - validType.length) !== -1) { return true; } } else if (/\/\*$/.test(validType)) { if (baseMimeType === validType.replace(/\/.*$/, "")) { return true; } } else { if (mimeType === validType) { return true; } } } return false; }; if (typeof jQuery !== "undefined" && jQuery !== null) { jQuery.fn.dropzone = function(options) { return this.each(function() { return new Dropzone(this, options); }); }; } if (typeof module !== "undefined" && module !== null) { module.exports = Dropzone; } else { window.Dropzone = Dropzone; } Dropzone.ADDED = "added"; Dropzone.QUEUED = "queued"; Dropzone.ACCEPTED = Dropzone.QUEUED; Dropzone.UPLOADING = "uploading"; Dropzone.PROCESSING = Dropzone.UPLOADING; Dropzone.CANCELED = "canceled"; Dropzone.ERROR = "error"; Dropzone.SUCCESS = "success"; /* # contentloaded.js # # Author: Diego Perini (diego.perini at gmail.com) # Summary: cross-browser wrapper for DOMContentLoaded # Updated: 20101020 # License: MIT # Version: 1.2 # # URL: # http://javascript.nwbox.com/ContentLoaded/ # http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE */ contentLoaded = function(win, fn) { var add, doc, done, init, poll, pre, rem, root, top; done = false; top = true; doc = win.document; root = doc.documentElement; add = (doc.addEventListener ? "addEventListener" : "attachEvent"); rem = (doc.addEventListener ? "removeEventListener" : "detachEvent"); pre = (doc.addEventListener ? "" : "on"); init = function(e) { if (e.type === "readystatechange" && doc.readyState !== "complete") { return; } (e.type === "load" ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) { return fn.call(win, e.type || e); } }; poll = function() { var e; try { root.doScroll("left"); } catch (_error) { e = _error; setTimeout(poll, 50); return; } return init("poll"); }; if (doc.readyState !== "complete") { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch (_error) {} if (top) { poll(); } } doc[add](pre + "DOMContentLoaded", init, false); doc[add](pre + "readystatechange", init, false); return win[add](pre + "load", init, false); } }; Dropzone._autoDiscoverFunction = function() { if (Dropzone.autoDiscover) { return Dropzone.discover(); } }; contentLoaded(window, Dropzone._autoDiscoverFunction); }).call(this); }); require.alias("component-emitter/index.js", "dropzone/deps/emitter/index.js"); require.alias("component-emitter/index.js", "emitter/index.js"); if (typeof exports == "object") { module.exports = require("dropzone"); } else if (typeof define == "function" && define.amd) { define(function(){ return require("dropzone"); }); } else { this["Dropzone"] = require("dropzone"); }})();
JavaScript
/* * jQuery Iframe Transport Plugin 1.8.2 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Helper variable to create unique names for the transport iframes: var counter = 0; // The iframe transport accepts four additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, // overrides the name property of the file input field(s), // can be a string or an array of strings. // options.formData: an array of objects with name and value properties, // equivalent to the return data of .serializeArray(), e.g.: // [{name: 'a', value: 1}, {name: 'b', value: 2}] // options.initialIframeSrc: the URL of the initial iframe src, // by default set to "javascript:false;" $.ajaxTransport('iframe', function (options) { if (options.async) { // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6: /*jshint scripturl: true */ var initialIframeSrc = options.initialIframeSrc || 'javascript:false;', /*jshint scripturl: false */ form, iframe, addParamChar; return { send: function (_, completeCallback) { form = $('<form style="display:none;"></form>'); form.attr('accept-charset', options.formAcceptCharset); addParamChar = /\?/.test(options.url) ? '&' : '?'; // XDomainRequest only supports GET and POST: if (options.type === 'DELETE') { options.url = options.url + addParamChar + '_method=DELETE'; options.type = 'POST'; } else if (options.type === 'PUT') { options.url = options.url + addParamChar + '_method=PUT'; options.type = 'POST'; } else if (options.type === 'PATCH') { options.url = options.url + addParamChar + '_method=PATCH'; options.type = 'POST'; } // IE versions below IE8 cannot set the name property of // elements that have already been added to the DOM, // so we set the name along with the iframe HTML markup: counter += 1; iframe = $( '<iframe src="' + initialIframeSrc + '" name="iframe-transport-' + counter + '"></iframe>' ).bind('load', function () { var fileInputClones, paramNames = $.isArray(options.paramName) ? options.paramName : [options.paramName]; iframe .unbind('load') .bind('load', function () { var response; // Wrap in a try/catch block to catch exceptions thrown // when trying to access cross-domain iframe contents: try { response = iframe.contents(); // Google Chrome and Firefox do not throw an // exception when calling iframe.contents() on // cross-domain requests, so we unify the response: if (!response.length || !response[0].firstChild) { throw new Error(); } } catch (e) { response = undefined; } // The complete callback returns the // iframe content document as response object: completeCallback( 200, 'success', {'iframe': response} ); // Fix for IE endless progress bar activity bug // (happens on form submits to iframe targets): $('<iframe src="' + initialIframeSrc + '"></iframe>') .appendTo(form); window.setTimeout(function () { // Removing the form in a setTimeout call // allows Chrome's developer tools to display // the response result form.remove(); }, 0); }); form .prop('target', iframe.prop('name')) .prop('action', options.url) .prop('method', options.type); if (options.formData) { $.each(options.formData, function (index, field) { $('<input type="hidden"/>') .prop('name', field.name) .val(field.value) .appendTo(form); }); } if (options.fileInput && options.fileInput.length && options.type === 'POST') { fileInputClones = options.fileInput.clone(); // Insert a clone for each file input field: options.fileInput.after(function (index) { return fileInputClones[index]; }); if (options.paramName) { options.fileInput.each(function (index) { $(this).prop( 'name', paramNames[index] || options.paramName ); }); } // Appending the file input fields to the hidden form // removes them from their original location: form .append(options.fileInput) .prop('enctype', 'multipart/form-data') // enctype must be set as encoding for IE: .prop('encoding', 'multipart/form-data'); // Remove the HTML5 form attribute from the input(s): options.fileInput.removeAttr('form'); } form.submit(); // Insert the file input fields at their original location // by replacing the clones with the originals: if (fileInputClones && fileInputClones.length) { options.fileInput.each(function (index, input) { var clone = $(fileInputClones[index]); // Restore the original name and form properties: $(input) .prop('name', clone.prop('name')) .attr('form', clone.attr('form')); clone.replaceWith(input); }); } }); form.append(iframe).appendTo(document.body); }, abort: function () { if (iframe) { // javascript:false as iframe src aborts the request // and prevents warning popups on HTTPS in IE6. // concat is used to avoid the "Script URL" JSLint error: iframe .unbind('load') .prop('src', initialIframeSrc); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, xml // and script. // Please note that the Content-Type for JSON responses has to be text/plain // or text/html, if the browser doesn't include application/json in the // Accept header, else IE will show a download dialog. // The Content-Type for XML responses on the other hand has to be always // application/xml or text/xml, so IE properly parses the XML response. // See also // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return iframe && $(iframe[0].body).text(); }, 'iframe json': function (iframe) { return iframe && $.parseJSON($(iframe[0].body).text()); }, 'iframe html': function (iframe) { return iframe && $(iframe[0].body).html(); }, 'iframe xml': function (iframe) { var xmlDoc = iframe && iframe[0]; return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc : $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) || $(xmlDoc.body).html()); }, 'iframe script': function (iframe) { return iframe && $.globalEval($(iframe[0].body).text()); } } }); }));
JavaScript
/* * jQuery File Upload jQuery UI Plugin 8.7.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* jshint nomen:false */ /* global define, window */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery', './jquery.fileupload-ui'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { progress: function (e, data) { if (data.context) { data.context.find('.progress').progressbar( 'option', 'value', parseInt(data.loaded / data.total * 100, 10) ); } }, progressall: function (e, data) { var $this = $(this); $this.find('.fileupload-progress') .find('.progress').progressbar( 'option', 'value', parseInt(data.loaded / data.total * 100, 10) ).end() .find('.progress-extended').each(function () { $(this).html( ($this.data('blueimp-fileupload') || $this.data('fileupload')) ._renderExtendedProgress(data) ); }); } }, _renderUpload: function (func, files) { var node = this._super(func, files), showIconText = $(window).width() > 480; node.find('.progress').empty().progressbar(); node.find('.start').button({ icons: {primary: 'ui-icon-circle-arrow-e'}, text: showIconText }); node.find('.cancel').button({ icons: {primary: 'ui-icon-cancel'}, text: showIconText }); if (node.hasClass('fade')) { node.hide(); } return node; }, _renderDownload: function (func, files) { var node = this._super(func, files), showIconText = $(window).width() > 480; node.find('.delete').button({ icons: {primary: 'ui-icon-trash'}, text: showIconText }); if (node.hasClass('fade')) { node.hide(); } return node; }, _transition: function (node) { var deferred = $.Deferred(); if (node.hasClass('fade')) { node.fadeToggle( this.options.transitionDuration, this.options.transitionEasing, function () { deferred.resolveWith(node); } ); } else { deferred.resolveWith(node); } return deferred; }, _create: function () { this._super(); this.element .find('.fileupload-buttonbar') .find('.fileinput-button').each(function () { var input = $(this).find('input:file').detach(); $(this) .button({icons: {primary: 'ui-icon-plusthick'}}) .append(input); }) .end().find('.start') .button({icons: {primary: 'ui-icon-circle-arrow-e'}}) .end().find('.cancel') .button({icons: {primary: 'ui-icon-cancel'}}) .end().find('.delete') .button({icons: {primary: 'ui-icon-trash'}}) .end().find('.progress').progressbar(); }, _destroy: function () { this.element .find('.fileupload-buttonbar') .find('.fileinput-button').each(function () { var input = $(this).find('input:file').detach(); $(this) .button('destroy') .append(input); }) .end().find('.start') .button('destroy') .end().find('.cancel') .button('destroy') .end().find('.delete') .button('destroy') .end().find('.progress').progressbar('destroy'); this._super(); } }); }));
JavaScript
/* * jQuery postMessage Transport Plugin 1.1.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; var counter = 0, names = [ 'accepts', 'cache', 'contents', 'contentType', 'crossDomain', 'data', 'dataType', 'headers', 'ifModified', 'mimeType', 'password', 'processData', 'timeout', 'traditional', 'type', 'url', 'username' ], convert = function (p) { return p; }; $.ajaxSetup({ converters: { 'postmessage text': convert, 'postmessage json': convert, 'postmessage html': convert } }); $.ajaxTransport('postmessage', function (options) { if (options.postMessage && window.postMessage) { var iframe, loc = $('<a>').prop('href', options.postMessage)[0], target = loc.protocol + '//' + loc.host, xhrUpload = options.xhr().upload; return { send: function (_, completeCallback) { counter += 1; var message = { id: 'postmessage-transport-' + counter }, eventName = 'message.' + message.id; iframe = $( '<iframe style="display:none;" src="' + options.postMessage + '" name="' + message.id + '"></iframe>' ).bind('load', function () { $.each(names, function (i, name) { message[name] = options[name]; }); message.dataType = message.dataType.replace('postmessage ', ''); $(window).bind(eventName, function (e) { e = e.originalEvent; var data = e.data, ev; if (e.origin === target && data.id === message.id) { if (data.type === 'progress') { ev = document.createEvent('Event'); ev.initEvent(data.type, false, true); $.extend(ev, data); xhrUpload.dispatchEvent(ev); } else { completeCallback( data.status, data.statusText, {postmessage: data.result}, data.headers ); iframe.remove(); $(window).unbind(eventName); } } }); iframe[0].contentWindow.postMessage( message, target ); }).appendTo(document.body); }, abort: function () { if (iframe) { iframe.remove(); } } }; } }); }));
JavaScript
/* * jQuery XDomainRequest Transport Plugin 1.1.3 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on Julian Aubourg's ajaxHooks xdr.js: * https://github.com/jaubourg/ajaxHooks/ */ /* global define, window, XDomainRequest */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; if (window.XDomainRequest && !$.support.cors) { $.ajaxTransport(function (s) { if (s.crossDomain && s.async) { if (s.timeout) { s.xdrTimeout = s.timeout; delete s.timeout; } var xdr; return { send: function (headers, completeCallback) { var addParamChar = /\?/.test(s.url) ? '&' : '?'; function callback(status, statusText, responses, responseHeaders) { xdr.onload = xdr.onerror = xdr.ontimeout = $.noop; xdr = null; completeCallback(status, statusText, responses, responseHeaders); } xdr = new XDomainRequest(); // XDomainRequest only supports GET and POST: if (s.type === 'DELETE') { s.url = s.url + addParamChar + '_method=DELETE'; s.type = 'POST'; } else if (s.type === 'PUT') { s.url = s.url + addParamChar + '_method=PUT'; s.type = 'POST'; } else if (s.type === 'PATCH') { s.url = s.url + addParamChar + '_method=PATCH'; s.type = 'POST'; } xdr.open(s.type, s.url); xdr.onload = function () { callback( 200, 'OK', {text: xdr.responseText}, 'Content-Type: ' + xdr.contentType ); }; xdr.onerror = function () { callback(404, 'Not Found'); }; if (s.xdrTimeout) { xdr.ontimeout = function () { callback(0, 'timeout'); }; xdr.timeout = s.xdrTimeout; } xdr.send((s.hasContent && s.data) || null); }, abort: function () { if (xdr) { xdr.onerror = $.noop(); xdr.abort(); } } }; } }); } }));
JavaScript