code
stringlengths
2
1.05M
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.dotPowDependencies = void 0; var _dependenciesDenseMatrixClass = require("./dependenciesDenseMatrixClass.generated"); var _dependenciesEqualScalar = require("./dependenciesEqualScalar.generated"); var _dependenciesMatrix = require("./dependenciesMatrix.generated"); var _dependenciesPow = require("./dependenciesPow.generated"); var _dependenciesTyped = require("./dependenciesTyped.generated"); var _factoriesAny = require("../../factoriesAny.js"); /** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ var dotPowDependencies = { DenseMatrixDependencies: _dependenciesDenseMatrixClass.DenseMatrixDependencies, equalScalarDependencies: _dependenciesEqualScalar.equalScalarDependencies, matrixDependencies: _dependenciesMatrix.matrixDependencies, powDependencies: _dependenciesPow.powDependencies, typedDependencies: _dependenciesTyped.typedDependencies, createDotPow: _factoriesAny.createDotPow }; exports.dotPowDependencies = dotPowDependencies;
import { combineReducers } from 'redux'; import user from './user'; import modals from './modals'; import navbar from './navbar'; const allReducers = combineReducers({ user, modals, navbar, }); export default allReducers;
/* PlayerManager.js KC3改 Player Manager Manages info about the player and all its holdings Includes HQ, Fleets, Docks, LandBases Does not include Ships and Gears which are managed by other Managers */ (function(){ "use strict"; window.PlayerManager = { hq: {}, consumables: {}, fleets: [], bases: [], baseConvertingSlots: [], fleetCount: 1, repairSlots: 2, repairShips: [-1,-1,-1,-1,-1], buildSlots: 2, combinedFleet: 0, statistics: {}, maxResource: 300000, maxConsumable: 3000, maxCoin: 200000, init :function(){ this.hq = new KC3Player(); this.consumables = { fcoin: 0, buckets : 0, devmats : 0, screws: 0, torch: 0, medals: 0, blueprints: 0 }; this.fleets = [ new KC3Fleet(), new KC3Fleet(), new KC3Fleet(), new KC3Fleet() ]; this.bases = [ new KC3LandBase(), new KC3LandBase(), new KC3LandBase(), new KC3LandBase() ]; this.akashiRepair = new KC3AkashiRepair(); return this; }, setHQ :function( serverSeconds, data ){ // Check if player suddenly changed if(this.hq.id !== 0 && this.hq.id != data.mid){ this.hq.logout(); this.hq = new KC3Player(); } // Update player with new data this.hq.update( data ); this.hq.save(); // Update related managers with new data if exists Object.assignIfDefined(PlayerManager.consumables, "fcoin", data.fcoin); PlayerManager.fleetCount = data.fleetCount; PlayerManager.repairSlots = data.repairSlots; PlayerManager.buildSlots = data.buildSlots; KC3ShipManager.max = data.maxShipSlots; // Not sure why, but always shown +3 at client side. see #1860 KC3GearManager.max = 3 + data.maxGearSlots; // Record values of recent hour if necessary if(typeof localStorage.lastExperience == "undefined"){ localStorage.lastExperience = 0; } var currentHour = Math.floor(serverSeconds / 3600); if(currentHour == localStorage.lastExperience){ return this; } localStorage.lastExperience = currentHour; KC3Database.Experience({ exp : data.exp, level: data.level, hour : currentHour }); return this; }, setFleets :function( data ){ var self = this; [0,1,2,3].forEach(function(i){ self.fleets[i].update( data[i] || {} ); }); this.saveFleets(); return this; }, setBases :function( data ){ var self = this; Array.numbers(0, data.length < 4 ? 3 : data.length - 1) .forEach(function(i){ self.bases[i] = new KC3LandBase(data[i]); }); if(self.bases.length > 4 && data.length < self.bases.length){ self.bases.splice(data.length < 4 ? 4 : data.length); } this.saveBases(); localStorage.setObject("baseConvertingSlots", self.baseConvertingSlots); return this; }, setBasesOnWorldMap :function( data ){ var airBase = data.api_air_base, mapInfo = data.api_map_info; if(typeof airBase !== "undefined") { // Map and keep World IDs only var openedWorldIds = (mapInfo || []).map(m => m.api_id) .map(id => String(id).slice(0, -1)); // Remove duplicate IDs openedWorldIds = [...new Set(openedWorldIds)]; // Filter unset land bases after event if event world API data still exist var openedBases = airBase.filter(ab => openedWorldIds.indexOf(String(ab.api_area_id)) > -1); this.setBases(openedBases); return true; } else if(this.bases[0].map > 0) { // Clean land bases after event if World 6 not opened this.setBases([]); return true; } // No base is set, tell invoker return false; }, setBaseConvertingSlots :function( data ){ // Clear Array to empty (reference unchanged) this.baseConvertingSlots.length = 0; if(typeof data !== "undefined") { // Let client know: these types of slotitem are free to equipped. // KC3 does not track them for now. /* if(!!data.api_unset_slot){ // Same structure with `api_get_member/require_info.api_unsetslot` } */ // Let client know: these slotitems are moving, not equippable. // For now, moving period of LBAS plane is 12 mins. if(Array.isArray(data.api_base_convert_slot)) { [].push.apply(this.baseConvertingSlots, data.api_base_convert_slot); } } localStorage.setObject("baseConvertingSlots", this.baseConvertingSlots); return this; }, setRepairDocks :function( data ){ // clone last repairing ship list, empty current list const lastRepair = this.repairShips.splice(0); this.repairShips.push(-1); const dockingShips = []; const self = this; $.each(data, function(ctr, ndock){ const dockNum = ndock.api_id; const shipRosterId = ndock.api_ship_id; // check if not in the repairing list, mark as repaired if(lastRepair[dockNum] > 0 && lastRepair[dockNum] != shipRosterId) { KC3ShipManager.get(lastRepair[dockNum]).applyRepair(); } if(ndock.api_state > 0){ self.repairShips[dockNum] = shipRosterId; dockingShips.push( { id: shipRosterId, completeTime: ndock.api_complete_time } ); KC3TimerManager.repair(dockNum).activate( ndock.api_complete_time, KC3ShipManager.get(shipRosterId).masterId, undefined, shipRosterId ); }else{ self.repairShips[dockNum] = -1; KC3TimerManager.repair(dockNum).deactivate(); } }); // "localStorage.dockingShips" is not supposed // to be modified, // it record the most recent docking ships // whenever a docking event comes localStorage.dockingShips = JSON.stringify(dockingShips); return this; }, // cached docking ships' status // the return value is an object whose properties are "x{ship_id}" // with value set to the completeTime getCachedDockingShips: function() { var dockingShips = {}; if (typeof localStorage.dockingShips !== "undefined") { try { var ndockData = JSON.parse( localStorage.dockingShips ); $.each(ndockData, function (i, v) { var key = "x" + v.id.toString(); dockingShips[key] = v.completeTime; }); } catch (err) { console.error("Error while processing cached docking ship", err); } } return dockingShips; }, setBuildDocks :function( data ){ $.each(data, function(ctr, kdock){ if(kdock.api_state > 0){ const faceId = kdock.api_created_ship_id; const timer = KC3TimerManager.build( kdock.api_id ); timer.activate( kdock.api_complete_time, faceId ); if(kdock.api_item1 > 999){ timer.lsc = true; }else{ timer.lsc = false; } timer.newShip = ConfigManager.info_dex_owned_ship ? ! PictureBook.isEverOwnedShip(faceId) : ! KC3ShipManager.masterExists(faceId); }else{ KC3TimerManager.build( kdock.api_id ).deactivate(); } }); return this; }, // data array always: [fuel, ammo, steel, bauxite] setResources :function( serverSeconds, absData, deltaData ){ // Only for displaying, because accuracy depends on previous values if(Array.isArray(deltaData) && deltaData.length === 4){ this.hq.lastMaterial[0] += deltaData[0] || 0; this.hq.lastMaterial[1] += deltaData[1] || 0; this.hq.lastMaterial[2] += deltaData[2] || 0; this.hq.lastMaterial[3] += deltaData[3] || 0; // Limit resource values between [0, 300000] this.hq.lastMaterial.map((v, i) => { this.hq.lastMaterial[i] = v.valueBetween(0, this.maxResource); }); this.hq.save(); return this; } // Sync with API absolute values and save to storage if(!Array.isArray(absData) || absData.length !== 4){ return this; } this.hq.lastMaterial = absData; this.hq.save(); // Record values of recent hour if necessary if(typeof localStorage.lastResource == "undefined"){ localStorage.lastResource = 0; } var currentHour = Math.floor(serverSeconds / 3600); if(currentHour == localStorage.lastResource){ return this; } localStorage.lastResource = currentHour; KC3Database.Resource({ rsc1 : absData[0], rsc2 : absData[1], rsc3 : absData[2], rsc4 : absData[3], hour : currentHour }); return this; }, // To only save consumables to localStorage without DB recording, let dataObj falsy // basic 4 consumables represented in array always: [torch, buckets, devmats, screws] setConsumables :function( serverSeconds, dataObj, deltaArray ){ // Only for displaying, because accuracy depends on previous values if(Array.isArray(deltaArray) && deltaArray.length === 4){ this.consumables.torch += deltaArray[0] || 0; this.consumables.torch = this.consumables.torch.valueBetween(0, this.maxConsumable); this.consumables.buckets += deltaArray[1] || 0; this.consumables.buckets = this.consumables.buckets.valueBetween(0, this.maxConsumable); this.consumables.devmats += deltaArray[2] || 0; this.consumables.devmats = this.consumables.devmats.valueBetween(0, this.maxConsumable); this.consumables.screws += deltaArray[3] || 0; this.consumables.screws = this.consumables.screws.valueBetween(0, this.maxConsumable); localStorage.consumables = JSON.stringify(this.consumables); return this; } // Merge and save consumables data to storage $.extend(this.consumables, dataObj); localStorage.consumables = JSON.stringify(this.consumables); // Record values of recent hour if necessary if(typeof localStorage.lastUseitem == "undefined"){ localStorage.lastUseitem = 0; } var currentHour = Math.floor(serverSeconds / 3600); if(currentHour == localStorage.lastUseitem || !dataObj || Object.keys(dataObj).length < 4){ return this; } localStorage.lastUseitem = currentHour; KC3Database.Useitem({ torch : this.consumables.torch, bucket : this.consumables.buckets, devmat : this.consumables.devmats, screw : this.consumables.screws, hour : currentHour }); return this; }, setStatistics :function( data ){ const oldStatistics = JSON.parse(localStorage.statistics || '{"exped":{},"pvp":{},"sortie":{}}'); const newStatistics = { exped: { rate: Number(data.exped.rate) || 0, total: Number(data.exped.total || oldStatistics.exped.total) || 0, success: Number(data.exped.success || oldStatistics.exped.success) || 0 }, pvp: { rate: Number(data.pvp.rate) || 0, win: Number(data.pvp.win || oldStatistics.pvp.win) || 0, lose: Number(data.pvp.lose || oldStatistics.pvp.lose) || 0, // these properties are always 0, maybe deprecated by devs, here ignored //attacked: data.pvp.attacked || oldStatistics.pvp.attacked, //attacked_win: data.pvp.attacked_win || oldStatistics.pvp.attacked_win }, sortie: { rate: Number(data.sortie.rate) || 0, win: Number(data.sortie.win || oldStatistics.sortie.win) || 0, lose: Number(data.sortie.lose || oldStatistics.sortie.lose) || 0 } }; // only `api_get_member/record` offer us `rate` (as string) values, // to get the rates before entering record screen, have to compute them by ourselves. // rate is displayed after a 'Math.round' in-game, although raw api data keeps 2 decimals, // but an exception: `api_war.api_rate` is not multiplied by 100, so no decimal after % it. // see `api_get_member/record` function at `Kcsapi.js` const getRate = (win = 0, lose = 0, total = undefined) => { // different with in-game displaying integer, we always keep 2 decimals let rate = Math.qckInt("floor", win / (total === undefined ? win + lose : total) * 100, 2); if(isNaN(rate) || rate === Infinity) rate = 0; return rate; }; if(!newStatistics.sortie.rate) { newStatistics.sortie.rate = getRate(newStatistics.sortie.win, newStatistics.sortie.lose); } if(!newStatistics.pvp.rate) { newStatistics.pvp.rate = getRate(newStatistics.pvp.win, newStatistics.pvp.lose); } if(!newStatistics.exped.rate) { newStatistics.exped.rate = getRate(newStatistics.exped.success, 0, newStatistics.exped.total); } localStorage.statistics = JSON.stringify(newStatistics); return this; }, setNewsfeed :function( data, timestamp = Date.now() ){ //console.log("newsfeed", data); localStorage.playerNewsFeed = JSON.stringify({ time: timestamp, log: data }); // Give up to save into DB, just keep recent 6 logs return this; // No way to track which logs are already recorded, // because no cursor/timestamp/state could be found in API /* $.each(data, function( index, element){ if(parseInt(element.api_state, 10) !== 0){ KC3Database.Newsfeed({ type: element.api_type, message: element.api_message, time: timestamp }); } }); */ }, // make sure to "loadFleets" before calling this function. prepareDeckbuilder: function() { return { version: 4, f1: PlayerManager.fleets[0].deckbuilder(), f2: PlayerManager.fleets[1].deckbuilder(), f3: PlayerManager.fleets[2].deckbuilder(), f4: PlayerManager.fleets[3].deckbuilder() }; }, // Refresh last home port time and material regeneration // Partially same effects with `setResources` portRefresh :function( serverSeconds, absMaterial ){ var self = this; if(!(this.hq.lastPortTime && this.hq.lastMaterial)) { if(!this.hq.lastPortTime) this.hq.lastPortTime = serverSeconds; if(!this.hq.lastMaterial) this.hq.lastMaterial = absMaterial; return this; } this.akashiRepair.onPort(this.fleets); var // get current player regen cap regenCap = this.hq.getRegenCap(), // get regen time regenTime = { // find next multiplier of 3 from last time start: Math.hrdInt("ceil" ,this.hq.lastPortTime,Math.log10(3 * 60),1), // find last multiplier of 3 that does not exceeds the current time end : Math.hrdInt("floor",serverSeconds,Math.log10(3 * 60),1), }, // get regeneration ticks regenRate = Math.max(0,regenTime.end - regenTime.start + 1), // set regeneration amount regenVal = [3,3,3,1] .map(function(x){return regenRate * x;}) .map(function(x,i){return Math.max(0,Math.min(x,regenCap - self.hq.lastMaterial[i]));}); console.log("Last port", this.hq.lastPortTime, regenTime, serverSeconds); // Check whether a server time is supplied, or keep the last refresh time. this.hq.lastPortTime = serverSeconds || this.hq.lastPortTime; console.log("Regenerated materials", regenVal); console.log("Materials before after", this.hq.lastMaterial, absMaterial); KC3Database.Naverall({ hour:Math.hrdInt('floor',serverSeconds/3.6,3,1), type:'regen', data:regenVal.concat([0,0,0,0]) }); this.hq.lastMaterial = absMaterial || this.hq.lastMaterial; this.hq.save(); return this; }, saveFleets :function(){ localStorage.fleets = JSON.stringify(this.fleets); return this; }, loadFleets :function(){ if(typeof localStorage.fleets != "undefined"){ var oldFleets =JSON.parse( localStorage.fleets ); this.fleets = this.fleets.map(function(x,i){ return (new KC3Fleet()).defineFormatted(oldFleets[i]); }); } return this; }, loadConsumables :function(){ if(typeof localStorage.consumables != "undefined"){ this.consumables = $.extend(this.consumables, JSON.parse(localStorage.consumables)); } return this; }, getConsumableById :function(useitemId, attrNameOnly = false){ // ID mapping see also `api_get_member/useitem` at Kcsapi.js#282 const attrNameMap = { "1": "buckets", "2": "torch", "3": "devmats", "4": "screws", "10": "furniture200", "11": "furniture400", "12": "furniture700", "31": "fuel", "32": "ammo", "33": "steel", "34": "bauxite", "44": "fcoin", "49": "dockKey", "50": "repairTeam", "51": "repairGoddess", "52": "furnitureFairy", "53": "portExpansion", "54": "mamiya", "55": "ring", "56": "chocolate", "57": "medals", "58": "blueprints", "59": "irako", "60": "presents", "61": "firstClassMedals", "62": "hishimochi", "63": "hqPersonnel", "64": "reinforceExpansion", "65": "protoCatapult", "66": "ration", "67": "resupplier", "68": "mackerel", "69": "mackerelCan", "70": "skilledCrew", "71": "nEngine", "72": "decoMaterial", "73": "constCorps", "74": "newAircraftBlueprint", "75": "newArtilleryMaterial", "76": "rationSpecial", "77": "newAviationMaterial", "78": "actionReport", "79": "straitMedal", "80": "xmasGiftBox", "81": "shogoMedalHard", "82": "shogoMedalNormal", "83": "shogoMedalEasy", "84": "shogoMedalCasual", }; // You may need to `loadConsumables` first for Strategy Room return attrNameOnly ? attrNameMap[useitemId] : this.consumables[attrNameMap[useitemId]]; }, saveBases :function(){ localStorage.bases = JSON.stringify(this.bases); return this; }, loadBases :function(){ if(typeof localStorage.bases != "undefined"){ var oldBases = JSON.parse( localStorage.bases ); this.bases = oldBases.map(function(baseData){ return (new KC3LandBase()).defineFormatted(baseData); }); } if(typeof localStorage.baseConvertingSlots != "undefined"){ this.baseConvertingSlots = localStorage.getObject("baseConvertingSlots"); } return this; }, cloneFleets :function(){ return this.fleets.map(function(x,i){ return x.ships.map(function(s){ return new KC3Ship(KC3ShipManager.get(s)); }); }); } }; })();
/** Demo script to handle the theme demo **/ var Demo = function () { // Handle Theme Settings var handleTheme = function () { var panel = $('.theme-panel'); if ($('body').hasClass('page-boxed') === false) { $('.layout-option', panel).val("fluid"); } $('.sidebar-option', panel).val("default"); $('.page-header-option', panel).val("fixed"); $('.page-footer-option', panel).val("default"); if ($('.sidebar-pos-option').attr("disabled") === false) { $('.sidebar-pos-option', panel).val(Metronic.isRTL() ? 'right' : 'left'); } //handle theme layout var resetLayout = function () { $("body"). removeClass("page-boxed"). removeClass("page-footer-fixed"). removeClass("page-sidebar-fixed"). removeClass("page-header-fixed"). removeClass("page-sidebar-reversed"); $('.page-header > .page-header-inner').removeClass("container"); if ($('.page-container').parent(".container").size() === 1) { $('.page-container').insertAfter('body > .clearfix'); } if ($('.page-footer > .container').size() === 1) { $('.page-footer').html($('.page-footer > .container').html()); } else if ($('.page-footer').parent(".container").size() === 1) { $('.page-footer').insertAfter('.page-container'); $('.scroll-to-top').insertAfter('.page-footer'); } $(".top-menu > .navbar-nav > li.dropdown").removeClass("dropdown-dark"); $('body > .container').remove(); }; var lastSelectedLayout = ''; var setLayout = function () { var layoutOption = $('.layout-option', panel).val(); var sidebarOption = $('.sidebar-option', panel).val(); var headerOption = $('.page-header-option', panel).val(); var footerOption = $('.page-footer-option', panel).val(); var sidebarPosOption = $('.sidebar-pos-option', panel).val(); var sidebarStyleOption = $('.sidebar-style-option', panel).val(); var sidebarMenuOption = $('.sidebar-menu-option', panel).val(); var headerTopDropdownStyle = $('.page-header-top-dropdown-style-option', panel).val(); if (sidebarOption == "fixed" && headerOption == "default") { alert('Default Header with Fixed Sidebar option is not supported. Proceed with Fixed Header with Fixed Sidebar.'); $('.page-header-option', panel).val("fixed"); $('.sidebar-option', panel).val("fixed"); sidebarOption = 'fixed'; headerOption = 'fixed'; } resetLayout(); // reset layout to default state if (layoutOption === "boxed") { $("body").addClass("page-boxed"); // set header $('.page-header > .page-header-inner').addClass("container"); var cont = $('body > .clearfix').after('<div class="container"></div>'); // set content $('.page-container').appendTo('body > .container'); // set footer if (footerOption === 'fixed') { $('.page-footer').html('<div class="container">' + $('.page-footer').html() + '</div>'); } else { $('.page-footer').appendTo('body > .container'); } } if (lastSelectedLayout != layoutOption) { //layout changed, run responsive handler: Metronic.runResizeHandlers(); } lastSelectedLayout = layoutOption; //header if (headerOption === 'fixed') { $("body").addClass("page-header-fixed"); $(".page-header").removeClass("navbar-static-top").addClass("navbar-fixed-top"); } else { $("body").removeClass("page-header-fixed"); $(".page-header").removeClass("navbar-fixed-top").addClass("navbar-static-top"); } //sidebar if ($('body').hasClass('page-full-width') === false) { if (sidebarOption === 'fixed') { $("body").addClass("page-sidebar-fixed"); $("page-sidebar-menu").addClass("page-sidebar-menu-fixed"); $("page-sidebar-menu").removeClass("page-sidebar-menu-default"); Layout.initFixedSidebarHoverEffect(); } else { $("body").removeClass("page-sidebar-fixed"); $("page-sidebar-menu").addClass("page-sidebar-menu-default"); $("page-sidebar-menu").removeClass("page-sidebar-menu-fixed"); $('.page-sidebar-menu').unbind('mouseenter').unbind('mouseleave'); } } // top dropdown style if (headerTopDropdownStyle === 'dark') { $(".top-menu > .navbar-nav > li.dropdown").addClass("dropdown-dark"); } else { $(".top-menu > .navbar-nav > li.dropdown").removeClass("dropdown-dark"); } //footer if (footerOption === 'fixed') { $("body").addClass("page-footer-fixed"); } else { $("body").removeClass("page-footer-fixed"); } //sidebar style if (sidebarStyleOption === 'compact') { $(".page-sidebar-menu").addClass("page-sidebar-menu-compact"); } else { $(".page-sidebar-menu").removeClass("page-sidebar-menu-compact"); } //sidebar menu if (sidebarMenuOption === 'hover') { if (sidebarOption == 'fixed') { $('.sidebar-menu-option', panel).val("accordion"); alert("Hover Sidebar Menu is not compatible with Fixed Sidebar Mode. Select Default Sidebar Mode Instead."); } else { $(".page-sidebar-menu").addClass("page-sidebar-menu-hover-submenu"); } } else { $(".page-sidebar-menu").removeClass("page-sidebar-menu-hover-submenu"); } //sidebar position if (Metronic.isRTL()) { if (sidebarPosOption === 'left') { $("body").addClass("page-sidebar-reversed"); $('#frontend-link').tooltip('destroy').tooltip({ placement: 'right' }); } else { $("body").removeClass("page-sidebar-reversed"); $('#frontend-link').tooltip('destroy').tooltip({ placement: 'left' }); } } else { if (sidebarPosOption === 'right') { $("body").addClass("page-sidebar-reversed"); $('#frontend-link').tooltip('destroy').tooltip({ placement: 'left' }); } else { $("body").removeClass("page-sidebar-reversed"); $('#frontend-link').tooltip('destroy').tooltip({ placement: 'right' }); } } Layout.fixContentHeight(); // fix content height Layout.initFixedSidebar(); // reinitialize fixed sidebar }; // handle theme colors var setColor = function (color) { var color_ = (Metronic.isRTL() ? color + '-rtl' : color); $('#style_color').attr("href", Layout.getLayoutCssPath() + 'themes/' + color_ + ".css"); }; $('.toggler', panel).click(function () { $('.toggler').hide(); $('.toggler-close').show(); $('.theme-panel > .theme-options').show(); }); $('.toggler-close', panel).click(function () { $('.toggler').show(); $('.toggler-close').hide(); $('.theme-panel > .theme-options').hide(); }); $('.theme-colors > ul > li', panel).click(function () { var color = $(this).attr("data-style"); setColor(color); $('ul > li', panel).removeClass("current"); $(this).addClass("current"); }); // set default theme options: if ($("body").hasClass("page-boxed")) { $('.layout-option', panel).val("boxed"); } if ($("body").hasClass("page-sidebar-fixed")) { $('.sidebar-option', panel).val("fixed"); } if ($("body").hasClass("page-header-fixed")) { $('.page-header-option', panel).val("fixed"); } if ($("body").hasClass("page-footer-fixed")) { $('.page-footer-option', panel).val("fixed"); } if ($("body").hasClass("page-sidebar-reversed")) { $('.sidebar-pos-option', panel).val("right"); } if ($(".page-sidebar-menu").hasClass("page-sidebar-menu-light")) { $('.sidebar-style-option', panel).val("light"); } if ($(".page-sidebar-menu").hasClass("page-sidebar-menu-hover-submenu")) { $('.sidebar-menu-option', panel).val("hover"); } var sidebarOption = $('.sidebar-option', panel).val(); var headerOption = $('.page-header-option', panel).val(); var footerOption = $('.page-footer-option', panel).val(); var sidebarPosOption = $('.sidebar-pos-option', panel).val(); var sidebarStyleOption = $('.sidebar-style-option', panel).val(); var sidebarMenuOption = $('.sidebar-menu-option', panel).val(); $('.layout-option, .page-header-top-dropdown-style-option, .page-header-option, .sidebar-option, .page-footer-option, .sidebar-pos-option, .sidebar-style-option, .sidebar-menu-option', panel).change(setLayout); }; // handle theme style var setThemeStyle = function(style) { var file = (style === 'rounded' ? 'components-rounded' : 'components'); file = (Metronic.isRTL() ? file + '-rtl' : file); $('#style_components').attr("href", Metronic.getGlobalCssPath() + file + ".css"); if ($.cookie) { $.cookie('layout-style-option', style); } }; // Handle var handlePromo = function() { var init = function() { var html = ''; html = '<div class="promo-layer" style="z-index: 100000; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0, 0.8)">'; html += ' <div style="z-index: 100001; top: 50%; left: 50%; margin: -300px 0 0 -400px; width: 800px; height: 600px; position: fixed;">'; html += ' <div class="row">'; html += ' <div class="col-md-12" style="text-align: center">'; html += ' <h3 style="color: white; margin-bottom: 30px; font-size: 28px; line-height: 36px; font-weight: 400;">You are one step behind in choosing a perfect <br>admin theme for your project.</h3>'; html += ' <p style="color: white; font-size: 18px;">Just to recap some important facts about Metronic:</p>'; html += ' <ul style="list-style:none; margin: 30px auto 20px auto; padding: 10px; display: block; width: 550px; text-align: left; background: #fddf00; color: #000000;transform:rotate(-2deg);">'; html += ' <li style="list-style:none; padding: 4px 8px; font-size: 15px;">'; html += ' <span style="display: inline-block; width: 10px; height: 10px; border-radius: 20px !important; background: rgba(0, 0, 0, 0.2); margin-right: 5px; margin-top: 7px;"></span>'; html += ' The Most Popular #1 Selling Admin Theme of All Time.'; html += ' </li>'; html += ' <li style="list-style:none; padding: 4px 8px; font-size: 15px;">'; html += ' <span style="display: inline-block; width: 10px; height: 10px; border-radius: 20px !important; background: rgba(0, 0, 0, 0.2); margin-right: 5px; margin-top: 7px;"></span>'; html += ' Trusted By Over 26000 Users Around The Globe.'; html += ' </li>'; html += ' <li style="list-style:none; padding: 4px 8px; font-size: 15px;">'; html += ' <span style="display: inline-block; width: 10px; height: 10px; border-radius: 20px !important; background: rgba(0, 0, 0, 0.2); margin-right: 5px; margin-top: 7px;"></span>'; html += ' Used By Listed Companies In Small To Enterprise Solutions.'; html += ' </li>'; html += ' <li style="list-style:none; padding: 4px 8px; font-size: 15px;">'; html += ' <span style="display: inline-block; width: 10px; height: 10px; border-radius: 20px !important; background: rgba(0, 0, 0, 0.2); margin-right: 5px; margin-top: 7px;"></span>'; html += ' Includes 500+ Templates, 80+ Plugins, 1000+ UI Components.'; html += ' </li>'; html += ' <li style="list-style:none; padding: 4px 8px; font-size: 15px;">'; html += ' <span style="display: inline-block; width: 10px; height: 10px; border-radius: 20px !important; background: rgba(0, 0, 0, 0.2); margin-right: 5px; margin-top: 7px;"></span>'; html += ' Backed By A Team With Combined 32 Years of Experience In The Field.'; html += ' </li>'; html += ' <li style="list-style:none; padding: 4px 8px; font-size: 15px;">'; html += ' <span style="display: inline-block; width: 10px; height: 10px; border-radius: 20px !important; background: rgba(0, 0, 0, 0.2); margin-right: 5px; margin-top: 7px;"></span>'; html += ' A Product Of Over 2 Years Of Continuous Improvements'; html += ' </li>'; html += ' <li style="list-style:none; padding: 4px 8px; font-size: 15px;">'; html += ' <span style="display: inline-block; width: 10px; height: 10px; border-radius: 20px !important; background: rgba(0, 0, 0, 0.2); margin-right: 5px; margin-top: 7px;"></span>'; html += ' Get All The Above & Even More Just For 27$'; html += ' </li>'; html += ' </ul>'; html += ' </div>'; html += ' </div>'; html += ' <div class="row">'; html += ' <div class="col-md-12" style="margin-top: 20px;">'; html += ' <center><a class="btn btn-circle btn-danger btn-lg" style="padding: 12px 28px; font-size: 14px; text-transform: uppercase1;" href="http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes&utm_source=preview&utm_medium=banner&utm_campaign=Preview%20Engage" title="Purchase Metronic just for 27$ and get lifetime updates for free" target="_blank">Purchase Now!</a>'; html += ' &nbsp;&nbsp;<a class="btn btn-circle btn-default btn-lg promo-remind" style="padding: 11px 28px; font-size: 14px; text-transform: uppercase1;background: none; color: #fff;" href="javascript:;">Remind Me Later</a>'; html += ' <a class="btn btn-circle btn-default btn-lg promo-dismiss" style="padding: 12px 12px; font-size: 14px; text-transform: uppercase1; background: none; color: #aaa; border: 0" href="javascript:;">Dismiss</a></center>'; html += ' </div>'; html += ' </div>'; html += ' </div>'; html += '</div>'; $('body').append(html); $('.promo-dismiss').click(function(){ $('.promo-layer').remove(); $.cookie('user-dismiss', 1, { expires: 7, path: '/' }); }); $('.promo-remind').click(function(){ $('.promo-layer').remove(); $.cookie('user-page-views', 1, { expires: 1, path: '/' }); }); } if ($.cookie) { var pageViews = $.cookie('user-page-views') ? parseInt($.cookie('user-page-views')) : 0; var userDismiss = $.cookie('user-dismiss') ? parseInt($.cookie('user-dismiss')) : 0; pageViews = pageViews + 1; $.cookie('user-page-views', pageViews, { expires: 1, path: '/' }); //alert(pageViews); if (userDismiss === 0 && (pageViews === 10 || pageViews === 30 || pageViews === 50)) { setTimeout(init, 1000); } } else { return; } }; return { //main function to initiate the theme init: function() { // handles style customer tool handleTheme(); handlePromo(); // handle layout style change $('.theme-panel .layout-style-option').change(function() { setThemeStyle($(this).val()); }); // set layout style from cookie if ($.cookie && $.cookie('layout-style-option') === 'rounded') { setThemeStyle($.cookie('layout-style-option')); $('.theme-panel .layout-style-option').val($.cookie('layout-style-option')); } } }; }();
var Endian = { BIG_ENDIAN: 'bigEndian', LITTLE_ENDIAN: 'littleEndian' };
IFEmailField = IF.extend(IFFormComponent, function(uniqueId, bindingName) { if (! this.register(uniqueId, bindingName)) { console.log("No email field found with id "+uniqueId); } }, { hasValidValues: function(c) { console.log("Validating email field with value " + c.value()); // If the value is empty, then it doesn't validate the email. (isRequired function instead) -lg i-1446 if (c.value() && !IFValidator.isValidEmailAddress(c.value())) { c.indicateValidationFailure(); c.displayErrorMessageForKey("VALID_EMAIL_REQUIRED"); return false; } if (c.isRequired() && !c.value()) { return false; } return true; }, // these accessors are mandatory for any component that wants to interact // with its form. value: function() { return this.element.value; // just return the value of the actual text box }, setValue: function(value) { this.element.value = value; } });
import React from 'react'; export default props => { return ( <svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" > <path strokeWidth="0.2" strokeLinejoin="round" d="M 9.99936,3.99807L 3.99936,3.99807C 2.89436,3.99807 2.00936,4.89406 2.00936,5.99807L 1.99936,17.9981C 1.99936,19.1021 2.89436,19.9981 3.99936,19.9981L 19.9994,19.9981C 21.1029,19.9981 21.9994,19.1021 21.9994,17.9981L 21.9994,7.99807C 21.9994,6.89406 21.1029,5.99807 19.9994,5.99807L 11.9994,5.99807L 9.99936,3.99807 Z " /> </svg> ); };
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Article Schema */ var ArticleSchema = new Schema({ created: { type: Date, default: Date.now }, title: { type: String, default: '', trim: true, required: 'Title cannot be blank' }, content: { type: String, default: '', trim: true }, user: { type: Schema.ObjectId, ref: 'User' }, visibility: { type: Boolean, default: true } }); mongoose.model('Article', ArticleSchema);
import 'jquery'; // bootstrap jQuery plugins import 'bootstrap-sass/assets/javascripts/bootstrap/affix'; import 'bootstrap-sass/assets/javascripts/bootstrap/alert'; import 'bootstrap-sass/assets/javascripts/bootstrap/dropdown'; import 'bootstrap-sass/assets/javascripts/bootstrap/modal'; import 'bootstrap-sass/assets/javascripts/bootstrap/tab'; import 'bootstrap-sass/assets/javascripts/bootstrap/transition'; import 'bootstrap-sass/assets/javascripts/bootstrap/tooltip';
'use strict'; var should = require('should'), request = require('supertest'), path = require('path'), mongoose = require('mongoose'), User = mongoose.model('User'), Meal = mongoose.model('Meal'), express = require(path.resolve('./config/lib/express')); /** * Globals */ var app, agent, credentials, user, meal; /** * Meal routes tests */ describe('Meal CRUD tests', function () { before(function (done) { // Get application app = express.init(mongoose); agent = request.agent(app); done(); }); beforeEach(function (done) { // Create user credentials credentials = { username: 'username', password: 'M3@n.jsI$Aw3$0m3' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new Meal user.save(function () { meal = { name: 'Meal name' }; done(); }); }); it('should be able to save a Meal if logged in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Meal agent.post('/api/meals') .send(meal) .expect(200) .end(function (mealSaveErr, mealSaveRes) { // Handle Meal save error if (mealSaveErr) { return done(mealSaveErr); } // Get a list of Meals agent.get('/api/meals') .end(function (mealsGetErr, mealsGetRes) { // Handle Meal save error if (mealsGetErr) { return done(mealsGetErr); } // Get Meals list var meals = mealsGetRes.body; // Set assertions (meals[0].user._id).should.equal(userId); (meals[0].name).should.match('Meal name'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save an Meal if not logged in', function (done) { agent.post('/api/meals') .send(meal) .expect(403) .end(function (mealSaveErr, mealSaveRes) { // Call the assertion callback done(mealSaveErr); }); }); it('should not be able to save an Meal if no name is provided', function (done) { // Invalidate name field meal.name = ''; agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Meal agent.post('/api/meals') .send(meal) .expect(400) .end(function (mealSaveErr, mealSaveRes) { // Set message assertion (mealSaveRes.body.message).should.match('Please fill Meal name'); // Handle Meal save error done(mealSaveErr); }); }); }); it('should be able to update an Meal if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Meal agent.post('/api/meals') .send(meal) .expect(200) .end(function (mealSaveErr, mealSaveRes) { // Handle Meal save error if (mealSaveErr) { return done(mealSaveErr); } // Update Meal name meal.name = 'WHY YOU GOTTA BE SO MEAN?'; // Update an existing Meal agent.put('/api/meals/' + mealSaveRes.body._id) .send(meal) .expect(200) .end(function (mealUpdateErr, mealUpdateRes) { // Handle Meal update error if (mealUpdateErr) { return done(mealUpdateErr); } // Set assertions (mealUpdateRes.body._id).should.equal(mealSaveRes.body._id); (mealUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of Meals if not signed in', function (done) { // Create new Meal model instance var mealObj = new Meal(meal); // Save the meal mealObj.save(function () { // Request Meals request(app).get('/api/meals') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Array).and.have.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single Meal if not signed in', function (done) { // Create new Meal model instance var mealObj = new Meal(meal); // Save the Meal mealObj.save(function () { request(app).get('/api/meals/' + mealObj._id) .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('name', meal.name); // Call the assertion callback done(); }); }); }); it('should return proper error for single Meal with an invalid Id, if not signed in', function (done) { // test is not a valid mongoose Id request(app).get('/api/meals/test') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'Meal is invalid'); // Call the assertion callback done(); }); }); it('should return proper error for single Meal which doesnt exist, if not signed in', function (done) { // This is a valid mongoose Id but a non-existent Meal request(app).get('/api/meals/559e9cd815f80b4c256a8f41') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'No Meal with that identifier has been found'); // Call the assertion callback done(); }); }); it('should be able to delete an Meal if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Meal agent.post('/api/meals') .send(meal) .expect(200) .end(function (mealSaveErr, mealSaveRes) { // Handle Meal save error if (mealSaveErr) { return done(mealSaveErr); } // Delete an existing Meal agent.delete('/api/meals/' + mealSaveRes.body._id) .send(meal) .expect(200) .end(function (mealDeleteErr, mealDeleteRes) { // Handle meal error error if (mealDeleteErr) { return done(mealDeleteErr); } // Set assertions (mealDeleteRes.body._id).should.equal(mealSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete an Meal if not signed in', function (done) { // Set Meal user meal.user = user; // Create new Meal model instance var mealObj = new Meal(meal); // Save the Meal mealObj.save(function () { // Try deleting Meal request(app).delete('/api/meals/' + mealObj._id) .expect(403) .end(function (mealDeleteErr, mealDeleteRes) { // Set message assertion (mealDeleteRes.body.message).should.match('User is not authorized'); // Handle Meal error error done(mealDeleteErr); }); }); }); it('should be able to get a single Meal that has an orphaned user reference', function (done) { // Create orphan user creds var _creds = { username: 'orphan', password: 'M3@n.jsI$Aw3$0m3' }; // Create orphan user var _orphan = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'orphan@test.com', username: _creds.username, password: _creds.password, provider: 'local' }); _orphan.save(function (err, orphan) { // Handle save error if (err) { return done(err); } agent.post('/api/auth/signin') .send(_creds) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var orphanId = orphan._id; // Save a new Meal agent.post('/api/meals') .send(meal) .expect(200) .end(function (mealSaveErr, mealSaveRes) { // Handle Meal save error if (mealSaveErr) { return done(mealSaveErr); } // Set assertions on new Meal (mealSaveRes.body.name).should.equal(meal.name); should.exist(mealSaveRes.body.user); should.equal(mealSaveRes.body.user._id, orphanId); // force the Meal to have an orphaned user reference orphan.remove(function () { // now signin with valid user agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (err, res) { // Handle signin error if (err) { return done(err); } // Get the Meal agent.get('/api/meals/' + mealSaveRes.body._id) .expect(200) .end(function (mealInfoErr, mealInfoRes) { // Handle Meal error if (mealInfoErr) { return done(mealInfoErr); } // Set assertions (mealInfoRes.body._id).should.equal(mealSaveRes.body._id); (mealInfoRes.body.name).should.equal(meal.name); should.equal(mealInfoRes.body.user, undefined); // Call the assertion callback done(); }); }); }); }); }); }); }); afterEach(function (done) { User.remove().exec(function () { Meal.remove().exec(done); }); }); });
const solo = require('./lib/index'); const options = { host: '127.0.0.1', port: 6379, ttl: 7000, ping: 3000, interval: 5000 }; solo('process1', options, (error, worker) => { console.log('Doing process 1'); setTimeout(() => worker.done(), 2000); });
/* eslint-disable max-len */ import axios from 'axios'; const hostname = 'http://localhost:8080/';
'use strict'; module.exports = { '#': require('./#'), custom: require('./custom'), isError: require('./is-error'), validError: require('./valid-error') }; //# sourceMappingURL=index-compiled.js.map
version https://git-lfs.github.com/spec/v1 oid sha256:9193cfa133c0676a829520d7c05df85aafd1a5eeaad6999cb684e977d68f2795 size 1547
var Errors, SubContent; Errors = require("./errors"); module.exports = SubContent = (function() { function SubContent(fullText) { this.fullText = fullText != null ? fullText : ""; this.text = ""; this.start = 0; this.end = 0; } SubContent.prototype.getInnerLoop = function(templaterState) { this.start = templaterState.calcEndTag(templaterState.loopOpen); this.end = templaterState.calcStartTag(templaterState.loopClose); return this.refreshText(); }; SubContent.prototype.getOuterLoop = function(templaterState) { this.start = templaterState.calcStartTag(templaterState.loopOpen); this.end = templaterState.calcEndTag(templaterState.loopClose); return this.refreshText(); }; SubContent.prototype.getInnerTag = function(templaterState) { this.start = templaterState.calcPosition(templaterState.tagStart); this.end = templaterState.calcPosition(templaterState.tagEnd) + 1; return this.refreshText(); }; SubContent.prototype.refreshText = function() { this.text = this.fullText.substr(this.start, this.end - this.start); return this; }; SubContent.prototype.getErrorProps = function(xmlTag) { return { xmlTag: xmlTag, text: this.fullText, start: this.start, previousEnd: this.end }; }; SubContent.prototype.getOuterXml = function(xmlTag) { var endCandidate, err, startCandiate; endCandidate = this.fullText.indexOf('</' + xmlTag + '>', this.end); startCandiate = Math.max(this.fullText.lastIndexOf('<' + xmlTag + '>', this.start), this.fullText.lastIndexOf('<' + xmlTag + ' ', this.start)); if (endCandidate === -1) { err = new Errors.XTTemplateError("Can't find endTag"); err.properties = this.getErrorProps(xmlTag); throw err; } if (startCandiate === -1) { err = new Errors.XTTemplateError("Can't find startTag"); err.properties = this.getErrorProps(xmlTag); throw err; } this.end = endCandidate + ('</' + xmlTag + '>').length; this.start = startCandiate; return this.refreshText(); }; SubContent.prototype.replace = function(newText) { this.fullText = this.fullText.substr(0, this.start) + newText + this.fullText.substr(this.end); this.end = this.start + newText.length; return this.refreshText(); }; return SubContent; })();
"use strict"; /*global $:false */ // http://stackoverflow.com/a/210733/2397542 - jQuery center function from Tony L. jQuery.fn.center = function () { this.css("position", "fixed"); this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop()) + "px"); this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft()) + "px"); return this; }; var WMcycler = { KEYCODE_ESCAPE: 27, KEYCODE_LEFT: 37, KEYCODE_RIGHT: 39, KEYCODE_SPACE: 32, period: 0, fullscreen: 0, poller_cycle: 0, current: 0, countdown: 0, nmaps: 0, paused: false, timer_counter: null, timer_reloader: null, updateProgress: function () { // update the countdown bar - 450 is the max width in pixels var progress = this.countdown / (this.period / 200) * 450; $("#wm_progress").css("width", progress); }, counterHandler: function () { if (this.paused) { $("#wm_progress").toggleClass("paused"); } else { this.updateProgress(); this.countdown--; if (this.countdown < 0) { this.switchMap(1); } } }, forceReload: function (that) { var d = new Date(), newurl = $(that).find('img').attr("src"); if (newurl !== undefined) { newurl = newurl.replace(/time=\d+/, "time=" + d.getTime()); $(that).find('img').attr("src", newurl); } }, // change to the next (or previous) map, reset the countdown, update the bar switchMap: function (direction) { var wm_new = this.current + direction; if (wm_new < 0) { wm_new += this.nmaps; } wm_new = wm_new % this.nmaps; var now = $(".weathermapholder").eq(this.current), next = $(".weathermapholder").eq(wm_new); if (this.fullscreen) { // in fullscreen, we centre everything, layer it with z-index and // cross-fade next.center(); now.css("z-index", 2); next.css("z-index", 3); now.fadeOut(1200, function () { // now that we're done with it, force a reload on the image just // passed WMcycler.forceReload(this); }); next.fadeIn(1200); } else { // in non-fullscreen mode, the fades just make things look strange. // Snap-changes now.hide(1, function () { // now that we're done with it, force a reload on the image just // passed // WMcycler.forceReload(); }); next.show(1); } this.countdown = this.period / 200; this.current = wm_new; $("#wm_current_map").text(this.current + 1); this.updateProgress(); }, hideControls: function () { $("#wmcyclecontrolbox").fadeOut(500); }, showControls: function () { $("#wmcyclecontrolbox").fadeIn(100); }, start: function (initialData) { $('.weathermapholder').hide(); this.period = initialData.period; this.poller_cycle = initialData.poller_cycle; this.fullscreen = initialData.fullscreen; this.nmaps = $(".weathermapholder").length; $("#wm_total_map").text(this.nmaps); // copy of this that we can pass into callbacks var that = this; this.initEvents(that); this.initKeys(that); // stop here if there were no maps if (this.nmaps > 0) { this.current = 0; this.switchMap(0); // figure out how long the refresh is, so that we get // through all the maps in exactly one poller cycle if (this.period === 0) { this.period = this.poller_cycle / this.nmaps; } this.countdown = this.period / 200; // a countdown timer in the top corner this.timer_counter = setInterval(function () { that.counterHandler(); }, 200); // when to reload the whole page (with new map data) this.timer_reloader = setTimeout(function () { that.reloadPage(); }, this.poller_cycle); this.initIdle(that); } }, reloadPage: function () { location.reload(true); }, initKeys: function (that) { $(document).keyup(function (event) { if (event.keyCode === that.KEYCODE_ESCAPE) { window.location.href = $('#cycle_stop').attr('href'); event.preventDefault(); } if (event.keyCode === that.KEYCODE_SPACE) { that.pauseAction(); event.preventDefault(); } // left if (event.keyCode === that.KEYCODE_LEFT) { that.previousAction(); event.preventDefault(); } // right if (event.keyCode === that.KEYCODE_RIGHT) { that.nextAction(); event.preventDefault(); } }); }, initEvents: function (that) { $("#cycle_pause").click(function () { that.pauseAction(); }); $("#cycle_next").click(function () { that.nextAction(); }); $("#cycle_prev").click(function () { that.previousAction(); }); }, initIdle: function (that) { // aim to get a video-player style OSD for fullscreen mode: // if the pointer is off the controls for more than 5 seconds, fade the // controls away // if the pointer moves after that, bring the controls back // if the pointer is over the controls, don't fade if (this.fullscreen) { $(document).idleTimer({ timeout: 5000 }); $(document).on("idle.idleTimer", function () { that.hideControls(); }); $(document).on("active.idleTimer", function () { that.showControls(); }); } }, nextAction: function () { this.switchMap(1); }, previousAction: function () { this.switchMap(-1); }, pauseAction: function () { this.paused = !this.paused; // remove the paused class on the progress bar, if we're mid-flash and // no longer paused if (!this.paused) { $("#wm_progress").removeClass("paused"); } } };
/** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../../..' export const run = editor => { Editor.setNodes(editor, { key: true }, { match: 'inline' }) } export const input = ( <editor> <block> <text /> <inline> <anchor /> word </inline> <focus /> </block> </editor> ) export const output = ( <editor> <block> <text /> <inline key> <anchor /> word </inline> <focus /> </block> </editor> )
// 有空改成 MVC 的 define('options', function(exports, module) { // 用户实际存下来的 options 数据 var user_options = {}; // 默认选项 // 展示时先 sort_by_category 然后再按 category 分别显示 var DEFAULT_OPTIONS = { /* "font-family": { "category": "界面", "description": "默认字体", "value": "Microsoft Yahei", "hint": "98 界面的默认字体,不同的字体用逗号分隔,排在前面的优先" }, "font-size": { "category": "界面", "description": "字体大小", "value": "12px", "hint": "默认字体大小,预设是 12px" }, "line-height": { "category": "界面", "description": "行间距", "value": "21px", "hint": "98 默认行间距为 1.1 倍,脚本预设为 21px 以提高可读性" },*/ "ignored_users": { "category": "界面", "description": "屏蔽列表", "value": [], "hint": "被屏蔽用户发表的主题和回复将不会显示" } /*, "block_qmd": { "category": "界面", "description": "屏蔽用户签名档", "value": false }*/ }; // 上传设置,保存时默认即上传了,故不对外界暴露 function upload() { var libcc98 = require('libcc98'); return libcc98.getDraftID('[cc98 blacklist settings]') .then(libcc98.deleteDraft) .then(libcc98.deleteTrash) .always(function() { libcc98.saveDraft({ 'recipient': libcc98.user_info.username, 'subject': '[cc98 blacklist settings]', 'message': JSON.stringify(user_options) }); }); } // 下载设置 function download() { var libcc98 = require('libcc98'); return libcc98.getDraft('[cc98 blacklist settings]') .then(function(pm) { user_options = JSON.parse(pm.message); }).reject(function() { load(); }); } // 保存并上传设置 function save() { localStorage.setItem('cc98-blacklist-settings', JSON.stringify(user_options)); upload(); } // 从本地载入用户设置 function load() { user_options = JSON.parse(localStorage.getItem('cc98-blacklist-settings')) || {}; // 如果新增了默认配置项,则加入到原配置中 for (var prop in DEFAULT_OPTIONS) { if (user_options[prop] === undefined) { user_options[prop] = DEFAULT_OPTIONS[prop]; } } // 默认不保存,免得和云端的冲突,反正是默认配置,保不保存也没区别 } function setValue(key, value) { user_options[key].value = value; save(); } function getProperty(key, property) { return user_options[key][property]; } function init() { load(); // blahblah } // 点确认/取消隐藏界面 var addButton = function() { var $ = require('jQuery'); var chaos = require('chaos'); // 先生成对应 DOM 结构,然后在鼠标点击时显示/隐藏该 div var div = $('<div id="blacklist-options"></div>'); var dl = $('<dl></dl>'); for (var key in user_options) { var dt = $('<dt>' + user_options[key].description + '</dt>'); dt.data('key', key); var dd = $('<dd></dd>'); // 如果是数组,则依次展现数组元素 if (Array.isArray(getProperty(key, 'value'))) { for (var i = 0; i !== getProperty(key, 'value').length; ++i) { var item = $('<span class="array-item">' + getProperty(key, 'value')[i] + '<a class="delete-item"></a></span>'); dd.append(item); } dd.append('<input type="text" class="new-item">').append('<a class="add-item"></a>'); } dl.append(dt).append(dd); div.append(dl); } div.append( ['<br><div><button class="blacklist-btn" id="submit-options">确定</button>', '<button class="blacklist-btn" id="upload-options">上传设置</button>', '<button class="blacklist-btn" id="download-options">下载设置</button>', '</div>' ].join('\n')); $('body').append(div); div.hide(); div.on('click', '.delete-item', function(e) { var item = $(this).parent(); var key = item.parent().prev().data('key'); var array = getProperty(key, 'value'); var value = item.text(); array.splice(array.indexOf(value), 1); setValue(key, array); item.remove(); }); $('.add-item').click(function(e) { var item = $(this).prev(); var value = item.prop('value').trim(); if (!value) { return; } var dd = item.parent(); var key = dd.prev().data('key'); var array = getProperty(key, 'value'); if (array.indexOf(value) !== -1) { return; } array.push(value); setValue(key, array); item.prop('value', ''); item.before('<span class="array-item">' + value + '<a class="delete-item"></a></span>'); }); $('.new-item').keyup(function(e) { if (e.keyCode === 13) { $(this).next().click(); } }); $('#submit-options').click(function(e) { div.hide(); }); $('#upload-options').click(function() { upload() .then(function() { alert('上传成功'); }, function() { alert('上传失败'); }); }); $('#download-options').click(function() { download() .then(function() { alert('下载成功,刷新页面后生效'); }, function() { alert('下载失败'); }); }); // 添加按钮 $('<a id="show-blacklist-options" href="javascript:;">黑名单</a>') .appendTo($('.TopLighNav1').children().children().eq(0)) .before('<img align="absmiddle" src="pic/navspacer.gif"> ') .on('click', function() { div.show(); }); chaos.addStyles([ '#blacklist-options {', ' position: absolute;', ' top: 150px;', ' left: 15%;', ' width: 70%;', ' margin: 0 auto;', ' border: 1px solid #ccc;', ' border-radius: 5px;', ' box-shadow: 0 0 4px rgba(0, 0, 0, 0.4);', ' padding: 20px;', ' background-color: #fff;', '}', '#blacklist-options dl { margin: 0; }', '#blacklist-options dt, #blacklist-options dd {', ' display: inline-block;', ' padding-top: 0;', ' color: #333;', ' font-size: 14px;', '}', '.array-item {', ' border: 0 none;', ' border-radius: 3px;', ' background-color: #ddd;', ' box-shadow: 1px 1px 0 rgba(0, 0, 0, 0.25);', ' padding: 0 5px;', ' display: inline-block;', ' margin-left: 30px;', '}', '.add-item, .delete-item {', ' display: inline-block;', ' vertical-align: middle;', ' width: 16px;', ' height: 16px;', ' cursor: pointer;', '}', '.delete-item {', ' margin-left: 4px;', ' background-image: url(http://file.cc98.org/uploadfile/2013/12/2/2101869387.png);', '}', '.add-item {', ' margin-left: 30px;', ' background-image: url(http://file.cc98.org/uploadfile/2013/12/2/2101873264.png);', '}', '.new-item {', ' margin-left: 30px;', ' width: 80px;', '}', ].join('\n')); }; init(); var that = {}; that.save = save; that.load = load; that.download = download; that.getProperty = getProperty; that.setValue = setValue; that.addButton = addButton; module.exports = that; });
/* * Aconite Readiness Notification Utilities * http://github.com/colinbdclark/aconite * * Copyright 2017, Colin Clark * Distributed under the MIT license. */ (function () { "use strict"; fluid.defaults("aconite.readinessResponder", { gradeNames: "fluid.modelComponent", readinessEventName: "onReady", model: { unknownReadinessCounter: 0 }, modelListeners: { unknownReadinessCounter: { funcName: "aconite.readinessResponder.fireWhenReady", args: ["{that}", "{change}.value"], excludeSource: "init" } } }); aconite.readinessResponder.fireWhenReady = function (that, unknownReadinessCounter) { if (unknownReadinessCounter === 0) { that.events[that.options.readinessEventName].fire(); } }; fluid.defaults("aconite.readinessNotifier", { gradeNames: "fluid.modelComponent", model: { unknownReadinessCounter: "{readinessResponder}.model.unknownReadinessCounter" }, listeners: { "onCreate.incrementCounter": { funcName: "aconite.readinessNotifier.incrementCounter", args: ["{that}"] }, "onReady.decrementCounter": { funcName: "aconite.readinessNotifier.decrementCounter", args: ["{that}"] } } }); aconite.readinessNotifier.incrementCounter = function (that) { that.applier.change("unknownReadinessCounter", that.model.unknownReadinessCounter + 1); }; aconite.readinessNotifier.decrementCounter = function (that) { that.applier.change("unknownReadinessCounter", that.model.unknownReadinessCounter - 1); }; })();
app.controller('EditTownAsAdminController', ['$scope', '$modalInstance', 'town', function($scope, $modalInstance, town) { $scope.town = angular.copy(town); $scope.edit = function(town) { $modalInstance.close(town); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; } ])
$(document).ready(function() { $('#bg').blurjs({ source: 'body', radius: 10, overlay: 'rgba(255, 255, 255, .5)' }); }); var _paq = _paq || []; _paq.push(["trackPageView"]); _paq.push(["enableLinkTracking"]); (function() { var u = (("https:" == document.location.protocol) ? "https" : "http") + "://stats.vincentrozenberg.com/"; _paq.push(["setTrackerUrl", u + "piwik.php"]); _paq.push(["setSiteId", "4"]); var d = document, g = d.createElement("script"), s = d.getElementsByTagName("script")[0]; g.type = "text/javascript"; g.defer = true; g.async = true; g.src = u + "piwik.js"; s.parentNode.insertBefore(g, s); })();
/* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties#Polyfill */ if (!Object.defineProperties) { Object.defineProperties = function(object, props) { function hasProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function convertToDescriptor(desc) { if (Object(desc) !== desc) { throw new TypeError('Descriptor can only be an Object.'); } var d = {}; if (hasProperty(desc, "enumerable")) { d.enumerable = !!desc.enumerable; } if (hasProperty(desc, "configurable")) { d.configurable = !!desc.configurable; } if (hasProperty(desc, "value")) { d.value = desc.value; } if (hasProperty(desc, "writable")) { d.writable = !!desc.writable; } if (hasProperty(desc, "get")) { throw new TypeError('getters & setters can not be defined on this javascript engine'); } if (hasProperty(desc, "set")) { throw new TypeError('getters & setters can not be defined on this javascript engine'); } return d; } if (Object(object) !== object) { throw new TypeError('Object.defineProperties can only be called on Objects.'); } if (Object(props) !== props) { throw new TypeError('Properties can only be an Object.'); } var properties = Object(props); for (propName in properties) { if (hasOwnProperty.call(properties, propName)) { var descr = convertToDescriptor(properties[propName]); object[propName] = descr.value; } } return object; } }
function MeteroitSpritesPool() { this.createBrownMeteroits(); this.createGreyMeteroits(); } ////// Brown MeteroitSpritesPool.prototype.borrowBrownMeteroit = function () { return this.brownMeteroits.shift(); }; MeteroitSpritesPool.prototype.returnBrownMeteroit = function(sprite) { this.brownMeteroits.push(sprite); }; // Grey MeteroitSpritesPool.prototype.borrowGreyMeteroit = function () { return this.greyMeteroits.shift(); }; MeteroitSpritesPool.prototype.returnGreyMeteroit = function(sprite) { this.greyMeteroits.push(sprite); }; // continue /// create the functions for the top // MeteroitSpritesPool.prototype.createBrownMeteroits = function () { this.brownMeteroits = []; this.addBrownMeteroitSprites(1, "meteorBrown_big1.png"); this.addBrownMeteroitSprites(1, "meteorBrown_big2.png"); this.addBrownMeteroitSprites(1, "meteorBrown_big3.png"); this.addBrownMeteroitSprites(1, "meteorBrown_big4.png"); this.addBrownMeteroitSprites(1, "meteorBrown_med1.png"); this.addBrownMeteroitSprites(1, "meteorBrown_med3.png"); this.addBrownMeteroitSprites(1, "meteorBrown_small1.png"); this.addBrownMeteroitSprites(1, "meteorBrown_small2.png"); this.addBrownMeteroitSprites(1, "meteorBrown_tiny1.png"); this.addBrownMeteroitSprites(1, "meteorBrown_tiny2.png"); // create method to shuffle and randomize the order that they appear in this.shuffle(this.brownMeteroits); }; // create function for GREY meteroits MeteroitSpritesPool.prototype.createGreyMeteroits = function () { this.greyMeteroits = []; this.addGreyMeteroitSprites(1, "meteorGrey_big1.png"); this.addGreyMeteroitSprites(1, "meteorGrey_big2.png"); this.addGreyMeteroitSprites(1, "meteorGrey_big3.png"); this.addGreyMeteroitSprites(1, "meteorGrey_big4.png"); this.addGreyMeteroitSprites(1, "meteorGrey_med1.png"); this.addGreyMeteroitSprites(1, "meteorGrey_med2.png"); this.addGreyMeteroitSprites(1, "meteorGrey_small1.png"); this.addGreyMeteroitSprites(1, "meteorGrey_small2.png"); this.addGreyMeteroitSprites(1, "meteorGrey_tiny1.png"); this.addGreyMeteroitSprites(1, "meteorGrey_tiny2.png"); // create method to shuffle and randomize the order that they appear in this.shuffle(this.greyMeteroits); }; // actual function for pushing sprites to Object Brown and Grey MeteroitSpritesPool.prototype.addBrownMeteroitSprites = function (amount, frameId) { for (var i = 0; i < amount; i++) { var sprite = PIXI.Sprite.fromFrame(frameId); this.brownMeteroits.push(sprite); } }; MeteroitSpritesPool.prototype.addGreyMeteroitSprites = function (amount, frameId) { for (var i = 0; i < amount; i++) { var sprite = PIXI.Sprite.fromFrame(frameId); this.greyMeteroits.push(sprite); } }; // shuffle it all MeteroitSpritesPool.prototype.shuffle = function(array) { var len = array.length; var shuffles = len * 3; for (var i = 0; i < shuffles; i++ ) { var meteorSlice = array.pop(); var pos = Math.floor(Math.random() * (len-1)); array.splice(pos, 0, meteorSlice); } };
/** * Problem: https://leetcode.com/problems/valid-parenthesis-string/description/ */ /** * @param {string} s * @return {boolean} */ var checkValidString = function(s) { let left = 0, change = 0, mark = 0, right = 0; for (let i = 0; i < s.length; ++i) { if ('(' === s[i]) { ++left; } else if ('*' === s[i]) { if (left) { --left; ++change; } else { ++mark; } } else if (')' === s[i]) { if (left) { --left; } else if (mark){ --mark; } else if (change) { --change; ++mark; } else { ++right; } } } return !left && !right; }; module.exports = checkValidString;
/*! * node-rcon - examples/stdio.js * Copyright(c) 2012 Justin Li <j-li.net> * MIT Licensed */ /* * This example reads commands from stdin and sends them on enter key press * You need to manually `npm install keypress` for this example to work */ var Rcon = require('../node-rcon'); var conn = new Rcon('localhost', 1234, 'password'); conn.on('auth', function() { console.log("Authed!"); }).on('response', function(str) { console.log("Got response: " + str); }).on('end', function() { console.log("Socket closed!"); process.exit(); }); conn.connect(); require('keypress')(process.stdin); process.stdin.setRawMode(true); process.stdin.resume(); var buffer = ""; process.stdin.on('keypress', function(chunk, key) { if (key && key.ctrl && (key.name == 'c' || key.name == 'd')) { conn.disconnect(); return; } process.stdout.write(chunk); if (key && (key.name == 'enter' || key.name == 'return')) { conn.send(buffer); buffer = ""; process.stdout.write("\n"); } else if (key && key.name == 'backspace') { buffer = buffer.slice(0, -1); process.stdout.write("\033[K"); // Clear to end of line } else { buffer += chunk; } });
var webpack = require('webpack'); module.exports = { entry: './src/js/app.jsx', output: { filename: 'components.js', path: './assets/js', }, module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel' } ] }, externals: { 'react': 'React' }, resolve: { extensions: ['', '.js', '.jsx'] } };
'use strict' var render = require('../../../render') render( { src: __dirname + '/../../../src/commonJS/*.js', separators: true }, __dirname + '/readme.md' )
/*! * Quill Editor v1.3.6 * https://quilljs.com/ * Copyright (c) 2014, Jason Chen * Copyright (c) 2013, salesforce.com */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Quill"] = factory(); else root["Quill"] = factory(); })(typeof self !== 'undefined' ? self : this, function () { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function (exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function (module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 110); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var container_1 = __webpack_require__(17); var format_1 = __webpack_require__(18); var leaf_1 = __webpack_require__(19); var scroll_1 = __webpack_require__(45); var inline_1 = __webpack_require__(46); var block_1 = __webpack_require__(47); var embed_1 = __webpack_require__(48); var text_1 = __webpack_require__(49); var attributor_1 = __webpack_require__(12); var class_1 = __webpack_require__(32); var style_1 = __webpack_require__(33); var store_1 = __webpack_require__(31); var Registry = __webpack_require__(1); var Parchment = { Scope: Registry.Scope, create: Registry.create, find: Registry.find, query: Registry.query, register: Registry.register, Container: container_1.default, Format: format_1.default, Leaf: leaf_1.default, Embed: embed_1.default, Scroll: scroll_1.default, Block: block_1.default, Inline: inline_1.default, Text: text_1.default, Attributor: { Attribute: attributor_1.default, Class: class_1.default, Style: style_1.default, Store: store_1.default, }, }; exports.default = Parchment; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var ParchmentError = /** @class */ (function (_super) { __extends(ParchmentError, _super); function ParchmentError(message) { var _this = this; message = '[Parchment] ' + message; _this = _super.call(this, message) || this; _this.message = message; _this.name = _this.constructor.name; return _this; } return ParchmentError; }(Error)); exports.ParchmentError = ParchmentError; var attributes = {}; var classes = {}; var tags = {}; var types = {}; exports.DATA_KEY = '__blot'; var Scope; (function (Scope) { Scope[Scope["TYPE"] = 3] = "TYPE"; Scope[Scope["LEVEL"] = 12] = "LEVEL"; Scope[Scope["ATTRIBUTE"] = 13] = "ATTRIBUTE"; Scope[Scope["BLOT"] = 14] = "BLOT"; Scope[Scope["INLINE"] = 7] = "INLINE"; Scope[Scope["BLOCK"] = 11] = "BLOCK"; Scope[Scope["BLOCK_BLOT"] = 10] = "BLOCK_BLOT"; Scope[Scope["INLINE_BLOT"] = 6] = "INLINE_BLOT"; Scope[Scope["BLOCK_ATTRIBUTE"] = 9] = "BLOCK_ATTRIBUTE"; Scope[Scope["INLINE_ATTRIBUTE"] = 5] = "INLINE_ATTRIBUTE"; Scope[Scope["ANY"] = 15] = "ANY"; })(Scope = exports.Scope || (exports.Scope = {})); function create(input, value) { var match = query(input); if (match == null) { throw new ParchmentError("Unable to create " + input + " blot"); } var BlotClass = match; var node = // @ts-ignore input instanceof Node || input['nodeType'] === Node.TEXT_NODE ? input : BlotClass.create(value); return new BlotClass(node, value); } exports.create = create; function find(node, bubble) { if (bubble === void 0) { bubble = false; } if (node == null) return null; // @ts-ignore if (node[exports.DATA_KEY] != null) return node[exports.DATA_KEY].blot; if (bubble) return find(node.parentNode, bubble); return null; } exports.find = find; function query(query, scope) { if (scope === void 0) { scope = Scope.ANY; } var match; if (typeof query === 'string') { match = types[query] || attributes[query]; // @ts-ignore } else if (query instanceof Text || query['nodeType'] === Node.TEXT_NODE) { match = types['text']; } else if (typeof query === 'number') { if (query & Scope.LEVEL & Scope.BLOCK) { match = types['block']; } else if (query & Scope.LEVEL & Scope.INLINE) { match = types['inline']; } } else if (query instanceof HTMLElement) { var names = (query.getAttribute('class') || '').split(/\s+/); for (var i in names) { match = classes[names[i]]; if (match) break; } match = match || tags[query.tagName]; } if (match == null) return null; // @ts-ignore if (scope & Scope.LEVEL & match.scope && scope & Scope.TYPE & match.scope) return match; return null; } exports.query = query; function register() { var Definitions = []; for (var _i = 0; _i < arguments.length; _i++) { Definitions[_i] = arguments[_i]; } if (Definitions.length > 1) { return Definitions.map(function (d) { return register(d); }); } var Definition = Definitions[0]; if (typeof Definition.blotName !== 'string' && typeof Definition.attrName !== 'string') { throw new ParchmentError('Invalid definition'); } else if (Definition.blotName === 'abstract') { throw new ParchmentError('Cannot register abstract class'); } types[Definition.blotName || Definition.attrName] = Definition; if (typeof Definition.keyName === 'string') { attributes[Definition.keyName] = Definition; } else { if (Definition.className != null) { classes[Definition.className] = Definition; } if (Definition.tagName != null) { if (Array.isArray(Definition.tagName)) { Definition.tagName = Definition.tagName.map(function (tagName) { return tagName.toUpperCase(); }); } else { Definition.tagName = Definition.tagName.toUpperCase(); } var tagNames = Array.isArray(Definition.tagName) ? Definition.tagName : [Definition.tagName]; tagNames.forEach(function (tag) { if (tags[tag] == null || Definition.className == null) { tags[tag] = Definition; } }); } } return Definition; } exports.register = register; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { var diff = __webpack_require__(51); var equal = __webpack_require__(11); var extend = __webpack_require__(3); var op = __webpack_require__(20); var NULL_CHARACTER = String.fromCharCode(0); // Placeholder char for embed in diff() var Delta = function (ops) { // Assume we are given a well formed ops if (Array.isArray(ops)) { this.ops = ops; } else if (ops != null && Array.isArray(ops.ops)) { this.ops = ops.ops; } else { this.ops = []; } }; Delta.prototype.insert = function (text, attributes) { var newOp = {}; if (text.length === 0) return this; newOp.insert = text; if (attributes != null && typeof attributes === 'object' && Object.keys(attributes).length > 0) { newOp.attributes = attributes; } return this.push(newOp); }; Delta.prototype['delete'] = function (length) { if (length <= 0) return this; return this.push({ 'delete': length }); }; Delta.prototype.retain = function (length, attributes) { if (length <= 0) return this; var newOp = { retain: length }; if (attributes != null && typeof attributes === 'object' && Object.keys(attributes).length > 0) { newOp.attributes = attributes; } return this.push(newOp); }; Delta.prototype.push = function (newOp) { var index = this.ops.length; var lastOp = this.ops[index - 1]; newOp = extend(true, {}, newOp); if (typeof lastOp === 'object') { if (typeof newOp['delete'] === 'number' && typeof lastOp['delete'] === 'number') { this.ops[index - 1] = { 'delete': lastOp['delete'] + newOp['delete'] }; return this; } // Since it does not matter if we insert before or after deleting at the same index, // always prefer to insert first if (typeof lastOp['delete'] === 'number' && newOp.insert != null) { index -= 1; lastOp = this.ops[index - 1]; if (typeof lastOp !== 'object') { this.ops.unshift(newOp); return this; } } if (equal(newOp.attributes, lastOp.attributes)) { if (typeof newOp.insert === 'string' && typeof lastOp.insert === 'string') { this.ops[index - 1] = { insert: lastOp.insert + newOp.insert }; if (typeof newOp.attributes === 'object') this.ops[index - 1].attributes = newOp.attributes return this; } else if (typeof newOp.retain === 'number' && typeof lastOp.retain === 'number') { this.ops[index - 1] = { retain: lastOp.retain + newOp.retain }; if (typeof newOp.attributes === 'object') this.ops[index - 1].attributes = newOp.attributes return this; } } } if (index === this.ops.length) { this.ops.push(newOp); } else { this.ops.splice(index, 0, newOp); } return this; }; Delta.prototype.chop = function () { var lastOp = this.ops[this.ops.length - 1]; if (lastOp && lastOp.retain && !lastOp.attributes) { this.ops.pop(); } return this; }; Delta.prototype.filter = function (predicate) { return this.ops.filter(predicate); }; Delta.prototype.forEach = function (predicate) { this.ops.forEach(predicate); }; Delta.prototype.map = function (predicate) { return this.ops.map(predicate); }; Delta.prototype.partition = function (predicate) { var passed = [], failed = []; this.forEach(function(op) { var target = predicate(op) ? passed : failed; target.push(op); }); return [passed, failed]; }; Delta.prototype.reduce = function (predicate, initial) { return this.ops.reduce(predicate, initial); }; Delta.prototype.changeLength = function () { return this.reduce(function (length, elem) { if (elem.insert) { return length + op.length(elem); } else if (elem.delete) { return length - elem.delete; } return length; }, 0); }; Delta.prototype.length = function () { return this.reduce(function (length, elem) { return length + op.length(elem); }, 0); }; Delta.prototype.slice = function (start, end) { start = start || 0; if (typeof end !== 'number') end = Infinity; var ops = []; var iter = op.iterator(this.ops); var index = 0; while (index < end && iter.hasNext()) { var nextOp; if (index < start) { nextOp = iter.next(start - index); } else { nextOp = iter.next(end - index); ops.push(nextOp); } index += op.length(nextOp); } return new Delta(ops); }; Delta.prototype.compose = function (other) { var thisIter = op.iterator(this.ops); var otherIter = op.iterator(other.ops); var delta = new Delta(); while (thisIter.hasNext() || otherIter.hasNext()) { if (otherIter.peekType() === 'insert') { delta.push(otherIter.next()); } else if (thisIter.peekType() === 'delete') { delta.push(thisIter.next()); } else { var length = Math.min(thisIter.peekLength(), otherIter.peekLength()); var thisOp = thisIter.next(length); var otherOp = otherIter.next(length); if (typeof otherOp.retain === 'number') { var newOp = {}; if (typeof thisOp.retain === 'number') { newOp.retain = length; } else { newOp.insert = thisOp.insert; } // Preserve null when composing with a retain, otherwise remove it for inserts var attributes = op.attributes.compose(thisOp.attributes, otherOp.attributes, typeof thisOp.retain === 'number'); if (attributes) newOp.attributes = attributes; delta.push(newOp); // Other op should be delete, we could be an insert or retain // Insert + delete cancels out } else if (typeof otherOp['delete'] === 'number' && typeof thisOp.retain === 'number') { delta.push(otherOp); } } } return delta.chop(); }; Delta.prototype.concat = function (other) { var delta = new Delta(this.ops.slice()); if (other.ops.length > 0) { delta.push(other.ops[0]); delta.ops = delta.ops.concat(other.ops.slice(1)); } return delta; }; Delta.prototype.diff = function (other, index) { if (this.ops === other.ops) { return new Delta(); } var strings = [this, other].map(function (delta) { return delta.map(function (op) { if (op.insert != null) { return typeof op.insert === 'string' ? op.insert : NULL_CHARACTER; } var prep = (delta === other) ? 'on' : 'with'; throw new Error('diff() called ' + prep + ' non-document'); }).join(''); }); var delta = new Delta(); var diffResult = diff(strings[0], strings[1], index); var thisIter = op.iterator(this.ops); var otherIter = op.iterator(other.ops); diffResult.forEach(function (component) { var length = component[1].length; while (length > 0) { var opLength = 0; switch (component[0]) { case diff.INSERT: opLength = Math.min(otherIter.peekLength(), length); delta.push(otherIter.next(opLength)); break; case diff.DELETE: opLength = Math.min(length, thisIter.peekLength()); thisIter.next(opLength); delta['delete'](opLength); break; case diff.EQUAL: opLength = Math.min(thisIter.peekLength(), otherIter.peekLength(), length); var thisOp = thisIter.next(opLength); var otherOp = otherIter.next(opLength); if (equal(thisOp.insert, otherOp.insert)) { delta.retain(opLength, op.attributes.diff(thisOp.attributes, otherOp.attributes)); } else { delta.push(otherOp)['delete'](opLength); } break; } length -= opLength; } }); return delta.chop(); }; Delta.prototype.eachLine = function (predicate, newline) { newline = newline || '\n'; var iter = op.iterator(this.ops); var line = new Delta(); var i = 0; while (iter.hasNext()) { if (iter.peekType() !== 'insert') return; var thisOp = iter.peek(); var start = op.length(thisOp) - iter.peekLength(); var index = typeof thisOp.insert === 'string' ? thisOp.insert.indexOf(newline, start) - start : -1; if (index < 0) { line.push(iter.next()); } else if (index > 0) { line.push(iter.next(index)); } else { if (predicate(line, iter.next(1).attributes || {}, i) === false) { return; } i += 1; line = new Delta(); } } if (line.length() > 0) { predicate(line, {}, i); } }; Delta.prototype.transform = function (other, priority) { priority = !!priority; if (typeof other === 'number') { return this.transformPosition(other, priority); } var thisIter = op.iterator(this.ops); var otherIter = op.iterator(other.ops); var delta = new Delta(); while (thisIter.hasNext() || otherIter.hasNext()) { if (thisIter.peekType() === 'insert' && (priority || otherIter.peekType() !== 'insert')) { delta.retain(op.length(thisIter.next())); } else if (otherIter.peekType() === 'insert') { delta.push(otherIter.next()); } else { var length = Math.min(thisIter.peekLength(), otherIter.peekLength()); var thisOp = thisIter.next(length); var otherOp = otherIter.next(length); if (thisOp['delete']) { // Our delete either makes their delete redundant or removes their retain continue; } else if (otherOp['delete']) { delta.push(otherOp); } else { // We retain either their retain or insert delta.retain(length, op.attributes.transform(thisOp.attributes, otherOp.attributes, priority)); } } } return delta.chop(); }; Delta.prototype.transformPosition = function (index, priority) { priority = !!priority; var thisIter = op.iterator(this.ops); var offset = 0; while (thisIter.hasNext() && offset <= index) { var length = thisIter.peekLength(); var nextType = thisIter.peekType(); thisIter.next(); if (nextType === 'delete') { index -= Math.min(length, index - offset); continue; } else if (nextType === 'insert' && (offset < index || !priority)) { index += length; } offset += length; } return index; }; module.exports = Delta; /***/ }), /* 3 */ /***/ (function(module, exports) { 'use strict'; var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { /**/ } return typeof key === 'undefined' || hasOwn.call(obj, key); }; module.exports = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = extend(deep, clone, copy); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { target[name] = copy; } } } } } // Return the modified object return target; }; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.BlockEmbed = exports.bubbleFormats = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _extend = __webpack_require__(3); var _extend2 = _interopRequireDefault(_extend); var _quillDelta = __webpack_require__(2); var _quillDelta2 = _interopRequireDefault(_quillDelta); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _break = __webpack_require__(16); var _break2 = _interopRequireDefault(_break); var _inline = __webpack_require__(6); var _inline2 = _interopRequireDefault(_inline); var _text = __webpack_require__(7); var _text2 = _interopRequireDefault(_text); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var NEWLINE_LENGTH = 1; var BlockEmbed = function (_Parchment$Embed) { _inherits(BlockEmbed, _Parchment$Embed); function BlockEmbed() { _classCallCheck(this, BlockEmbed); return _possibleConstructorReturn(this, (BlockEmbed.__proto__ || Object.getPrototypeOf(BlockEmbed)).apply(this, arguments)); } _createClass(BlockEmbed, [{ key: 'attach', value: function attach() { _get(BlockEmbed.prototype.__proto__ || Object.getPrototypeOf(BlockEmbed.prototype), 'attach', this).call(this); this.attributes = new _parchment2.default.Attributor.Store(this.domNode); } }, { key: 'delta', value: function delta() { return new _quillDelta2.default().insert(this.value(), (0, _extend2.default)(this.formats(), this.attributes.values())); } }, { key: 'format', value: function format(name, value) { var attribute = _parchment2.default.query(name, _parchment2.default.Scope.BLOCK_ATTRIBUTE); if (attribute != null) { this.attributes.attribute(attribute, value); } } }, { key: 'formatAt', value: function formatAt(index, length, name, value) { this.format(name, value); } }, { key: 'insertAt', value: function insertAt(index, value, def) { if (typeof value === 'string' && value.endsWith('\n')) { var block = _parchment2.default.create(Block.blotName); this.parent.insertBefore(block, index === 0 ? this : this.next); block.insertAt(0, value.slice(0, -1)); } else { _get(BlockEmbed.prototype.__proto__ || Object.getPrototypeOf(BlockEmbed.prototype), 'insertAt', this).call(this, index, value, def); } } }]); return BlockEmbed; }(_parchment2.default.Embed); BlockEmbed.scope = _parchment2.default.Scope.BLOCK_BLOT; // It is important for cursor behavior BlockEmbeds use tags that are block level elements var Block = function (_Parchment$Block) { _inherits(Block, _Parchment$Block); function Block(domNode) { _classCallCheck(this, Block); var _this2 = _possibleConstructorReturn(this, (Block.__proto__ || Object.getPrototypeOf(Block)).call(this, domNode)); _this2.cache = {}; return _this2; } _createClass(Block, [{ key: 'delta', value: function delta() { if (this.cache.delta == null) { this.cache.delta = this.descendants(_parchment2.default.Leaf).reduce(function (delta, leaf) { if (leaf.length() === 0) { return delta; } else { return delta.insert(leaf.value(), bubbleFormats(leaf)); } }, new _quillDelta2.default()).insert('\n', bubbleFormats(this)); } return this.cache.delta; } }, { key: 'deleteAt', value: function deleteAt(index, length) { _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'deleteAt', this).call(this, index, length); this.cache = {}; } }, { key: 'formatAt', value: function formatAt(index, length, name, value) { if (length <= 0) return; if (_parchment2.default.query(name, _parchment2.default.Scope.BLOCK)) { if (index + length === this.length()) { this.format(name, value); } } else { _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'formatAt', this).call(this, index, Math.min(length, this.length() - index - 1), name, value); } this.cache = {}; } }, { key: 'insertAt', value: function insertAt(index, value, def) { if (def != null) return _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'insertAt', this).call(this, index, value, def); if (value.length === 0) return; var lines = value.split('\n'); var text = lines.shift(); if (text.length > 0) { if (index < this.length() - 1 || this.children.tail == null) { _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'insertAt', this).call(this, Math.min(index, this.length() - 1), text); } else { this.children.tail.insertAt(this.children.tail.length(), text); } this.cache = {}; } var block = this; lines.reduce(function (index, line) { block = block.split(index, true); block.insertAt(0, line); return line.length; }, index + text.length); } }, { key: 'insertBefore', value: function insertBefore(blot, ref) { var head = this.children.head; _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'insertBefore', this).call(this, blot, ref); if (head instanceof _break2.default) { head.remove(); } this.cache = {}; } }, { key: 'length', value: function length() { if (this.cache.length == null) { this.cache.length = _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'length', this).call(this) + NEWLINE_LENGTH; } return this.cache.length; } }, { key: 'moveChildren', value: function moveChildren(target, ref) { _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'moveChildren', this).call(this, target, ref); this.cache = {}; } }, { key: 'optimize', value: function optimize(context) { _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'optimize', this).call(this, context); this.cache = {}; } }, { key: 'path', value: function path(index) { return _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'path', this).call(this, index, true); } }, { key: 'removeChild', value: function removeChild(child) { _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'removeChild', this).call(this, child); this.cache = {}; } }, { key: 'split', value: function split(index) { var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (force && (index === 0 || index >= this.length() - NEWLINE_LENGTH)) { var clone = this.clone(); if (index === 0) { this.parent.insertBefore(clone, this); return this; } else { this.parent.insertBefore(clone, this.next); return clone; } } else { var next = _get(Block.prototype.__proto__ || Object.getPrototypeOf(Block.prototype), 'split', this).call(this, index, force); this.cache = {}; return next; } } }]); return Block; }(_parchment2.default.Block); Block.blotName = 'block'; Block.tagName = 'P'; Block.defaultChild = 'break'; Block.allowedChildren = [_inline2.default, _parchment2.default.Embed, _text2.default]; function bubbleFormats(blot) { var formats = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (blot == null) return formats; if (typeof blot.formats === 'function') { formats = (0, _extend2.default)(formats, blot.formats()); } if (blot.parent == null || blot.parent.blotName == 'scroll' || blot.parent.statics.scope !== blot.statics.scope) { return formats; } return bubbleFormats(blot.parent, formats); } exports.bubbleFormats = bubbleFormats; exports.BlockEmbed = BlockEmbed; exports.default = Block; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.overload = exports.expandConfig = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); __webpack_require__(50); var _quillDelta = __webpack_require__(2); var _quillDelta2 = _interopRequireDefault(_quillDelta); var _editor = __webpack_require__(14); var _editor2 = _interopRequireDefault(_editor); var _emitter3 = __webpack_require__(8); var _emitter4 = _interopRequireDefault(_emitter3); var _module = __webpack_require__(9); var _module2 = _interopRequireDefault(_module); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _selection = __webpack_require__(15); var _selection2 = _interopRequireDefault(_selection); var _extend = __webpack_require__(3); var _extend2 = _interopRequireDefault(_extend); var _logger = __webpack_require__(10); var _logger2 = _interopRequireDefault(_logger); var _theme = __webpack_require__(34); var _theme2 = _interopRequireDefault(_theme); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var debug = (0, _logger2.default)('quill'); var Quill = function () { _createClass(Quill, null, [{ key: 'debug', value: function debug(limit) { if (limit === true) { limit = 'log'; } _logger2.default.level(limit); } }, { key: 'find', value: function find(node) { return node.__quill || _parchment2.default.find(node); } }, { key: 'import', value: function _import(name) { if (this.imports[name] == null) { debug.error('Cannot import ' + name + '. Are you sure it was registered?'); } return this.imports[name]; } }, { key: 'register', value: function register(path, target) { var _this = this; var overwrite = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (typeof path !== 'string') { var name = path.attrName || path.blotName; if (typeof name === 'string') { // register(Blot | Attributor, overwrite) this.register('formats/' + name, path, target); } else { Object.keys(path).forEach(function (key) { _this.register(key, path[key], target); }); } } else { if (this.imports[path] != null && !overwrite) { debug.warn('Overwriting ' + path + ' with', target); } this.imports[path] = target; if ((path.startsWith('blots/') || path.startsWith('formats/')) && target.blotName !== 'abstract') { _parchment2.default.register(target); } else if (path.startsWith('modules') && typeof target.register === 'function') { target.register(); } } } }]); function Quill(container) { var _this2 = this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, Quill); this.options = expandConfig(container, options); this.container = this.options.container; if (this.container == null) { return debug.error('Invalid Quill container', container); } if (this.options.debug) { Quill.debug(this.options.debug); } var html = this.container.innerHTML.trim(); this.container.classList.add('ql-container'); this.container.innerHTML = ''; this.container.__quill = this; this.root = this.addContainer('ql-editor'); this.root.classList.add('ql-blank'); this.root.setAttribute('data-gramm', false); this.scrollingContainer = this.options.scrollingContainer || this.root; this.emitter = new _emitter4.default(); this.scroll = _parchment2.default.create(this.root, { emitter: this.emitter, whitelist: this.options.formats }); this.editor = new _editor2.default(this.scroll); this.selection = new _selection2.default(this.scroll, this.emitter); this.theme = new this.options.theme(this, this.options); this.keyboard = this.theme.addModule('keyboard'); this.clipboard = this.theme.addModule('clipboard'); this.history = this.theme.addModule('history'); this.theme.init(); this.emitter.on(_emitter4.default.events.EDITOR_CHANGE, function (type) { if (type === _emitter4.default.events.TEXT_CHANGE) { _this2.root.classList.toggle('ql-blank', _this2.editor.isBlank()); } }); this.emitter.on(_emitter4.default.events.SCROLL_UPDATE, function (source, mutations) { var range = _this2.selection.lastRange; var index = range && range.length === 0 ? range.index : undefined; modify.call(_this2, function () { return _this2.editor.update(null, mutations, index); }, source); }); var contents = this.clipboard.convert('<div class=\'ql-editor\' style="white-space: normal;">' + html + '<p><br></p></div>'); this.setContents(contents); this.history.clear(); if (this.options.placeholder) { this.root.setAttribute('data-placeholder', this.options.placeholder); } if (this.options.readOnly) { this.disable(); } } _createClass(Quill, [{ key: 'addContainer', value: function addContainer(container) { var refNode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (typeof container === 'string') { var className = container; container = document.createElement('div'); container.classList.add(className); } this.container.insertBefore(container, refNode); return container; } }, { key: 'blur', value: function blur() { this.selection.setRange(null); } }, { key: 'deleteText', value: function deleteText(index, length, source) { var _this3 = this; var _overload = overload(index, length, source); var _overload2 = _slicedToArray(_overload, 4); index = _overload2[0]; length = _overload2[1]; source = _overload2[3]; return modify.call(this, function () { return _this3.editor.deleteText(index, length); }, source, index, -1 * length); } }, { key: 'disable', value: function disable() { this.enable(false); } }, { key: 'enable', value: function enable() { var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; this.scroll.enable(enabled); this.container.classList.toggle('ql-disabled', !enabled); } }, { key: 'focus', value: function focus() { var scrollTop = this.scrollingContainer.scrollTop; this.selection.focus(); this.scrollingContainer.scrollTop = scrollTop; this.scrollIntoView(); } }, { key: 'format', value: function format(name, value) { var _this4 = this; var source = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _emitter4.default.sources.API; return modify.call(this, function () { var range = _this4.getSelection(true); var change = new _quillDelta2.default(); if (range == null) { return change; } else if (_parchment2.default.query(name, _parchment2.default.Scope.BLOCK)) { change = _this4.editor.formatLine(range.index, range.length, _defineProperty({}, name, value)); } else if (range.length === 0) { _this4.selection.format(name, value); return change; } else { change = _this4.editor.formatText(range.index, range.length, _defineProperty({}, name, value)); } _this4.setSelection(range, _emitter4.default.sources.SILENT); return change; }, source); } }, { key: 'formatLine', value: function formatLine(index, length, name, value, source) { var _this5 = this; var formats = void 0; var _overload3 = overload(index, length, name, value, source); var _overload4 = _slicedToArray(_overload3, 4); index = _overload4[0]; length = _overload4[1]; formats = _overload4[2]; source = _overload4[3]; return modify.call(this, function () { return _this5.editor.formatLine(index, length, formats); }, source, index, 0); } }, { key: 'formatText', value: function formatText(index, length, name, value, source) { var _this6 = this; var formats = void 0; var _overload5 = overload(index, length, name, value, source); var _overload6 = _slicedToArray(_overload5, 4); index = _overload6[0]; length = _overload6[1]; formats = _overload6[2]; source = _overload6[3]; return modify.call(this, function () { return _this6.editor.formatText(index, length, formats); }, source, index, 0); } }, { key: 'getBounds', value: function getBounds(index) { var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var bounds = void 0; if (typeof index === 'number') { bounds = this.selection.getBounds(index, length); } else { bounds = this.selection.getBounds(index.index, index.length); } var containerBounds = this.container.getBoundingClientRect(); return { bottom: bounds.bottom - containerBounds.top, height: bounds.height, left: bounds.left - containerBounds.left, right: bounds.right - containerBounds.left, top: bounds.top - containerBounds.top, width: bounds.width }; } }, { key: 'getContents', value: function getContents() { var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.getLength() - index; var _overload7 = overload(index, length); var _overload8 = _slicedToArray(_overload7, 2); index = _overload8[0]; length = _overload8[1]; return this.editor.getContents(index, length); } }, { key: 'getFormat', value: function getFormat() { var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.getSelection(true); var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; if (typeof index === 'number') { return this.editor.getFormat(index, length); } else { return this.editor.getFormat(index.index, index.length); } } }, { key: 'getIndex', value: function getIndex(blot) { return blot.offset(this.scroll); } }, { key: 'getLength', value: function getLength() { return this.scroll.length(); } }, { key: 'getLeaf', value: function getLeaf(index) { return this.scroll.leaf(index); } }, { key: 'getLine', value: function getLine(index) { return this.scroll.line(index); } }, { key: 'getLines', value: function getLines() { var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Number.MAX_VALUE; if (typeof index !== 'number') { return this.scroll.lines(index.index, index.length); } else { return this.scroll.lines(index, length); } } }, { key: 'getModule', value: function getModule(name) { return this.theme.modules[name]; } }, { key: 'getSelection', value: function getSelection() { var focus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (focus) this.focus(); this.update(); // Make sure we access getRange with editor in consistent state return this.selection.getRange()[0]; } }, { key: 'getText', value: function getText() { var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.getLength() - index; var _overload9 = overload(index, length); var _overload10 = _slicedToArray(_overload9, 2); index = _overload10[0]; length = _overload10[1]; return this.editor.getText(index, length); } }, { key: 'hasFocus', value: function hasFocus() { return this.selection.hasFocus(); } }, { key: 'insertEmbed', value: function insertEmbed(index, embed, value) { var _this7 = this; var source = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Quill.sources.API; return modify.call(this, function () { return _this7.editor.insertEmbed(index, embed, value); }, source, index); } }, { key: 'insertText', value: function insertText(index, text, name, value, source) { var _this8 = this; var formats = void 0; var _overload11 = overload(index, 0, name, value, source); var _overload12 = _slicedToArray(_overload11, 4); index = _overload12[0]; formats = _overload12[2]; source = _overload12[3]; return modify.call(this, function () { return _this8.editor.insertText(index, text, formats); }, source, index, text.length); } }, { key: 'isEnabled', value: function isEnabled() { return !this.container.classList.contains('ql-disabled'); } }, { key: 'off', value: function off() { return this.emitter.off.apply(this.emitter, arguments); } }, { key: 'on', value: function on() { return this.emitter.on.apply(this.emitter, arguments); } }, { key: 'once', value: function once() { return this.emitter.once.apply(this.emitter, arguments); } }, { key: 'pasteHTML', value: function pasteHTML(index, html, source) { this.clipboard.dangerouslyPasteHTML(index, html, source); } }, { key: 'removeFormat', value: function removeFormat(index, length, source) { var _this9 = this; var _overload13 = overload(index, length, source); var _overload14 = _slicedToArray(_overload13, 4); index = _overload14[0]; length = _overload14[1]; source = _overload14[3]; return modify.call(this, function () { return _this9.editor.removeFormat(index, length); }, source, index); } }, { key: 'scrollIntoView', value: function scrollIntoView() { this.selection.scrollIntoView(this.scrollingContainer); } }, { key: 'setContents', value: function setContents(delta) { var _this10 = this; var source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _emitter4.default.sources.API; return modify.call(this, function () { delta = new _quillDelta2.default(delta); var length = _this10.getLength(); var deleted = _this10.editor.deleteText(0, length); var applied = _this10.editor.applyDelta(delta); var lastOp = applied.ops[applied.ops.length - 1]; if (lastOp != null && typeof lastOp.insert === 'string' && lastOp.insert[lastOp.insert.length - 1] === '\n') { _this10.editor.deleteText(_this10.getLength() - 1, 1); applied.delete(1); } var ret = deleted.compose(applied); return ret; }, source); } }, { key: 'setSelection', value: function setSelection(index, length, source) { if (index == null) { this.selection.setRange(null, length || Quill.sources.API); } else { var _overload15 = overload(index, length, source); var _overload16 = _slicedToArray(_overload15, 4); index = _overload16[0]; length = _overload16[1]; source = _overload16[3]; this.selection.setRange(new _selection.Range(index, length), source); if (source !== _emitter4.default.sources.SILENT) { this.selection.scrollIntoView(this.scrollingContainer); } } } }, { key: 'setText', value: function setText(text) { var source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _emitter4.default.sources.API; var delta = new _quillDelta2.default().insert(text); return this.setContents(delta, source); } }, { key: 'update', value: function update() { var source = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _emitter4.default.sources.USER; var change = this.scroll.update(source); // Will update selection before selection.update() does if text changes this.selection.update(source); return change; } }, { key: 'updateContents', value: function updateContents(delta) { var _this11 = this; var source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _emitter4.default.sources.API; return modify.call(this, function () { delta = new _quillDelta2.default(delta); return _this11.editor.applyDelta(delta, source); }, source, true); } }]); return Quill; }(); Quill.DEFAULTS = { bounds: null, formats: null, modules: {}, placeholder: '', readOnly: false, scrollingContainer: null, strict: true, theme: 'default' }; Quill.events = _emitter4.default.events; Quill.sources = _emitter4.default.sources; // eslint-disable-next-line no-undef Quill.version = false ? 'dev' : "1.3.6"; Quill.imports = { 'delta': _quillDelta2.default, 'parchment': _parchment2.default, 'core/module': _module2.default, 'core/theme': _theme2.default }; function expandConfig(container, userConfig) { userConfig = (0, _extend2.default)(true, { container: container, modules: { clipboard: true, keyboard: true, history: true } }, userConfig); if (!userConfig.theme || userConfig.theme === Quill.DEFAULTS.theme) { userConfig.theme = _theme2.default; } else { userConfig.theme = Quill.import('themes/' + userConfig.theme); if (userConfig.theme == null) { throw new Error('Invalid theme ' + userConfig.theme + '. Did you register it?'); } } var themeConfig = (0, _extend2.default)(true, {}, userConfig.theme.DEFAULTS); [themeConfig, userConfig].forEach(function (config) { config.modules = config.modules || {}; Object.keys(config.modules).forEach(function (module) { if (config.modules[module] === true) { config.modules[module] = {}; } }); }); var moduleNames = Object.keys(themeConfig.modules).concat(Object.keys(userConfig.modules)); var moduleConfig = moduleNames.reduce(function (config, name) { var moduleClass = Quill.import('modules/' + name); if (moduleClass == null) { debug.error('Cannot load ' + name + ' module. Are you sure you registered it?'); } else { config[name] = moduleClass.DEFAULTS || {}; } return config; }, {}); // Special case toolbar shorthand if (userConfig.modules != null && userConfig.modules.toolbar && userConfig.modules.toolbar.constructor !== Object) { userConfig.modules.toolbar = { container: userConfig.modules.toolbar }; } userConfig = (0, _extend2.default)(true, {}, Quill.DEFAULTS, { modules: moduleConfig }, themeConfig, userConfig); ['bounds', 'container', 'scrollingContainer'].forEach(function (key) { if (typeof userConfig[key] === 'string') { userConfig[key] = document.querySelector(userConfig[key]); } }); userConfig.modules = Object.keys(userConfig.modules).reduce(function (config, name) { if (userConfig.modules[name]) { config[name] = userConfig.modules[name]; } return config; }, {}); return userConfig; } // Handle selection preservation and TEXT_CHANGE emission // common to modification APIs function modify(modifier, source, index, shift) { if (this.options.strict && !this.isEnabled() && source === _emitter4.default.sources.USER) { return new _quillDelta2.default(); } var range = index == null ? null : this.getSelection(); var oldDelta = this.editor.delta; var change = modifier(); if (range != null) { if (index === true) index = range.index; if (shift == null) { range = shiftRange(range, change, source); } else if (shift !== 0) { range = shiftRange(range, index, shift, source); } this.setSelection(range, _emitter4.default.sources.SILENT); } if (change.length() > 0) { var _emitter; var args = [_emitter4.default.events.TEXT_CHANGE, change, oldDelta, source]; (_emitter = this.emitter).emit.apply(_emitter, [_emitter4.default.events.EDITOR_CHANGE].concat(args)); if (source !== _emitter4.default.sources.SILENT) { var _emitter2; (_emitter2 = this.emitter).emit.apply(_emitter2, args); } } return change; } function overload(index, length, name, value, source) { var formats = {}; if (typeof index.index === 'number' && typeof index.length === 'number') { // Allow for throwaway end (used by insertText/insertEmbed) if (typeof length !== 'number') { source = value, value = name, name = length, length = index.length, index = index.index; } else { length = index.length, index = index.index; } } else if (typeof length !== 'number') { source = value, value = name, name = length, length = 0; } // Handle format being object, two format name/value strings or excluded if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { formats = name; source = value; } else if (typeof name === 'string') { if (value != null) { formats[name] = value; } else { source = name; } } // Handle optional source source = source || _emitter4.default.sources.API; return [index, length, formats, source]; } function shiftRange(range, index, length, source) { if (range == null) return null; var start = void 0, end = void 0; if (index instanceof _quillDelta2.default) { var _map = [range.index, range.index + range.length].map(function (pos) { return index.transformPosition(pos, source !== _emitter4.default.sources.USER); }); var _map2 = _slicedToArray(_map, 2); start = _map2[0]; end = _map2[1]; } else { var _map3 = [range.index, range.index + range.length].map(function (pos) { if (pos < index || pos === index && source === _emitter4.default.sources.USER) return pos; if (length >= 0) { return pos + length; } else { return Math.max(index, pos + length); } }); var _map4 = _slicedToArray(_map3, 2); start = _map4[0]; end = _map4[1]; } return new _selection.Range(start, end - start); } exports.expandConfig = expandConfig; exports.overload = overload; exports.default = Quill; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _text = __webpack_require__(7); var _text2 = _interopRequireDefault(_text); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Inline = function (_Parchment$Inline) { _inherits(Inline, _Parchment$Inline); function Inline() { _classCallCheck(this, Inline); return _possibleConstructorReturn(this, (Inline.__proto__ || Object.getPrototypeOf(Inline)).apply(this, arguments)); } _createClass(Inline, [{ key: 'formatAt', value: function formatAt(index, length, name, value) { if (Inline.compare(this.statics.blotName, name) < 0 && _parchment2.default.query(name, _parchment2.default.Scope.BLOT)) { var blot = this.isolate(index, length); if (value) { blot.wrap(name, value); } } else { _get(Inline.prototype.__proto__ || Object.getPrototypeOf(Inline.prototype), 'formatAt', this).call(this, index, length, name, value); } } }, { key: 'optimize', value: function optimize(context) { _get(Inline.prototype.__proto__ || Object.getPrototypeOf(Inline.prototype), 'optimize', this).call(this, context); if (this.parent instanceof Inline && Inline.compare(this.statics.blotName, this.parent.statics.blotName) > 0) { var parent = this.parent.isolate(this.offset(), this.length()); this.moveChildren(parent); parent.wrap(this); } } }], [{ key: 'compare', value: function compare(self, other) { var selfIndex = Inline.order.indexOf(self); var otherIndex = Inline.order.indexOf(other); if (selfIndex >= 0 || otherIndex >= 0) { return selfIndex - otherIndex; } else if (self === other) { return 0; } else if (self < other) { return -1; } else { return 1; } } }]); return Inline; }(_parchment2.default.Inline); Inline.allowedChildren = [Inline, _parchment2.default.Embed, _text2.default]; // Lower index means deeper in the DOM tree, since not found (-1) is for embeds Inline.order = ['cursor', 'inline', // Must be lower 'underline', 'strike', 'italic', 'bold', 'script', 'link', 'code' // Must be higher ]; exports.default = Inline; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TextBlot = function (_Parchment$Text) { _inherits(TextBlot, _Parchment$Text); function TextBlot() { _classCallCheck(this, TextBlot); return _possibleConstructorReturn(this, (TextBlot.__proto__ || Object.getPrototypeOf(TextBlot)).apply(this, arguments)); } return TextBlot; }(_parchment2.default.Text); exports.default = TextBlot; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _eventemitter = __webpack_require__(54); var _eventemitter2 = _interopRequireDefault(_eventemitter); var _logger = __webpack_require__(10); var _logger2 = _interopRequireDefault(_logger); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var debug = (0, _logger2.default)('quill:events'); var EVENTS = ['selectionchange', 'mousedown', 'mouseup', 'click']; EVENTS.forEach(function (eventName) { document.addEventListener(eventName, function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } [].slice.call(document.querySelectorAll('.ql-container')).forEach(function (node) { // TODO use WeakMap if (node.__quill && node.__quill.emitter) { var _node$__quill$emitter; (_node$__quill$emitter = node.__quill.emitter).handleDOM.apply(_node$__quill$emitter, args); } }); }); }); var Emitter = function (_EventEmitter) { _inherits(Emitter, _EventEmitter); function Emitter() { _classCallCheck(this, Emitter); var _this = _possibleConstructorReturn(this, (Emitter.__proto__ || Object.getPrototypeOf(Emitter)).call(this)); _this.listeners = {}; _this.on('error', debug.error); return _this; } _createClass(Emitter, [{ key: 'emit', value: function emit() { debug.log.apply(debug, arguments); _get(Emitter.prototype.__proto__ || Object.getPrototypeOf(Emitter.prototype), 'emit', this).apply(this, arguments); } }, { key: 'handleDOM', value: function handleDOM(event) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } (this.listeners[event.type] || []).forEach(function (_ref) { var node = _ref.node, handler = _ref.handler; if (event.target === node || node.contains(event.target)) { handler.apply(undefined, [event].concat(args)); } }); } }, { key: 'listenDOM', value: function listenDOM(eventName, node, handler) { if (!this.listeners[eventName]) { this.listeners[eventName] = []; } this.listeners[eventName].push({ node: node, handler: handler }); } }]); return Emitter; }(_eventemitter2.default); Emitter.events = { EDITOR_CHANGE: 'editor-change', SCROLL_BEFORE_UPDATE: 'scroll-before-update', SCROLL_OPTIMIZE: 'scroll-optimize', SCROLL_UPDATE: 'scroll-update', SELECTION_CHANGE: 'selection-change', TEXT_CHANGE: 'text-change' }; Emitter.sources = { API: 'api', SILENT: 'silent', USER: 'user' }; exports.default = Emitter; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Module = function Module(quill) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, Module); this.quill = quill; this.options = options; }; Module.DEFAULTS = {}; exports.default = Module; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var levels = ['error', 'warn', 'log', 'info']; var level = 'warn'; function debug(method) { if (levels.indexOf(method) <= levels.indexOf(level)) { var _console; for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } (_console = console)[method].apply(_console, args); // eslint-disable-line no-console } } function namespace(ns) { return levels.reduce(function (logger, method) { logger[method] = debug.bind(console, method, ns); return logger; }, {}); } debug.level = namespace.level = function (newLevel) { level = newLevel; }; exports.default = namespace; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { var pSlice = Array.prototype.slice; var objectKeys = __webpack_require__(52); var isArguments = __webpack_require__(53); var deepEqual = module.exports = function (actual, expected, opts) { if (!opts) opts = {}; // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (actual instanceof Date && expected instanceof Date) { return actual.getTime() === expected.getTime(); // 7.3. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') { return opts.strict ? actual === expected : actual == expected; // 7.4. For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected, opts); } } function isUndefinedOrNull(value) { return value === null || value === undefined; } function isBuffer (x) { if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false; if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { return false; } if (x.length > 0 && typeof x[0] !== 'number') return false; return true; } function objEquiv(a, b, opts) { var i, key; if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return deepEqual(a, b, opts); } if (isBuffer(a)) { if (!isBuffer(b)) { return false; } if (a.length !== b.length) return false; for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } try { var ka = objectKeys(a), kb = objectKeys(b); } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!deepEqual(a[key], b[key], opts)) return false; } return typeof a === typeof b; } /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Registry = __webpack_require__(1); var Attributor = /** @class */ (function () { function Attributor(attrName, keyName, options) { if (options === void 0) { options = {}; } this.attrName = attrName; this.keyName = keyName; var attributeBit = Registry.Scope.TYPE & Registry.Scope.ATTRIBUTE; if (options.scope != null) { // Ignore type bits, force attribute bit this.scope = (options.scope & Registry.Scope.LEVEL) | attributeBit; } else { this.scope = Registry.Scope.ATTRIBUTE; } if (options.whitelist != null) this.whitelist = options.whitelist; } Attributor.keys = function (node) { return [].map.call(node.attributes, function (item) { return item.name; }); }; Attributor.prototype.add = function (node, value) { if (!this.canAdd(node, value)) return false; node.setAttribute(this.keyName, value); return true; }; Attributor.prototype.canAdd = function (node, value) { var match = Registry.query(node, Registry.Scope.BLOT & (this.scope | Registry.Scope.TYPE)); if (match == null) return false; if (this.whitelist == null) return true; if (typeof value === 'string') { return this.whitelist.indexOf(value.replace(/["']/g, '')) > -1; } else { return this.whitelist.indexOf(value) > -1; } }; Attributor.prototype.remove = function (node) { node.removeAttribute(this.keyName); }; Attributor.prototype.value = function (node) { var value = node.getAttribute(this.keyName); if (this.canAdd(node, value) && value) { return value; } return ''; }; return Attributor; }()); exports.default = Attributor; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.Code = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _quillDelta = __webpack_require__(2); var _quillDelta2 = _interopRequireDefault(_quillDelta); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _block = __webpack_require__(4); var _block2 = _interopRequireDefault(_block); var _inline = __webpack_require__(6); var _inline2 = _interopRequireDefault(_inline); var _text = __webpack_require__(7); var _text2 = _interopRequireDefault(_text); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Code = function (_Inline) { _inherits(Code, _Inline); function Code() { _classCallCheck(this, Code); return _possibleConstructorReturn(this, (Code.__proto__ || Object.getPrototypeOf(Code)).apply(this, arguments)); } return Code; }(_inline2.default); Code.blotName = 'code'; Code.tagName = 'CODE'; var CodeBlock = function (_Block) { _inherits(CodeBlock, _Block); function CodeBlock() { _classCallCheck(this, CodeBlock); return _possibleConstructorReturn(this, (CodeBlock.__proto__ || Object.getPrototypeOf(CodeBlock)).apply(this, arguments)); } _createClass(CodeBlock, [{ key: 'delta', value: function delta() { var _this3 = this; var text = this.domNode.textContent; if (text.endsWith('\n')) { // Should always be true text = text.slice(0, -1); } return text.split('\n').reduce(function (delta, frag) { return delta.insert(frag).insert('\n', _this3.formats()); }, new _quillDelta2.default()); } }, { key: 'format', value: function format(name, value) { if (name === this.statics.blotName && value) return; var _descendant = this.descendant(_text2.default, this.length() - 1), _descendant2 = _slicedToArray(_descendant, 1), text = _descendant2[0]; if (text != null) { text.deleteAt(text.length() - 1, 1); } _get(CodeBlock.prototype.__proto__ || Object.getPrototypeOf(CodeBlock.prototype), 'format', this).call(this, name, value); } }, { key: 'formatAt', value: function formatAt(index, length, name, value) { if (length === 0) return; if (_parchment2.default.query(name, _parchment2.default.Scope.BLOCK) == null || name === this.statics.blotName && value === this.statics.formats(this.domNode)) { return; } var nextNewline = this.newlineIndex(index); if (nextNewline < 0 || nextNewline >= index + length) return; var prevNewline = this.newlineIndex(index, true) + 1; var isolateLength = nextNewline - prevNewline + 1; var blot = this.isolate(prevNewline, isolateLength); var next = blot.next; blot.format(name, value); if (next instanceof CodeBlock) { next.formatAt(0, index - prevNewline + length - isolateLength, name, value); } } }, { key: 'insertAt', value: function insertAt(index, value, def) { if (def != null) return; var _descendant3 = this.descendant(_text2.default, index), _descendant4 = _slicedToArray(_descendant3, 2), text = _descendant4[0], offset = _descendant4[1]; text.insertAt(offset, value); } }, { key: 'length', value: function length() { var length = this.domNode.textContent.length; if (!this.domNode.textContent.endsWith('\n')) { return length + 1; } return length; } }, { key: 'newlineIndex', value: function newlineIndex(searchIndex) { var reverse = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!reverse) { var offset = this.domNode.textContent.slice(searchIndex).indexOf('\n'); return offset > -1 ? searchIndex + offset : -1; } else { return this.domNode.textContent.slice(0, searchIndex).lastIndexOf('\n'); } } }, { key: 'optimize', value: function optimize(context) { if (!this.domNode.textContent.endsWith('\n')) { this.appendChild(_parchment2.default.create('text', '\n')); } _get(CodeBlock.prototype.__proto__ || Object.getPrototypeOf(CodeBlock.prototype), 'optimize', this).call(this, context); var next = this.next; if (next != null && next.prev === this && next.statics.blotName === this.statics.blotName && this.statics.formats(this.domNode) === next.statics.formats(next.domNode)) { next.optimize(context); next.moveChildren(this); next.remove(); } } }, { key: 'replace', value: function replace(target) { _get(CodeBlock.prototype.__proto__ || Object.getPrototypeOf(CodeBlock.prototype), 'replace', this).call(this, target); [].slice.call(this.domNode.querySelectorAll('*')).forEach(function (node) { var blot = _parchment2.default.find(node); if (blot == null) { node.parentNode.removeChild(node); } else if (blot instanceof _parchment2.default.Embed) { blot.remove(); } else { blot.unwrap(); } }); } }], [{ key: 'create', value: function create(value) { var domNode = _get(CodeBlock.__proto__ || Object.getPrototypeOf(CodeBlock), 'create', this).call(this, value); domNode.setAttribute('spellcheck', false); return domNode; } }, { key: 'formats', value: function formats() { return true; } }]); return CodeBlock; }(_block2.default); CodeBlock.blotName = 'code-block'; CodeBlock.tagName = 'PRE'; CodeBlock.TAB = ' '; exports.Code = Code; exports.default = CodeBlock; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _quillDelta = __webpack_require__(2); var _quillDelta2 = _interopRequireDefault(_quillDelta); var _op = __webpack_require__(20); var _op2 = _interopRequireDefault(_op); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _code = __webpack_require__(13); var _code2 = _interopRequireDefault(_code); var _cursor = __webpack_require__(24); var _cursor2 = _interopRequireDefault(_cursor); var _block = __webpack_require__(4); var _block2 = _interopRequireDefault(_block); var _break = __webpack_require__(16); var _break2 = _interopRequireDefault(_break); var _clone = __webpack_require__(21); var _clone2 = _interopRequireDefault(_clone); var _deepEqual = __webpack_require__(11); var _deepEqual2 = _interopRequireDefault(_deepEqual); var _extend = __webpack_require__(3); var _extend2 = _interopRequireDefault(_extend); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ASCII = /^[ -~]*$/; var Editor = function () { function Editor(scroll) { _classCallCheck(this, Editor); this.scroll = scroll; this.delta = this.getDelta(); } _createClass(Editor, [{ key: 'applyDelta', value: function applyDelta(delta) { var _this = this; var consumeNextNewline = false; this.scroll.update(); var scrollLength = this.scroll.length(); this.scroll.batchStart(); delta = normalizeDelta(delta); delta.reduce(function (index, op) { var length = op.retain || op.delete || op.insert.length || 1; var attributes = op.attributes || {}; if (op.insert != null) { if (typeof op.insert === 'string') { var text = op.insert; if (text.endsWith('\n') && consumeNextNewline) { consumeNextNewline = false; text = text.slice(0, -1); } if (index >= scrollLength && !text.endsWith('\n')) { consumeNextNewline = true; } _this.scroll.insertAt(index, text); var _scroll$line = _this.scroll.line(index), _scroll$line2 = _slicedToArray(_scroll$line, 2), line = _scroll$line2[0], offset = _scroll$line2[1]; var formats = (0, _extend2.default)({}, (0, _block.bubbleFormats)(line)); if (line instanceof _block2.default) { var _line$descendant = line.descendant(_parchment2.default.Leaf, offset), _line$descendant2 = _slicedToArray(_line$descendant, 1), leaf = _line$descendant2[0]; formats = (0, _extend2.default)(formats, (0, _block.bubbleFormats)(leaf)); } attributes = _op2.default.attributes.diff(formats, attributes) || {}; } else if (_typeof(op.insert) === 'object') { var key = Object.keys(op.insert)[0]; // There should only be one key if (key == null) return index; _this.scroll.insertAt(index, key, op.insert[key]); } scrollLength += length; } Object.keys(attributes).forEach(function (name) { _this.scroll.formatAt(index, length, name, attributes[name]); }); return index + length; }, 0); delta.reduce(function (index, op) { if (typeof op.delete === 'number') { _this.scroll.deleteAt(index, op.delete); return index; } return index + (op.retain || op.insert.length || 1); }, 0); this.scroll.batchEnd(); return this.update(delta); } }, { key: 'deleteText', value: function deleteText(index, length) { this.scroll.deleteAt(index, length); return this.update(new _quillDelta2.default().retain(index).delete(length)); } }, { key: 'formatLine', value: function formatLine(index, length) { var _this2 = this; var formats = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; this.scroll.update(); Object.keys(formats).forEach(function (format) { if (_this2.scroll.whitelist != null && !_this2.scroll.whitelist[format]) return; var lines = _this2.scroll.lines(index, Math.max(length, 1)); var lengthRemaining = length; lines.forEach(function (line) { var lineLength = line.length(); if (!(line instanceof _code2.default)) { line.format(format, formats[format]); } else { var codeIndex = index - line.offset(_this2.scroll); var codeLength = line.newlineIndex(codeIndex + lengthRemaining) - codeIndex + 1; line.formatAt(codeIndex, codeLength, format, formats[format]); } lengthRemaining -= lineLength; }); }); this.scroll.optimize(); return this.update(new _quillDelta2.default().retain(index).retain(length, (0, _clone2.default)(formats))); } }, { key: 'formatText', value: function formatText(index, length) { var _this3 = this; var formats = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; Object.keys(formats).forEach(function (format) { _this3.scroll.formatAt(index, length, format, formats[format]); }); return this.update(new _quillDelta2.default().retain(index).retain(length, (0, _clone2.default)(formats))); } }, { key: 'getContents', value: function getContents(index, length) { return this.delta.slice(index, index + length); } }, { key: 'getDelta', value: function getDelta() { return this.scroll.lines().reduce(function (delta, line) { return delta.concat(line.delta()); }, new _quillDelta2.default()); } }, { key: 'getFormat', value: function getFormat(index) { var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var lines = [], leaves = []; if (length === 0) { this.scroll.path(index).forEach(function (path) { var _path = _slicedToArray(path, 1), blot = _path[0]; if (blot instanceof _block2.default) { lines.push(blot); } else if (blot instanceof _parchment2.default.Leaf) { leaves.push(blot); } }); } else { lines = this.scroll.lines(index, length); leaves = this.scroll.descendants(_parchment2.default.Leaf, index, length); } var formatsArr = [lines, leaves].map(function (blots) { if (blots.length === 0) return {}; var formats = (0, _block.bubbleFormats)(blots.shift()); while (Object.keys(formats).length > 0) { var blot = blots.shift(); if (blot == null) return formats; formats = combineFormats((0, _block.bubbleFormats)(blot), formats); } return formats; }); return _extend2.default.apply(_extend2.default, formatsArr); } }, { key: 'getText', value: function getText(index, length) { return this.getContents(index, length).filter(function (op) { return typeof op.insert === 'string'; }).map(function (op) { return op.insert; }).join(''); } }, { key: 'insertEmbed', value: function insertEmbed(index, embed, value) { this.scroll.insertAt(index, embed, value); return this.update(new _quillDelta2.default().retain(index).insert(_defineProperty({}, embed, value))); } }, { key: 'insertText', value: function insertText(index, text) { var _this4 = this; var formats = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); this.scroll.insertAt(index, text); Object.keys(formats).forEach(function (format) { _this4.scroll.formatAt(index, text.length, format, formats[format]); }); return this.update(new _quillDelta2.default().retain(index).insert(text, (0, _clone2.default)(formats))); } }, { key: 'isBlank', value: function isBlank() { if (this.scroll.children.length == 0) return true; if (this.scroll.children.length > 1) return false; var block = this.scroll.children.head; if (block.statics.blotName !== _block2.default.blotName) return false; if (block.children.length > 1) return false; return block.children.head instanceof _break2.default; } }, { key: 'removeFormat', value: function removeFormat(index, length) { var text = this.getText(index, length); var _scroll$line3 = this.scroll.line(index + length), _scroll$line4 = _slicedToArray(_scroll$line3, 2), line = _scroll$line4[0], offset = _scroll$line4[1]; var suffixLength = 0, suffix = new _quillDelta2.default(); if (line != null) { if (!(line instanceof _code2.default)) { suffixLength = line.length() - offset; } else { suffixLength = line.newlineIndex(offset) - offset + 1; } suffix = line.delta().slice(offset, offset + suffixLength - 1).insert('\n'); } var contents = this.getContents(index, length + suffixLength); var diff = contents.diff(new _quillDelta2.default().insert(text).concat(suffix)); var delta = new _quillDelta2.default().retain(index).concat(diff); return this.applyDelta(delta); } }, { key: 'update', value: function update(change) { var mutations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var cursorIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var oldDelta = this.delta; if (mutations.length === 1 && mutations[0].type === 'characterData' && mutations[0].target.data.match(ASCII) && _parchment2.default.find(mutations[0].target)) { // Optimization for character changes var textBlot = _parchment2.default.find(mutations[0].target); var formats = (0, _block.bubbleFormats)(textBlot); var index = textBlot.offset(this.scroll); var oldValue = mutations[0].oldValue.replace(_cursor2.default.CONTENTS, ''); var oldText = new _quillDelta2.default().insert(oldValue); var newText = new _quillDelta2.default().insert(textBlot.value()); var diffDelta = new _quillDelta2.default().retain(index).concat(oldText.diff(newText, cursorIndex)); change = diffDelta.reduce(function (delta, op) { if (op.insert) { return delta.insert(op.insert, formats); } else { return delta.push(op); } }, new _quillDelta2.default()); this.delta = oldDelta.compose(change); } else { this.delta = this.getDelta(); if (!change || !(0, _deepEqual2.default)(oldDelta.compose(change), this.delta)) { change = oldDelta.diff(this.delta, cursorIndex); } } return change; } }]); return Editor; }(); function combineFormats(formats, combined) { return Object.keys(combined).reduce(function (merged, name) { if (formats[name] == null) return merged; if (combined[name] === formats[name]) { merged[name] = combined[name]; } else if (Array.isArray(combined[name])) { if (combined[name].indexOf(formats[name]) < 0) { merged[name] = combined[name].concat([formats[name]]); } } else { merged[name] = [combined[name], formats[name]]; } return merged; }, {}); } function normalizeDelta(delta) { return delta.reduce(function (delta, op) { if (op.insert === 1) { var attributes = (0, _clone2.default)(op.attributes); delete attributes['image']; return delta.insert({ image: op.attributes.image }, attributes); } if (op.attributes != null && (op.attributes.list === true || op.attributes.bullet === true)) { op = (0, _clone2.default)(op); if (op.attributes.list) { op.attributes.list = 'ordered'; } else { op.attributes.list = 'bullet'; delete op.attributes.bullet; } } if (typeof op.insert === 'string') { var text = op.insert.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); return delta.insert(text, op.attributes); } return delta.push(op); }, new _quillDelta2.default()); } exports.default = Editor; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.Range = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _clone = __webpack_require__(21); var _clone2 = _interopRequireDefault(_clone); var _deepEqual = __webpack_require__(11); var _deepEqual2 = _interopRequireDefault(_deepEqual); var _emitter3 = __webpack_require__(8); var _emitter4 = _interopRequireDefault(_emitter3); var _logger = __webpack_require__(10); var _logger2 = _interopRequireDefault(_logger); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var debug = (0, _logger2.default)('quill:selection'); var Range = function Range(index) { var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; _classCallCheck(this, Range); this.index = index; this.length = length; }; var Selection = function () { function Selection(scroll, emitter) { var _this = this; _classCallCheck(this, Selection); this.emitter = emitter; this.scroll = scroll; this.composing = false; this.mouseDown = false; this.root = this.scroll.domNode; this.cursor = _parchment2.default.create('cursor', this); // savedRange is last non-null range this.lastRange = this.savedRange = new Range(0, 0); this.handleComposition(); this.handleDragging(); this.emitter.listenDOM('selectionchange', document, function () { if (!_this.mouseDown) { setTimeout(_this.update.bind(_this, _emitter4.default.sources.USER), 1); } }); this.emitter.on(_emitter4.default.events.EDITOR_CHANGE, function (type, delta) { if (type === _emitter4.default.events.TEXT_CHANGE && delta.length() > 0) { _this.update(_emitter4.default.sources.SILENT); } }); this.emitter.on(_emitter4.default.events.SCROLL_BEFORE_UPDATE, function () { if (!_this.hasFocus()) return; var native = _this.getNativeRange(); if (native == null) return; if (native.start.node === _this.cursor.textNode) return; // cursor.restore() will handle // TODO unclear if this has negative side effects _this.emitter.once(_emitter4.default.events.SCROLL_UPDATE, function () { try { _this.setNativeRange(native.start.node, native.start.offset, native.end.node, native.end.offset); } catch (ignored) {} }); }); this.emitter.on(_emitter4.default.events.SCROLL_OPTIMIZE, function (mutations, context) { if (context.range) { var _context$range = context.range, startNode = _context$range.startNode, startOffset = _context$range.startOffset, endNode = _context$range.endNode, endOffset = _context$range.endOffset; _this.setNativeRange(startNode, startOffset, endNode, endOffset); } }); this.update(_emitter4.default.sources.SILENT); } _createClass(Selection, [{ key: 'handleComposition', value: function handleComposition() { var _this2 = this; this.root.addEventListener('compositionstart', function () { _this2.composing = true; }); this.root.addEventListener('compositionend', function () { _this2.composing = false; if (_this2.cursor.parent) { var range = _this2.cursor.restore(); if (!range) return; setTimeout(function () { _this2.setNativeRange(range.startNode, range.startOffset, range.endNode, range.endOffset); }, 1); } }); } }, { key: 'handleDragging', value: function handleDragging() { var _this3 = this; this.emitter.listenDOM('mousedown', document.body, function () { _this3.mouseDown = true; }); this.emitter.listenDOM('mouseup', document.body, function () { _this3.mouseDown = false; _this3.update(_emitter4.default.sources.USER); }); } }, { key: 'focus', value: function focus() { if (this.hasFocus()) return; this.root.focus(); this.setRange(this.savedRange); } }, { key: 'format', value: function format(_format, value) { if (this.scroll.whitelist != null && !this.scroll.whitelist[_format]) return; this.scroll.update(); var nativeRange = this.getNativeRange(); if (nativeRange == null || !nativeRange.native.collapsed || _parchment2.default.query(_format, _parchment2.default.Scope.BLOCK)) return; if (nativeRange.start.node !== this.cursor.textNode) { var blot = _parchment2.default.find(nativeRange.start.node, false); if (blot == null) return; // TODO Give blot ability to not split if (blot instanceof _parchment2.default.Leaf) { var after = blot.split(nativeRange.start.offset); blot.parent.insertBefore(this.cursor, after); } else { blot.insertBefore(this.cursor, nativeRange.start.node); // Should never happen } this.cursor.attach(); } this.cursor.format(_format, value); this.scroll.optimize(); this.setNativeRange(this.cursor.textNode, this.cursor.textNode.data.length); this.update(); } }, { key: 'getBounds', value: function getBounds(index) { var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var scrollLength = this.scroll.length(); index = Math.min(index, scrollLength - 1); length = Math.min(index + length, scrollLength - 1) - index; var node = void 0, _scroll$leaf = this.scroll.leaf(index), _scroll$leaf2 = _slicedToArray(_scroll$leaf, 2), leaf = _scroll$leaf2[0], offset = _scroll$leaf2[1]; if (leaf == null) return null; var _leaf$position = leaf.position(offset, true); var _leaf$position2 = _slicedToArray(_leaf$position, 2); node = _leaf$position2[0]; offset = _leaf$position2[1]; var range = document.createRange(); if (length > 0) { range.setStart(node, offset); var _scroll$leaf3 = this.scroll.leaf(index + length); var _scroll$leaf4 = _slicedToArray(_scroll$leaf3, 2); leaf = _scroll$leaf4[0]; offset = _scroll$leaf4[1]; if (leaf == null) return null; var _leaf$position3 = leaf.position(offset, true); var _leaf$position4 = _slicedToArray(_leaf$position3, 2); node = _leaf$position4[0]; offset = _leaf$position4[1]; range.setEnd(node, offset); return range.getBoundingClientRect(); } else { var side = 'left'; var rect = void 0; if (node instanceof Text) { if (offset < node.data.length) { range.setStart(node, offset); range.setEnd(node, offset + 1); } else { range.setStart(node, offset - 1); range.setEnd(node, offset); side = 'right'; } rect = range.getBoundingClientRect(); } else { rect = leaf.domNode.getBoundingClientRect(); if (offset > 0) side = 'right'; } return { bottom: rect.top + rect.height, height: rect.height, left: rect[side], right: rect[side], top: rect.top, width: 0 }; } } }, { key: 'getNativeRange', value: function getNativeRange() { var selection = document.getSelection(); if (selection == null || selection.rangeCount <= 0) return null; var nativeRange = selection.getRangeAt(0); if (nativeRange == null) return null; var range = this.normalizeNative(nativeRange); debug.info('getNativeRange', range); return range; } }, { key: 'getRange', value: function getRange() { var normalized = this.getNativeRange(); if (normalized == null) return [null, null]; var range = this.normalizedToRange(normalized); return [range, normalized]; } }, { key: 'hasFocus', value: function hasFocus() { return document.activeElement === this.root; } }, { key: 'normalizedToRange', value: function normalizedToRange(range) { var _this4 = this; var positions = [[range.start.node, range.start.offset]]; if (!range.native.collapsed) { positions.push([range.end.node, range.end.offset]); } var indexes = positions.map(function (position) { var _position = _slicedToArray(position, 2), node = _position[0], offset = _position[1]; var blot = _parchment2.default.find(node, true); var index = blot.offset(_this4.scroll); if (offset === 0) { return index; } else if (blot instanceof _parchment2.default.Container) { return index + blot.length(); } else { return index + blot.index(node, offset); } }); var end = Math.min(Math.max.apply(Math, _toConsumableArray(indexes)), this.scroll.length() - 1); var start = Math.min.apply(Math, [end].concat(_toConsumableArray(indexes))); return new Range(start, end - start); } }, { key: 'normalizeNative', value: function normalizeNative(nativeRange) { if (!contains(this.root, nativeRange.startContainer) || !nativeRange.collapsed && !contains(this.root, nativeRange.endContainer)) { return null; } var range = { start: { node: nativeRange.startContainer, offset: nativeRange.startOffset }, end: { node: nativeRange.endContainer, offset: nativeRange.endOffset }, native: nativeRange }; [range.start, range.end].forEach(function (position) { var node = position.node, offset = position.offset; while (!(node instanceof Text) && node.childNodes.length > 0) { if (node.childNodes.length > offset) { node = node.childNodes[offset]; offset = 0; } else if (node.childNodes.length === offset) { node = node.lastChild; offset = node instanceof Text ? node.data.length : node.childNodes.length + 1; } else { break; } } position.node = node, position.offset = offset; }); return range; } }, { key: 'rangeToNative', value: function rangeToNative(range) { var _this5 = this; var indexes = range.collapsed ? [range.index] : [range.index, range.index + range.length]; var args = []; var scrollLength = this.scroll.length(); indexes.forEach(function (index, i) { index = Math.min(scrollLength - 1, index); var node = void 0, _scroll$leaf5 = _this5.scroll.leaf(index), _scroll$leaf6 = _slicedToArray(_scroll$leaf5, 2), leaf = _scroll$leaf6[0], offset = _scroll$leaf6[1]; var _leaf$position5 = leaf.position(offset, i !== 0); var _leaf$position6 = _slicedToArray(_leaf$position5, 2); node = _leaf$position6[0]; offset = _leaf$position6[1]; args.push(node, offset); }); if (args.length < 2) { args = args.concat(args); } return args; } }, { key: 'scrollIntoView', value: function scrollIntoView(scrollingContainer) { var range = this.lastRange; if (range == null) return; var bounds = this.getBounds(range.index, range.length); if (bounds == null) return; var limit = this.scroll.length() - 1; var _scroll$line = this.scroll.line(Math.min(range.index, limit)), _scroll$line2 = _slicedToArray(_scroll$line, 1), first = _scroll$line2[0]; var last = first; if (range.length > 0) { var _scroll$line3 = this.scroll.line(Math.min(range.index + range.length, limit)); var _scroll$line4 = _slicedToArray(_scroll$line3, 1); last = _scroll$line4[0]; } if (first == null || last == null) return; var scrollBounds = scrollingContainer.getBoundingClientRect(); if (bounds.top < scrollBounds.top) { scrollingContainer.scrollTop -= scrollBounds.top - bounds.top; } else if (bounds.bottom > scrollBounds.bottom) { scrollingContainer.scrollTop += bounds.bottom - scrollBounds.bottom; } } }, { key: 'setNativeRange', value: function setNativeRange(startNode, startOffset) { var endNode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : startNode; var endOffset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : startOffset; var force = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; debug.info('setNativeRange', startNode, startOffset, endNode, endOffset); if (startNode != null && (this.root.parentNode == null || startNode.parentNode == null || endNode.parentNode == null)) { return; } var selection = document.getSelection(); if (selection == null) return; if (startNode != null) { if (!this.hasFocus()) this.root.focus(); var native = (this.getNativeRange() || {}).native; if (native == null || force || startNode !== native.startContainer || startOffset !== native.startOffset || endNode !== native.endContainer || endOffset !== native.endOffset) { if (startNode.tagName == "BR") { startOffset = [].indexOf.call(startNode.parentNode.childNodes, startNode); startNode = startNode.parentNode; } if (endNode.tagName == "BR") { endOffset = [].indexOf.call(endNode.parentNode.childNodes, endNode); endNode = endNode.parentNode; } var range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); selection.removeAllRanges(); selection.addRange(range); } } else { selection.removeAllRanges(); this.root.blur(); document.body.focus(); // root.blur() not enough on IE11+Travis+SauceLabs (but not local VMs) } } }, { key: 'setRange', value: function setRange(range) { var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var source = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _emitter4.default.sources.API; if (typeof force === 'string') { source = force; force = false; } debug.info('setRange', range); if (range != null) { var args = this.rangeToNative(range); this.setNativeRange.apply(this, _toConsumableArray(args).concat([force])); } else { this.setNativeRange(null); } this.update(source); } }, { key: 'update', value: function update() { var source = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _emitter4.default.sources.USER; var oldRange = this.lastRange; var _getRange = this.getRange(), _getRange2 = _slicedToArray(_getRange, 2), lastRange = _getRange2[0], nativeRange = _getRange2[1]; this.lastRange = lastRange; if (this.lastRange != null) { this.savedRange = this.lastRange; } if (!(0, _deepEqual2.default)(oldRange, this.lastRange)) { var _emitter; if (!this.composing && nativeRange != null && nativeRange.native.collapsed && nativeRange.start.node !== this.cursor.textNode) { this.cursor.restore(); } var args = [_emitter4.default.events.SELECTION_CHANGE, (0, _clone2.default)(this.lastRange), (0, _clone2.default)(oldRange), source]; (_emitter = this.emitter).emit.apply(_emitter, [_emitter4.default.events.EDITOR_CHANGE].concat(args)); if (source !== _emitter4.default.sources.SILENT) { var _emitter2; (_emitter2 = this.emitter).emit.apply(_emitter2, args); } } } }]); return Selection; }(); function contains(parent, descendant) { try { // Firefox inserts inaccessible nodes around video elements descendant.parentNode; } catch (e) { return false; } // IE11 has bug with Text nodes // https://connect.microsoft.com/IE/feedback/details/780874/node-contains-is-incorrect if (descendant instanceof Text) { descendant = descendant.parentNode; } return parent.contains(descendant); } exports.Range = Range; exports.default = Selection; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Break = function (_Parchment$Embed) { _inherits(Break, _Parchment$Embed); function Break() { _classCallCheck(this, Break); return _possibleConstructorReturn(this, (Break.__proto__ || Object.getPrototypeOf(Break)).apply(this, arguments)); } _createClass(Break, [{ key: 'insertInto', value: function insertInto(parent, ref) { if (parent.children.length === 0) { _get(Break.prototype.__proto__ || Object.getPrototypeOf(Break.prototype), 'insertInto', this).call(this, parent, ref); } else { this.remove(); } } }, { key: 'length', value: function length() { return 0; } }, { key: 'value', value: function value() { return ''; } }], [{ key: 'value', value: function value() { return undefined; } }]); return Break; }(_parchment2.default.Embed); Break.blotName = 'break'; Break.tagName = 'BR'; exports.default = Break; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var linked_list_1 = __webpack_require__(44); var shadow_1 = __webpack_require__(30); var Registry = __webpack_require__(1); var ContainerBlot = /** @class */ (function (_super) { __extends(ContainerBlot, _super); function ContainerBlot(domNode) { var _this = _super.call(this, domNode) || this; _this.build(); return _this; } ContainerBlot.prototype.appendChild = function (other) { this.insertBefore(other); }; ContainerBlot.prototype.attach = function () { _super.prototype.attach.call(this); this.children.forEach(function (child) { child.attach(); }); }; ContainerBlot.prototype.build = function () { var _this = this; this.children = new linked_list_1.default(); // Need to be reversed for if DOM nodes already in order [].slice .call(this.domNode.childNodes) .reverse() .forEach(function (node) { try { var child = makeBlot(node); _this.insertBefore(child, _this.children.head || undefined); } catch (err) { if (err instanceof Registry.ParchmentError) return; else throw err; } }); }; ContainerBlot.prototype.deleteAt = function (index, length) { if (index === 0 && length === this.length()) { return this.remove(); } this.children.forEachAt(index, length, function (child, offset, length) { child.deleteAt(offset, length); }); }; ContainerBlot.prototype.descendant = function (criteria, index) { var _a = this.children.find(index), child = _a[0], offset = _a[1]; if ((criteria.blotName == null && criteria(child)) || (criteria.blotName != null && child instanceof criteria)) { return [child, offset]; } else if (child instanceof ContainerBlot) { return child.descendant(criteria, offset); } else { return [null, -1]; } }; ContainerBlot.prototype.descendants = function (criteria, index, length) { if (index === void 0) { index = 0; } if (length === void 0) { length = Number.MAX_VALUE; } var descendants = []; var lengthLeft = length; this.children.forEachAt(index, length, function (child, index, length) { if ((criteria.blotName == null && criteria(child)) || (criteria.blotName != null && child instanceof criteria)) { descendants.push(child); } if (child instanceof ContainerBlot) { descendants = descendants.concat(child.descendants(criteria, index, lengthLeft)); } lengthLeft -= length; }); return descendants; }; ContainerBlot.prototype.detach = function () { this.children.forEach(function (child) { child.detach(); }); _super.prototype.detach.call(this); }; ContainerBlot.prototype.formatAt = function (index, length, name, value) { this.children.forEachAt(index, length, function (child, offset, length) { child.formatAt(offset, length, name, value); }); }; ContainerBlot.prototype.insertAt = function (index, value, def) { var _a = this.children.find(index), child = _a[0], offset = _a[1]; if (child) { child.insertAt(offset, value, def); } else { var blot = def == null ? Registry.create('text', value) : Registry.create(value, def); this.appendChild(blot); } }; ContainerBlot.prototype.insertBefore = function (childBlot, refBlot) { if (this.statics.allowedChildren != null && !this.statics.allowedChildren.some(function (child) { return childBlot instanceof child; })) { throw new Registry.ParchmentError("Cannot insert " + childBlot.statics.blotName + " into " + this.statics.blotName); } childBlot.insertInto(this, refBlot); }; ContainerBlot.prototype.length = function () { return this.children.reduce(function (memo, child) { return memo + child.length(); }, 0); }; ContainerBlot.prototype.moveChildren = function (targetParent, refNode) { this.children.forEach(function (child) { targetParent.insertBefore(child, refNode); }); }; ContainerBlot.prototype.optimize = function (context) { _super.prototype.optimize.call(this, context); if (this.children.length === 0) { if (this.statics.defaultChild != null) { var child = Registry.create(this.statics.defaultChild); this.appendChild(child); child.optimize(context); } else { this.remove(); } } }; ContainerBlot.prototype.path = function (index, inclusive) { if (inclusive === void 0) { inclusive = false; } var _a = this.children.find(index, inclusive), child = _a[0], offset = _a[1]; var position = [[this, index]]; if (child instanceof ContainerBlot) { return position.concat(child.path(offset, inclusive)); } else if (child != null) { position.push([child, offset]); } return position; }; ContainerBlot.prototype.removeChild = function (child) { this.children.remove(child); }; ContainerBlot.prototype.replace = function (target) { if (target instanceof ContainerBlot) { target.moveChildren(this); } _super.prototype.replace.call(this, target); }; ContainerBlot.prototype.split = function (index, force) { if (force === void 0) { force = false; } if (!force) { if (index === 0) return this; if (index === this.length()) return this.next; } var after = this.clone(); this.parent.insertBefore(after, this.next); this.children.forEachAt(index, this.length(), function (child, offset, length) { child = child.split(offset, force); after.appendChild(child); }); return after; }; ContainerBlot.prototype.unwrap = function () { this.moveChildren(this.parent, this.next); this.remove(); }; ContainerBlot.prototype.update = function (mutations, context) { var _this = this; var addedNodes = []; var removedNodes = []; mutations.forEach(function (mutation) { if (mutation.target === _this.domNode && mutation.type === 'childList') { addedNodes.push.apply(addedNodes, mutation.addedNodes); removedNodes.push.apply(removedNodes, mutation.removedNodes); } }); removedNodes.forEach(function (node) { // Check node has actually been removed // One exception is Chrome does not immediately remove IFRAMEs // from DOM but MutationRecord is correct in its reported removal if (node.parentNode != null && // @ts-ignore node.tagName !== 'IFRAME' && document.body.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_CONTAINED_BY) { return; } var blot = Registry.find(node); if (blot == null) return; if (blot.domNode.parentNode == null || blot.domNode.parentNode === _this.domNode) { blot.detach(); } }); addedNodes .filter(function (node) { return node.parentNode == _this.domNode; }) .sort(function (a, b) { if (a === b) return 0; if (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) { return 1; } return -1; }) .forEach(function (node) { var refBlot = null; if (node.nextSibling != null) { refBlot = Registry.find(node.nextSibling); } var blot = makeBlot(node); if (blot.next != refBlot || blot.next == null) { if (blot.parent != null) { blot.parent.removeChild(_this); } _this.insertBefore(blot, refBlot || undefined); } }); }; return ContainerBlot; }(shadow_1.default)); function makeBlot(node) { var blot = Registry.find(node); if (blot == null) { try { blot = Registry.create(node); } catch (e) { blot = Registry.create(Registry.Scope.INLINE); [].slice.call(node.childNodes).forEach(function (child) { // @ts-ignore blot.domNode.appendChild(child); }); if (node.parentNode) { node.parentNode.replaceChild(blot.domNode, node); } blot.attach(); } } return blot; } exports.default = ContainerBlot; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var attributor_1 = __webpack_require__(12); var store_1 = __webpack_require__(31); var container_1 = __webpack_require__(17); var Registry = __webpack_require__(1); var FormatBlot = /** @class */ (function (_super) { __extends(FormatBlot, _super); function FormatBlot(domNode) { var _this = _super.call(this, domNode) || this; _this.attributes = new store_1.default(_this.domNode); return _this; } FormatBlot.formats = function (domNode) { if (typeof this.tagName === 'string') { return true; } else if (Array.isArray(this.tagName)) { return domNode.tagName.toLowerCase(); } return undefined; }; FormatBlot.prototype.format = function (name, value) { var format = Registry.query(name); if (format instanceof attributor_1.default) { this.attributes.attribute(format, value); } else if (value) { if (format != null && (name !== this.statics.blotName || this.formats()[name] !== value)) { this.replaceWith(name, value); } } }; FormatBlot.prototype.formats = function () { var formats = this.attributes.values(); var format = this.statics.formats(this.domNode); if (format != null) { formats[this.statics.blotName] = format; } return formats; }; FormatBlot.prototype.replaceWith = function (name, value) { var replacement = _super.prototype.replaceWith.call(this, name, value); this.attributes.copy(replacement); return replacement; }; FormatBlot.prototype.update = function (mutations, context) { var _this = this; _super.prototype.update.call(this, mutations, context); if (mutations.some(function (mutation) { return mutation.target === _this.domNode && mutation.type === 'attributes'; })) { this.attributes.build(); } }; FormatBlot.prototype.wrap = function (name, value) { var wrapper = _super.prototype.wrap.call(this, name, value); if (wrapper instanceof FormatBlot && wrapper.statics.scope === this.statics.scope) { this.attributes.move(wrapper); } return wrapper; }; return FormatBlot; }(container_1.default)); exports.default = FormatBlot; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var shadow_1 = __webpack_require__(30); var Registry = __webpack_require__(1); var LeafBlot = /** @class */ (function (_super) { __extends(LeafBlot, _super); function LeafBlot() { return _super !== null && _super.apply(this, arguments) || this; } LeafBlot.value = function (domNode) { return true; }; LeafBlot.prototype.index = function (node, offset) { if (this.domNode === node || this.domNode.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_CONTAINED_BY) { return Math.min(offset, 1); } return -1; }; LeafBlot.prototype.position = function (index, inclusive) { var offset = [].indexOf.call(this.parent.domNode.childNodes, this.domNode); if (index > 0) offset += 1; return [this.parent.domNode, offset]; }; LeafBlot.prototype.value = function () { return _a = {}, _a[this.statics.blotName] = this.statics.value(this.domNode) || true, _a; var _a; }; LeafBlot.scope = Registry.Scope.INLINE_BLOT; return LeafBlot; }(shadow_1.default)); exports.default = LeafBlot; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { var equal = __webpack_require__(11); var extend = __webpack_require__(3); var lib = { attributes: { compose: function (a, b, keepNull) { if (typeof a !== 'object') a = {}; if (typeof b !== 'object') b = {}; var attributes = extend(true, {}, b); if (!keepNull) { attributes = Object.keys(attributes).reduce(function (copy, key) { if (attributes[key] != null) { copy[key] = attributes[key]; } return copy; }, {}); } for (var key in a) { if (a[key] !== undefined && b[key] === undefined) { attributes[key] = a[key]; } } return Object.keys(attributes).length > 0 ? attributes : undefined; }, diff: function(a, b) { if (typeof a !== 'object') a = {}; if (typeof b !== 'object') b = {}; var attributes = Object.keys(a).concat(Object.keys(b)).reduce(function (attributes, key) { if (!equal(a[key], b[key])) { attributes[key] = b[key] === undefined ? null : b[key]; } return attributes; }, {}); return Object.keys(attributes).length > 0 ? attributes : undefined; }, transform: function (a, b, priority) { if (typeof a !== 'object') return b; if (typeof b !== 'object') return undefined; if (!priority) return b; // b simply overwrites us without priority var attributes = Object.keys(b).reduce(function (attributes, key) { if (a[key] === undefined) attributes[key] = b[key]; // null is a valid value return attributes; }, {}); return Object.keys(attributes).length > 0 ? attributes : undefined; } }, iterator: function (ops) { return new Iterator(ops); }, length: function (op) { if (typeof op['delete'] === 'number') { return op['delete']; } else if (typeof op.retain === 'number') { return op.retain; } else { return typeof op.insert === 'string' ? op.insert.length : 1; } } }; function Iterator(ops) { this.ops = ops; this.index = 0; this.offset = 0; }; Iterator.prototype.hasNext = function () { return this.peekLength() < Infinity; }; Iterator.prototype.next = function (length) { if (!length) length = Infinity; var nextOp = this.ops[this.index]; if (nextOp) { var offset = this.offset; var opLength = lib.length(nextOp) if (length >= opLength - offset) { length = opLength - offset; this.index += 1; this.offset = 0; } else { this.offset += length; } if (typeof nextOp['delete'] === 'number') { return { 'delete': length }; } else { var retOp = {}; if (nextOp.attributes) { retOp.attributes = nextOp.attributes; } if (typeof nextOp.retain === 'number') { retOp.retain = length; } else if (typeof nextOp.insert === 'string') { retOp.insert = nextOp.insert.substr(offset, length); } else { // offset should === 0, length should === 1 retOp.insert = nextOp.insert; } return retOp; } } else { return { retain: Infinity }; } }; Iterator.prototype.peek = function () { return this.ops[this.index]; }; Iterator.prototype.peekLength = function () { if (this.ops[this.index]) { // Should never return 0 if our index is being managed correctly return lib.length(this.ops[this.index]) - this.offset; } else { return Infinity; } }; Iterator.prototype.peekType = function () { if (this.ops[this.index]) { if (typeof this.ops[this.index]['delete'] === 'number') { return 'delete'; } else if (typeof this.ops[this.index].retain === 'number') { return 'retain'; } else { return 'insert'; } } return 'retain'; }; module.exports = lib; /***/ }), /* 21 */ /***/ (function(module, exports) { var clone = (function () { 'use strict'; function _instanceof(obj, type) { return type != null && obj instanceof type; } var nativeMap; try { nativeMap = Map; } catch(_) { // maybe a reference error because no `Map`. Give it a dummy value that no // value will ever be an instanceof. nativeMap = function () {}; } var nativeSet; try { nativeSet = Set; } catch(_) { nativeSet = function () {}; } var nativePromise; try { nativePromise = Promise; } catch(_) { nativePromise = function () {}; } /** * Clones (copies) an Object using deep copying. * * This function supports circular references by default, but if you are certain * there are no circular references in your object, you can save some CPU time * by calling clone(obj, false). * * Caution: if `circular` is false and `parent` contains circular references, * your program may enter an infinite loop and crash. * * @param `parent` - the object to be cloned * @param `circular` - set to true if the object to be cloned may contain * circular references. (optional - true by default) * @param `depth` - set to a number if the object is only to be cloned to * a particular depth. (optional - defaults to Infinity) * @param `prototype` - sets the prototype to be used when cloning an object. * (optional - defaults to parent prototype). * @param `includeNonEnumerable` - set to true if the non-enumerable properties * should be cloned as well. Non-enumerable properties on the prototype * chain will be ignored. (optional - false by default) */ function clone(parent, circular, depth, prototype, includeNonEnumerable) { if (typeof circular === 'object') { depth = circular.depth; prototype = circular.prototype; includeNonEnumerable = circular.includeNonEnumerable; circular = circular.circular; } // maintain two arrays for circular references, where corresponding parents // and children have the same index var allParents = []; var allChildren = []; var useBuffer = typeof Buffer != 'undefined'; if (typeof circular == 'undefined') circular = true; if (typeof depth == 'undefined') depth = Infinity; // recurse this function so we don't reset allParents and allChildren function _clone(parent, depth) { // cloning null always returns null if (parent === null) return null; if (depth === 0) return parent; var child; var proto; if (typeof parent != 'object') { return parent; } if (_instanceof(parent, nativeMap)) { child = new nativeMap(); } else if (_instanceof(parent, nativeSet)) { child = new nativeSet(); } else if (_instanceof(parent, nativePromise)) { child = new nativePromise(function (resolve, reject) { parent.then(function(value) { resolve(_clone(value, depth - 1)); }, function(err) { reject(_clone(err, depth - 1)); }); }); } else if (clone.__isArray(parent)) { child = []; } else if (clone.__isRegExp(parent)) { child = new RegExp(parent.source, __getRegExpFlags(parent)); if (parent.lastIndex) child.lastIndex = parent.lastIndex; } else if (clone.__isDate(parent)) { child = new Date(parent.getTime()); } else if (useBuffer && Buffer.isBuffer(parent)) { child = new Buffer(parent.length); parent.copy(child); return child; } else if (_instanceof(parent, Error)) { child = Object.create(parent); } else { if (typeof prototype == 'undefined') { proto = Object.getPrototypeOf(parent); child = Object.create(proto); } else { child = Object.create(prototype); proto = prototype; } } if (circular) { var index = allParents.indexOf(parent); if (index != -1) { return allChildren[index]; } allParents.push(parent); allChildren.push(child); } if (_instanceof(parent, nativeMap)) { parent.forEach(function(value, key) { var keyChild = _clone(key, depth - 1); var valueChild = _clone(value, depth - 1); child.set(keyChild, valueChild); }); } if (_instanceof(parent, nativeSet)) { parent.forEach(function(value) { var entryChild = _clone(value, depth - 1); child.add(entryChild); }); } for (var i in parent) { var attrs; if (proto) { attrs = Object.getOwnPropertyDescriptor(proto, i); } if (attrs && attrs.set == null) { continue; } child[i] = _clone(parent[i], depth - 1); } if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(parent); for (var i = 0; i < symbols.length; i++) { // Don't need to worry about cloning a symbol because it is a primitive, // like a number or string. var symbol = symbols[i]; var descriptor = Object.getOwnPropertyDescriptor(parent, symbol); if (descriptor && !descriptor.enumerable && !includeNonEnumerable) { continue; } child[symbol] = _clone(parent[symbol], depth - 1); if (!descriptor.enumerable) { Object.defineProperty(child, symbol, { enumerable: false }); } } } if (includeNonEnumerable) { var allPropertyNames = Object.getOwnPropertyNames(parent); for (var i = 0; i < allPropertyNames.length; i++) { var propertyName = allPropertyNames[i]; var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName); if (descriptor && descriptor.enumerable) { continue; } child[propertyName] = _clone(parent[propertyName], depth - 1); Object.defineProperty(child, propertyName, { enumerable: false }); } } return child; } return _clone(parent, depth); } /** * Simple flat clone using prototype, accepts only objects, usefull for property * override on FLAT configuration object (no nested props). * * USE WITH CAUTION! This may not behave as you wish if you do not know how this * works. */ clone.clonePrototype = function clonePrototype(parent) { if (parent === null) return null; var c = function () {}; c.prototype = parent; return new c(); }; // private utility functions function __objToStr(o) { return Object.prototype.toString.call(o); } clone.__objToStr = __objToStr; function __isDate(o) { return typeof o === 'object' && __objToStr(o) === '[object Date]'; } clone.__isDate = __isDate; function __isArray(o) { return typeof o === 'object' && __objToStr(o) === '[object Array]'; } clone.__isArray = __isArray; function __isRegExp(o) { return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; } clone.__isRegExp = __isRegExp; function __getRegExpFlags(re) { var flags = ''; if (re.global) flags += 'g'; if (re.ignoreCase) flags += 'i'; if (re.multiline) flags += 'm'; return flags; } clone.__getRegExpFlags = __getRegExpFlags; return clone; })(); if (typeof module === 'object' && module.exports) { module.exports = clone; } /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _emitter = __webpack_require__(8); var _emitter2 = _interopRequireDefault(_emitter); var _block = __webpack_require__(4); var _block2 = _interopRequireDefault(_block); var _break = __webpack_require__(16); var _break2 = _interopRequireDefault(_break); var _code = __webpack_require__(13); var _code2 = _interopRequireDefault(_code); var _container = __webpack_require__(25); var _container2 = _interopRequireDefault(_container); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function isLine(blot) { return blot instanceof _block2.default || blot instanceof _block.BlockEmbed; } var Scroll = function (_Parchment$Scroll) { _inherits(Scroll, _Parchment$Scroll); function Scroll(domNode, config) { _classCallCheck(this, Scroll); var _this = _possibleConstructorReturn(this, (Scroll.__proto__ || Object.getPrototypeOf(Scroll)).call(this, domNode)); _this.emitter = config.emitter; if (Array.isArray(config.whitelist)) { _this.whitelist = config.whitelist.reduce(function (whitelist, format) { whitelist[format] = true; return whitelist; }, {}); } // Some reason fixes composition issues with character languages in Windows/Chrome, Safari _this.domNode.addEventListener('DOMNodeInserted', function () {}); _this.optimize(); _this.enable(); return _this; } _createClass(Scroll, [{ key: 'batchStart', value: function batchStart() { this.batch = true; } }, { key: 'batchEnd', value: function batchEnd() { this.batch = false; this.optimize(); } }, { key: 'deleteAt', value: function deleteAt(index, length) { var _line = this.line(index), _line2 = _slicedToArray(_line, 2), first = _line2[0], offset = _line2[1]; var _line3 = this.line(index + length), _line4 = _slicedToArray(_line3, 1), last = _line4[0]; _get(Scroll.prototype.__proto__ || Object.getPrototypeOf(Scroll.prototype), 'deleteAt', this).call(this, index, length); if (last != null && first !== last && offset > 0) { if (first instanceof _block.BlockEmbed || last instanceof _block.BlockEmbed) { this.optimize(); return; } if (first instanceof _code2.default) { var newlineIndex = first.newlineIndex(first.length(), true); if (newlineIndex > -1) { first = first.split(newlineIndex + 1); if (first === last) { this.optimize(); return; } } } else if (last instanceof _code2.default) { var _newlineIndex = last.newlineIndex(0); if (_newlineIndex > -1) { last.split(_newlineIndex + 1); } } var ref = last.children.head instanceof _break2.default ? null : last.children.head; first.moveChildren(last, ref); first.remove(); } this.optimize(); } }, { key: 'enable', value: function enable() { var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; this.domNode.setAttribute('contenteditable', enabled); } }, { key: 'formatAt', value: function formatAt(index, length, format, value) { if (this.whitelist != null && !this.whitelist[format]) return; _get(Scroll.prototype.__proto__ || Object.getPrototypeOf(Scroll.prototype), 'formatAt', this).call(this, index, length, format, value); this.optimize(); } }, { key: 'insertAt', value: function insertAt(index, value, def) { if (def != null && this.whitelist != null && !this.whitelist[value]) return; if (index >= this.length()) { if (def == null || _parchment2.default.query(value, _parchment2.default.Scope.BLOCK) == null) { var blot = _parchment2.default.create(this.statics.defaultChild); this.appendChild(blot); if (def == null && value.endsWith('\n')) { value = value.slice(0, -1); } blot.insertAt(0, value, def); } else { var embed = _parchment2.default.create(value, def); this.appendChild(embed); } } else { _get(Scroll.prototype.__proto__ || Object.getPrototypeOf(Scroll.prototype), 'insertAt', this).call(this, index, value, def); } this.optimize(); } }, { key: 'insertBefore', value: function insertBefore(blot, ref) { if (blot.statics.scope === _parchment2.default.Scope.INLINE_BLOT) { var wrapper = _parchment2.default.create(this.statics.defaultChild); wrapper.appendChild(blot); blot = wrapper; } _get(Scroll.prototype.__proto__ || Object.getPrototypeOf(Scroll.prototype), 'insertBefore', this).call(this, blot, ref); } }, { key: 'leaf', value: function leaf(index) { return this.path(index).pop() || [null, -1]; } }, { key: 'line', value: function line(index) { if (index === this.length()) { return this.line(index - 1); } return this.descendant(isLine, index); } }, { key: 'lines', value: function lines() { var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Number.MAX_VALUE; var getLines = function getLines(blot, index, length) { var lines = [], lengthLeft = length; blot.children.forEachAt(index, length, function (child, index, length) { if (isLine(child)) { lines.push(child); } else if (child instanceof _parchment2.default.Container) { lines = lines.concat(getLines(child, index, lengthLeft)); } lengthLeft -= length; }); return lines; }; return getLines(this, index, length); } }, { key: 'optimize', value: function optimize() { var mutations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this.batch === true) return; _get(Scroll.prototype.__proto__ || Object.getPrototypeOf(Scroll.prototype), 'optimize', this).call(this, mutations, context); if (mutations.length > 0) { this.emitter.emit(_emitter2.default.events.SCROLL_OPTIMIZE, mutations, context); } } }, { key: 'path', value: function path(index) { return _get(Scroll.prototype.__proto__ || Object.getPrototypeOf(Scroll.prototype), 'path', this).call(this, index).slice(1); // Exclude self } }, { key: 'update', value: function update(mutations) { if (this.batch === true) return; var source = _emitter2.default.sources.USER; if (typeof mutations === 'string') { source = mutations; } if (!Array.isArray(mutations)) { mutations = this.observer.takeRecords(); } if (mutations.length > 0) { this.emitter.emit(_emitter2.default.events.SCROLL_BEFORE_UPDATE, source, mutations); } _get(Scroll.prototype.__proto__ || Object.getPrototypeOf(Scroll.prototype), 'update', this).call(this, mutations.concat([])); // pass copy if (mutations.length > 0) { this.emitter.emit(_emitter2.default.events.SCROLL_UPDATE, source, mutations); } } }]); return Scroll; }(_parchment2.default.Scroll); Scroll.blotName = 'scroll'; Scroll.className = 'ql-editor'; Scroll.tagName = 'DIV'; Scroll.defaultChild = 'block'; Scroll.allowedChildren = [_block2.default, _block.BlockEmbed, _container2.default]; exports.default = Scroll; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SHORTKEY = exports.default = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _clone = __webpack_require__(21); var _clone2 = _interopRequireDefault(_clone); var _deepEqual = __webpack_require__(11); var _deepEqual2 = _interopRequireDefault(_deepEqual); var _extend = __webpack_require__(3); var _extend2 = _interopRequireDefault(_extend); var _quillDelta = __webpack_require__(2); var _quillDelta2 = _interopRequireDefault(_quillDelta); var _op = __webpack_require__(20); var _op2 = _interopRequireDefault(_op); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _quill = __webpack_require__(5); var _quill2 = _interopRequireDefault(_quill); var _logger = __webpack_require__(10); var _logger2 = _interopRequireDefault(_logger); var _module = __webpack_require__(9); var _module2 = _interopRequireDefault(_module); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var debug = (0, _logger2.default)('quill:keyboard'); var SHORTKEY = /Mac/i.test(navigator.platform) ? 'metaKey' : 'ctrlKey'; var Keyboard = function (_Module) { _inherits(Keyboard, _Module); _createClass(Keyboard, null, [{ key: 'match', value: function match(evt, binding) { binding = normalize(binding); if (['altKey', 'ctrlKey', 'metaKey', 'shiftKey'].some(function (key) { return !!binding[key] !== evt[key] && binding[key] !== null; })) { return false; } return binding.key === (evt.which || evt.keyCode); } }]); function Keyboard(quill, options) { _classCallCheck(this, Keyboard); var _this = _possibleConstructorReturn(this, (Keyboard.__proto__ || Object.getPrototypeOf(Keyboard)).call(this, quill, options)); _this.bindings = {}; Object.keys(_this.options.bindings).forEach(function (name) { if (name === 'list autofill' && quill.scroll.whitelist != null && !quill.scroll.whitelist['list']) { return; } if (_this.options.bindings[name]) { _this.addBinding(_this.options.bindings[name]); } }); _this.addBinding({ key: Keyboard.keys.ENTER, shiftKey: null }, handleEnter); _this.addBinding({ key: Keyboard.keys.ENTER, metaKey: null, ctrlKey: null, altKey: null }, function () {}); if (/Firefox/i.test(navigator.userAgent)) { // Need to handle delete and backspace for Firefox in the general case #1171 _this.addBinding({ key: Keyboard.keys.BACKSPACE }, { collapsed: true }, handleBackspace); _this.addBinding({ key: Keyboard.keys.DELETE }, { collapsed: true }, handleDelete); } else { _this.addBinding({ key: Keyboard.keys.BACKSPACE }, { collapsed: true, prefix: /^.?$/ }, handleBackspace); _this.addBinding({ key: Keyboard.keys.DELETE }, { collapsed: true, suffix: /^.?$/ }, handleDelete); } _this.addBinding({ key: Keyboard.keys.BACKSPACE }, { collapsed: false }, handleDeleteRange); _this.addBinding({ key: Keyboard.keys.DELETE }, { collapsed: false }, handleDeleteRange); _this.addBinding({ key: Keyboard.keys.BACKSPACE, altKey: null, ctrlKey: null, metaKey: null, shiftKey: null }, { collapsed: true, offset: 0 }, handleBackspace); _this.listen(); return _this; } _createClass(Keyboard, [{ key: 'addBinding', value: function addBinding(key) { var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var handler = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var binding = normalize(key); if (binding == null || binding.key == null) { return debug.warn('Attempted to add invalid keyboard binding', binding); } if (typeof context === 'function') { context = { handler: context }; } if (typeof handler === 'function') { handler = { handler: handler }; } binding = (0, _extend2.default)(binding, context, handler); this.bindings[binding.key] = this.bindings[binding.key] || []; this.bindings[binding.key].push(binding); } }, { key: 'listen', value: function listen() { var _this2 = this; this.quill.root.addEventListener('keydown', function (evt) { if (evt.defaultPrevented) return; var which = evt.which || evt.keyCode; var bindings = (_this2.bindings[which] || []).filter(function (binding) { return Keyboard.match(evt, binding); }); if (bindings.length === 0) return; var range = _this2.quill.getSelection(); if (range == null || !_this2.quill.hasFocus()) return; var _quill$getLine = _this2.quill.getLine(range.index), _quill$getLine2 = _slicedToArray(_quill$getLine, 2), line = _quill$getLine2[0], offset = _quill$getLine2[1]; var _quill$getLeaf = _this2.quill.getLeaf(range.index), _quill$getLeaf2 = _slicedToArray(_quill$getLeaf, 2), leafStart = _quill$getLeaf2[0], offsetStart = _quill$getLeaf2[1]; var _ref = range.length === 0 ? [leafStart, offsetStart] : _this2.quill.getLeaf(range.index + range.length), _ref2 = _slicedToArray(_ref, 2), leafEnd = _ref2[0], offsetEnd = _ref2[1]; var prefixText = leafStart instanceof _parchment2.default.Text ? leafStart.value().slice(0, offsetStart) : ''; var suffixText = leafEnd instanceof _parchment2.default.Text ? leafEnd.value().slice(offsetEnd) : ''; var curContext = { collapsed: range.length === 0, empty: range.length === 0 && line.length() <= 1, format: _this2.quill.getFormat(range), offset: offset, prefix: prefixText, suffix: suffixText }; var prevented = bindings.some(function (binding) { if (binding.collapsed != null && binding.collapsed !== curContext.collapsed) return false; if (binding.empty != null && binding.empty !== curContext.empty) return false; if (binding.offset != null && binding.offset !== curContext.offset) return false; if (Array.isArray(binding.format)) { // any format is present if (binding.format.every(function (name) { return curContext.format[name] == null; })) { return false; } } else if (_typeof(binding.format) === 'object') { // all formats must match if (!Object.keys(binding.format).every(function (name) { if (binding.format[name] === true) return curContext.format[name] != null; if (binding.format[name] === false) return curContext.format[name] == null; return (0, _deepEqual2.default)(binding.format[name], curContext.format[name]); })) { return false; } } if (binding.prefix != null && !binding.prefix.test(curContext.prefix)) return false; if (binding.suffix != null && !binding.suffix.test(curContext.suffix)) return false; return binding.handler.call(_this2, range, curContext) !== true; }); if (prevented) { evt.preventDefault(); } }); } }]); return Keyboard; }(_module2.default); Keyboard.keys = { BACKSPACE: 8, TAB: 9, ENTER: 13, ESCAPE: 27, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, DELETE: 46 }; Keyboard.DEFAULTS = { bindings: { 'bold': makeFormatHandler('bold'), 'italic': makeFormatHandler('italic'), 'underline': makeFormatHandler('underline'), 'indent': { // highlight tab or tab at beginning of list, indent or blockquote key: Keyboard.keys.TAB, format: ['blockquote', 'indent', 'list'], handler: function handler(range, context) { if (context.collapsed && context.offset !== 0) return true; this.quill.format('indent', '+1', _quill2.default.sources.USER); } }, 'outdent': { key: Keyboard.keys.TAB, shiftKey: true, format: ['blockquote', 'indent', 'list'], // highlight tab or tab at beginning of list, indent or blockquote handler: function handler(range, context) { if (context.collapsed && context.offset !== 0) return true; this.quill.format('indent', '-1', _quill2.default.sources.USER); } }, 'outdent backspace': { key: Keyboard.keys.BACKSPACE, collapsed: true, shiftKey: null, metaKey: null, ctrlKey: null, altKey: null, format: ['indent', 'list'], offset: 0, handler: function handler(range, context) { if (context.format.indent != null) { this.quill.format('indent', '-1', _quill2.default.sources.USER); } else if (context.format.list != null) { this.quill.format('list', false, _quill2.default.sources.USER); } } }, 'indent code-block': makeCodeBlockHandler(true), 'outdent code-block': makeCodeBlockHandler(false), 'remove tab': { key: Keyboard.keys.TAB, shiftKey: true, collapsed: true, prefix: /\t$/, handler: function handler(range) { this.quill.deleteText(range.index - 1, 1, _quill2.default.sources.USER); } }, 'tab': { key: Keyboard.keys.TAB, handler: function handler(range) { this.quill.history.cutoff(); var delta = new _quillDelta2.default().retain(range.index).delete(range.length).insert('\t'); this.quill.updateContents(delta, _quill2.default.sources.USER); this.quill.history.cutoff(); this.quill.setSelection(range.index + 1, _quill2.default.sources.SILENT); } }, 'list empty enter': { key: Keyboard.keys.ENTER, collapsed: true, format: ['list'], empty: true, handler: function handler(range, context) { this.quill.format('list', false, _quill2.default.sources.USER); if (context.format.indent) { this.quill.format('indent', false, _quill2.default.sources.USER); } } }, 'checklist enter': { key: Keyboard.keys.ENTER, collapsed: true, format: { list: 'checked' }, handler: function handler(range) { var _quill$getLine3 = this.quill.getLine(range.index), _quill$getLine4 = _slicedToArray(_quill$getLine3, 2), line = _quill$getLine4[0], offset = _quill$getLine4[1]; var formats = (0, _extend2.default)({}, line.formats(), { list: 'checked' }); var delta = new _quillDelta2.default().retain(range.index).insert('\n', formats).retain(line.length() - offset - 1).retain(1, { list: 'unchecked' }); this.quill.updateContents(delta, _quill2.default.sources.USER); this.quill.setSelection(range.index + 1, _quill2.default.sources.SILENT); this.quill.scrollIntoView(); } }, 'header enter': { key: Keyboard.keys.ENTER, collapsed: true, format: ['header'], suffix: /^$/, handler: function handler(range, context) { var _quill$getLine5 = this.quill.getLine(range.index), _quill$getLine6 = _slicedToArray(_quill$getLine5, 2), line = _quill$getLine6[0], offset = _quill$getLine6[1]; var delta = new _quillDelta2.default().retain(range.index).insert('\n', context.format).retain(line.length() - offset - 1).retain(1, { header: null }); this.quill.updateContents(delta, _quill2.default.sources.USER); this.quill.setSelection(range.index + 1, _quill2.default.sources.SILENT); this.quill.scrollIntoView(); } }, 'list autofill': { key: ' ', collapsed: true, format: { list: false }, prefix: /^\s*?(\d+\.|-|\*|\[ ?\]|\[x\])$/, handler: function handler(range, context) { var length = context.prefix.length; var _quill$getLine7 = this.quill.getLine(range.index), _quill$getLine8 = _slicedToArray(_quill$getLine7, 2), line = _quill$getLine8[0], offset = _quill$getLine8[1]; if (offset > length) return true; var value = void 0; switch (context.prefix.trim()) { case '[]':case '[ ]': value = 'unchecked'; break; case '[x]': value = 'checked'; break; case '-':case '*': value = 'bullet'; break; default: value = 'ordered'; } this.quill.insertText(range.index, ' ', _quill2.default.sources.USER); this.quill.history.cutoff(); var delta = new _quillDelta2.default().retain(range.index - offset).delete(length + 1).retain(line.length() - 2 - offset).retain(1, { list: value }); this.quill.updateContents(delta, _quill2.default.sources.USER); this.quill.history.cutoff(); this.quill.setSelection(range.index - length, _quill2.default.sources.SILENT); } }, 'code exit': { key: Keyboard.keys.ENTER, collapsed: true, format: ['code-block'], prefix: /\n\n$/, suffix: /^\s+$/, handler: function handler(range) { var _quill$getLine9 = this.quill.getLine(range.index), _quill$getLine10 = _slicedToArray(_quill$getLine9, 2), line = _quill$getLine10[0], offset = _quill$getLine10[1]; var delta = new _quillDelta2.default().retain(range.index + line.length() - offset - 2).retain(1, { 'code-block': null }).delete(1); this.quill.updateContents(delta, _quill2.default.sources.USER); } }, 'embed left': makeEmbedArrowHandler(Keyboard.keys.LEFT, false), 'embed left shift': makeEmbedArrowHandler(Keyboard.keys.LEFT, true), 'embed right': makeEmbedArrowHandler(Keyboard.keys.RIGHT, false), 'embed right shift': makeEmbedArrowHandler(Keyboard.keys.RIGHT, true) } }; function makeEmbedArrowHandler(key, shiftKey) { var _ref3; var where = key === Keyboard.keys.LEFT ? 'prefix' : 'suffix'; return _ref3 = { key: key, shiftKey: shiftKey, altKey: null }, _defineProperty(_ref3, where, /^$/), _defineProperty(_ref3, 'handler', function handler(range) { var index = range.index; if (key === Keyboard.keys.RIGHT) { index += range.length + 1; } var _quill$getLeaf3 = this.quill.getLeaf(index), _quill$getLeaf4 = _slicedToArray(_quill$getLeaf3, 1), leaf = _quill$getLeaf4[0]; if (!(leaf instanceof _parchment2.default.Embed)) return true; if (key === Keyboard.keys.LEFT) { if (shiftKey) { this.quill.setSelection(range.index - 1, range.length + 1, _quill2.default.sources.USER); } else { this.quill.setSelection(range.index - 1, _quill2.default.sources.USER); } } else { if (shiftKey) { this.quill.setSelection(range.index, range.length + 1, _quill2.default.sources.USER); } else { this.quill.setSelection(range.index + range.length + 1, _quill2.default.sources.USER); } } return false; }), _ref3; } function handleBackspace(range, context) { if (range.index === 0 || this.quill.getLength() <= 1) return; var _quill$getLine11 = this.quill.getLine(range.index), _quill$getLine12 = _slicedToArray(_quill$getLine11, 1), line = _quill$getLine12[0]; var formats = {}; if (context.offset === 0) { var _quill$getLine13 = this.quill.getLine(range.index - 1), _quill$getLine14 = _slicedToArray(_quill$getLine13, 1), prev = _quill$getLine14[0]; if (prev != null && prev.length() > 1) { var curFormats = line.formats(); var prevFormats = this.quill.getFormat(range.index - 1, 1); formats = _op2.default.attributes.diff(curFormats, prevFormats) || {}; } } // Check for astral symbols var length = /[\uD800-\uDBFF][\uDC00-\uDFFF]$/.test(context.prefix) ? 2 : 1; this.quill.deleteText(range.index - length, length, _quill2.default.sources.USER); if (Object.keys(formats).length > 0) { this.quill.formatLine(range.index - length, length, formats, _quill2.default.sources.USER); } this.quill.focus(); } function handleDelete(range, context) { // Check for astral symbols var length = /^[\uD800-\uDBFF][\uDC00-\uDFFF]/.test(context.suffix) ? 2 : 1; if (range.index >= this.quill.getLength() - length) return; var formats = {}, nextLength = 0; var _quill$getLine15 = this.quill.getLine(range.index), _quill$getLine16 = _slicedToArray(_quill$getLine15, 1), line = _quill$getLine16[0]; if (context.offset >= line.length() - 1) { var _quill$getLine17 = this.quill.getLine(range.index + 1), _quill$getLine18 = _slicedToArray(_quill$getLine17, 1), next = _quill$getLine18[0]; if (next) { var curFormats = line.formats(); var nextFormats = this.quill.getFormat(range.index, 1); formats = _op2.default.attributes.diff(curFormats, nextFormats) || {}; nextLength = next.length(); } } this.quill.deleteText(range.index, length, _quill2.default.sources.USER); if (Object.keys(formats).length > 0) { this.quill.formatLine(range.index + nextLength - 1, length, formats, _quill2.default.sources.USER); } } function handleDeleteRange(range) { var lines = this.quill.getLines(range); var formats = {}; if (lines.length > 1) { var firstFormats = lines[0].formats(); var lastFormats = lines[lines.length - 1].formats(); formats = _op2.default.attributes.diff(lastFormats, firstFormats) || {}; } this.quill.deleteText(range, _quill2.default.sources.USER); if (Object.keys(formats).length > 0) { this.quill.formatLine(range.index, 1, formats, _quill2.default.sources.USER); } this.quill.setSelection(range.index, _quill2.default.sources.SILENT); this.quill.focus(); } function handleEnter(range, context) { var _this3 = this; if (range.length > 0) { this.quill.scroll.deleteAt(range.index, range.length); // So we do not trigger text-change } var lineFormats = Object.keys(context.format).reduce(function (lineFormats, format) { if (_parchment2.default.query(format, _parchment2.default.Scope.BLOCK) && !Array.isArray(context.format[format])) { lineFormats[format] = context.format[format]; } return lineFormats; }, {}); this.quill.insertText(range.index, '\n', lineFormats, _quill2.default.sources.USER); // Earlier scroll.deleteAt might have messed up our selection, // so insertText's built in selection preservation is not reliable this.quill.setSelection(range.index + 1, _quill2.default.sources.SILENT); this.quill.focus(); Object.keys(context.format).forEach(function (name) { if (lineFormats[name] != null) return; if (Array.isArray(context.format[name])) return; if (name === 'link') return; _this3.quill.format(name, context.format[name], _quill2.default.sources.USER); }); } function makeCodeBlockHandler(indent) { return { key: Keyboard.keys.TAB, shiftKey: !indent, format: { 'code-block': true }, handler: function handler(range) { var CodeBlock = _parchment2.default.query('code-block'); var index = range.index, length = range.length; var _quill$scroll$descend = this.quill.scroll.descendant(CodeBlock, index), _quill$scroll$descend2 = _slicedToArray(_quill$scroll$descend, 2), block = _quill$scroll$descend2[0], offset = _quill$scroll$descend2[1]; if (block == null) return; var scrollIndex = this.quill.getIndex(block); var start = block.newlineIndex(offset, true) + 1; var end = block.newlineIndex(scrollIndex + offset + length); var lines = block.domNode.textContent.slice(start, end).split('\n'); offset = 0; lines.forEach(function (line, i) { if (indent) { block.insertAt(start + offset, CodeBlock.TAB); offset += CodeBlock.TAB.length; if (i === 0) { index += CodeBlock.TAB.length; } else { length += CodeBlock.TAB.length; } } else if (line.startsWith(CodeBlock.TAB)) { block.deleteAt(start + offset, CodeBlock.TAB.length); offset -= CodeBlock.TAB.length; if (i === 0) { index -= CodeBlock.TAB.length; } else { length -= CodeBlock.TAB.length; } } offset += line.length + 1; }); this.quill.update(_quill2.default.sources.USER); this.quill.setSelection(index, length, _quill2.default.sources.SILENT); } }; } function makeFormatHandler(format) { return { key: format[0].toUpperCase(), shortKey: true, handler: function handler(range, context) { this.quill.format(format, !context.format[format], _quill2.default.sources.USER); } }; } function normalize(binding) { if (typeof binding === 'string' || typeof binding === 'number') { return normalize({ key: binding }); } if ((typeof binding === 'undefined' ? 'undefined' : _typeof(binding)) === 'object') { binding = (0, _clone2.default)(binding, false); } if (typeof binding.key === 'string') { if (Keyboard.keys[binding.key.toUpperCase()] != null) { binding.key = Keyboard.keys[binding.key.toUpperCase()]; } else if (binding.key.length === 1) { binding.key = binding.key.toUpperCase().charCodeAt(0); } else { return null; } } if (binding.shortKey) { binding[SHORTKEY] = binding.shortKey; delete binding.shortKey; } return binding; } exports.default = Keyboard; exports.SHORTKEY = SHORTKEY; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _text = __webpack_require__(7); var _text2 = _interopRequireDefault(_text); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Cursor = function (_Parchment$Embed) { _inherits(Cursor, _Parchment$Embed); _createClass(Cursor, null, [{ key: 'value', value: function value() { return undefined; } }]); function Cursor(domNode, selection) { _classCallCheck(this, Cursor); var _this = _possibleConstructorReturn(this, (Cursor.__proto__ || Object.getPrototypeOf(Cursor)).call(this, domNode)); _this.selection = selection; _this.textNode = document.createTextNode(Cursor.CONTENTS); _this.domNode.appendChild(_this.textNode); _this._length = 0; return _this; } _createClass(Cursor, [{ key: 'detach', value: function detach() { // super.detach() will also clear domNode.__blot if (this.parent != null) this.parent.removeChild(this); } }, { key: 'format', value: function format(name, value) { if (this._length !== 0) { return _get(Cursor.prototype.__proto__ || Object.getPrototypeOf(Cursor.prototype), 'format', this).call(this, name, value); } var target = this, index = 0; while (target != null && target.statics.scope !== _parchment2.default.Scope.BLOCK_BLOT) { index += target.offset(target.parent); target = target.parent; } if (target != null) { this._length = Cursor.CONTENTS.length; target.optimize(); target.formatAt(index, Cursor.CONTENTS.length, name, value); this._length = 0; } } }, { key: 'index', value: function index(node, offset) { if (node === this.textNode) return 0; return _get(Cursor.prototype.__proto__ || Object.getPrototypeOf(Cursor.prototype), 'index', this).call(this, node, offset); } }, { key: 'length', value: function length() { return this._length; } }, { key: 'position', value: function position() { return [this.textNode, this.textNode.data.length]; } }, { key: 'remove', value: function remove() { _get(Cursor.prototype.__proto__ || Object.getPrototypeOf(Cursor.prototype), 'remove', this).call(this); this.parent = null; } }, { key: 'restore', value: function restore() { if (this.selection.composing || this.parent == null) return; var textNode = this.textNode; var range = this.selection.getNativeRange(); var restoreText = void 0, start = void 0, end = void 0; if (range != null && range.start.node === textNode && range.end.node === textNode) { var _ref = [textNode, range.start.offset, range.end.offset]; restoreText = _ref[0]; start = _ref[1]; end = _ref[2]; } // Link format will insert text outside of anchor tag while (this.domNode.lastChild != null && this.domNode.lastChild !== this.textNode) { this.domNode.parentNode.insertBefore(this.domNode.lastChild, this.domNode); } if (this.textNode.data !== Cursor.CONTENTS) { var text = this.textNode.data.split(Cursor.CONTENTS).join(''); if (this.next instanceof _text2.default) { restoreText = this.next.domNode; this.next.insertAt(0, text); this.textNode.data = Cursor.CONTENTS; } else { this.textNode.data = text; this.parent.insertBefore(_parchment2.default.create(this.textNode), this); this.textNode = document.createTextNode(Cursor.CONTENTS); this.domNode.appendChild(this.textNode); } } this.remove(); if (start != null) { var _map = [start, end].map(function (offset) { return Math.max(0, Math.min(restoreText.data.length, offset - 1)); }); var _map2 = _slicedToArray(_map, 2); start = _map2[0]; end = _map2[1]; return { startNode: restoreText, startOffset: start, endNode: restoreText, endOffset: end }; } } }, { key: 'update', value: function update(mutations, context) { var _this2 = this; if (mutations.some(function (mutation) { return mutation.type === 'characterData' && mutation.target === _this2.textNode; })) { var range = this.restore(); if (range) context.range = range; } } }, { key: 'value', value: function value() { return ''; } }]); return Cursor; }(_parchment2.default.Embed); Cursor.blotName = 'cursor'; Cursor.className = 'ql-cursor'; Cursor.tagName = 'span'; Cursor.CONTENTS = '\uFEFF'; // Zero width no break space exports.default = Cursor; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _block = __webpack_require__(4); var _block2 = _interopRequireDefault(_block); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Container = function (_Parchment$Container) { _inherits(Container, _Parchment$Container); function Container() { _classCallCheck(this, Container); return _possibleConstructorReturn(this, (Container.__proto__ || Object.getPrototypeOf(Container)).apply(this, arguments)); } return Container; }(_parchment2.default.Container); Container.allowedChildren = [_block2.default, _block.BlockEmbed, Container]; exports.default = Container; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ColorStyle = exports.ColorClass = exports.ColorAttributor = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ColorAttributor = function (_Parchment$Attributor) { _inherits(ColorAttributor, _Parchment$Attributor); function ColorAttributor() { _classCallCheck(this, ColorAttributor); return _possibleConstructorReturn(this, (ColorAttributor.__proto__ || Object.getPrototypeOf(ColorAttributor)).apply(this, arguments)); } _createClass(ColorAttributor, [{ key: 'value', value: function value(domNode) { var value = _get(ColorAttributor.prototype.__proto__ || Object.getPrototypeOf(ColorAttributor.prototype), 'value', this).call(this, domNode); if (!value.startsWith('rgb(')) return value; value = value.replace(/^[^\d]+/, '').replace(/[^\d]+$/, ''); return '#' + value.split(',').map(function (component) { return ('00' + parseInt(component).toString(16)).slice(-2); }).join(''); } }]); return ColorAttributor; }(_parchment2.default.Attributor.Style); var ColorClass = new _parchment2.default.Attributor.Class('color', 'ql-color', { scope: _parchment2.default.Scope.INLINE }); var ColorStyle = new ColorAttributor('color', 'color', { scope: _parchment2.default.Scope.INLINE }); exports.ColorAttributor = ColorAttributor; exports.ColorClass = ColorClass; exports.ColorStyle = ColorStyle; /***/ }), /* 27 */, /* 28 */, /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _quill = __webpack_require__(5); var _quill2 = _interopRequireDefault(_quill); var _block = __webpack_require__(4); var _block2 = _interopRequireDefault(_block); var _break = __webpack_require__(16); var _break2 = _interopRequireDefault(_break); var _container = __webpack_require__(25); var _container2 = _interopRequireDefault(_container); var _cursor = __webpack_require__(24); var _cursor2 = _interopRequireDefault(_cursor); var _embed = __webpack_require__(35); var _embed2 = _interopRequireDefault(_embed); var _inline = __webpack_require__(6); var _inline2 = _interopRequireDefault(_inline); var _scroll = __webpack_require__(22); var _scroll2 = _interopRequireDefault(_scroll); var _text = __webpack_require__(7); var _text2 = _interopRequireDefault(_text); var _clipboard = __webpack_require__(55); var _clipboard2 = _interopRequireDefault(_clipboard); var _history = __webpack_require__(42); var _history2 = _interopRequireDefault(_history); var _keyboard = __webpack_require__(23); var _keyboard2 = _interopRequireDefault(_keyboard); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _quill2.default.register({ 'blots/block': _block2.default, 'blots/block/embed': _block.BlockEmbed, 'blots/break': _break2.default, 'blots/container': _container2.default, 'blots/cursor': _cursor2.default, 'blots/embed': _embed2.default, 'blots/inline': _inline2.default, 'blots/scroll': _scroll2.default, 'blots/text': _text2.default, 'modules/clipboard': _clipboard2.default, 'modules/history': _history2.default, 'modules/keyboard': _keyboard2.default }); _parchment2.default.register(_block2.default, _break2.default, _cursor2.default, _inline2.default, _scroll2.default, _text2.default); exports.default = _quill2.default; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Registry = __webpack_require__(1); var ShadowBlot = /** @class */ (function () { function ShadowBlot(domNode) { this.domNode = domNode; // @ts-ignore this.domNode[Registry.DATA_KEY] = { blot: this }; } Object.defineProperty(ShadowBlot.prototype, "statics", { // Hack for accessing inherited static methods get: function () { return this.constructor; }, enumerable: true, configurable: true }); ShadowBlot.create = function (value) { if (this.tagName == null) { throw new Registry.ParchmentError('Blot definition missing tagName'); } var node; if (Array.isArray(this.tagName)) { if (typeof value === 'string') { value = value.toUpperCase(); if (parseInt(value).toString() === value) { value = parseInt(value); } } if (typeof value === 'number') { node = document.createElement(this.tagName[value - 1]); } else if (this.tagName.indexOf(value) > -1) { node = document.createElement(value); } else { node = document.createElement(this.tagName[0]); } } else { node = document.createElement(this.tagName); } if (this.className) { node.classList.add(this.className); } return node; }; ShadowBlot.prototype.attach = function () { if (this.parent != null) { this.scroll = this.parent.scroll; } }; ShadowBlot.prototype.clone = function () { var domNode = this.domNode.cloneNode(false); return Registry.create(domNode); }; ShadowBlot.prototype.detach = function () { if (this.parent != null) this.parent.removeChild(this); // @ts-ignore delete this.domNode[Registry.DATA_KEY]; }; ShadowBlot.prototype.deleteAt = function (index, length) { var blot = this.isolate(index, length); blot.remove(); }; ShadowBlot.prototype.formatAt = function (index, length, name, value) { var blot = this.isolate(index, length); if (Registry.query(name, Registry.Scope.BLOT) != null && value) { blot.wrap(name, value); } else if (Registry.query(name, Registry.Scope.ATTRIBUTE) != null) { var parent = Registry.create(this.statics.scope); blot.wrap(parent); parent.format(name, value); } }; ShadowBlot.prototype.insertAt = function (index, value, def) { var blot = def == null ? Registry.create('text', value) : Registry.create(value, def); var ref = this.split(index); this.parent.insertBefore(blot, ref); }; ShadowBlot.prototype.insertInto = function (parentBlot, refBlot) { if (refBlot === void 0) { refBlot = null; } if (this.parent != null) { this.parent.children.remove(this); } var refDomNode = null; parentBlot.children.insertBefore(this, refBlot); if (refBlot != null) { refDomNode = refBlot.domNode; } if (this.domNode.parentNode != parentBlot.domNode || this.domNode.nextSibling != refDomNode) { parentBlot.domNode.insertBefore(this.domNode, refDomNode); } this.parent = parentBlot; this.attach(); }; ShadowBlot.prototype.isolate = function (index, length) { var target = this.split(index); target.split(length); return target; }; ShadowBlot.prototype.length = function () { return 1; }; ShadowBlot.prototype.offset = function (root) { if (root === void 0) { root = this.parent; } if (this.parent == null || this == root) return 0; return this.parent.children.offset(this) + this.parent.offset(root); }; ShadowBlot.prototype.optimize = function (context) { // TODO clean up once we use WeakMap // @ts-ignore if (this.domNode[Registry.DATA_KEY] != null) { // @ts-ignore delete this.domNode[Registry.DATA_KEY].mutations; } }; ShadowBlot.prototype.remove = function () { if (this.domNode.parentNode != null) { this.domNode.parentNode.removeChild(this.domNode); } this.detach(); }; ShadowBlot.prototype.replace = function (target) { if (target.parent == null) return; target.parent.insertBefore(this, target.next); target.remove(); }; ShadowBlot.prototype.replaceWith = function (name, value) { var replacement = typeof name === 'string' ? Registry.create(name, value) : name; replacement.replace(this); return replacement; }; ShadowBlot.prototype.split = function (index, force) { return index === 0 ? this : this.next; }; ShadowBlot.prototype.update = function (mutations, context) { // Nothing to do by default }; ShadowBlot.prototype.wrap = function (name, value) { var wrapper = typeof name === 'string' ? Registry.create(name, value) : name; if (this.parent != null) { this.parent.insertBefore(wrapper, this.next); } wrapper.appendChild(this); return wrapper; }; ShadowBlot.blotName = 'abstract'; return ShadowBlot; }()); exports.default = ShadowBlot; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var attributor_1 = __webpack_require__(12); var class_1 = __webpack_require__(32); var style_1 = __webpack_require__(33); var Registry = __webpack_require__(1); var AttributorStore = /** @class */ (function () { function AttributorStore(domNode) { this.attributes = {}; this.domNode = domNode; this.build(); } AttributorStore.prototype.attribute = function (attribute, value) { // verb if (value) { if (attribute.add(this.domNode, value)) { if (attribute.value(this.domNode) != null) { this.attributes[attribute.attrName] = attribute; } else { delete this.attributes[attribute.attrName]; } } } else { attribute.remove(this.domNode); delete this.attributes[attribute.attrName]; } }; AttributorStore.prototype.build = function () { var _this = this; this.attributes = {}; var attributes = attributor_1.default.keys(this.domNode); var classes = class_1.default.keys(this.domNode); var styles = style_1.default.keys(this.domNode); attributes .concat(classes) .concat(styles) .forEach(function (name) { var attr = Registry.query(name, Registry.Scope.ATTRIBUTE); if (attr instanceof attributor_1.default) { _this.attributes[attr.attrName] = attr; } }); }; AttributorStore.prototype.copy = function (target) { var _this = this; Object.keys(this.attributes).forEach(function (key) { var value = _this.attributes[key].value(_this.domNode); target.format(key, value); }); }; AttributorStore.prototype.move = function (target) { var _this = this; this.copy(target); Object.keys(this.attributes).forEach(function (key) { _this.attributes[key].remove(_this.domNode); }); this.attributes = {}; }; AttributorStore.prototype.values = function () { var _this = this; return Object.keys(this.attributes).reduce(function (attributes, name) { attributes[name] = _this.attributes[name].value(_this.domNode); return attributes; }, {}); }; return AttributorStore; }()); exports.default = AttributorStore; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var attributor_1 = __webpack_require__(12); function match(node, prefix) { var className = node.getAttribute('class') || ''; return className.split(/\s+/).filter(function (name) { return name.indexOf(prefix + "-") === 0; }); } var ClassAttributor = /** @class */ (function (_super) { __extends(ClassAttributor, _super); function ClassAttributor() { return _super !== null && _super.apply(this, arguments) || this; } ClassAttributor.keys = function (node) { return (node.getAttribute('class') || '').split(/\s+/).map(function (name) { return name .split('-') .slice(0, -1) .join('-'); }); }; ClassAttributor.prototype.add = function (node, value) { if (!this.canAdd(node, value)) return false; this.remove(node); node.classList.add(this.keyName + "-" + value); return true; }; ClassAttributor.prototype.remove = function (node) { var matches = match(node, this.keyName); matches.forEach(function (name) { node.classList.remove(name); }); if (node.classList.length === 0) { node.removeAttribute('class'); } }; ClassAttributor.prototype.value = function (node) { var result = match(node, this.keyName)[0] || ''; var value = result.slice(this.keyName.length + 1); // +1 for hyphen return this.canAdd(node, value) ? value : ''; }; return ClassAttributor; }(attributor_1.default)); exports.default = ClassAttributor; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var attributor_1 = __webpack_require__(12); function camelize(name) { var parts = name.split('-'); var rest = parts .slice(1) .map(function (part) { return part[0].toUpperCase() + part.slice(1); }) .join(''); return parts[0] + rest; } var StyleAttributor = /** @class */ (function (_super) { __extends(StyleAttributor, _super); function StyleAttributor() { return _super !== null && _super.apply(this, arguments) || this; } StyleAttributor.keys = function (node) { return (node.getAttribute('style') || '').split(';').map(function (value) { var arr = value.split(':'); return arr[0].trim(); }); }; StyleAttributor.prototype.add = function (node, value) { if (!this.canAdd(node, value)) return false; // @ts-ignore node.style[camelize(this.keyName)] = value; return true; }; StyleAttributor.prototype.remove = function (node) { // @ts-ignore node.style[camelize(this.keyName)] = ''; if (!node.getAttribute('style')) { node.removeAttribute('style'); } }; StyleAttributor.prototype.value = function (node) { // @ts-ignore var value = node.style[camelize(this.keyName)]; return this.canAdd(node, value) ? value : ''; }; return StyleAttributor; }(attributor_1.default)); exports.default = StyleAttributor; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Theme = function () { function Theme(quill, options) { _classCallCheck(this, Theme); this.quill = quill; this.options = options; this.modules = {}; } _createClass(Theme, [{ key: 'init', value: function init() { var _this = this; Object.keys(this.options.modules).forEach(function (name) { if (_this.modules[name] == null) { _this.addModule(name); } }); } }, { key: 'addModule', value: function addModule(name) { var moduleClass = this.quill.constructor.import('modules/' + name); this.modules[name] = new moduleClass(this.quill, this.options.modules[name] || {}); return this.modules[name]; } }]); return Theme; }(); Theme.DEFAULTS = { modules: {} }; Theme.themes = { 'default': Theme }; exports.default = Theme; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _text = __webpack_require__(7); var _text2 = _interopRequireDefault(_text); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var GUARD_TEXT = '\uFEFF'; var Embed = function (_Parchment$Embed) { _inherits(Embed, _Parchment$Embed); function Embed(node) { _classCallCheck(this, Embed); var _this = _possibleConstructorReturn(this, (Embed.__proto__ || Object.getPrototypeOf(Embed)).call(this, node)); _this.contentNode = document.createElement('span'); _this.contentNode.setAttribute('contenteditable', false); [].slice.call(_this.domNode.childNodes).forEach(function (childNode) { _this.contentNode.appendChild(childNode); }); _this.leftGuard = document.createTextNode(GUARD_TEXT); _this.rightGuard = document.createTextNode(GUARD_TEXT); _this.domNode.appendChild(_this.leftGuard); _this.domNode.appendChild(_this.contentNode); _this.domNode.appendChild(_this.rightGuard); return _this; } _createClass(Embed, [{ key: 'index', value: function index(node, offset) { if (node === this.leftGuard) return 0; if (node === this.rightGuard) return 1; return _get(Embed.prototype.__proto__ || Object.getPrototypeOf(Embed.prototype), 'index', this).call(this, node, offset); } }, { key: 'restore', value: function restore(node) { var range = void 0, textNode = void 0; var text = node.data.split(GUARD_TEXT).join(''); if (node === this.leftGuard) { if (this.prev instanceof _text2.default) { var prevLength = this.prev.length(); this.prev.insertAt(prevLength, text); range = { startNode: this.prev.domNode, startOffset: prevLength + text.length }; } else { textNode = document.createTextNode(text); this.parent.insertBefore(_parchment2.default.create(textNode), this); range = { startNode: textNode, startOffset: text.length }; } } else if (node === this.rightGuard) { if (this.next instanceof _text2.default) { this.next.insertAt(0, text); range = { startNode: this.next.domNode, startOffset: text.length }; } else { textNode = document.createTextNode(text); this.parent.insertBefore(_parchment2.default.create(textNode), this.next); range = { startNode: textNode, startOffset: text.length }; } } node.data = GUARD_TEXT; return range; } }, { key: 'update', value: function update(mutations, context) { var _this2 = this; mutations.forEach(function (mutation) { if (mutation.type === 'characterData' && (mutation.target === _this2.leftGuard || mutation.target === _this2.rightGuard)) { var range = _this2.restore(mutation.target); if (range) context.range = range; } }); } }]); return Embed; }(_parchment2.default.Embed); exports.default = Embed; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AlignStyle = exports.AlignClass = exports.AlignAttribute = undefined; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var config = { scope: _parchment2.default.Scope.BLOCK, whitelist: ['right', 'center', 'justify'] }; var AlignAttribute = new _parchment2.default.Attributor.Attribute('align', 'align', config); var AlignClass = new _parchment2.default.Attributor.Class('align', 'ql-align', config); var AlignStyle = new _parchment2.default.Attributor.Style('align', 'text-align', config); exports.AlignAttribute = AlignAttribute; exports.AlignClass = AlignClass; exports.AlignStyle = AlignStyle; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BackgroundStyle = exports.BackgroundClass = undefined; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _color = __webpack_require__(26); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var BackgroundClass = new _parchment2.default.Attributor.Class('background', 'ql-bg', { scope: _parchment2.default.Scope.INLINE }); var BackgroundStyle = new _color.ColorAttributor('background', 'background-color', { scope: _parchment2.default.Scope.INLINE }); exports.BackgroundClass = BackgroundClass; exports.BackgroundStyle = BackgroundStyle; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DirectionStyle = exports.DirectionClass = exports.DirectionAttribute = undefined; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var config = { scope: _parchment2.default.Scope.BLOCK, whitelist: ['rtl'] }; var DirectionAttribute = new _parchment2.default.Attributor.Attribute('direction', 'dir', config); var DirectionClass = new _parchment2.default.Attributor.Class('direction', 'ql-direction', config); var DirectionStyle = new _parchment2.default.Attributor.Style('direction', 'direction', config); exports.DirectionAttribute = DirectionAttribute; exports.DirectionClass = DirectionClass; exports.DirectionStyle = DirectionStyle; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FontClass = exports.FontStyle = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var config = { scope: _parchment2.default.Scope.INLINE, whitelist: ['serif', 'monospace'] }; var FontClass = new _parchment2.default.Attributor.Class('font', 'ql-font', config); var FontStyleAttributor = function (_Parchment$Attributor) { _inherits(FontStyleAttributor, _Parchment$Attributor); function FontStyleAttributor() { _classCallCheck(this, FontStyleAttributor); return _possibleConstructorReturn(this, (FontStyleAttributor.__proto__ || Object.getPrototypeOf(FontStyleAttributor)).apply(this, arguments)); } _createClass(FontStyleAttributor, [{ key: 'value', value: function value(node) { return _get(FontStyleAttributor.prototype.__proto__ || Object.getPrototypeOf(FontStyleAttributor.prototype), 'value', this).call(this, node).replace(/["']/g, ''); } }]); return FontStyleAttributor; }(_parchment2.default.Attributor.Style); var FontStyle = new FontStyleAttributor('font', 'font-family', config); exports.FontStyle = FontStyle; exports.FontClass = FontClass; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SizeStyle = exports.SizeClass = undefined; var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SizeClass = new _parchment2.default.Attributor.Class('size', 'ql-size', { scope: _parchment2.default.Scope.INLINE, whitelist: ['small', 'large', 'huge'] }); var SizeStyle = new _parchment2.default.Attributor.Style('size', 'font-size', { scope: _parchment2.default.Scope.INLINE, whitelist: ['10px', '18px', '32px'] }); exports.SizeClass = SizeClass; exports.SizeStyle = SizeStyle; /***/ }), /* 41 */, /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getLastChangeIndex = exports.default = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _quill = __webpack_require__(5); var _quill2 = _interopRequireDefault(_quill); var _module = __webpack_require__(9); var _module2 = _interopRequireDefault(_module); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var History = function (_Module) { _inherits(History, _Module); function History(quill, options) { _classCallCheck(this, History); var _this = _possibleConstructorReturn(this, (History.__proto__ || Object.getPrototypeOf(History)).call(this, quill, options)); _this.lastRecorded = 0; _this.ignoreChange = false; _this.clear(); _this.quill.on(_quill2.default.events.EDITOR_CHANGE, function (eventName, delta, oldDelta, source) { if (eventName !== _quill2.default.events.TEXT_CHANGE || _this.ignoreChange) return; if (!_this.options.userOnly || source === _quill2.default.sources.USER) { _this.record(delta, oldDelta); } else { _this.transform(delta); } }); _this.quill.keyboard.addBinding({ key: 'Z', shortKey: true }, _this.undo.bind(_this)); _this.quill.keyboard.addBinding({ key: 'Z', shortKey: true, shiftKey: true }, _this.redo.bind(_this)); if (/Win/i.test(navigator.platform)) { _this.quill.keyboard.addBinding({ key: 'Y', shortKey: true }, _this.redo.bind(_this)); } return _this; } _createClass(History, [{ key: 'change', value: function change(source, dest) { if (this.stack[source].length === 0) return; var delta = this.stack[source].pop(); this.stack[dest].push(delta); this.lastRecorded = 0; this.ignoreChange = true; this.quill.updateContents(delta[source], _quill2.default.sources.USER); this.ignoreChange = false; var index = getLastChangeIndex(delta[source]); this.quill.setSelection(index); } }, { key: 'clear', value: function clear() { this.stack = { undo: [], redo: [] }; } }, { key: 'cutoff', value: function cutoff() { this.lastRecorded = 0; } }, { key: 'record', value: function record(changeDelta, oldDelta) { if (changeDelta.ops.length === 0) return; this.stack.redo = []; var undoDelta = this.quill.getContents().diff(oldDelta); var timestamp = Date.now(); if (this.lastRecorded + this.options.delay > timestamp && this.stack.undo.length > 0) { var delta = this.stack.undo.pop(); undoDelta = undoDelta.compose(delta.undo); changeDelta = delta.redo.compose(changeDelta); } else { this.lastRecorded = timestamp; } this.stack.undo.push({ redo: changeDelta, undo: undoDelta }); if (this.stack.undo.length > this.options.maxStack) { this.stack.undo.shift(); } } }, { key: 'redo', value: function redo() { this.change('redo', 'undo'); } }, { key: 'transform', value: function transform(delta) { this.stack.undo.forEach(function (change) { change.undo = delta.transform(change.undo, true); change.redo = delta.transform(change.redo, true); }); this.stack.redo.forEach(function (change) { change.undo = delta.transform(change.undo, true); change.redo = delta.transform(change.redo, true); }); } }, { key: 'undo', value: function undo() { this.change('undo', 'redo'); } }]); return History; }(_module2.default); History.DEFAULTS = { delay: 1000, maxStack: 100, userOnly: false }; function endsWithNewlineChange(delta) { var lastOp = delta.ops[delta.ops.length - 1]; if (lastOp == null) return false; if (lastOp.insert != null) { return typeof lastOp.insert === 'string' && lastOp.insert.endsWith('\n'); } if (lastOp.attributes != null) { return Object.keys(lastOp.attributes).some(function (attr) { return _parchment2.default.query(attr, _parchment2.default.Scope.BLOCK) != null; }); } return false; } function getLastChangeIndex(delta) { var deleteLength = delta.reduce(function (length, op) { length += op.delete || 0; return length; }, 0); var changeIndex = delta.length() - deleteLength; if (endsWithNewlineChange(delta)) { changeIndex -= 1; } return changeIndex; } exports.default = History; exports.getLastChangeIndex = getLastChangeIndex; /***/ }), /* 43 */, /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedList = /** @class */ (function () { function LinkedList() { this.head = this.tail = null; this.length = 0; } LinkedList.prototype.append = function () { var nodes = []; for (var _i = 0; _i < arguments.length; _i++) { nodes[_i] = arguments[_i]; } this.insertBefore(nodes[0], null); if (nodes.length > 1) { this.append.apply(this, nodes.slice(1)); } }; LinkedList.prototype.contains = function (node) { var cur, next = this.iterator(); while ((cur = next())) { if (cur === node) return true; } return false; }; LinkedList.prototype.insertBefore = function (node, refNode) { if (!node) return; node.next = refNode; if (refNode != null) { node.prev = refNode.prev; if (refNode.prev != null) { refNode.prev.next = node; } refNode.prev = node; if (refNode === this.head) { this.head = node; } } else if (this.tail != null) { this.tail.next = node; node.prev = this.tail; this.tail = node; } else { node.prev = null; this.head = this.tail = node; } this.length += 1; }; LinkedList.prototype.offset = function (target) { var index = 0, cur = this.head; while (cur != null) { if (cur === target) return index; index += cur.length(); cur = cur.next; } return -1; }; LinkedList.prototype.remove = function (node) { if (!this.contains(node)) return; if (node.prev != null) node.prev.next = node.next; if (node.next != null) node.next.prev = node.prev; if (node === this.head) this.head = node.next; if (node === this.tail) this.tail = node.prev; this.length -= 1; }; LinkedList.prototype.iterator = function (curNode) { if (curNode === void 0) { curNode = this.head; } // TODO use yield when we can return function () { var ret = curNode; if (curNode != null) curNode = curNode.next; return ret; }; }; LinkedList.prototype.find = function (index, inclusive) { if (inclusive === void 0) { inclusive = false; } var cur, next = this.iterator(); while ((cur = next())) { var length = cur.length(); if (index < length || (inclusive && index === length && (cur.next == null || cur.next.length() !== 0))) { return [cur, index]; } index -= length; } return [null, 0]; }; LinkedList.prototype.forEach = function (callback) { var cur, next = this.iterator(); while ((cur = next())) { callback(cur); } }; LinkedList.prototype.forEachAt = function (index, length, callback) { if (length <= 0) return; var _a = this.find(index), startNode = _a[0], offset = _a[1]; var cur, curIndex = index - offset, next = this.iterator(startNode); while ((cur = next()) && curIndex < index + length) { var curLength = cur.length(); if (index > curIndex) { callback(cur, index - curIndex, Math.min(length, curIndex + curLength - index)); } else { callback(cur, 0, Math.min(curLength, index + length - curIndex)); } curIndex += curLength; } }; LinkedList.prototype.map = function (callback) { return this.reduce(function (memo, cur) { memo.push(callback(cur)); return memo; }, []); }; LinkedList.prototype.reduce = function (callback, memo) { var cur, next = this.iterator(); while ((cur = next())) { memo = callback(memo, cur); } return memo; }; return LinkedList; }()); exports.default = LinkedList; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var container_1 = __webpack_require__(17); var Registry = __webpack_require__(1); var OBSERVER_CONFIG = { attributes: true, characterData: true, characterDataOldValue: true, childList: true, subtree: true, }; var MAX_OPTIMIZE_ITERATIONS = 100; var ScrollBlot = /** @class */ (function (_super) { __extends(ScrollBlot, _super); function ScrollBlot(node) { var _this = _super.call(this, node) || this; _this.scroll = _this; _this.observer = new MutationObserver(function (mutations) { _this.update(mutations); }); _this.observer.observe(_this.domNode, OBSERVER_CONFIG); _this.attach(); return _this; } ScrollBlot.prototype.detach = function () { _super.prototype.detach.call(this); this.observer.disconnect(); }; ScrollBlot.prototype.deleteAt = function (index, length) { this.update(); if (index === 0 && length === this.length()) { this.children.forEach(function (child) { child.remove(); }); } else { _super.prototype.deleteAt.call(this, index, length); } }; ScrollBlot.prototype.formatAt = function (index, length, name, value) { this.update(); _super.prototype.formatAt.call(this, index, length, name, value); }; ScrollBlot.prototype.insertAt = function (index, value, def) { this.update(); _super.prototype.insertAt.call(this, index, value, def); }; ScrollBlot.prototype.optimize = function (mutations, context) { var _this = this; if (mutations === void 0) { mutations = []; } if (context === void 0) { context = {}; } _super.prototype.optimize.call(this, context); // We must modify mutations directly, cannot make copy and then modify var records = [].slice.call(this.observer.takeRecords()); // Array.push currently seems to be implemented by a non-tail recursive function // so we cannot just mutations.push.apply(mutations, this.observer.takeRecords()); while (records.length > 0) mutations.push(records.pop()); // TODO use WeakMap var mark = function (blot, markParent) { if (markParent === void 0) { markParent = true; } if (blot == null || blot === _this) return; if (blot.domNode.parentNode == null) return; // @ts-ignore if (blot.domNode[Registry.DATA_KEY].mutations == null) { // @ts-ignore blot.domNode[Registry.DATA_KEY].mutations = []; } if (markParent) mark(blot.parent); }; var optimize = function (blot) { // Post-order traversal if ( // @ts-ignore blot.domNode[Registry.DATA_KEY] == null || // @ts-ignore blot.domNode[Registry.DATA_KEY].mutations == null) { return; } if (blot instanceof container_1.default) { blot.children.forEach(optimize); } blot.optimize(context); }; var remaining = mutations; for (var i = 0; remaining.length > 0; i += 1) { if (i >= MAX_OPTIMIZE_ITERATIONS) { throw new Error('[Parchment] Maximum optimize iterations reached'); } remaining.forEach(function (mutation) { var blot = Registry.find(mutation.target, true); if (blot == null) return; if (blot.domNode === mutation.target) { if (mutation.type === 'childList') { mark(Registry.find(mutation.previousSibling, false)); [].forEach.call(mutation.addedNodes, function (node) { var child = Registry.find(node, false); mark(child, false); if (child instanceof container_1.default) { child.children.forEach(function (grandChild) { mark(grandChild, false); }); } }); } else if (mutation.type === 'attributes') { mark(blot.prev); } } mark(blot); }); this.children.forEach(optimize); remaining = [].slice.call(this.observer.takeRecords()); records = remaining.slice(); while (records.length > 0) mutations.push(records.pop()); } }; ScrollBlot.prototype.update = function (mutations, context) { var _this = this; if (context === void 0) { context = {}; } mutations = mutations || this.observer.takeRecords(); // TODO use WeakMap mutations .map(function (mutation) { var blot = Registry.find(mutation.target, true); if (blot == null) return null; // @ts-ignore if (blot.domNode[Registry.DATA_KEY].mutations == null) { // @ts-ignore blot.domNode[Registry.DATA_KEY].mutations = [mutation]; return blot; } else { // @ts-ignore blot.domNode[Registry.DATA_KEY].mutations.push(mutation); return null; } }) .forEach(function (blot) { if (blot == null || blot === _this || //@ts-ignore blot.domNode[Registry.DATA_KEY] == null) return; // @ts-ignore blot.update(blot.domNode[Registry.DATA_KEY].mutations || [], context); }); // @ts-ignore if (this.domNode[Registry.DATA_KEY].mutations != null) { // @ts-ignore _super.prototype.update.call(this, this.domNode[Registry.DATA_KEY].mutations, context); } this.optimize(mutations, context); }; ScrollBlot.blotName = 'scroll'; ScrollBlot.defaultChild = 'block'; ScrollBlot.scope = Registry.Scope.BLOCK_BLOT; ScrollBlot.tagName = 'DIV'; return ScrollBlot; }(container_1.default)); exports.default = ScrollBlot; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var format_1 = __webpack_require__(18); var Registry = __webpack_require__(1); // Shallow object comparison function isEqual(obj1, obj2) { if (Object.keys(obj1).length !== Object.keys(obj2).length) return false; // @ts-ignore for (var prop in obj1) { // @ts-ignore if (obj1[prop] !== obj2[prop]) return false; } return true; } var InlineBlot = /** @class */ (function (_super) { __extends(InlineBlot, _super); function InlineBlot() { return _super !== null && _super.apply(this, arguments) || this; } InlineBlot.formats = function (domNode) { if (domNode.tagName === InlineBlot.tagName) return undefined; return _super.formats.call(this, domNode); }; InlineBlot.prototype.format = function (name, value) { var _this = this; if (name === this.statics.blotName && !value) { this.children.forEach(function (child) { if (!(child instanceof format_1.default)) { child = child.wrap(InlineBlot.blotName, true); } _this.attributes.copy(child); }); this.unwrap(); } else { _super.prototype.format.call(this, name, value); } }; InlineBlot.prototype.formatAt = function (index, length, name, value) { if (this.formats()[name] != null || Registry.query(name, Registry.Scope.ATTRIBUTE)) { var blot = this.isolate(index, length); blot.format(name, value); } else { _super.prototype.formatAt.call(this, index, length, name, value); } }; InlineBlot.prototype.optimize = function (context) { _super.prototype.optimize.call(this, context); var formats = this.formats(); if (Object.keys(formats).length === 0) { return this.unwrap(); // unformatted span } var next = this.next; if (next instanceof InlineBlot && next.prev === this && isEqual(formats, next.formats())) { next.moveChildren(this); next.remove(); } }; InlineBlot.blotName = 'inline'; InlineBlot.scope = Registry.Scope.INLINE_BLOT; InlineBlot.tagName = 'SPAN'; return InlineBlot; }(format_1.default)); exports.default = InlineBlot; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var format_1 = __webpack_require__(18); var Registry = __webpack_require__(1); var BlockBlot = /** @class */ (function (_super) { __extends(BlockBlot, _super); function BlockBlot() { return _super !== null && _super.apply(this, arguments) || this; } BlockBlot.formats = function (domNode) { var tagName = Registry.query(BlockBlot.blotName).tagName; if (domNode.tagName === tagName) return undefined; return _super.formats.call(this, domNode); }; BlockBlot.prototype.format = function (name, value) { if (Registry.query(name, Registry.Scope.BLOCK) == null) { return; } else if (name === this.statics.blotName && !value) { this.replaceWith(BlockBlot.blotName); } else { _super.prototype.format.call(this, name, value); } }; BlockBlot.prototype.formatAt = function (index, length, name, value) { if (Registry.query(name, Registry.Scope.BLOCK) != null) { this.format(name, value); } else { _super.prototype.formatAt.call(this, index, length, name, value); } }; BlockBlot.prototype.insertAt = function (index, value, def) { if (def == null || Registry.query(value, Registry.Scope.INLINE) != null) { // Insert text or inline _super.prototype.insertAt.call(this, index, value, def); } else { var after = this.split(index); var blot = Registry.create(value, def); after.parent.insertBefore(blot, after); } }; BlockBlot.prototype.update = function (mutations, context) { if (navigator.userAgent.match(/Trident/)) { this.build(); } else { _super.prototype.update.call(this, mutations, context); } }; BlockBlot.blotName = 'block'; BlockBlot.scope = Registry.Scope.BLOCK_BLOT; BlockBlot.tagName = 'P'; return BlockBlot; }(format_1.default)); exports.default = BlockBlot; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var leaf_1 = __webpack_require__(19); var EmbedBlot = /** @class */ (function (_super) { __extends(EmbedBlot, _super); function EmbedBlot() { return _super !== null && _super.apply(this, arguments) || this; } EmbedBlot.formats = function (domNode) { return undefined; }; EmbedBlot.prototype.format = function (name, value) { // super.formatAt wraps, which is what we want in general, // but this allows subclasses to overwrite for formats // that just apply to particular embeds _super.prototype.formatAt.call(this, 0, this.length(), name, value); }; EmbedBlot.prototype.formatAt = function (index, length, name, value) { if (index === 0 && length === this.length()) { this.format(name, value); } else { _super.prototype.formatAt.call(this, index, length, name, value); } }; EmbedBlot.prototype.formats = function () { return this.statics.formats(this.domNode); }; return EmbedBlot; }(leaf_1.default)); exports.default = EmbedBlot; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var leaf_1 = __webpack_require__(19); var Registry = __webpack_require__(1); var TextBlot = /** @class */ (function (_super) { __extends(TextBlot, _super); function TextBlot(node) { var _this = _super.call(this, node) || this; _this.text = _this.statics.value(_this.domNode); return _this; } TextBlot.create = function (value) { return document.createTextNode(value); }; TextBlot.value = function (domNode) { var text = domNode.data; // @ts-ignore if (text['normalize']) text = text['normalize'](); return text; }; TextBlot.prototype.deleteAt = function (index, length) { this.domNode.data = this.text = this.text.slice(0, index) + this.text.slice(index + length); }; TextBlot.prototype.index = function (node, offset) { if (this.domNode === node) { return offset; } return -1; }; TextBlot.prototype.insertAt = function (index, value, def) { if (def == null) { this.text = this.text.slice(0, index) + value + this.text.slice(index); this.domNode.data = this.text; } else { _super.prototype.insertAt.call(this, index, value, def); } }; TextBlot.prototype.length = function () { return this.text.length; }; TextBlot.prototype.optimize = function (context) { _super.prototype.optimize.call(this, context); this.text = this.statics.value(this.domNode); if (this.text.length === 0) { this.remove(); } else if (this.next instanceof TextBlot && this.next.prev === this) { this.insertAt(this.length(), this.next.value()); this.next.remove(); } }; TextBlot.prototype.position = function (index, inclusive) { if (inclusive === void 0) { inclusive = false; } return [this.domNode, index]; }; TextBlot.prototype.split = function (index, force) { if (force === void 0) { force = false; } if (!force) { if (index === 0) return this; if (index === this.length()) return this.next; } var after = Registry.create(this.domNode.splitText(index)); this.parent.insertBefore(after, this.next); this.text = this.statics.value(this.domNode); return after; }; TextBlot.prototype.update = function (mutations, context) { var _this = this; if (mutations.some(function (mutation) { return mutation.type === 'characterData' && mutation.target === _this.domNode; })) { this.text = this.statics.value(this.domNode); } }; TextBlot.prototype.value = function () { return this.text; }; TextBlot.blotName = 'text'; TextBlot.scope = Registry.Scope.INLINE_BLOT; return TextBlot; }(leaf_1.default)); exports.default = TextBlot; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var elem = document.createElement('div'); elem.classList.toggle('test-class', false); if (elem.classList.contains('test-class')) { var _toggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function (token, force) { if (arguments.length > 1 && !this.contains(token) === !force) { return force; } else { return _toggle.call(this, token); } }; } if (!String.prototype.startsWith) { String.prototype.startsWith = function (searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }; } if (!String.prototype.endsWith) { String.prototype.endsWith = function (searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; } if (!Array.prototype.find) { Object.defineProperty(Array.prototype, "find", { value: function value(predicate) { if (this === null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; } }); } document.addEventListener("DOMContentLoaded", function () { // Disable resizing in Firefox document.execCommand("enableObjectResizing", false, false); // Disable automatic linkifying in IE11 document.execCommand("autoUrlDetect", false, false); }); /***/ }), /* 51 */ /***/ (function(module, exports) { /** * This library modifies the diff-patch-match library by Neil Fraser * by removing the patch and match functionality and certain advanced * options in the diff function. The original license is as follows: * * === * * Diff Match and Patch * * Copyright 2006 Google Inc. * http://code.google.com/p/google-diff-match-patch/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The data structure representing a diff is an array of tuples: * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] * which means: delete 'Hello', add 'Goodbye' and keep ' world.' */ var DIFF_DELETE = -1; var DIFF_INSERT = 1; var DIFF_EQUAL = 0; /** * Find the differences between two texts. Simplifies the problem by stripping * any common prefix or suffix off the texts before diffing. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {Int} cursor_pos Expected edit position in text1 (optional) * @return {Array} Array of diff tuples. */ function diff_main(text1, text2, cursor_pos) { // Check for equality (speedup). if (text1 == text2) { if (text1) { return [[DIFF_EQUAL, text1]]; } return []; } // Check cursor_pos within bounds if (cursor_pos < 0 || text1.length < cursor_pos) { cursor_pos = null; } // Trim off common prefix (speedup). var commonlength = diff_commonPrefix(text1, text2); var commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); // Trim off common suffix (speedup). commonlength = diff_commonSuffix(text1, text2); var commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text2 = text2.substring(0, text2.length - commonlength); // Compute the diff on the middle block. var diffs = diff_compute_(text1, text2); // Restore the prefix and suffix. if (commonprefix) { diffs.unshift([DIFF_EQUAL, commonprefix]); } if (commonsuffix) { diffs.push([DIFF_EQUAL, commonsuffix]); } diff_cleanupMerge(diffs); if (cursor_pos != null) { diffs = fix_cursor(diffs, cursor_pos); } diffs = fix_emoji(diffs); return diffs; }; /** * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @return {Array} Array of diff tuples. */ function diff_compute_(text1, text2) { var diffs; if (!text1) { // Just add some text (speedup). return [[DIFF_INSERT, text2]]; } if (!text2) { // Just delete some text (speedup). return [[DIFF_DELETE, text1]]; } var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; var i = longtext.indexOf(shorttext); if (i != -1) { // Shorter text is inside the longer text (speedup). diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; // Swap insertions for deletions if diff is reversed. if (text1.length > text2.length) { diffs[0][0] = diffs[2][0] = DIFF_DELETE; } return diffs; } if (shorttext.length == 1) { // Single character string. // After the previous speedup, the character can't be an equality. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; } // Check to see if the problem can be split in two. var hm = diff_halfMatch_(text1, text2); if (hm) { // A half-match was found, sort out the return data. var text1_a = hm[0]; var text1_b = hm[1]; var text2_a = hm[2]; var text2_b = hm[3]; var mid_common = hm[4]; // Send both pairs off for separate processing. var diffs_a = diff_main(text1_a, text2_a); var diffs_b = diff_main(text1_b, text2_b); // Merge the results. return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); } return diff_bisect_(text1, text2); }; /** * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @return {Array} Array of diff tuples. * @private */ function diff_bisect_(text1, text2) { // Cache the text lengths to prevent multiple calls. var text1_length = text1.length; var text2_length = text2.length; var max_d = Math.ceil((text1_length + text2_length) / 2); var v_offset = max_d; var v_length = 2 * max_d; var v1 = new Array(v_length); var v2 = new Array(v_length); // Setting all elements to -1 is faster in Chrome & Firefox than mixing // integers and undefined. for (var x = 0; x < v_length; x++) { v1[x] = -1; v2[x] = -1; } v1[v_offset + 1] = 0; v2[v_offset + 1] = 0; var delta = text1_length - text2_length; // If the total number of characters is odd, then the front path will collide // with the reverse path. var front = (delta % 2 != 0); // Offsets for start and end of k loop. // Prevents mapping of space beyond the grid. var k1start = 0; var k1end = 0; var k2start = 0; var k2end = 0; for (var d = 0; d < max_d; d++) { // Walk the front path one step. for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { var k1_offset = v_offset + k1; var x1; if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) { x1 = v1[k1_offset + 1]; } else { x1 = v1[k1_offset - 1] + 1; } var y1 = x1 - k1; while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) == text2.charAt(y1)) { x1++; y1++; } v1[k1_offset] = x1; if (x1 > text1_length) { // Ran off the right of the graph. k1end += 2; } else if (y1 > text2_length) { // Ran off the bottom of the graph. k1start += 2; } else if (front) { var k2_offset = v_offset + delta - k1; if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { // Mirror x2 onto top-left coordinate system. var x2 = text1_length - v2[k2_offset]; if (x1 >= x2) { // Overlap detected. return diff_bisectSplit_(text1, text2, x1, y1); } } } } // Walk the reverse path one step. for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { var k2_offset = v_offset + k2; var x2; if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) { x2 = v2[k2_offset + 1]; } else { x2 = v2[k2_offset - 1] + 1; } var y2 = x2 - k2; while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) == text2.charAt(text2_length - y2 - 1)) { x2++; y2++; } v2[k2_offset] = x2; if (x2 > text1_length) { // Ran off the left of the graph. k2end += 2; } else if (y2 > text2_length) { // Ran off the top of the graph. k2start += 2; } else if (!front) { var k1_offset = v_offset + delta - k2; if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { var x1 = v1[k1_offset]; var y1 = v_offset + x1 - k1_offset; // Mirror x2 onto top-left coordinate system. x2 = text1_length - x2; if (x1 >= x2) { // Overlap detected. return diff_bisectSplit_(text1, text2, x1, y1); } } } } } // Diff took too long and hit the deadline or // number of diffs equals number of characters, no commonality at all. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; }; /** * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @return {Array} Array of diff tuples. */ function diff_bisectSplit_(text1, text2, x, y) { var text1a = text1.substring(0, x); var text2a = text2.substring(0, y); var text1b = text1.substring(x); var text2b = text2.substring(y); // Compute both diffs serially. var diffs = diff_main(text1a, text2a); var diffsb = diff_main(text1b, text2b); return diffs.concat(diffsb); }; /** * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. */ function diff_commonPrefix(text1, text2) { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { return 0; } // Binary search. // Performance analysis: http://neil.fraser.name/news/2007/10/09/ var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. */ function diff_commonSuffix(text1, text2) { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { return 0; } // Binary search. // Performance analysis: http://neil.fraser.name/news/2007/10/09/ var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Do the two texts share a substring which is at least half the length of the * longer text? * This speedup can produce non-minimal diffs. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {Array.<string>} Five element Array, containing the prefix of * text1, the suffix of text1, the prefix of text2, the suffix of * text2 and the common middle. Or null if there was no match. */ function diff_halfMatch_(text1, text2) { var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; // Pointless. } /** * Does a substring of shorttext exist within longtext such that the substring * is at least half the length of longtext? * Closure, but does not reference any external variables. * @param {string} longtext Longer string. * @param {string} shorttext Shorter string. * @param {number} i Start index of quarter length substring within longtext. * @return {Array.<string>} Five element Array, containing the prefix of * longtext, the suffix of longtext, the prefix of shorttext, the suffix * of shorttext and the common middle. Or null if there was no match. * @private */ function diff_halfMatchI_(longtext, shorttext, i) { // Start with a 1/4 length substring at position i as a seed. var seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); var j = -1; var best_common = ''; var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; while ((j = shorttext.indexOf(seed, j + 1)) != -1) { var prefixLength = diff_commonPrefix(longtext.substring(i), shorttext.substring(j)); var suffixLength = diff_commonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); if (best_common.length < suffixLength + prefixLength) { best_common = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); best_longtext_a = longtext.substring(0, i - suffixLength); best_longtext_b = longtext.substring(i + prefixLength); best_shorttext_a = shorttext.substring(0, j - suffixLength); best_shorttext_b = shorttext.substring(j + prefixLength); } } if (best_common.length * 2 >= longtext.length) { return [best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common]; } else { return null; } } // First check if the second quarter is the seed for a half-match. var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); // Check again based on the third quarter. var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); var hm; if (!hm1 && !hm2) { return null; } else if (!hm2) { hm = hm1; } else if (!hm1) { hm = hm2; } else { // Both matched. Select the longest. hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } // A half-match was found, sort out the return data. var text1_a, text1_b, text2_a, text2_b; if (text1.length > text2.length) { text1_a = hm[0]; text1_b = hm[1]; text2_a = hm[2]; text2_b = hm[3]; } else { text2_a = hm[0]; text2_b = hm[1]; text1_a = hm[2]; text1_b = hm[3]; } var mid_common = hm[4]; return [text1_a, text1_b, text2_a, text2_b, mid_common]; }; /** * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {Array} diffs Array of diff tuples. */ function diff_cleanupMerge(diffs) { diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end. var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ''; var text_insert = ''; var commonlength; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete + count_insert > 1) { if (count_delete !== 0 && count_insert !== 0) { // Factor out any common prefixies. commonlength = diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if ((pointer - count_delete - count_insert) > 0 && diffs[pointer - count_delete - count_insert - 1][0] == DIFF_EQUAL) { diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); } else { diffs.splice(0, 0, [DIFF_EQUAL, text_insert.substring(0, commonlength)]); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } // Factor out any common suffixies. commonlength = diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring(0, text_insert.length - commonlength); text_delete = text_delete.substring(0, text_delete.length - commonlength); } } // Delete the offending records and add the merged ones. if (count_delete === 0) { diffs.splice(pointer - count_insert, count_delete + count_insert, [DIFF_INSERT, text_insert]); } else if (count_insert === 0) { diffs.splice(pointer - count_delete, count_delete + count_insert, [DIFF_DELETE, text_delete]); } else { diffs.splice(pointer - count_delete - count_insert, count_delete + count_insert, [DIFF_DELETE, text_delete], [DIFF_INSERT, text_insert]); } pointer = pointer - count_delete - count_insert + (count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1; } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { // Merge this equality with the previous one. diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ''; text_insert = ''; break; } } if (diffs[diffs.length - 1][1] === '') { diffs.pop(); // Remove the dummy entry at the end. } // Second pass: look for single edits surrounded on both sides by equalities // which can be shifted sideways to eliminate an equality. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC var changes = false; pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { // This is a single edit surrounded by equalities. if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { // Shift the edit over the previous equality. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { // Shift the edit over the next equality. diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } // If shifts were made, the diff needs reordering and another shift sweep. if (changes) { diff_cleanupMerge(diffs); } }; var diff = diff_main; diff.INSERT = DIFF_INSERT; diff.DELETE = DIFF_DELETE; diff.EQUAL = DIFF_EQUAL; module.exports = diff; /* * Modify a diff such that the cursor position points to the start of a change: * E.g. * cursor_normalize_diff([[DIFF_EQUAL, 'abc']], 1) * => [1, [[DIFF_EQUAL, 'a'], [DIFF_EQUAL, 'bc']]] * cursor_normalize_diff([[DIFF_INSERT, 'new'], [DIFF_DELETE, 'xyz']], 2) * => [2, [[DIFF_INSERT, 'new'], [DIFF_DELETE, 'xy'], [DIFF_DELETE, 'z']]] * * @param {Array} diffs Array of diff tuples * @param {Int} cursor_pos Suggested edit position. Must not be out of bounds! * @return {Array} A tuple [cursor location in the modified diff, modified diff] */ function cursor_normalize_diff (diffs, cursor_pos) { if (cursor_pos === 0) { return [DIFF_EQUAL, diffs]; } for (var current_pos = 0, i = 0; i < diffs.length; i++) { var d = diffs[i]; if (d[0] === DIFF_DELETE || d[0] === DIFF_EQUAL) { var next_pos = current_pos + d[1].length; if (cursor_pos === next_pos) { return [i + 1, diffs]; } else if (cursor_pos < next_pos) { // copy to prevent side effects diffs = diffs.slice(); // split d into two diff changes var split_pos = cursor_pos - current_pos; var d_left = [d[0], d[1].slice(0, split_pos)]; var d_right = [d[0], d[1].slice(split_pos)]; diffs.splice(i, 1, d_left, d_right); return [i + 1, diffs]; } else { current_pos = next_pos; } } } throw new Error('cursor_pos is out of bounds!') } /* * Modify a diff such that the edit position is "shifted" to the proposed edit location (cursor_position). * * Case 1) * Check if a naive shift is possible: * [0, X], [ 1, Y] -> [ 1, Y], [0, X] (if X + Y === Y + X) * [0, X], [-1, Y] -> [-1, Y], [0, X] (if X + Y === Y + X) - holds same result * Case 2) * Check if the following shifts are possible: * [0, 'pre'], [ 1, 'prefix'] -> [ 1, 'pre'], [0, 'pre'], [ 1, 'fix'] * [0, 'pre'], [-1, 'prefix'] -> [-1, 'pre'], [0, 'pre'], [-1, 'fix'] * ^ ^ * d d_next * * @param {Array} diffs Array of diff tuples * @param {Int} cursor_pos Suggested edit position. Must not be out of bounds! * @return {Array} Array of diff tuples */ function fix_cursor (diffs, cursor_pos) { var norm = cursor_normalize_diff(diffs, cursor_pos); var ndiffs = norm[1]; var cursor_pointer = norm[0]; var d = ndiffs[cursor_pointer]; var d_next = ndiffs[cursor_pointer + 1]; if (d == null) { // Text was deleted from end of original string, // cursor is now out of bounds in new string return diffs; } else if (d[0] !== DIFF_EQUAL) { // A modification happened at the cursor location. // This is the expected outcome, so we can return the original diff. return diffs; } else { if (d_next != null && d[1] + d_next[1] === d_next[1] + d[1]) { // Case 1) // It is possible to perform a naive shift ndiffs.splice(cursor_pointer, 2, d_next, d) return merge_tuples(ndiffs, cursor_pointer, 2) } else if (d_next != null && d_next[1].indexOf(d[1]) === 0) { // Case 2) // d[1] is a prefix of d_next[1] // We can assume that d_next[0] !== 0, since d[0] === 0 // Shift edit locations.. ndiffs.splice(cursor_pointer, 2, [d_next[0], d[1]], [0, d[1]]); var suffix = d_next[1].slice(d[1].length); if (suffix.length > 0) { ndiffs.splice(cursor_pointer + 2, 0, [d_next[0], suffix]); } return merge_tuples(ndiffs, cursor_pointer, 3) } else { // Not possible to perform any modification return diffs; } } } /* * Check diff did not split surrogate pairs. * Ex. [0, '\uD83D'], [-1, '\uDC36'], [1, '\uDC2F'] -> [-1, '\uD83D\uDC36'], [1, '\uD83D\uDC2F'] * '\uD83D\uDC36' === '🐶', '\uD83D\uDC2F' === '🐯' * * @param {Array} diffs Array of diff tuples * @return {Array} Array of diff tuples */ function fix_emoji (diffs) { var compact = false; var starts_with_pair_end = function (str) { return str.charCodeAt(0) >= 0xDC00 && str.charCodeAt(0) <= 0xDFFF; } var ends_with_pair_start = function (str) { return str.charCodeAt(str.length-1) >= 0xD800 && str.charCodeAt(str.length-1) <= 0xDBFF; } for (var i = 2; i < diffs.length; i += 1) { if (diffs[i-2][0] === DIFF_EQUAL && ends_with_pair_start(diffs[i-2][1]) && diffs[i-1][0] === DIFF_DELETE && starts_with_pair_end(diffs[i-1][1]) && diffs[i][0] === DIFF_INSERT && starts_with_pair_end(diffs[i][1])) { compact = true; diffs[i-1][1] = diffs[i-2][1].slice(-1) + diffs[i-1][1]; diffs[i][1] = diffs[i-2][1].slice(-1) + diffs[i][1]; diffs[i-2][1] = diffs[i-2][1].slice(0, -1); } } if (!compact) { return diffs; } var fixed_diffs = []; for (var i = 0; i < diffs.length; i += 1) { if (diffs[i][1].length > 0) { fixed_diffs.push(diffs[i]); } } return fixed_diffs; } /* * Try to merge tuples with their neigbors in a given range. * E.g. [0, 'a'], [0, 'b'] -> [0, 'ab'] * * @param {Array} diffs Array of diff tuples. * @param {Int} start Position of the first element to merge (diffs[start] is also merged with diffs[start - 1]). * @param {Int} length Number of consecutive elements to check. * @return {Array} Array of merged diff tuples. */ function merge_tuples (diffs, start, length) { // Check from (start-1) to (start+length). for (var i = start + length - 1; i >= 0 && i >= start - 1; i--) { if (i + 1 < diffs.length) { var left_d = diffs[i]; var right_d = diffs[i+1]; if (left_d[0] === right_d[1]) { diffs.splice(i, 2, [left_d[0], left_d[1] + right_d[1]]); } } } return diffs; } /***/ }), /* 52 */ /***/ (function(module, exports) { exports = module.exports = typeof Object.keys === 'function' ? Object.keys : shim; exports.shim = shim; function shim (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; } /***/ }), /* 53 */ /***/ (function(module, exports) { var supportsArgumentsClass = (function () { return Object.prototype.toString.call(arguments) })() == '[object Arguments]'; exports = module.exports = supportsArgumentsClass ? supported : unsupported; exports.supported = supported; function supported(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; }; exports.unsupported = unsupported; function unsupported(object){ return object && typeof object == 'object' && typeof object.length == 'number' && Object.prototype.hasOwnProperty.call(object, 'callee') && !Object.prototype.propertyIsEnumerable.call(object, 'callee') || false; }; /***/ }), /* 54 */ /***/ (function(module, exports) { 'use strict'; var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @api private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {Mixed} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @api private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @api public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @api public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {String|Symbol} event The event name. * @param {Boolean} exists Only check if there are listeners. * @returns {Array|Boolean} * @api public */ EventEmitter.prototype.listeners = function listeners(event, exists) { var evt = prefix ? prefix + event : event , available = this._events[evt]; if (exists) return !!available; if (!available) return []; if (available.fn) return [available.fn]; for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { ee[i] = available[i].fn; } return ee; }; /** * Calls each of the listeners registered for a given event. * * @param {String|Symbol} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @api public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {String|Symbol} event The event name. * @param {Function} fn The listener function. * @param {Mixed} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @api public */ EventEmitter.prototype.on = function on(event, fn, context) { var listener = new EE(fn, context || this) , evt = prefix ? prefix + event : event; if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; else if (!this._events[evt].fn) this._events[evt].push(listener); else this._events[evt] = [this._events[evt], listener]; return this; }; /** * Add a one-time listener for a given event. * * @param {String|Symbol} event The event name. * @param {Function} fn The listener function. * @param {Mixed} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @api public */ EventEmitter.prototype.once = function once(event, fn, context) { var listener = new EE(fn, context || this, true) , evt = prefix ? prefix + event : event; if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; else if (!this._events[evt].fn) this._events[evt].push(listener); else this._events[evt] = [this._events[evt], listener]; return this; }; /** * Remove the listeners of a given event. * * @param {String|Symbol} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {Mixed} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @api public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { if (--this._eventsCount === 0) this._events = new Events(); else delete this._events[evt]; return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { if (--this._eventsCount === 0) this._events = new Events(); else delete this._events[evt]; } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else if (--this._eventsCount === 0) this._events = new Events(); else delete this._events[evt]; } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {String|Symbol} [event] The event name. * @returns {EventEmitter} `this`. * @api public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) { if (--this._eventsCount === 0) this._events = new Events(); else delete this._events[evt]; } } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // This function doesn't apply anymore. // EventEmitter.prototype.setMaxListeners = function setMaxListeners() { return this; }; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // if ('undefined' !== typeof module) { module.exports = EventEmitter; } /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.matchText = exports.matchSpacing = exports.matchNewline = exports.matchBlot = exports.matchAttributor = exports.default = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extend2 = __webpack_require__(3); var _extend3 = _interopRequireDefault(_extend2); var _quillDelta = __webpack_require__(2); var _quillDelta2 = _interopRequireDefault(_quillDelta); var _parchment = __webpack_require__(0); var _parchment2 = _interopRequireDefault(_parchment); var _quill = __webpack_require__(5); var _quill2 = _interopRequireDefault(_quill); var _logger = __webpack_require__(10); var _logger2 = _interopRequireDefault(_logger); var _module = __webpack_require__(9); var _module2 = _interopRequireDefault(_module); var _align = __webpack_require__(36); var _background = __webpack_require__(37); var _code = __webpack_require__(13); var _code2 = _interopRequireDefault(_code); var _color = __webpack_require__(26); var _direction = __webpack_require__(38); var _font = __webpack_require__(39); var _size = __webpack_require__(40); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var debug = (0, _logger2.default)('quill:clipboard'); var DOM_KEY = '__ql-matcher'; var CLIPBOARD_CONFIG = [[Node.TEXT_NODE, matchText], [Node.TEXT_NODE, matchNewline], ['br', matchBreak], [Node.ELEMENT_NODE, matchNewline], [Node.ELEMENT_NODE, matchBlot], [Node.ELEMENT_NODE, matchSpacing], [Node.ELEMENT_NODE, matchAttributor], [Node.ELEMENT_NODE, matchStyles], ['li', matchIndent], ['b', matchAlias.bind(matchAlias, 'bold')], ['i', matchAlias.bind(matchAlias, 'italic')], ['style', matchIgnore]]; var ATTRIBUTE_ATTRIBUTORS = [_align.AlignAttribute, _direction.DirectionAttribute].reduce(function (memo, attr) { memo[attr.keyName] = attr; return memo; }, {}); var STYLE_ATTRIBUTORS = [_align.AlignStyle, _background.BackgroundStyle, _color.ColorStyle, _direction.DirectionStyle, _font.FontStyle, _size.SizeStyle].reduce(function (memo, attr) { memo[attr.keyName] = attr; return memo; }, {}); var Clipboard = function (_Module) { _inherits(Clipboard, _Module); function Clipboard(quill, options) { _classCallCheck(this, Clipboard); var _this = _possibleConstructorReturn(this, (Clipboard.__proto__ || Object.getPrototypeOf(Clipboard)).call(this, quill, options)); _this.quill.root.addEventListener('paste', _this.onPaste.bind(_this)); _this.container = _this.quill.addContainer('ql-clipboard'); _this.container.setAttribute('contenteditable', true); _this.container.setAttribute('tabindex', -1); _this.matchers = []; CLIPBOARD_CONFIG.concat(_this.options.matchers).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), selector = _ref2[0], matcher = _ref2[1]; if (!options.matchVisual && matcher === matchSpacing) return; _this.addMatcher(selector, matcher); }); return _this; } _createClass(Clipboard, [{ key: 'addMatcher', value: function addMatcher(selector, matcher) { this.matchers.push([selector, matcher]); } }, { key: 'convert', value: function convert(html) { if (typeof html === 'string') { this.container.innerHTML = html.replace(/\>\r?\n +\</g, '><'); // Remove spaces between tags return this.convert(); } var formats = this.quill.getFormat(this.quill.selection.savedRange.index); if (formats[_code2.default.blotName]) { var text = this.container.innerText; this.container.innerHTML = ''; return new _quillDelta2.default().insert(text, _defineProperty({}, _code2.default.blotName, formats[_code2.default.blotName])); } var _prepareMatching = this.prepareMatching(), _prepareMatching2 = _slicedToArray(_prepareMatching, 2), elementMatchers = _prepareMatching2[0], textMatchers = _prepareMatching2[1]; var delta = traverse(this.container, elementMatchers, textMatchers); // Remove trailing newline if (deltaEndsWith(delta, '\n') && delta.ops[delta.ops.length - 1].attributes == null) { delta = delta.compose(new _quillDelta2.default().retain(delta.length() - 1).delete(1)); } debug.log('convert', this.container.innerHTML, delta); this.container.innerHTML = ''; return delta; } }, { key: 'dangerouslyPasteHTML', value: function dangerouslyPasteHTML(index, html) { var source = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _quill2.default.sources.API; if (typeof index === 'string') { this.quill.setContents(this.convert(index), html); this.quill.setSelection(0, _quill2.default.sources.SILENT); } else { var paste = this.convert(html); this.quill.updateContents(new _quillDelta2.default().retain(index).concat(paste), source); this.quill.setSelection(index + paste.length(), _quill2.default.sources.SILENT); } } }, { key: 'onPaste', value: function onPaste(e) { var _this2 = this; if (e.defaultPrevented || !this.quill.isEnabled()) return; var range = this.quill.getSelection(); var delta = new _quillDelta2.default().retain(range.index); var scrollTop = this.quill.scrollingContainer.scrollTop; this.container.focus(); this.quill.selection.update(_quill2.default.sources.SILENT); setTimeout(function () { delta = delta.concat(_this2.convert()).delete(range.length); _this2.quill.updateContents(delta, _quill2.default.sources.USER); // range.length contributes to delta.length() _this2.quill.setSelection(delta.length() - range.length, _quill2.default.sources.SILENT); _this2.quill.scrollingContainer.scrollTop = scrollTop; _this2.quill.focus(); }, 1); } }, { key: 'prepareMatching', value: function prepareMatching() { var _this3 = this; var elementMatchers = [], textMatchers = []; this.matchers.forEach(function (pair) { var _pair = _slicedToArray(pair, 2), selector = _pair[0], matcher = _pair[1]; switch (selector) { case Node.TEXT_NODE: textMatchers.push(matcher); break; case Node.ELEMENT_NODE: elementMatchers.push(matcher); break; default: [].forEach.call(_this3.container.querySelectorAll(selector), function (node) { // TODO use weakmap node[DOM_KEY] = node[DOM_KEY] || []; node[DOM_KEY].push(matcher); }); break; } }); return [elementMatchers, textMatchers]; } }]); return Clipboard; }(_module2.default); Clipboard.DEFAULTS = { matchers: [], matchVisual: true }; function applyFormat(delta, format, value) { if ((typeof format === 'undefined' ? 'undefined' : _typeof(format)) === 'object') { return Object.keys(format).reduce(function (delta, key) { return applyFormat(delta, key, format[key]); }, delta); } else { return delta.reduce(function (delta, op) { if (op.attributes && op.attributes[format]) { return delta.push(op); } else { return delta.insert(op.insert, (0, _extend3.default)({}, _defineProperty({}, format, value), op.attributes)); } }, new _quillDelta2.default()); } } function computeStyle(node) { if (node.nodeType !== Node.ELEMENT_NODE) return {}; var DOM_KEY = '__ql-computed-style'; return node[DOM_KEY] || (node[DOM_KEY] = window.getComputedStyle(node)); } function deltaEndsWith(delta, text) { var endText = ""; for (var i = delta.ops.length - 1; i >= 0 && endText.length < text.length; --i) { var op = delta.ops[i]; if (typeof op.insert !== 'string') break; endText = op.insert + endText; } return endText.slice(-1 * text.length) === text; } function isLine(node) { if (node.childNodes.length === 0) return false; // Exclude embed blocks var style = computeStyle(node); return ['block', 'list-item'].indexOf(style.display) > -1; } function traverse(node, elementMatchers, textMatchers) { // Post-order if (node.nodeType === node.TEXT_NODE) { return textMatchers.reduce(function (delta, matcher) { return matcher(node, delta); }, new _quillDelta2.default()); } else if (node.nodeType === node.ELEMENT_NODE) { return [].reduce.call(node.childNodes || [], function (delta, childNode) { var childrenDelta = traverse(childNode, elementMatchers, textMatchers); if (childNode.nodeType === node.ELEMENT_NODE) { childrenDelta = elementMatchers.reduce(function (childrenDelta, matcher) { return matcher(childNode, childrenDelta); }, childrenDelta); childrenDelta = (childNode[DOM_KEY] || []).reduce(function (childrenDelta, matcher) { return matcher(childNode, childrenDelta); }, childrenDelta); } return delta.concat(childrenDelta); }, new _quillDelta2.default()); } else { return new _quillDelta2.default(); } } function matchAlias(format, node, delta) { return applyFormat(delta, format, true); } function matchAttributor(node, delta) { var attributes = _parchment2.default.Attributor.Attribute.keys(node); var classes = _parchment2.default.Attributor.Class.keys(node); var styles = _parchment2.default.Attributor.Style.keys(node); var formats = {}; attributes.concat(classes).concat(styles).forEach(function (name) { var attr = _parchment2.default.query(name, _parchment2.default.Scope.ATTRIBUTE); if (attr != null) { formats[attr.attrName] = attr.value(node); if (formats[attr.attrName]) return; } attr = ATTRIBUTE_ATTRIBUTORS[name]; if (attr != null && (attr.attrName === name || attr.keyName === name)) { formats[attr.attrName] = attr.value(node) || undefined; } attr = STYLE_ATTRIBUTORS[name]; if (attr != null && (attr.attrName === name || attr.keyName === name)) { attr = STYLE_ATTRIBUTORS[name]; formats[attr.attrName] = attr.value(node) || undefined; } }); if (Object.keys(formats).length > 0) { delta = applyFormat(delta, formats); } return delta; } function matchBlot(node, delta) { var match = _parchment2.default.query(node); if (match == null) return delta; if (match.prototype instanceof _parchment2.default.Embed) { var embed = {}; var value = match.value(node); if (value != null) { embed[match.blotName] = value; delta = new _quillDelta2.default().insert(embed, match.formats(node)); } } else if (typeof match.formats === 'function') { delta = applyFormat(delta, match.blotName, match.formats(node)); } return delta; } function matchBreak(node, delta) { if (!deltaEndsWith(delta, '\n')) { delta.insert('\n'); } return delta; } function matchIgnore() { return new _quillDelta2.default(); } function matchIndent(node, delta) { var match = _parchment2.default.query(node); if (match == null || match.blotName !== 'list-item' || !deltaEndsWith(delta, '\n')) { return delta; } var indent = -1, parent = node.parentNode; while (!parent.classList.contains('ql-clipboard')) { if ((_parchment2.default.query(parent) || {}).blotName === 'list') { indent += 1; } parent = parent.parentNode; } if (indent <= 0) return delta; return delta.compose(new _quillDelta2.default().retain(delta.length() - 1).retain(1, { indent: indent })); } function matchNewline(node, delta) { if (!deltaEndsWith(delta, '\n')) { if (isLine(node) || delta.length() > 0 && node.nextSibling && isLine(node.nextSibling)) { delta.insert('\n'); } } return delta; } function matchSpacing(node, delta) { if (isLine(node) && node.nextElementSibling != null && !deltaEndsWith(delta, '\n\n')) { var nodeHeight = node.offsetHeight + parseFloat(computeStyle(node).marginTop) + parseFloat(computeStyle(node).marginBottom); if (node.nextElementSibling.offsetTop > node.offsetTop + nodeHeight * 1.5) { delta.insert('\n'); } } return delta; } function matchStyles(node, delta) { var formats = {}; var style = node.style || {}; if (style.fontStyle && computeStyle(node).fontStyle === 'italic') { formats.italic = true; } if (style.fontWeight && (computeStyle(node).fontWeight.startsWith('bold') || parseInt(computeStyle(node).fontWeight) >= 700)) { formats.bold = true; } if (Object.keys(formats).length > 0) { delta = applyFormat(delta, formats); } if (parseFloat(style.textIndent || 0) > 0) { // Could be 0.5in delta = new _quillDelta2.default().insert('\t').concat(delta); } return delta; } function matchText(node, delta) { var text = node.data; // Word represents empty line with <o:p>&nbsp;</o:p> if (node.parentNode.tagName === 'O:P') { return delta.insert(text.trim()); } if (text.trim().length === 0 && node.parentNode.classList.contains('ql-clipboard')) { return delta; } if (!computeStyle(node.parentNode).whiteSpace.startsWith('pre')) { // eslint-disable-next-line func-style var replacer = function replacer(collapse, match) { match = match.replace(/[^\u00a0]/g, ''); // \u00a0 is nbsp; return match.length < 1 && collapse ? ' ' : match; }; text = text.replace(/\r\n/g, ' ').replace(/\n/g, ' '); text = text.replace(/\s\s+/g, replacer.bind(replacer, true)); // collapse whitespace if (node.previousSibling == null && isLine(node.parentNode) || node.previousSibling != null && isLine(node.previousSibling)) { text = text.replace(/^\s+/, replacer.bind(replacer, false)); } if (node.nextSibling == null && isLine(node.parentNode) || node.nextSibling != null && isLine(node.nextSibling)) { text = text.replace(/\s+$/, replacer.bind(replacer, false)); } } return delta.insert(text); } exports.default = Clipboard; exports.matchAttributor = matchAttributor; exports.matchBlot = matchBlot; exports.matchNewline = matchNewline; exports.matchSpacing = matchSpacing; exports.matchText = matchText; /***/ }), /* 56 */, /* 57 */, /* 58 */, /* 59 */, /* 60 */, /* 61 */, /* 62 */, /* 63 */, /* 64 */, /* 65 */, /* 66 */, /* 67 */, /* 68 */, /* 69 */, /* 70 */, /* 71 */, /* 72 */, /* 73 */, /* 74 */, /* 75 */, /* 76 */, /* 77 */, /* 78 */, /* 79 */, /* 80 */, /* 81 */, /* 82 */, /* 83 */, /* 84 */, /* 85 */, /* 86 */, /* 87 */, /* 88 */, /* 89 */, /* 90 */, /* 91 */, /* 92 */, /* 93 */, /* 94 */, /* 95 */, /* 96 */, /* 97 */, /* 98 */, /* 99 */, /* 100 */, /* 101 */, /* 102 */, /* 103 */, /* 104 */, /* 105 */, /* 106 */, /* 107 */, /* 108 */, /* 109 */, /* 110 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(29); /***/ }) /******/ ])["default"]; });
(function () { 'use strict'; define(['app'], function (app) { app.controller('robotCtrl', robotCtrl); robotCtrl.$inject = ['$location','$rootScope']; function robotCtrl($location,$rootScope) { /* js hint valid this: true*/ var vm = this; vm.location = $location.path().split('/')[2]; $rootScope.$on('$routeChangeSuccess', function () { console.log('>>>>>>>>>>>', $location.path().split('/')); vm.location = $location.path().split('/')[2]; }); } }); }());
export { default } from 'ember-powered-datepicker/components/powered-datepicker-nav';
/** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ import { ComplexDependencies } from './dependenciesComplexClass.generated'; import { typedDependencies } from './dependenciesTyped.generated'; import { createSqrt } from '../../factoriesAny.js'; export var sqrtDependencies = { ComplexDependencies: ComplexDependencies, typedDependencies: typedDependencies, createSqrt: createSqrt };
'use strict'; var ext = require('./.gruntExt'); var iwc = require('./.gruntIwc').load(ext); module.exports = function (grunt) { // Common ext.configure({ clean: { component: ['dist/*'] }, connect: { demo: { options: { port: 3008, base: '.' } } } }); // Add build tasks for components iwc.component('iwc-iconmenu', 'src/menu', 'dist'); iwc.components(); // Build the task libraries ext.registerTask('default', ['clean', 'components']); ext.registerTask('dev', ['default', 'connect', 'watch']); // Load config ext.initConfig(grunt); };
/** This converts to keycodes to real characters. Language dependency included. Calls executeKey to show the keys in effect **/ function action_handleKeyCode(keyCode,e) { console.log("KC2:"+keyCode); console.log(keyCode); return false; } /** This gets called due when a different event gets called **/ function action_handleKeyCode2(keyCode,e,possible_socket) { if (dolog) { console.log("kc:"+keyCode); } if (keyCode==38) { // UP if ( (previousKeyBufferCharArray[0]!="up") && (players[0].direction!="down") ) { if (dolog) { console.log("Pushing up"); } keyBuffers[0].push({"direction" : "up"}); previousKeyBufferCharArray[0]="up"; } } else if (keyCode==40) { // DOWN if ( (previousKeyBufferCharArray[0]!="down") && (players[0].direction!="up") ) { if (dolog) { console.log("Pushing down"); } keyBuffers[0].push({"direction" : "down"}); previousKeyBufferCharArray[0]="down"; } } else if (keyCode==39) { // RIGHT if ( (previousKeyBufferCharArray[0]!="right") && (players[0].direction!="left") ) { if (dolog) { console.log("Pushing right"); } keyBuffers[0].push({"direction" : "right"}); previousKeyBufferCharArray[0]="right"; } } else if (keyCode==37) { // LEFT if (dolog) { console.log("Pushing left"); } if ( (previousKeyBufferCharArray[0]!="left") && (players[0].direction!="right") ) { keyBuffers[0].push({"direction" : "left"}); previousKeyBufferCharArray[0]="left"; } } else if (keyCode==69) { // Start the editor editor(1); } else if (keyCode==67) { // Color picker if (dolog) { console.log("Color picker"); } if (isEditing==true) { colorpicker(); } } //2nd player W A S D else if (keyCode==87) { //W if ( (previousKeyBufferCharArray[1]!="up") && (players[1].direction!="down") ) { keyBuffers[1].push({"direction" : "up"}); previousKeyBufferCharArray[1]="up"; } } else if (keyCode==83) { //S if (isEditing==true) { saveEditor(); } else if ( (previousKeyBufferCharArray[1]!="down") && (players[1].direction!="up") ) { keyBuffers[1].push({"direction" : "down"}); previousKeyBufferCharArray[1]="down"; } } else if (keyCode==68) { //D if ( (previousKeyBufferCharArray[1]!="right") && (players[1].direction!="left") ) { keyBuffers[1].push({"direction" : "right"}); previousKeyBufferCharArray[1]="right"; } } else if (keyCode==65) { //A if ( (previousKeyBufferCharArray[1]!="left") && (players[1].direction!="right") ) { keyBuffers[1].push({"direction" : "left"}); previousKeyBufferCharArray[1]="left"; } } else if ( (keyCode>=48) && (keyCode<=57) ) { //If we press 1-9 console.log("Editing : "+isEditing+" ; Cropping: "+isCropping); // This is placed right at the start because isEditing and isCropping might be true at the same time, so isCropping will get reached even if isEditing==true if (isCropping==true){ // Crop mode // Levels 1 - 9 document.getElementById('panel').style.display='none'; document.getElementById('ansi').style.display='inline'; var level = keyCode-48; editor(level); } else if (isEditing==true) { // Edit mode // Levels 1 - 9 var level = keyCode-48; editor(level); } else if ( (keyCode>=49) && (keyCode<=53) ) { // Player select mode console.log("number of players: "+numberOfPlayers); restart(keyCode-48); } } else if (keyCode==82) { if (confirm('Do you want to reset the levels?')) { localStorage.clear(); window.location.href=window.location.href; } } else if ( (keyCode==107) || (keyCode==171) ) { //Pressing + $('#canvastable').show(); console.log('Cropping!'); document.getElementById('panel').style.display='inline'; document.getElementById('ansi').style.display='none'; isCropping = true; } } function executeParsedKey(keyCode, character, possible_socket) { console.log("1:"+keyCode); } keypress = function(e) { var keyCode = e.which; if (keyCode != 0) { e.preventDefault(); action_handleKeyCode(keyCode, e); } }; var keydown = function(e) { var keyCode = e.which; e.preventDefault(); action_handleKeyCode2(keyCode, e); }; var mouseup = function(e) { mouseDown=false; if (isEditing==true) storeLocally(); };
/* Copyright (c) 2014 Zachary Seguin 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. */ 'use strict'; angular .module('YouWantFood', [ 'ngRoute', 'ngSanitize', 'ngResource', 'ui.bootstrap' ]) .config(['$sceDelegateProvider', '$routeProvider', '$locationProvider', function($sceDelegateProvider, $routeProvider, $locationProvider) { $sceDelegateProvider.resourceUrlWhitelist(['https://projects.zacharyseguin.ca/**']); $routeProvider .when('/', { templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/Home.html', controller: 'Home' }) .when('/outlet/:outletId', { templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/OutletDetails.html', controller: 'OutletDetails' }) .when('/email/subscribe', { templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/EmailSubscribe.html', controller: 'EmailSubscribe' }) .when('/email/unsubscribe', { templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/EmailUnsubscribe.html', controller: 'EmailUnsubscribe' }) .when('/email/confirmed', { templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/EmailConfirmed.html' }) .when('/email/confirmation-error', { templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/EmailConfirmationError.html' }) .when('/error', { templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/Error.html' }) .otherwise({ templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/NotFound.html' }); $locationProvider.html5Mode(true); }]);
'use strict'; const fs = require('fs'); const path = require('path'); const semver = require('semver'); const sri = require('sri-toolbox'); const { app, files } = require('../config'); const PUBLIC_DIR = path.join(__dirname, '../public/'); const SRI_CACHE = {}; function capitalize(str) { if (typeof str !== 'string') { return ''; } return str.charAt(0).toUpperCase() + str.slice(1); } function generateSri(file, fromString) { if (typeof SRI_CACHE[file] === 'undefined') { file = fromString ? file : fs.readFileSync(file); SRI_CACHE[file] = sri.generate({ algorithms: ['sha384'] }, file); } return SRI_CACHE[file]; } // This is used only in the templates function getSri(file) { if (typeof SRI_CACHE[file] === 'undefined') { SRI_CACHE[file] = generateSri(path.join(PUBLIC_DIR, file)); } return SRI_CACHE[file]; } function generateDataJson() { const data = { timestamp: new Date().toISOString(), bootstrap: {}, fontawesome: {} }; files.bootstrap.forEach((bootstrap) => { const bootstrapVersion = bootstrap.version; if (semver.satisfies(semver.coerce(bootstrapVersion), '<4')) { data.bootstrap[bootstrapVersion] = { css: bootstrap.stylesheet, js: bootstrap.javascript }; } }); files['@fortawesome/fontawesome-free'].forEach((fontawesome) => { data.fontawesome[fontawesome.version] = fontawesome.stylesheet; }); return data; } function getCurrentSiteurl(req) { let proto = req.get('x-forwarded-proto'); if (typeof proto === 'undefined') { proto = req.protocol; } return `${proto}://${req.hostname}`; } function getPageTitle(pageTitle) { return `${pageTitle} · ${app.title_suffix}`; } function generateBodyClass(pathname) { if (pathname === '/') { return 'page-home'; // only for the homepage } // Remove any backslashes pathname = pathname.replace(/\//g, ''); // Make the first letter lowercase pathname = pathname.charAt(0).toLowerCase() + pathname.slice(1); return `page-${pathname}`; } function selectedTheme(selected) { if (typeof selected === 'undefined' || selected === '') { return app.theme; } const theme = Number.parseInt(selected, 10); return theme === 0 || theme ? theme : app.theme; } function getTheme(selected) { const { themes } = files.bootswatch4; selected = selectedTheme(selected); return { uri: files.bootswatch4.bootstrap .replace('SWATCH_VERSION', files.bootswatch4.version) .replace('SWATCH_NAME', themes[selected].name), sri: themes[selected].sri }; } function getThemeQuery(req) { const totalThemes = files.bootswatch4.themes.length; const query = Number.parseInt(req.query.theme, 10); // Safety checks if (Number.isNaN(query) || query < 0 || query >= totalThemes) { return ''; } return String(query); } function appendLocals(req, res) { const siteUrl = getCurrentSiteurl(req); const pageUrl = req.originalUrl; // OK, hack-ish way... const pathname = pageUrl.split('?')[0]; const canonicalUrl = new URL(pathname, app.siteurl); const theme = getThemeQuery(req); const bodyClass = generateBodyClass(pathname); const locals = { siteUrl, canonicalUrl, pageUrl, theme, bodyClass }; res.locals = Object.assign(res.locals, locals); return res; } module.exports = { appendLocals, capitalize, generateDataJson, theme: { get: getTheme, selected: selectedTheme }, getCurrentSiteurl, getPageTitle, generateBodyClass, generateSri, getSri }; // vim: ft=javascript sw=4 sts=4 et:
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { themr } from 'react-css-themr'; import { INPUT } from '../identifiers'; import InjectedFontIcon from '../font_icon/FontIcon'; const factory = (FontIcon) => { class Input extends React.Component { static propTypes = { children: PropTypes.node, className: PropTypes.string, defaultValue: PropTypes.string, disabled: PropTypes.bool, error: PropTypes.oneOfType([ PropTypes.string, PropTypes.node, ]), floating: PropTypes.bool, hint: PropTypes.oneOfType([ PropTypes.string, PropTypes.node, ]), icon: PropTypes.oneOfType([ PropTypes.string, PropTypes.element, ]), label: PropTypes.oneOfType([ PropTypes.string, PropTypes.node, ]), maxLength: PropTypes.number, multiline: PropTypes.bool, name: PropTypes.string, onBlur: PropTypes.func, onChange: PropTypes.func, onFocus: PropTypes.func, onKeyPress: PropTypes.func, required: PropTypes.bool, role: PropTypes.string, rows: PropTypes.number, theme: PropTypes.shape({ bar: PropTypes.string, counter: PropTypes.string, disabled: PropTypes.string, error: PropTypes.string, errored: PropTypes.string, hidden: PropTypes.string, hint: PropTypes.string, icon: PropTypes.string, input: PropTypes.string, inputElement: PropTypes.string, required: PropTypes.string, withIcon: PropTypes.string, }), type: PropTypes.string, value: PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.string, ]), }; static defaultProps = { className: '', hint: '', disabled: false, floating: true, multiline: false, required: false, role: 'input', type: 'text', }; componentDidMount() { if (this.props.multiline) { window.addEventListener('resize', this.handleAutoresize); this.handleAutoresize(); } } componentWillReceiveProps(nextProps) { if (!this.props.multiline && nextProps.multiline) { window.addEventListener('resize', this.handleAutoresize); } else if (this.props.multiline && !nextProps.multiline) { window.removeEventListener('resize', this.handleAutoresize); } } componentDidUpdate() { // resize the textarea, if nessesary if (this.props.multiline) this.handleAutoresize(); } componentWillUnmount() { if (this.props.multiline) window.removeEventListener('resize', this.handleAutoresize); } handleChange = (event) => { const { onChange, multiline, maxLength } = this.props; const valueFromEvent = event.target.value; // Trim value to maxLength if that exists (only on multiline inputs). // Note that this is still required even tho we have the onKeyPress filter // because the user could paste smt in the textarea. const haveToTrim = (multiline && maxLength && event.target.value.length > maxLength); const value = haveToTrim ? valueFromEvent.substr(0, maxLength) : valueFromEvent; // propagate to to store and therefore to the input if (onChange) onChange(value, event); }; handleAutoresize = () => { const element = this.inputNode; const rows = this.props.rows; if (typeof rows === 'number' && !isNaN(rows)) { element.style.height = null; } else { // compute the height difference between inner height and outer height const style = getComputedStyle(element, null); const heightOffset = style.boxSizing === 'content-box' ? -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)) : parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth); // resize the input to its content size element.style.height = 'auto'; element.style.height = `${element.scrollHeight + heightOffset}px`; } } handleKeyPress = (event) => { // prevent insertion of more characters if we're a multiline input // and maxLength exists const { multiline, maxLength, onKeyPress } = this.props; if (multiline && maxLength) { // check if smt is selected, in which case the newly added charcter would // replace the selected characters, so the length of value doesn't actually // increase. const isReplacing = event.target.selectionEnd - event.target.selectionStart; const value = event.target.value; if (!isReplacing && value.length === maxLength) { event.preventDefault(); event.stopPropagation(); return undefined; } } if (onKeyPress) onKeyPress(event); return undefined; }; blur() { this.inputNode.blur(); } focus() { this.inputNode.focus(); } valuePresent = value => ( value !== null && value !== undefined && value !== '' && !(typeof value === 'number' && isNaN(value)) ) render() { const { children, defaultValue, disabled, error, floating, hint, icon, name, label: labelText, maxLength, multiline, required, role, theme, type, value, onKeyPress, rows = 1, ...others } = this.props; const length = maxLength && value ? value.length : 0; const labelClassName = classnames(theme.label, { [theme.fixed]: !floating }); const className = classnames(theme.input, { [theme.disabled]: disabled, [theme.errored]: error, [theme.hidden]: type === 'hidden', [theme.withIcon]: icon, }, this.props.className); const valuePresent = this.valuePresent(value) || this.valuePresent(defaultValue); const inputElementProps = { ...others, className: classnames(theme.inputElement, { [theme.filled]: valuePresent }), onChange: this.handleChange, ref: (node) => { this.inputNode = node; }, role, name, defaultValue, disabled, required, type, value, }; if (!multiline) { inputElementProps.maxLength = maxLength; inputElementProps.onKeyPress = onKeyPress; } else { inputElementProps.rows = rows; inputElementProps.onKeyPress = this.handleKeyPress; } return ( <div data-react-toolbox="input" className={className}> {React.createElement(multiline ? 'textarea' : 'input', inputElementProps)} {icon ? <FontIcon className={theme.icon} value={icon} /> : null} <span className={theme.bar} /> {labelText ? <label className={labelClassName}> {labelText} {required ? <span className={theme.required}> * </span> : null} </label> : null} {hint ? <span hidden={labelText} className={theme.hint}>{hint}</span> : null} {error ? <span className={theme.error}>{error}</span> : null} {maxLength ? <span className={theme.counter}>{length}/{maxLength}</span> : null} {children} </div> ); } } return Input; }; const Input = factory(InjectedFontIcon); export default themr(INPUT)(Input); export { factory as inputFactory }; export { Input };
// const BlueRPC = require('../../lib'); // describe('HTTP', // require('./tests.skip.js')( // BlueRPC.Server.HTTP, // BlueRPC.Client.HTTP // ) // ); // const async = require('async'); // module.exports = (Server, Client) => { // return () => { // let server, client, client2, state; // beforeEach((done) => { // state = { // server: { // clients: 0, // store: [], // }, // }; // server = new Server(); // server.on('connect', () => { // state.server.clients++; // }); // server.on('close', () => { // state.server.clients--; // }); // server.register('echo', (params) => { // return params[0]; // }); // server.register('save', (params) => { // state.server.store.push(params[0]); // }); // server.listen({}, () => { // client = new Client(); // client2 = new Client(); // async.parallel([ // (cb) => { // client.on('connect', () => { // cb(null, null); // }); // }, // (cb) => { // client2.on('connect', () => { // cb(null, null); // }); // }, // ], (err, results) => done()); // }); // }); // afterEach((done) => { // client.end(); // client2.end(); // server.deRegister('echo'); // server.deRegister('save'); // server.close(done); // }); // describe('Request', () => { // it('client: should send and receive hello (2x)', (done) => { // const message = 'hello'; // async.parallel([ // (cb) => { // setTimeout(() => { // client.request('echo', [message], (err, result) => { // cb(err, result); // }); // }, 0); // }, // (cb) => { // setTimeout(() => { // client.request('echo', [message], (err, result) => { // cb(err, result); // }); // }, 10); // }, // ], (err, results) => { // expect(results[0]).toBe(message); // expect(results[1]).toBe(message); // done(); // }); // }); // it('client2: should send and receive world (2x)', (done) => { // const message = 'world'; // async.parallel([ // (cb) => { // setTimeout(() => { // client2.request('echo', [message], (err, result) => { // cb(err, result); // }); // }, 0); // }, // (cb) => { // setTimeout(() => { // client2.request('echo', [message], (err, result) => { // cb(err, result); // }); // }, 10); // }, // ], (err, results) => { // expect(results[0]).toBe(message); // expect(results[1]).toBe(message); // done(); // }); // }); // it('should have 2 connections', (done) => { // setTimeout(() => { // expect(state.server.clients).toBe(2); // done(); // }, 0); // }); // }); // describe('Notify', () => { // it('should receive messages fron client', (done) => { // const messages = ['foo', 'bar']; // async.parallel([ // (cb) => { // setTimeout(() => { // client.notify('save', [messages[0]]); // cb(null,null); // }, 0); // }, // (cb) => { // setTimeout(() => { // client.notify('save', [messages[1]]); // cb(null,null); // }, 10); // }, // ], (err, results) => { // setTimeout(() => { // expect(state.server.store.length).toBe(2); // expect(state.server.store).toContain(messages[0]); // expect(state.server.store).toContain(messages[1]); // done(); // }, 0); // }); // }); // it('should have 2 connections', (done) => { // setTimeout(() => { // expect(state.server.clients).toBe(2); // done(); // }, 0); // }); // }); // describe('Batch', () => { // it('should send and receive batch(req: 1, notify: 1)', (done) => { // const message = 'hello'; // let res = null; // setTimeout(() => { // const req = client.makeRequest('echo', [message], function(err, result){ // res = result; // }); // const not = client.makeNotify('save', [message]); // client.batch([req, not]); // }, 0); // setTimeout(() => { // expect(res).toBe(message); // expect(state.server.store.length).toBe(1); // expect(state.server.store).toContain(message); // done(); // }, 10); // }); // it('should have 2 connections', (done) => { // setTimeout(() => { // expect(state.server.clients).toBe(2); // done(); // }, 0); // }); // }); // }; // };
(function(exports) { // $(document).ready(function() { console.log('bar.js'); var senior = (6/8), major = (35/56), game = (12/24); var data = [ {label: "Cornell University Senior", detail: "6 of 8 semesters", value: senior}, {label: "Computer Science Major", detail: "35 of 56 core credits", value: major}, // 35 out of 56 credits {label: "Game Design Minor", detail: "12 of 24 credits", value: game} ]; var blueShades = function(d) { frac = d.value; // get fraction // return d3.hsl(200, frac, 0.3); return d3.rgb(30, 150, 150); }; var dataset = [senior, major, game]; var width = 760, barHeight = 80; var x = d3.scale.linear() .range([0, width]); var chart = d3.select(".bar-chart") .append("svg"); // .attr("width", width); chart.attr("height", barHeight * data.length); var bar = chart.selectAll("g") .data(data) .enter().append("g") // .attr("class", "bar-chart-item") .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; }); // gray bar bar.append("rect") .attr("class", "gray-rect") .attr("fill", "#dadada") .attr("width", 760) .attr("rx", 2) .attr("ry", 2) .attr("height", barHeight - 15); // blue bar bar.append("rect") .attr("class", "blue-rect") .attr("fill", function(d) { return blueShades(d); }) // .attr("width", function(d) { return x(d.value); }) .attr("width", 760) .attr("rx", 2) .attr("ry", 2) .attr("height", barHeight - 15); bar.append("text") .attr("class", "completed") // .attr("x", function(d) { return x(d.value) - 20; }) .attr("x", 760/2) .attr("y", barHeight / 2) .attr("dy", "0em") .attr("text-anchor", "middle") .text(function(d) { return d.label; }); bar.append("text") .attr("class", "percents") .attr("text-anchor", "start") // .attr("x", function(d) { return x(d.value) + 20; }) .attr("x", function(d) { return 760; }) .attr("y", barHeight / 2) .attr("dy", "0em") .text(function(d) { return d.detail; }); // .text(function(d) { return Math.round(d.value * 100) + "% completed"; }); bar.on("mouseover", function(d) { wid = d3.select(this).select(".blue-rect").attr("width"); xval = d3.select(this).select(".completed").attr("x"); xval2 = d3.select(this).select(".percents").attr("x"); len = d3.select(this).select(".completed").node().getBBox().width; // console.log(len); d3.select(this).select(".blue-rect").transition() .attrTween("width", function() { return d3.interpolate(wid, x(d.value)); }) // .ease("linear") .duration(200); d3.select(this).select(".completed").transition() .attrTween("x", function() { return d3.interpolate(xval, x(d.value) - len/2 - 20); }) // .ease("linear") .duration(200); d3.select(this).select(".percents").transition() .attrTween("x", function() { return d3.interpolate(xval2, x(d.value) + 20); }) .duration(200); }) .on("mouseout", function(d) { wid = d3.select(this).select(".blue-rect").attr("width"); xval = d3.select(this).select(".completed").attr("x"); xval2 = d3.select(this).select(".percents").attr("x"); d3.select(this).select(".blue-rect").transition() .attrTween("width", function() { return d3.interpolate(wid, 760); }) // .ease("linear") .duration(200); d3.select(this).select(".completed").transition() .attrTween("x", function() { return d3.interpolate(xval, 760/2); }) // .ease("linear") .duration(200); d3.select(this).select(".percents").transition() .attrTween("x", function() { return d3.interpolate(xval2, 760); }) .duration(200); }); })(this.bar = {}); (function(exports) { // $(document).ready(function() { // Thanks to http://bl.ocks.org/dbuezas/9306799 // and http://bl.ocks.org/mbostock/32bd93b1cc0fbccc9bf9 // based on hours per two weeks console.log('pie.js'); var data = [ {label: 'Quora', count: 3, desc: 'I like reading funny and random anecdotes. At the heart of Quora is storytelling.'}, {label: 'Gaming', count: 2, desc: 'My favorite Games include Bastion, Don\'t Starve, and Crypt of the NecroDancer.'}, {label: 'Band', count: 4, desc: 'Saxophones Rule.'}, {label: 'Painting', count: 1, desc: 'Started with acrylic, now experimenting with watercolor too.'}, {label: 'Napping', count: 2, desc: '<insert sleeping pusheen>'}, {label: 'Spotify', count: 3, desc: 'Genres appreciated include dance pop, chill pop, ambient, and swing.'} ]; var color = d3.scale.ordinal() // .range(['#98c3c7', '#419596', '#00657a', '#003b56']); .range(['#003b56', '#00657a', '#419596', '#98c3c7']); var blueShades = function(d) { // rgb(0,150,130) is our base (angle 0) frac = d.startAngle / (2 * Math.PI); // get fraction amt = frac * 225; return d3.rgb(30 + amt, 150, 150); }; var hoverShades = function(d) { // rgb(0,150,130) is our base (angle 0) frac = d.startAngle / (2 * Math.PI); // get fraction amt = frac * 225; return d3.rgb(amt + 60, 180, 180); }; var width = 800, height = 450, radius = Math.min(width, height) / 2; var outerRadius = height / 2 - 20, innerRadius = outerRadius / 3; var pie = d3.layout.pie() .sort(null) // disables the sort by size .padAngle(0.025) .value(function(d) { return d.count; }); var arc = d3.svg.arc() .padRadius(outerRadius) .innerRadius(innerRadius); var innerArc = d3.svg.arc() .outerRadius(outerRadius) .innerRadius(innerRadius); // cool trick to center labels - use an extra arc var outerArc = d3.svg.arc() .innerRadius(0.9 * radius) .outerRadius(0.9 * radius); var svg = d3.select(".pie-chart") .append("svg") .append("g") .attr("transform", "translate(" + width / 2 + "," + (height + 50) / 2 + ")"); var g = svg.selectAll(".slice-group") .data(pie(data)) .enter().append("g") .attr("class", "slice-group"); // PIE SLICES g.append("path") .each(function(d) { d.outerRadius = outerRadius - 20; }) .attr("d", arc) .style("fill", function(d) { return blueShades(d); }) .on("mouseover", function(d) { d3.select(this).style("fill", function(d) { return hoverShades(d); }); d3.select(this.parentNode).select('.label-desc') .text(function(d) { return d.data.desc; }) .call(wrap, 150); }) .on("mouseout", function(d) { d3.select(this).style("fill", function(d) { return blueShades(d); }); d3.select(this.parentNode).select('.label-desc').text(''); }); g.append("text").attr("class", "label-blurb"); g.append("text").attr("class", "label-desc"); g.append("polyline"); // TEXT LABELS var text = svg.selectAll(".slice-group").selectAll(".label-blurb") .attr("dy", "0.25em") // center the text next to the lines .text(function(d) { return d.data.label; }); var desc = svg.selectAll(".slice-group").selectAll(".label-desc") .attr("dy", "2em") // center the text next to the lines .attr("font-size", "0.7em"); function midAngle(d) { return d.startAngle + (d.endAngle - d.startAngle)/2; } function wrap(text, width) { text.each(function() { var text = d3.select(this), words = text.text().split(/\s+/).reverse(), word, line = [], lineNumber = 0, y = text.attr("y"), dy = parseFloat(text.attr("dy")), tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", "1.4em").text(word); } } }); } text.attr("transform", function(d) { pos = outerArc.centroid(d); // returns [x,y] // editing the x coord pos[0] = radius * (midAngle(d) < Math.PI ? 1.05 : -1.05); return "translate(" + pos + ")"; }) // aligning to end of text vs. beginning of text .attr("text-anchor", function(d) { return midAngle(d) < Math.PI ? "start" : "end"; }); desc.attr("transform", function(d) { pos = outerArc.centroid(d); // returns [x,y] // editing the x coord pos[0] = radius * (midAngle(d) < Math.PI ? 1.05 : -1.05); return "translate(" + pos + ")"; }) // aligning to end of text vs. beginning of text .attr("text-anchor", function(d) { return midAngle(d) < Math.PI ? "start" : "end"; }); // LINES var line = svg.selectAll(".slice-group").selectAll("polyline"); line.attr("points", function(d) { pos = outerArc.centroid(d); pos[0] = radius * (midAngle(d) < Math.PI ? 1.0 : -1.0); return [innerArc.centroid(d), outerArc.centroid(d), pos]; }); })(this.pie = {});
import React from 'react' import { Link } from 'react-router-dom' import RaisedButton from 'material-ui/RaisedButton' class Home extends React.Component { render() { return ( <div id='home' > <h1>Welcome to Bookaholics Anonymous</h1> <h4>Trade books with people in your area</h4> <Link to='/login'> <RaisedButton label='Login' primary className='home-btns'/> </Link> <Link to='/register'> <RaisedButton label='Register' primary className='home-btns'/> </Link> </div> ); } } export default Home
'use strict'; var yaocho = angular.module('yaocho'); yaocho.controller('NavCtrl', ['$scope', '$rootScope', function($scope, $rootScope) { var locationTrail = []; $rootScope.ui = { backHidden: true, current: { title: gettext('Mozilla Support'), } }; $scope.ui = $rootScope.ui; $scope.back = function() { window.history.back(); }; $scope.showMenu = function() { $rootScope.$emit('mainMenu.show'); }; $rootScope.$on('$locationChangeSuccess', function(ev) { $scope.ui.backHidden = false; }); }]); yaocho.controller('FlashCtrl', ['$scope', '$rootScope', '$timeout', function($scope, $rootScope, $timeout) { $scope.messages = []; $rootScope.$on('flash', function(ev, message) { $scope.messages.push(message); $timeout(function() { var index = $scope.messages.indexOf(message); if (index >= 0) { $scope.messages.splice(index, 1); } }, 5000) }) }]); yaocho.controller('LoadingCtrl', ['$scope', '$rootScope', function($scope, $rootScope) { $scope.total = 0; $scope.loaded = 0; $scope.message = null; $rootScope.$on('loading.incr', function(ev, message) { if (message) { $scope.message = message; } $scope.total++; }); $rootScope.$on('loading.decr', function(ev, count) { $scope.loaded++; if ($scope.loaded > $scope.total) { console.error('More things finished loading than started loading.'); } }); $rootScope.$on('loading.flush', function(ev) { if ($scope.loaded !== $scope.total) { console.error('Loading flush when not everything was loaded.'); } $scope.total = 0; $scope.loaded = 0; $scope.message = null; }); }]); yaocho.directive('alink', ['urlManager', '$location', 'safeApply', function(urlManager, $location, safeApply) { return { restrict: 'A', link: function(scope, element, attrs){ var params = {}; angular.forEach(attrs, function(value, key){ if(key !== 'view' && key !== 'text' && key !== 'class' && key.charAt(0) !== '$'){ params[key] = value; } }); element.on('click', function(ev) { ev.preventDefault(); safeApply(function() { var url = urlManager.reverse(attrs.view, params); $location.url(url); }); }); } } }]);
export const androidSync = {"viewBox":"0 0 512 512","children":[{"name":"path","attribs":{"d":"M256,93.09V32l-80,81.454l80,81.456v-61.093c65.996,0,120,54.982,120,122.183c0,20.363-5,39.714-14.004,57.016L391,342.547\r\n\tc15.996-25.457,25-54.988,25-86.547C416,166.401,343.998,93.09,256,93.09z M256,378.184c-66.001,0-120-54.988-120-122.184\r\n\tc0-20.363,5-39.709,13.999-57.02L121,169.454C104.999,193.89,96,224.436,96,256c0,89.599,72.002,162.91,160,162.91V480l80-81.453\r\n\tl-80-81.457V378.184z"},"children":[]}]};
// @flow import { first, last } from 'lodash/fp'; import { Pattern, CaptureElement, CaptureWildcard } from '../modules/patternMatcher'; import type { Transformer } from '../modules/transformer/types'; import { basePercentage } from '../modules/math/types'; import type { PercentageNode } from '../modules/math/types'; // eslint-disable-line import { TOKEN_NUMBER, TOKEN_PERCENTAGE } from '../tokenTypes'; import { uncastArray } from '../util'; const entityTransform: Transformer = { // TODO: Could be made more efficient pattern: new Pattern([ new CaptureElement(TOKEN_NUMBER).negate().lazy().any(), new Pattern([ new CaptureElement(TOKEN_NUMBER), new CaptureElement(TOKEN_PERCENTAGE), new CaptureWildcard().lazy().any(), ]), ]), transform: (captureGroups, transform) => transform([ captureGroups[0], captureGroups[3], ], segments => { const value: number = captureGroups[1][0].value; const percentage: PercentageNode = { ...basePercentage, value }; const concatSegments = [].concat( first(segments), percentage, last(segments) ); return uncastArray(concatSegments); }), }; export default entityTransform;
var https = require('https'); var qsocks = require('qsocks'); var fs = require('fs'); var request = require('request'); var Promise = require("promise"); // var js2xmlparser = require('js2xmlparser'); var appList = require('./lib/app-list'); var connList = require('./lib/app-connections'); var appTables = require('./lib/app-tables'); var libDimensions = require('./lib/app-library-dimensions'); var libMeasures = require('./lib/app-library-measures'); var libObjects = require('./lib/app-library-masterobjects'); var appBookmarks = require('./lib/app-bookmarks'); var appSheets = require('./lib/app-sheets'); var appStories = require('./lib/app-stories'); var cmd_args = process.argv; var using_defaults = true; var server_address = 'localhost'; var server_certificate = __dirname + '\\client.pfx'; var pem_client_key_certificate = __dirname + '\\client_key.pem'; var pem_client_certificate = __dirname + '\\client.pem'; var pem_root_certificate = __dirname + '\\root.pem'; var user_directory = ''; var user_name = ''; var origin = 'localhost'; var single_app = false; var single_user = false; var single_app_id = ''; var users_list = []; cmd_args.forEach(function(val,index){ if(index!=0 && index!=1){ switch(val){ case '-h': helper(); break; case '-a': if(cmd_args[index+1]){ server_address = cmd_args[index+1]; using_defaults=false; } else{ console.log("Please check the server address argument. Type '-h' for help."); process.exit(); } break; case '-c': if(cmd_args[index+1]){ server_certificate = cmd_args[index+1]; using_defaults=false; } else{ console.log("Please check the server certificate file path argument. Type '-h' for help."); process.exit(); } break; case '-ud': if(cmd_args[index+1]) user_directory = cmd_args[index+1]; else{ console.log("Please check the user directory argument. Type '-h' for help."); process.exit(); } break; case '-un': if(cmd_args[index+1]) user_name = cmd_args[index+1]; else{ console.log("Please check the user name argument. Type '-h' for help."); process.exit(); } break; case '-o': if(cmd_args[index+1]){ origin = cmd_args[index+1]; using_defaults=false; } else{ console.log("Please check the origin address argument. Type '-h' for help."); process.exit(); } break; case '-s': if(cmd_args[index+1]){ single_app_id = cmd_args[index+1]; single_app=true; } else{ console.log("Please check the application id argument. Type '-h' for help."); process.exit(); } break; case '-su': single_user=true; break; default: if (cmd_args[index-1]!='-h'&&cmd_args[index-1]!='-a'&&cmd_args[index-1]!='-c'&&cmd_args[index-1]!='-ud'&&cmd_args[index-1]!='-un'&&cmd_args[index-1]!='-o'&&cmd_args[index-1]!='-s') console.log("'"+val+"' is not a valid command. Type '-h' for help."); break; } } }) //check for root admin specification to be different than null if(user_directory=='' || user_name==''){ console.log("Root admin is not correctly specified. Type '-h' for help."); process.exit(); } console.log(); console.log("Loading the Applications Information for your environment"); //default configs warning if(using_defaults){ console.log(); console.log("Warning: besides user identification, you are using all"); console.log(" the default configurations."); } users_list.push({userDirectory: user_directory.toUpperCase(), userId: user_name}); if(!single_user) { //loading a list of all users to get their personal developments var get_ulist_options = { hostname: server_address, port: 4242, path: '/qrs/user?xrfkey=abcdefghijklmnop', method: 'GET', headers: { 'x-qlik-xrfkey' : 'abcdefghijklmnop', 'X-Qlik-User' : 'UserDirectory= sensedemo; UserId= sense ' }, key: fs.readFileSync(pem_client_key_certificate), cert: fs.readFileSync(pem_client_certificate), ca: fs.readFileSync(pem_root_certificate) }; https.get(get_ulist_options, function(res) { res.on("data", function(chunk) { var jsonified = JSON.parse(chunk); for (var i = 0; i < jsonified.length; i++){ if(jsonified[i].userDirectory != 'INTERNAL' && !(jsonified[i].userDirectory.toUpperCase() == user_directory.toUpperCase() && jsonified[i].userId.toUpperCase() == user_name.toUpperCase())){ users_list.push({userDirectory: jsonified[i].userDirectory, userId: jsonified[i].userId}); } } appsInfo(users_list); }); }).on('error', function(e) { console.log("Got error: " + e.message); }); } else { appsInfo(users_list); } //Load apps infos (TODO finish for all users) function appsInfo(users_list){ // console.log("Users to load: ", users_list); console.log("Loading information as user: " + users_list[0].userDirectory + "\\" + users_list[0].userId); //setting up the connection (based on mindspank's https://github.com/mindspank/qsocks examples) var connection_data = { server_address : server_address, server_certificate : server_certificate, user_directory : users_list[0].userDirectory, user_name : users_list[0].userId, origin : origin, single_app_id: single_app_id } //Request defaults var r = request.defaults({ rejectUnauthorized: false, host: connection_data.server_address, pfx: fs.readFileSync(connection_data.server_certificate) }) //Authenticating the user var b = JSON.stringify({ "UserDirectory": connection_data.user_directory, "UserId": connection_data.user_name, "Attributes": [] }); var u = 'https://'+connection_data.server_address+':4243/qps/ticket?xrfkey=abcdefghijklmnop'; r.post({ uri: u, body: b, headers: { 'x-qlik-xrfkey': 'abcdefghijklmnop', 'content-type': 'application/json' } }, function(err, res, body) { var hub = 'https://'+connection_data.server_address+'/hub/?qlikTicket='; var ticket = JSON.parse(body)['Ticket']; r.get(hub + ticket, function(error, response, body) { var cookies = response.headers['set-cookie']; var o = 'http://'+connection_data.origin; var config = { host: connection_data.server_address, isSecure: true, origin: o, rejectUnauthorized: false, headers: { "Content-Type": "application/json", "Cookie": cookies[0] } } // Connect to qsocks/qix engine qsocks.Connect(config).then(function(global) { // console.log(global); run(connection_data, single_app); function run(connection_data, single_app){ appList.getAppList(connection_data, global).then(function(apl_msg){ console.log(apl_msg); connList.getAppConnections(connection_data, global).then(function(cn_msg){ console.log(cn_msg); appTables.getAppTbls(connection_data, global, cookies, single_app).then(function(tbl_msg){ console.log(tbl_msg); libDimensions.getLibDimensions(connection_data, global, cookies, single_app).then(function(libDim_msg){ console.log(libDim_msg); libMeasures.getLibMeasures(connection_data, global, cookies, single_app).then(function(libMsr_msg){ console.log(libMsr_msg); libObjects.getLibObjects(connection_data, global, cookies, single_app).then(function(libObj_msg){ console.log(libObj_msg); appBookmarks.getBookmarks(connection_data, global, cookies, single_app).then(function(bmk_msg){ console.log(bmk_msg); appSheets.getSheets(connection_data, global, cookies, single_app).then(function(sht_msg){ console.log(sht_msg); appStories.getAppStories(connection_data, global, cookies, single_app).then(function(str_msg){ console.log(str_msg); console.log("Success: Finished loading all the data for your user " + users_list[0].userDirectory + "\\" + users_list[0].userId); users_list.shift(); // console.log(users_list.length); // console.log(users_list[0].userId); if(users_list.length==0) process.exit(); else appsInfo(users_list); });//app stories });//app sheets });//app bookmarks });//lib objects });//lib measures });//lib dimensions });//app tables });// connections }); //app list }// run })//qsocks connect (global) });// r.get });// r }//appsInfo() /*************************** Command Line Helper ***************************/ function helper(){ console.log(); console.log("******************************************************"); console.log(" Welcome to the Applications Information Loader "); console.log(" for your Qlik Server Environment "); console.log("******************************************************"); console.log(" Configuration instructions "); console.log(); console.log("This tool requires the following information."); console.log(); console.log("* Qlik Sense Server") console.log(" -a: Qlik Sense Server address.") console.log(" Default if unspecified: 'localhost'") console.log(); console.log(" -c: Qlik Sense Server certificate location (at the "); console.log(" moment it was only tested with blank password"); console.log(" certificates). If the path has spaces, indicate it"); console.log(" using double quotes."); console.log(" Default if unspecified: file 'client.pfx' at root"); console.log(" folder of this tool") console.log(); console.log(); console.log("* Root Admin") console.log(" -ud: User Directory of the Qlik Sense Server Root Admin"); console.log(" to call the server API functions"); console.log(" This is mandatory.") console.log(); console.log(" -un: User Name of the Qlik Sense Server Root Admin to"); console.log(" call the server API functions"); console.log(" This is mandatory.") console.log(); console.log(); console.log("* Origin address for the request (this computer)") console.log(" -o: This is optional. Default value is 'localhost'. "); console.log(" The origin specified needs an entry in the Whitelist"); console.log(" for the virtual proxy to allow websocket communication."); console.log(); console.log(); console.log("* Additional Options") console.log(" -s: Single application mode."); console.log(" Load information of only one application given it's ID."); console.log(" Applications list and connections are still fully loaded."); console.log(); console.log(" -su: Single user mode."); console.log(" Load information of only for the user specified as Root Admin."); console.log(); console.log(" -h: Launches this helper."); process.exit(); }
/** * * DASH4 configuration * https://github.com/smollweide/dash4 * */ const { PluginTerminal } = require('@dash4/plugin-terminal'); const { PluginReadme } = require('@dash4/plugin-readme'); const { PluginNpmScripts } = require('@dash4/plugin-npm-scripts'); const { PluginActions } = require('@dash4/plugin-actions'); async function getConfig() { return { port: 4444, tabs: [ { title: 'START', rows: [ [new PluginReadme({ file: 'readme.md' })], [ new PluginTerminal({ title: 'Development Mode (Light)', cmd: 'npm start', dark: true, autostart: false, }), new PluginTerminal({ title: 'Development Mode (Dark)', cmd: 'npm run start:dark', dark: true, autostart: false, }), new PluginTerminal({ title: 'Cypress Mode', cmd: 'npm run cypress-test', dark: true, autostart: false, }), new PluginTerminal({ title: 'Production Mode', cmd: 'npm run prod', dark: true, autostart: false, }), ], [ new PluginNpmScripts({ scripts: [ { title: 'Run Linting', cmd: 'npm run lint' }, { title: 'Run Tests', cmd: 'npm run test' }, { title: 'Run Visual Tests', cmd: 'npm run visual-test' }, { title: 'Get Lighthouse Score', cmd: 'npm run lighthouse-test' }, ], }), new PluginNpmScripts({ scripts: [ { title: 'Run Prettier', cmd: 'npm run prettier' }, { title: 'Update Dependencies', cmd: 'npm run update-dependencies' }, { title: 'Clean', cmd: 'npm run clean' }, ], }), ], [ new PluginActions({ title: 'Links', actions: [ { type: 'link', href: 'https://nitro-project-test.netlify.app/', title: 'Proto Server', }, ], }), ], ], }, { title: 'READMES', rows: [ [new PluginReadme({ file: 'project/docs/nitro.md' })], [ new PluginReadme({ file: 'project/docs/nitro-config.md' }), new PluginReadme({ file: 'project/docs/nitro-webpack.md' }), new PluginReadme({ file: 'project/docs/nitro-themes.md' }), new PluginReadme({ file: 'project/docs/nitro-exporter.md' }), ], ], }, ], }; } module.exports = getConfig;
'use strict'; /* React component containing the whole game interface */ import React from 'react'; import Globals from '../../libs/globals'; import Socket from '../../libs/socket'; import reactBootstrap from 'react-bootstrap'; var Button = reactBootstrap.Button; var Glyphicon = reactBootstrap.Glyphicon; var ButtonToolbar = reactBootstrap.ButtonToolbar; export default class Room extends React.Component { constructor(props) { super(props); this.state = { players: [] }; } /** * Triggered when the component is rendered, initialize the component */ componentDidMount() { this.initSocket(); } /** * Render the room interface * @return {React.Element} the rendered element */ render() { var playersRendered, players = this.state.players, startButton; //include himself if no players in the room if(players.length === 0) { players.push({ id: this.props.player.getId(), name: this.props.player.getName() }); } playersRendered = players.map((player) => { return (<li className={'player-elem'} key={player.id}><Glyphicon glyph="user" /> {player.name}</li>); }); if(players.length >= 2) { startButton = (<Button bsSize={'small'} className={'pull-right'} bsStyle={'success'} ref="startButton" onClick={this.start.bind(this)}> Start <Glyphicon glyph="arrow-right" /> </Button>); } else { playersRendered.push(<li key={'waiting'}>Waiting for more players...</li>); } return ( <div className={'room'}> <ul className={'list-info'}> {playersRendered} </ul> <ButtonToolbar className={'pull-right'}> {startButton} <Button bsSize="small" className={'pull-right'} bsStyle="info" ref="leaveButton" onClick={this.leave.bind(this)}> Leave Game #{this.props.game.id} <Glyphicon glyph="arrow-left" /> </Button> </ButtonToolbar> </div> ); } /** * Start button */ start() { Socket.emit(Globals.socket.gameStart, this.props.game.id); } /** * Leave button */ leave() { Socket.emit(Globals.socket.gameQuit); } /** * Init the socket receiver for the game */ initSocket() { //list of players Socket.on(Globals.socket.gamePlayers, (response) => { this.setState({players: response.players}); }); //game started Socket.on(Globals.socket.gameStart, (response) => { var other = this.state.players.filter(e => e.id !== this.props.player.getId()); this.props.onStart(response.board, {other: other, me: { id: this.props.player.getId(), name: this.props.player.getName() } }); }); //game leave Socket.on(Globals.socket.gameQuit, () => { this.props.onLeave(); }); } /** * When the component is destroyed */ componentWillUnmount() { Socket.removeAllListeners(Globals.socket.gamePlayers); Socket.removeAllListeners(Globals.socket.gameStart); Socket.removeAllListeners(Globals.socket.gameQuit); } } Room.propTypes = { player: React.PropTypes.any.isRequired, game: React.PropTypes.any.isRequired, onStart: React.PropTypes.func, onLeave: React.PropTypes.func }; Room.displayName = 'Room';
import { moduleFor, test } from 'ember-qunit'; moduleFor('route:people/index', 'PeopleIndexRoute', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); test('it exists', function() { var route = this.subject(); ok(route); });
"use strict"; import {xhrGet} from './xhrGet'; import lzbase62 from "./lzbase62.min"; import {json} from './json'; let kanaPos = { 'ア' : {start:0.932,dulation:0.579}, 'イ' : {start:2.135,dulation:0.452}, 'ウ' : {start:3.383,dulation:0.439}, 'エ' : {start:4.654,dulation:0.412}, 'オ' : {start:5.957,dulation:0.434}, 'カ' : {start:7.402,dulation:0.513}, 'キ' : {start:8.595,dulation:0.310}, 'ク' : {start:9.746,dulation:0.378}, 'ケ' : {start:10.960,dulation:0.410}, 'コ' : {start:12.288,dulation:0.348}, 'サ' : {start:13.748,dulation:0.299}, 'シ' : {start:14.741,dulation:0.372}, 'ス' : {start:15.874,dulation:0.370}, 'セ' : {start:16.984,dulation:0.343}, 'ソ' : {start:18.092,dulation:0.287}, 'タ' : {start:19.486,dulation:0.391}, 'チ' : {start:20.593,dulation:0.358}, 'ツ' : {start:21.701,dulation:0.378}, 'テ' : {start:22.761,dulation:0.305}, 'ト' : {start:23.819,dulation:0.269}, 'ナ' : {start:25.669,dulation:0.403}, 'ニ' : {start:26.730,dulation:0.400}, 'ヌ' : {start:27.845,dulation:0.382}, 'ネ' : {start:28.987,dulation:0.359}, 'ノ' : {start:30.061,dulation:0.316}, 'ハ' : {start:32.065,dulation:0.444}, 'ヒ' : {start:33.252,dulation:0.341}, 'フ' : {start:34.221,dulation:0.464}, 'ヘ' : {start:35.354,dulation:0.356}, 'ホ' : {start:36.435,dulation:0.395}, 'マ' : {start:39.229,dulation:0.469}, 'ミ' : {start:40.265,dulation:0.349}, 'ム' : {start:41.455,dulation:0.371}, 'メ' : {start:42.586,dulation:0.343}, 'モ' : {start:43.679,dulation:0.281}, 'ラ' : {start:46.607,dulation:0.367}, 'リ' : {start:47.663,dulation:0.310}, 'ル' : {start:48.765,dulation:0.335}, 'レ' : {start:49.801,dulation:0.360}, 'ロ' : {start:50.803,dulation:0.310}, 'ヤ' : {start:58.073,dulation:0.455}, 'ユ' : {start:59.019,dulation:0.390}, 'ヨ' : {start:60.006,dulation:0.275}, 'ワ' : {start:53.676,dulation:0.505}, 'ヲ' : {start:54.744,dulation:0.351}, 'ン' : {start:55.828,dulation:0.317}, 'ガ' : {start:62.907,dulation:0.365}, 'ギ' : {start:63.943,dulation:0.353}, 'グ' : {start:65.178,dulation:0.307}, 'ゲ' : {start:66.286,dulation:0.404}, 'ゴ' : {start:67.435,dulation:0.382}, 'ザ' : {start:69.180,dulation:0.390}, 'ジ' : {start:70.200,dulation:0.363}, 'ズ' : {start:71.296,dulation:0.348}, 'ゼ' : {start:72.418,dulation:0.327}, 'ゾ' : {start:73.431,dulation:0.274}, 'バ' : {start:75.452,dulation:0.413}, 'ビ' : {start:76.523,dulation:0.335}, 'ブ' : {start:77.646,dulation:0.361}, 'ベ' : {start:78.823,dulation:0.359}, 'ボ' : {start:80.012,dulation:0.320}, 'ダ' : {start:81.987,dulation:0.565}, 'ヂ' : {start:83.007,dulation:0.343}, 'ヅ' : {start:84.086,dulation:0.395}, 'デ' : {start:85.137,dulation:0.362}, 'ド' : {start:86.206,dulation:0.310}, 'パ' : {start:88.755,dulation:0.320}, 'ピ' : {start:89.819,dulation:0.305}, 'プ' : {start:90.821,dulation:0.410}, 'ペ' : {start:91.906,dulation:0.390}, 'ポ' : {start:93.018,dulation:0.347}, 'キャ' : {start:95.415,dulation:0.432}, 'キュ' : {start:96.540,dulation:0.415}, 'キョ' : {start:98.014,dulation:0.336}, 'シャ' : {start:99.399,dulation:0.556}, 'シュ' : {start:100.528,dulation:0.438}, 'ショ' : {start:101.491,dulation:0.344}, 'チャ' : {start:103.782,dulation:0.462}, 'チュ' : {start:104.838,dulation:0.395}, 'チョ' : {start:105.913,dulation:0.275}, 'ニャ' : {start:108.189,dulation:0.396}, 'ニュ' : {start:109.302,dulation:0.378}, 'ニョ' : {start:110.345,dulation:0.362}, 'ミャ' : {start:112.013,dulation:0.455}, 'ミュ' : {start:113.101,dulation:0.365}, 'ミョ' : {start:114.149,dulation:0.298}, 'ギャ' : {start:116.243,dulation:0.395}, 'ギュ' : {start:117.311,dulation:0.508}, 'ギョ' : {start:118.426,dulation:0.356}, 'ビャ' : {start:120.360,dulation:0.346}, 'ビュ' : {start:121.411,dulation:0.324}, 'ビョ' : {start:122.535,dulation:0.373}, 'リャ' : {start:124.609,dulation:0.389}, 'リュ' : {start:125.698,dulation:0.328}, 'リョ' : {start:126.783,dulation:0.298} }; export class Movie { constructor(vm){ this.movieData = null; this.loaded = false; this.vm = vm; let audio = vm.audio; let filter = this.filter = audio.audioctx.createBiquadFilter(); filter.type = 'lowpass'; filter.frequency.value = 4000; filter.Q.value = 0.0001; this.gain = audio.audioctx.createGain(); this.gain.gain.value = 0.5; this.gain.connect(audio.audioctx.destination); this.filter.connect(this.gain); } loadMovie(){ let self = this; if(this.movieData){ this.loaded = true; } else { xhrGet('../../dist/res/movie.txt') .then((d)=>{ return new Promise((resolve,reject)=>{ let t = []; lzbase62.decompress(d,{ onData(data){ t.push(data); }, onEnd(){ self.movieData = JSON.parse(t.join('')); self.loaded = true; resolve(self.movieData); } }); }); // movieData = JSON.parse(t); // loaded = true; }); } return Promise.resolve(this.movieData); } createMovieVoice(){ let bs = this.vm.audio.audioctx.createBufferSource(); let movieSample = this.vm.audio.getWaveSample(24); bs.buffer = movieSample.sample; bs.loop = false; bs.onended = (function(){ this.disconnect(); }).bind(bs); return bs; } *playMovie(colors) { let vm = this.vm; while(!this.loaded){ yield; } let bs = this.bs = this.createMovieVoice(); this.bs.connect(this.filter); bs.start(0); this.idx = 0; let e = this.movieData.length; for(this.idx = 0;this.idx < e;++this.idx){ let md = this.movieData[this.idx]; for(var y = 0,ey = vm.consoleHeight;y < ey;++y){ for(var x = 0,ex = vm.consoleWidth;x < ex;++x){ let cn = md[x + y * ex]; let c = colors[cn]; vm.setColor(x,y,c[0],c[1]); } } yield; } } pause(){ this.bs.stop(); } resume(){ this.bs = this.createMovieVoice(); this.bs.connect(this.filter); this.bs.connect(this.filter); this.bs.start(0,this.idx / 60); } stop(){ this.bs.stop(); } visibilityChange(){ let bs = this.bs; if(window.document.hidden){ bs.stop(0); } else { bs = createMovieVoice(); bs.connect(this.filter); bs.start(0,this.idx / 60); } } }
var batchcompute = require('./batchcompute'); /** * */ var jobId = 'job-00000000559638EC00005F780000069A'; batchcompute.getJob({ jobId:jobId },function(err, result) { if(err) { console.log(err); return; } console.log(data); });
function match(p, r) { if(Array.isArray(p)) { return p.every(function(p, i) { return match(p, r[i]) }) } else if(typeof(p) == 'object' && p && !(p instanceof Number || p instanceof String || p instanceof RegExp || p instanceof Boolean)) { for(var k in p) { if(!match(p[k], r[k])) return false } return true } else if(p instanceof RegExp && (typeof(r) == 'string' || r instanceof String)) { return p.test(r) } else if(p === undefined) { return true } else if(p === null) { return p === null || p === undefined } else { return p === r } } module.exports = match
/* Copyright 2017 Apinf Oy This file is covered by the EUPL license. You may obtain a copy of the licence at https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 */ Template.mostFrequentUsersTable.helpers({ users () { const buckets = Template.instance().data.buckets; const users = []; buckets.forEach(bucket => { bucket.request_url.buckets.forEach(req => { const user = {}; // Get value of email user.email = bucket.user_email.buckets[0].key; user.calls = req.doc_count; user.url = req.key; users.push(user); }); }); return users; }, });
/** * @author zhangpeng * @date 2015-10-02 * @file 扩展ejs模板,增加layout和widget相关功能 * extend ejs template system, supporting layout and widget functionalities * * layout实现:在layout中通过特殊标记留坑,在template中标记各个坑对应的块,然后在res.render的callback中去填坑 * widget实现:load_widget时输出html并保存js,css路径,然后在res.render的callback中填充js,css */ // node modules var _ = require('underscore'); // system modules var path = require('path'); /** * * @param options.webRoot // required, rootPath * @param options.tplDir // required, template folder path relative to rootPath * @param options.staticDir // static folder path relative to rootPath (js, css) * if options.staticDir was not assigned, we would suppose that template files(html) && static files(js, css) are in the same folder, * else we would use options.staticDir + templatePath to find static files * * @param options.map // map generated by fis3, if using fis3 * if options.map was assigned, we would use map to find static files * * @param options.conf // conf for extension * @param options.consts // global constants used in template * @param options.funcs // global functions used in template * * @param options.LoggerCreate // used to output log of this middleware * * @returns {Function} middleware function */ module.exports = function (options) { if (!options) throw new Error('options is undefined!'); if (!options.webRoot) throw new Error('options.webRoot is undefined!'); if (!options.tplDir) throw new Error('options.tplDir is undefined!'); var opts = { map: {}, conf: { usePageCache: true, useMinJs: false, // whethe to replace .js to .min.js whiteListJs: [], // js that can not be replaced useMinCss: false, // whethe to replace .css to .min.css whiteListCss: [], // css that can not be replaced mergeJs: true, // merge js files in static dir mergeCss: true // merge css files in static dir }, extConf: { // 各种类型文件的后缀名 tplExt: '.html', scriptExt: '.js', styleExt: '.css' }, consts: {}, funcs: {}, maxCacheCopyNum: 20, // 最大的cache拷贝份数 maxCacheExpireTime: 10 * 60 * 1e3, // cache过期时间 maxDeltaHitIgnore: 0, // hit差值小于该值的cache不按热度排序, 按时间排序 maxHitIgnore: 10, // hit小于该值的cache按时间排序 LoggerCreate: require(path.join(__dirname, 'lib', 'tool', 'Logger')) }; _.extend(opts, options); // init sub middlewares var ConstantsHelper = require(path.join(__dirname, 'lib', 'helper', 'Constants'))(opts.consts, opts.LoggerCreate); var FunctionsHelper = require(path.join(__dirname, 'lib', 'helper', 'Functions'))(opts.funcs, opts.LoggerCreate); var UserAgentHelper = require(path.join(__dirname, 'lib', 'helper', 'UserAgentHelper'))(opts.LoggerCreate); var PageCacheHelper = require(path.join(__dirname, 'lib', 'tool', 'PageCache'))(opts); var Resource = require(path.join(__dirname, 'lib', 'resource', 'Resource'))(opts); var Page = Resource.Page; var logger = opts.LoggerCreate('template-extension'); var userPageCache = opts.conf.usePageCache; return function (req, res, next) { if (res.renderPage) throw new Error('res.renderPage already exists!'); // renderPage之外也对外暴露的middlerware // cache和ua相关, 必须先设置ua UserAgentHelper(req, res); res.renderPage = function (view, options, callback) { var uaIdentity = res.locals.AgentHelper.uaIdentity; // 先查cache var cache = PageCacheHelper.read(view, options, uaIdentity); if (userPageCache && cache) { logger.info({page: view}, 'found cache, won\'t render again'); res.send(cache); return callback && callback(void 0, cache); } logger.info({page: view}, 'start rendering page'); if (!view.module || !view.page) throw new Error('res.renderPage must be called as: \nres.render({module: \'moduleName\', page: \'pageName\'}, options, callback)'); // sub-middleware ConstantsHelper(req, res); FunctionsHelper(req, res); var page = new Page(view.module, view.page); page.render(res, options, function (err, str) { if (err) return req.next(err); res.send(str); PageCacheHelper.write(view, options, uaIdentity, str); }); }; next(); } };
// Copyright 2015 Teem2 LLC, MIT License (see LICENSE) // Parts copyright 2012 Google, Inc. All Rights Reserved. (APACHE 2.0 license) define.class('$gl/glshader', function(require, exports, self){ this.matrix = mat4() this.viewmatrix = mat4() this.position = function(){ return mesh.pos * matrix * viewmatrix } this.color = function(){ var rel = mesh.edge//cursor_pos var dpdx = dFdx(rel) var dpdy = dFdy(rel) var edge = min(length(vec2(length(dpdx), length(dpdy))) * SQRT_1_2, 1.) if(edge > 0.04){ if(rel.x < dpdx.x) return vec4(fgcolor.rgb,1.) return vec4(0.) } return vec4(fgcolor.rgb, smoothstep(edge, -edge, shape.box(rel, 0,0,0.05,1.))) } this.cursorgeom = define.struct({ pos:vec2, edge:vec2 }).extend(function(){ this.addCursor = function(textbuf, start){ var pos = textbuf.cursorRect(start) //pos.y = 0//this.textbuf.font_size - this.textbuf.font_size * this.textbuf.cursor_sink pos.w = textbuf.font_size //+ 10; //console.log("Rik - please find out why cursorwidth is near invisible at small fontsizes ;-) "); //this.cursor.mesh.length = 0 this.pushQuad( pos.x, pos.y, 0, 0, pos.x + pos.w, pos.y, 1, 0, pos.x, pos.y + pos.h, 0, 1, pos.x + pos.w, pos.y + pos.h, 1, 1 ) } }) this.mesh = this.cursorgeom.array() this.fgcolor = vec4("white"); })
/*jshint browser:true*/ /*jslint nomen: true*/ /*global define, require*/ define(['jquery', 'underscore', 'oro/tools', 'oro/mediator', 'orofilter/js/map-filter-module-name', 'oro/datafilter/collection-filters-manager'], function ($, _, tools, mediator, mapFilterModuleName, FiltersManager) { 'use strict'; var initialized = false, methods = { initBuilder: function () { this.metadata = _.extend({filters: {}}, this.$el.data('metadata')); this.modules = {}; methods.collectModules.call(this); tools.loadModules(this.modules, _.bind(methods.build, this)); }, /** * Collects required modules */ collectModules: function () { var modules = this.modules; _.each(this.metadata.filters || {}, function (filter) { var type = filter.type; modules[type] = mapFilterModuleName(type); }); }, build: function () { var options = methods.combineOptions.call(this); options.collection = this.collection; var filtersList = new FiltersManager(options); this.$el.prepend(filtersList.render().$el); mediator.trigger('datagrid_filters:rendered', this.collection); if (this.collection.length === 0 && this.metadata.state.filters.length === 0) { filtersList.$el.hide(); } }, /** * Process metadata and combines options for filters * * @returns {Object} */ combineOptions: function () { var filters= {}, modules = this.modules, collection = this.collection; _.each(this.metadata.filters, function (options) { if (_.has(options, 'name') && _.has(options, 'type')) { // @TODO pass collection only for specific filters if (options.type == 'selectrow') { options.collection = collection } var Filter = modules[options.type].extend(options); filters[options.name] = new Filter(); } }); return {filters: filters}; } }, initHandler = function (collection, $el) { methods.initBuilder.call({$el: $el, collection: collection}); initialized = true; }; return { init: function () { initialized = false; mediator.once('datagrid_collection_set_after', initHandler); mediator.once('hash_navigation_request:start', function() { if (!initialized) { mediator.off('datagrid_collection_set_after', initHandler); } }); } }; });
(function (angular) { 'use strict'; var module = angular.module('angular-smilies', []); /** * Smilies and Emojis parser * @param config * @constructor */ function SmiliesParser (config) { this.config = config; } /** * Returns the config * @returns {object} */ SmiliesParser.prototype.getConfig = function () { return this.config; }; /** * Parse a string * @param {string} input * @returns {string} */ SmiliesParser.prototype.parse = function (input) { if (!input) { return input; } // parse smileys names var output = this.replaceSmileys(input); // parse emojis for (var emoji in this.config.emojis) { if (this.config.emojis.hasOwnProperty(emoji)) { output = this.replaceEmoji(output, emoji); } } return output; }; /** * Replace all smilies * @param {string} input * @returns {string} */ SmiliesParser.prototype.replaceSmileys = function (input) { var regex = new RegExp(':(' + this.config.smilies.join('|') + '):', 'g'); return input.replace(regex, this.config.template); }; /** * Replace a particular emoji * @param {string} input * @param {string} emoji * @returns {string} */ SmiliesParser.prototype.replaceEmoji = function (input, emoji) { // create a suitable template var template = this.config.template.replace(/\$1/g, this.config.emojis[emoji]); // escape the emoji for regex usage emoji = emoji.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); var regex; if (/^[a-z]+$/i.test(emoji)) { // always use word boundaries if emoji is letters only regex = new RegExp('\\b' + emoji + '\\b', 'gi'); } else if (this.config.alwaysUseBoundaries) { // word boundaries are not useable with special characters (not words) // use a look ahead to not consume the possible space between two consecutive emojis regex = new RegExp('(?:^|\\W)' + emoji + '(?=$|\\W)', 'gi'); } else { regex = new RegExp(emoji, 'gi'); } return input.replace(regex, template); }; /** * @ngdoc provider * @name smiliesParser * @memberof angular-smilies * @description Smilies parser service */ module.provider('smiliesParser', function () { var config = { main: smiliesConfig.main, smilies: smiliesConfig.smilies, emojis: smiliesConfig.emojis, template: '<i class="smiley-$1" title="$1"></i>', alwaysUseBoundaries: false }; /** * Ensure that all smileys used by emojis exists */ function checkEmojis () { var smiliesMap = {}; config.smilies.forEach(function (smilies) { smiliesMap[smilies] = true; }); for (var emoji in config.emojis) { if (config.emojis.hasOwnProperty(emoji) && !smiliesMap[config.emojis[emoji]]) { delete config.emojis[emoji]; } } } /** * Change the main smiley * @param {string} main */ this.setMainSmiley = function (main) { config.main = main; }; /** * Replace the list of smileys * @param {string[]} smilies */ this.setSmilies = function (smilies) { config.smilies = smilies; checkEmojis(); }; /** * Add a new smiley * @param {string} smiley */ this.addSmiley = function (smiley) { var idx = config.smilies.indexOf(smiley); if (idx === -1) { config.smilies.push(smiley); } }; /** * Remove an existing smiley * @param {string} smiley */ this.removeSmiley = function (smiley) { var idx = config.smilies.indexOf(smiley); if (idx !== -1) { config.smilies.splice(idx, 1); checkEmojis(); } }; /** * Replace the map of emojis * @param {{string: string}} emojis */ this.setEmojis = function (emojis) { config.emojis = emojis; checkEmojis(); }; /** * Add a new emoji * @param {string} emoji * @param {string} smiley */ this.addEmoji = function (emoji, smiley) { config.emojis[emoji] = smiley; checkEmojis(); }; /** * Remove and existing emoji * @param {string} emoji */ this.removeEmoji = function (emoji) { delete config.emojis[emoji]; }; /** * Set the HTML template * @param {string} template */ this.setTemplate = function (template) { config.template = template; }; /** * Set if the parser must always use word boundaries * @param {boolean} use */ this.alwaysUseBoundaries = function (use) { config.alwaysUseBoundaries = use; }; /** * Returns the service * @returns {SmiliesParser} */ this.$get = function () { return new SmiliesParser(config); }; }); /** * @ngdoc filter * @name smilies * @memberof angular-smilies * @description Smilies parser filter */ module.filter('smilies', function (smiliesParser) { return function (input) { return smiliesParser.parse(input); }; }); /** * @ngdoc directive * @name smilies * @memberof angular-smilies * @description Smilies parser directive */ module.directive('smilies', function (smiliesParser) { return { restrict: 'A', scope: { source: '=smilies' }, link: function ($scope, el) { el.html(smiliesParser.parse($scope.source)); } }; }); /** * @ngdoc directive * @name smiliesSelector * @memberof angular-smilies * @description Smilies selector directive */ module.directive('smiliesSelector', function ($timeout, smiliesParser) { var templateUrl; try { angular.module('ui.bootstrap.popover'); templateUrl = 'template/smilies/button-uib.html'; } catch (e) { try { angular.module('mgcrea.ngStrap.popover'); templateUrl = 'template/smilies/button-strap.html'; } catch (e) { console.error('No Popover module found'); return {}; } } return { restrict: 'A', templateUrl: templateUrl, scope: { source: '=smiliesSelector', placement: '@smiliesPlacement', title: '@smiliesTitle', keepOpen: '@smiliesKeepOpen' }, link: function ($scope, el) { $scope.config = smiliesParser.getConfig(); $scope.append = function (smiley) { $scope.source += ' :' + smiley + ':'; if (!$scope.placement) { $scope.placement = 'left'; } if ($scope.keepOpen === undefined) { $timeout(function () { el.children('i').triggerHandler('click'); // close the popover }); } }; } }; }); /** * @ngdoc directive * @name focusOnChange * @memberof angular-smilies * @description Helper directive for input focusing */ module.directive('focusOnChange', function () { return { restrict: 'A', link: function ($scope, el, attrs) { $scope.$watch(attrs.focusOnChange, function () { el[0].focus(); }); } }; }); /* register popover templates */ module.run(function ($templateCache) { $templateCache.put('template/smilies/button-uib.html', '<i class="smiley-{{config.main}} smilies-selector" ' + 'uib-popover-template="\'template/smilies/popover-uib.html\'" ' + 'popover-placement="{{placement}}" ' + 'popover-trigger="outsideClick" ' + 'popover-title="{{title}}"></i>' ); $templateCache.put('template/smilies/popover-uib.html', '<div ng-model="config.smilies" class="smilies-selector-content">' + '<i class="smiley-{{smiley}}" ng-repeat="smiley in config.smilies" ng-click="append(smiley)"></i>' + '</div>' ); $templateCache.put('template/smilies/button-strap.html', '<i class="smiley-{{config.main}} smilies-selector" bs-popover ' + 'data-template="template/smilies/popover-strap.html" ' + 'data-placement="{{placement}}" ' + 'title="{{title}}"></i>' ); $templateCache.put('template/smilies/popover-strap.html', '<div class="popover" tabindex="-1">' + '<div class="arrow"></div>' + '<h3 class="popover-title" ng-bind="title" ng-show="title"></h3>' + '<div class="popover-content">' + $templateCache.get('template/smilies/popover-uib.html') + '</div>' + '</div>' ); }); }(angular));
var Template = require('../index.js').Template; var e = require('element.js').e; var Badge = function () { return e.span([], { classes: ['badge'] }); }; Template.prototype.append = function (item) { if (Array.isArray(item)) { for (var i=0; i<item.length; i++) { this.append(item[i]); } } else { if (typeof item == 'object' && item.tag == 'li') { item.addClass('list-group-item'); if (item.inner.length == 1) { console.log(typeof item.inner[0]); if (typeof item.inner[0] == 'object' && !item.inner[0].hasClass('badge')) { item.prepend(Badge()); } if (typeof item.inner[0] != 'object') { item.prepend(Badge()); } } this.body.append(item); } else { var wrapper = e.li([Badge(), item], { classes: [ 'list-group-item' ] }); this.body.append(wrapper); } } }; Template.prototype.setBadge = function (index, content) { this.body.inner[index].inner[0].inner = (Array.isArray(content)) ? content : [content]; }; var listgroup = new Template(); listgroup.body = e.ul([], { classes: [ 'list-group' ] }); exports.Template = listgroup;
/*jshint esversion: 6 */ import Ember from 'ember'; export function initialize(app){} var get, set; get = Ember.get; set = Ember.set; // Set title and metaTags properties in any route to update page title and meta tags respectively. Ember.Route.reopen({ tagsData: Ember.inject.service('tags-data'), title: null, metaTags: null, titleObserver: Ember.observer('title', function(){ var changedTitle = get(this, 'title'); return this.setTitle(changedTitle); }), tagsObserver: Ember.observer('metaTags', function(){ var changedTags = get(this, 'metaTags'); return this.parseTags(changedTags, false); }), setTitle: function(title) { window.document.title = title; return; }, parseTags: function(tags, resetTags) { var that; that = this; if(!tags){ return; } return tags.forEach(function(tag) { var content, name; if(resetTags){ content = ''; } else{ content = get(tag, 'tagContent'); } name = get(tag, 'tagName'); return that.setMetaTag(name, content); }); }, getTagAttribute: function(name){ var openGraph, swiftType; openGraph = /^og:/; swiftType = /^st:/; //https://swiftype.com/documentation/meta_tags if( openGraph.test(name) || swiftType.test(name) ){ return 'property'; } return 'name'; }, setMetaTag: function(name, content) { var attr; attr = this.getTagAttribute(name); if (Ember.$(`meta[${attr}='${name}']`).length > 0) { return Ember.$(`meta[${attr}='${name}']`).attr('content', content); } else { return Ember.$('head').append(`<meta ${attr}='${name}' content='${content}'>`); } }, initRouteData: function(type, value){ var oldValue; oldValue = get(this, type); if(value){ set(this, type, value); this.notifyPropertyChange(type); } else if( !Ember.isBlank(oldValue) ){ // If title or metaTags are defined in route as properties, then they will be picked up from here. this.notifyPropertyChange(type); } else if ( Ember.isEqual(type, 'title') ){ // Set default title as routeName if no title is provided. Meta tags will remain null if not provided. value = get(this, 'routeName'); set(this, type, value); } }, readServiceData: function(){ // Seed title and Meta tags on load var routeName, seedTitle, seedMetaTags; routeName = get(this, 'routeName'); seedTitle = get(this, `tagsData.${routeName}.title`); seedMetaTags = get(this, `tagsData.${routeName}.metaTags`); this.initRouteData('title', seedTitle); this.initRouteData('metaTags', seedMetaTags); }, clearTags: function(){ var tags = get(this, 'metaTags'); return this.parseTags(tags, true); }, enter: function(){ this._super(); this.readServiceData(); }, exit: function(){ this._super(); this.clearTags(); } }); export default { name: 'seo', initialize: initialize };
/*! * numeral.js language configuration * language : chinese Hong Kong (hk) * author : Rich Daley : https://github.com/pedantic-git */ (function () { var language = { delimiters: { thousands: ',', decimal: '.' }, abbreviations: { thousand: '千', million: '百萬', billion: '十億', trillion: '兆' }, ordinal: function (number) { // Should go before number but numeral.js doesn't currently // support this return '第'; }, currency: { symbol: '$' } }; // Node if (typeof module !== 'undefined' && module.exports) { module.exports = language; } // Browser if (typeof window !== 'undefined' && this.numeral && this.numeral.language) { this.numeral.language('zh-hk', language); } }());
var expect = require('chai').expect; var sinon = require('sinon'); var fireworm = require('fireworm'); var Config = require('../lib/config'); var App = require('../lib/app'); var FakeReporter = require('./support/fake_reporter'); describe('App', function() { var app, config, sandbox; beforeEach(function() { sandbox = sinon.sandbox.create(); }); afterEach(function() { sandbox.restore(); }); describe('triggerRun', function() { beforeEach(function(done) { config = new Config('dev', {}, { reporter: new FakeReporter() }); app = new App(config, function() {}); sandbox.spy(app, 'triggerRun'); app.start(done); }); afterEach(function(done) { app.exit(null, done); }); it('triggers a run on start', function() { expect(app.triggerRun.calledWith('Start')).to.be.true(); }); it('can only be executed once at the same time', function() { sandbox.stub(app, 'cleanUpProcessLaunchers'); app.triggerRun('one'); app.triggerRun('two'); expect(app.cleanUpProcessLaunchers.callCount).to.eq(1); }); }); describe('pause running', function() { beforeEach(function(done) { config = new Config('dev', {}, { reporter: new FakeReporter() }); app = new App(config, function() {}); app.start(done); }); afterEach(function(done) { app.exit(null, done); }); it('starts off not paused', function() { expect(app.paused).to.be.false(); }); it('doesn\'t run tests when reset and paused', function(done) { app.paused = true; var runHook = sandbox.spy(app, 'runHook'); app.runTests(null, done); expect(runHook.called).to.be.false(); }); it('runs tests when reset and not paused', function(done) { var runHook = sandbox.spy(app, 'runHook'); app.runTests(null, done); expect(runHook.called).to.be.true(); }); }); describe('file watching', function() { beforeEach(function() { sandbox.stub(Config.prototype, 'readConfigFile', function(file, cb) { cb(); }); }); it('adds a watch', function(done) { var add = sandbox.spy(fireworm.prototype, 'add'); var srcFiles = ['test.js']; config = new Config('dev', {}, { src_files: srcFiles, reporter: new FakeReporter() }); app = new App(config, done); app.start(function() { expect(add.getCall(0).args[0]).to.eq(srcFiles); app.exit(); }); }); it('triggers a test run on change', function(done) { var srcFiles = ['test.js']; config = new Config('dev', {}, { src_files: srcFiles, reporter: new FakeReporter() }); app = new App(config, done); app.start(function() { sandbox.spy(app, 'triggerRun'); app.fileWatcher.onFileChanged.call(app.fileWatcher, 'test.js'); expect(app.triggerRun.calledWith('File changed: test.js')).to.be.true(); app.exit(); }); }); it('creates no watcher', function(done) { config = new Config('dev', {}, { src_files: ['test.js'], disable_watching: true, reporter: new FakeReporter() }); app = new App(config, done); app.start(function() { expect(app.fileWatcher).to.eq(undefined); app.exit(); }); }); }); });
console.warn( "THREE.Water2: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." ); /** * References: * http://www.valvesoftware.com/publications/2010/siggraph2010_vlachos_waterflow.pdf * http://graphicsrunner.blogspot.de/2010/08/water-using-flow-maps.html * */ THREE.Water = function ( geometry, options ) { THREE.Mesh.call( this, geometry ); this.type = 'Water'; var scope = this; options = options || {}; var color = ( options.color !== undefined ) ? new THREE.Color( options.color ) : new THREE.Color( 0xFFFFFF ); var textureWidth = options.textureWidth || 512; var textureHeight = options.textureHeight || 512; var clipBias = options.clipBias || 0; var flowDirection = options.flowDirection || new THREE.Vector2( 1, 0 ); var flowSpeed = options.flowSpeed || 0.03; var reflectivity = options.reflectivity || 0.02; var scale = options.scale || 1; var shader = options.shader || THREE.Water.WaterShader; var encoding = options.encoding !== undefined ? options.encoding : THREE.LinearEncoding; var textureLoader = new THREE.TextureLoader(); var flowMap = options.flowMap || undefined; var normalMap0 = options.normalMap0 || textureLoader.load( 'textures/water/Water_1_M_Normal.jpg' ); var normalMap1 = options.normalMap1 || textureLoader.load( 'textures/water/Water_2_M_Normal.jpg' ); var cycle = 0.15; // a cycle of a flow map phase var halfCycle = cycle * 0.5; var textureMatrix = new THREE.Matrix4(); var clock = new THREE.Clock(); // internal components if ( THREE.Reflector === undefined ) { console.error( 'THREE.Water: Required component THREE.Reflector not found.' ); return; } if ( THREE.Refractor === undefined ) { console.error( 'THREE.Water: Required component THREE.Refractor not found.' ); return; } var reflector = new THREE.Reflector( geometry, { textureWidth: textureWidth, textureHeight: textureHeight, clipBias: clipBias, encoding: encoding } ); var refractor = new THREE.Refractor( geometry, { textureWidth: textureWidth, textureHeight: textureHeight, clipBias: clipBias, encoding: encoding } ); reflector.matrixAutoUpdate = false; refractor.matrixAutoUpdate = false; // material this.material = new THREE.ShaderMaterial( { uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib[ 'fog' ], shader.uniforms ] ), vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, transparent: true, fog: true } ); if ( flowMap !== undefined ) { this.material.defines.USE_FLOWMAP = ''; this.material.uniforms[ "tFlowMap" ] = { type: 't', value: flowMap }; } else { this.material.uniforms[ "flowDirection" ] = { type: 'v2', value: flowDirection }; } // maps normalMap0.wrapS = normalMap0.wrapT = THREE.RepeatWrapping; normalMap1.wrapS = normalMap1.wrapT = THREE.RepeatWrapping; this.material.uniforms[ "tReflectionMap" ].value = reflector.getRenderTarget().texture; this.material.uniforms[ "tRefractionMap" ].value = refractor.getRenderTarget().texture; this.material.uniforms[ "tNormalMap0" ].value = normalMap0; this.material.uniforms[ "tNormalMap1" ].value = normalMap1; // water this.material.uniforms[ "color" ].value = color; this.material.uniforms[ "reflectivity" ].value = reflectivity; this.material.uniforms[ "textureMatrix" ].value = textureMatrix; // inital values this.material.uniforms[ "config" ].value.x = 0; // flowMapOffset0 this.material.uniforms[ "config" ].value.y = halfCycle; // flowMapOffset1 this.material.uniforms[ "config" ].value.z = halfCycle; // halfCycle this.material.uniforms[ "config" ].value.w = scale; // scale // functions function updateTextureMatrix( camera ) { textureMatrix.set( 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 ); textureMatrix.multiply( camera.projectionMatrix ); textureMatrix.multiply( camera.matrixWorldInverse ); textureMatrix.multiply( scope.matrixWorld ); } function updateFlow() { var delta = clock.getDelta(); var config = scope.material.uniforms[ "config" ]; config.value.x += flowSpeed * delta; // flowMapOffset0 config.value.y = config.value.x + halfCycle; // flowMapOffset1 // Important: The distance between offsets should be always the value of "halfCycle". // Moreover, both offsets should be in the range of [ 0, cycle ]. // This approach ensures a smooth water flow and avoids "reset" effects. if ( config.value.x >= cycle ) { config.value.x = 0; config.value.y = halfCycle; } else if ( config.value.y >= cycle ) { config.value.y = config.value.y - cycle; } } // this.onBeforeRender = function ( renderer, scene, camera ) { updateTextureMatrix( camera ); updateFlow(); scope.visible = false; reflector.matrixWorld.copy( scope.matrixWorld ); refractor.matrixWorld.copy( scope.matrixWorld ); reflector.onBeforeRender( renderer, scene, camera ); refractor.onBeforeRender( renderer, scene, camera ); scope.visible = true; }; }; THREE.Water.prototype = Object.create( THREE.Mesh.prototype ); THREE.Water.prototype.constructor = THREE.Water; THREE.Water.WaterShader = { uniforms: { 'color': { type: 'c', value: null }, 'reflectivity': { type: 'f', value: 0 }, 'tReflectionMap': { type: 't', value: null }, 'tRefractionMap': { type: 't', value: null }, 'tNormalMap0': { type: 't', value: null }, 'tNormalMap1': { type: 't', value: null }, 'textureMatrix': { type: 'm4', value: null }, 'config': { type: 'v4', value: new THREE.Vector4() } }, vertexShader: [ '#include <common>', '#include <fog_pars_vertex>', '#include <logdepthbuf_pars_vertex>', 'uniform mat4 textureMatrix;', 'varying vec4 vCoord;', 'varying vec2 vUv;', 'varying vec3 vToEye;', 'void main() {', ' vUv = uv;', ' vCoord = textureMatrix * vec4( position, 1.0 );', ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );', ' vToEye = cameraPosition - worldPosition.xyz;', ' vec4 mvPosition = viewMatrix * worldPosition;', // used in fog_vertex ' gl_Position = projectionMatrix * mvPosition;', ' #include <logdepthbuf_vertex>', ' #include <fog_vertex>', '}' ].join( '\n' ), fragmentShader: [ '#include <common>', '#include <fog_pars_fragment>', '#include <logdepthbuf_pars_fragment>', 'uniform sampler2D tReflectionMap;', 'uniform sampler2D tRefractionMap;', 'uniform sampler2D tNormalMap0;', 'uniform sampler2D tNormalMap1;', '#ifdef USE_FLOWMAP', ' uniform sampler2D tFlowMap;', '#else', ' uniform vec2 flowDirection;', '#endif', 'uniform vec3 color;', 'uniform float reflectivity;', 'uniform vec4 config;', 'varying vec4 vCoord;', 'varying vec2 vUv;', 'varying vec3 vToEye;', 'void main() {', ' #include <logdepthbuf_fragment>', ' float flowMapOffset0 = config.x;', ' float flowMapOffset1 = config.y;', ' float halfCycle = config.z;', ' float scale = config.w;', ' vec3 toEye = normalize( vToEye );', // determine flow direction ' vec2 flow;', ' #ifdef USE_FLOWMAP', ' flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0;', ' #else', ' flow = flowDirection;', ' #endif', ' flow.x *= - 1.0;', // sample normal maps (distort uvs with flowdata) ' vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 );', ' vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 );', // linear interpolate to get the final normal color ' float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle;', ' vec4 normalColor = mix( normalColor0, normalColor1, flowLerp );', // calculate normal vector ' vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) );', // calculate the fresnel term to blend reflection and refraction maps ' float theta = max( dot( toEye, normal ), 0.0 );', ' float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 );', // calculate final uv coords ' vec3 coord = vCoord.xyz / vCoord.w;', ' vec2 uv = coord.xy + coord.z * normal.xz * 0.05;', ' vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) );', ' vec4 refractColor = texture2D( tRefractionMap, uv );', // multiply water color with the mix of both textures ' gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance );', ' #include <tonemapping_fragment>', ' #include <encodings_fragment>', ' #include <fog_fragment>', '}' ].join( '\n' ) };
/** * Routes API requests either to the server or to a local JSON file if the * DEMO constant is set to true. */ 'use strict'; angular.module('hackaFinderApp') .factory('API', ['$http', '$log', 'Validate', 'Authenticate', 'DEMO', function ($http, $log, Validate, Authenticate, DEMO) { // ----------------- // // - PRIVATE STATE - // // ----------------- // // Service settings. var json = '/components/api/api.service.demo.json', /// DEMO data file. msg = Validate.getErrorMessages(); // Map server API paths to the local JSON file. var apiPaths = { '/api/users': { get: 'usersGet', post: 'usersPost', put: 'usersPost' }, '/api/auth/users': { post: 'usersPost' }, '/api/auth/users/event': { post: 'usersAuthEventGet' /// POST so it supports authentication. }, '/api/auth/events': { get: 'eventsAuthPost', post: 'eventsAuthPost', put: 'eventsAuthPost' }, '/api/auth/events/all': { post: 'eventsAuthAllGet' /// POST so it supports authentication. }, '/api/auth/teams/remove': { post: 'teamsAuthRemovePost' }, '/api/auth/teams/confirm': { post: 'teamsAuthConfirmPost' }, '/api/auth/teams/pending': { post: 'teamsAuthPendingPost' }, '/api/auth/menu': { get: 'menuAuthGet' } }; // --------------------- // // - PRIVATE FUNCTIONS - // // --------------------- // /** * Prepare to make an HTTP request. * * @param {object} req - The request object. * @param {string} req.op - The HTTP operation. * @param {string} req.path - The API location. * @param {string} [req.id] - An optional GET identifier. * @param {object} [req.data] - Optional data to send with the request. * @param {object} req.auth - Indicates if the user is logged in with the * user profile or null as the property value. * @param {function} next - The final callback upon completion. * @throws - If the callback is missing or the path is not a valid string. */ function prepareRequest(req, next) { // Extract request options. var op = req.op, route, path = req.path, id = req.id, auth = req.auth; // Ensure there is a callback. if (!angular.isFunction(next)) { throw new Error(msg.callback); } // Define the route. if (angular.isString(path) && apiPaths[path] && apiPaths[path][op]) { route = (DEMO ? apiPaths[path][op] : path); if (!DEMO && angular.isString(id)) { route += '/' + id; } } else { throw new Error(msg.path); } // Prepare the request object. req.route = route; // Return an error if the user requests a protected resource while not // logged in. if (!angular.isObject(auth) && route.indexOf('auth') > -1 && route.indexOf('menu') === -1) { var err = new Error(msg.restricted); err.dbi = {status: 401, msg: msg.restricted}; return next(err, null); } // Get the resource. if (angular.isFunction(req.makeCall)) { req.makeCall(req, next); } else { makeCall(req, next); } } /** * Route the API request either to the local JSON file when in demo mode or * to the server otherwise then pass the response to the callback. * * @param {object} req - The request object. * @param {string} req.op - The HTTP operation. * @param {string} req.route - The HTTP API route. * @param {object} [req.data] - Optional data to send. * @param {object} [req._test] - An optional test function to run before the * callback, typically $httpBackend.flush(). * @param {function} next - The final callback upon completion. * @throws - If the request contains an invalid operation. */ function makeCall(req, next) { // Extract request options. var op = req.op, route = req.route, data = req.data, test = req._test || angular.noop; /// Used in unit testing. // Ensure this is a valid operation supported by the $http object. if (!angular.isDefined($http[op]) || !angular.isFunction($http[op])) { throw new Error(msg.op); } // Route the request either to the local JSON file or to the server. if (DEMO) { /// Get the correct object from the JSON file. $http.get(json) .then(function(res) { test(); next(null, {status: res.status, data: res.data[route]}); }, function(err) { test(); next(err, null); }); } else { /// Get the correct response from the server. $http[op].apply(null, [route, data]) .then(function(res) { test(); next(null, res); }, function(err) { test(); next(err, null); }); } } // -------------- // // - PUBLIC API - // // -------------- // return { /** * Expose internal functions for testing. */ _test: { prepareRequest: prepareRequest, makeCall: makeCall }, /** * Get a resource from the server or simulate the process using the * demo JSON file. Supports a flexible function signature with or without * the <id> parameter. * * @param {string} path - The API location. * @param {string} [id] - An optional GET identifier. * @param {function} next - The final callback upon completion. */ get: function(path, id, next) { // Support a variable method signature. if (angular.isFunction(id)) { next = id; id = null; } // Create a request object. var req = { op: 'get', path: path, id: id, data: null, auth: Authenticate.getUser() }; req.user = req.auth; // Prepare to make the HTTP call. prepareRequest(req, next); }, /** * Post data to the server or simulate the process using the demo * JSON file. * * @param {string} path - The API location. * @param {object} data - The POST data. * @param {function} next - The final callback upon completion. */ post: function(path, id, data, next) { // Support the method signature "function(path, data, next)". if (angular.isFunction(data)) { next = data; data = id; id = null; } // Create a request object. var req = { op: 'post', path: path, id: id, data: data, auth: Authenticate.getUser() }; if (angular.isObject(req.data)) { if (!angular.isObject(req.data.user)) { req.data.user = req.auth; } } else { req.data = {user: req.auth}; } // Prepare to make the HTTP call. prepareRequest(req, next); }, /** * Put data onto the server or simulate the process using the demo * JSON file. * * @param {string} path - The API location. * @param {object} data - The PUT data. * @param {function} next - The final callback upon completion. */ put: function(path, data, next) { // Create a request object. var req = { op: 'put', path: path, id: null, data: data, auth: Authenticate.getUser() }; if (angular.isObject(req.data)) { if (!angular.isObject(req.data.user)) { req.data.user = req.auth; } } else { req.data = {user: req.auth}; } // Prepare to make the HTTP call. prepareRequest(req, next); } }; }]);
//! moment.js //! version : 2.4.0 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.4.0", round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // 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})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // 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?|S{1,4}|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 parseTokenDigits = /\d+/, // nonzero number of digits 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 0000-W00 or 0000-W00-0 + 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)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d:?\d\d|Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ 'YYYY-MM-DD', 'GGGG-[W]WW', 'GGGG-[W]WW-E', 'YYYY-DDD' ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(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', D : 'date', w : 'week', W : 'isoWeek', M : 'month', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // 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 toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(10 * a / 6), 4); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); } }, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; 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) { checkOverflow(config); extend(this, config); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 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]; } } if (b.hasOwnProperty("toString")) { a.toString = b.toString; } if (b.hasOwnProperty("valueOf")) { a.valueOf = b.valueOf; } 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; 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]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { 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 ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop, index; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment.fn._lang[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment.fn._lang, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function initializeParsingFlags(config) { config._pf = { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLanguage(key) { return key ? key.toLowerCase().replace('_', '-') : key; } /************************************ Languages ************************************/ extend(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.utc([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 : "DD/MM/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) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(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. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); // 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]; } // Remove a language from the `languages` cache. Mostly useful in tests. function unloadLang(key) { delete 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) { var i = 0, j, lang, next, split, get = function (k) { if (!languages[k] && hasModule) { try { require('./lang/' + k); } catch (e) { } } return languages[k]; }; if (!key) { return moment.fn._lang; } if (!isArray(key)) { //short-circuit everything else lang = get(key); if (lang) { return lang; } key = [key]; } //pick the language from the array //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root while (i < key.length) { split = normalizeLanguage(key[i]).split('-'); j = split.length; next = normalizeLanguage(key[i + 1]); next = next ? next.split('-') : null; while (j > 0) { lang = get(split.slice(0, j).join('-')); if (lang) { return lang; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return moment.fn._lang; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { 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) { if (!m.isValid()) { return m.lang().invalidDate(); } format = expandFormat(format, m.lang()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, lang) { var i = 5; function replaceLongDateFormatTokens(input) { return lang.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a; switch (token) { case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return parseTokenFourDigits; case 'YYYYY': case 'GGGGG': case 'ggggg': 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 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'ww': case 'W': case 'WW': case 'e': case 'E': return parseTokenOneOrTwoDigits; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i")); return a; } } function timezoneMinutesFromString(string) { var tzchunk = (parseTokenTimezone.exec(string) || [])[0], parts = (tzchunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(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' : if (input != null) { datePartArray[MONTH] = toInt(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[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000); break; case 'YYYY' : case 'YYYYY' : datePartArray[YEAR] = toInt(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[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('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; case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'dd': case 'ddd': case 'dddd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gg': case 'gggg': case 'GG': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = input; } break; } } // 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 dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse, fixYear, w, temp, lang, weekday, week; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { fixYear = function (val) { return val ? (val.length < 3 ? (parseInt(val, 10) > 68 ? '19' + val : '20' + val) : val) : (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]); }; w = config._w; if (w.GG != null || w.W != null || w.E != null) { temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1); } else { lang = getLangDefinition(config._l); weekday = w.d != null ? parseWeekday(w.d, lang) : (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0); week = parseInt(w.w, 10) || 1; //if we're parsing 'd', then the low day numbers may be next week if (w.d != null && weekday < lang._week.dow) { week++; } temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow); } config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR]; if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; 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[HOUR] += toInt((config._tzm || 0) / 60); input[MINUTE] += toInt((config._tzm || 0) % 60); config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var lang = getLangDefinition(config._l), string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, lang).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (getParseRegexForToken(token, config).exec(string) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = extend({}, config); initializeParsingFlags(tempConfig); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function makeDateFromString(config) { var i, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 4; i > 0; i--) { if (match[i]) { // match[5] should be "T" or undefined config._f = isoDates[i - 1] + (match[6] || " "); break; } } 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); dateFromConfig(config); } else if (isDate(input)) { config._d = new Date(+input); } else if (typeof(input) === 'object') { dateFromObject(config); } else { config._d = new Date(input); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, language) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = language.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return 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() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = new Date(Date.UTC(year, 0)).getUTCDay(), daysToAdd, dayOfYear; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; if (typeof config._pf === 'undefined') { initializeParsingFlags(config); } if (input === null) { return moment.invalid({nullInput: true}); } 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, strict) { if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } return makeMoment({ _i : input, _f : format, _l : lang, _strict : strict, _isUTC : false }); }; // creating with utc moment.utc = function (input, format, lang, strict) { var m; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } m = makeMoment({ _useUTC : true, _isUTC : true, _l : lang, _i : input, _f : format, _strict : strict }).utc(); return m; }; // 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)), // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso, timeEmpty, dateTimeEmpty; if (isNumber) { if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } 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) { var r; if (!key) { return moment.fn._lang._abbr; } if (values) { loadLang(normalizeLanguage(key), values); } else if (values === null) { unloadLang(key); key = 'en'; } else if (!languages[key]) { getLangDefinition(key); } r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key); return r._abbr; }; // 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; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function (input) { return moment(input).parseZone(); }; /************************************ Moment Prototype ************************************/ extend(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.clone().lang('en').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 () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, 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().zone(this.zone()).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 () { return isLeapYear(this.year()); }, 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) { input = parseWeekday(input, this.lang()); return this.add({ d : input - day }); } else { return day; } }, month : function (input) { var utc = this._isUTC ? 'UTC' : '', dayOfMonth; 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 'isoWeek': 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); } else if (units === 'isoWeek') { this.isoWeekday(1); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add((units === 'isoWeek' ? 'week' : 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" : ""; }, parseZone : function () { if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, 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.day() + 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); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // 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 ************************************/ extend(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 + toInt(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, toIsoString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); } }); 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 = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); // moment.js language configuration // language : Moroccan Arabic (ar-ma) // author : ElFadili Yassine : https://github.com/ElFadiliY // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('ar-ma', { months : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), monthsShort : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), weekdays : "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"), weekdaysMin : "Ø­_Ù†_Ø«_ر_Ø®_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Arabic (ar) // author : Abdel Said : https://github.com/abdelsaid // changes in months, weekdays : Ahmed Elkhatib (function (factory) { factory(moment); }(function (moment) { return moment.lang('ar', { months : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), monthsShort : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), weekdays : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysMin : "Ø­_Ù†_Ø«_ر_Ø®_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : bulgarian (bg) // author : Krasen Borisov : https://github.com/kraz (function (factory) { factory(moment); }(function (moment) { return moment.lang('bg', { months : "януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"), monthsShort : "янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"), weekdays : "неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"), weekdaysShort : "нед_пон_вто_сря_чет_пет_съб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Днес в] LT', nextDay : '[Утре в] LT', nextWeek : 'dddd [в] LT', lastDay : '[Вчера в] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[Ð’ изминалата] dddd [в] LT'; case 1: case 2: case 4: case 5: return '[Ð’ изминалия] dddd [в] LT'; } }, sameElse : 'L' }, relativeTime : { future : "след %s", past : "преди %s", s : "няколко секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дни", M : "месец", MM : "%d месеца", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : breton (br) // author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou (function (factory) { factory(moment); }(function (moment) { function relativeTimeWithMutation(number, withoutSuffix, key) { var format = { 'mm': "munutenn", 'MM': "miz", 'dd': "devezh" }; return number + ' ' + mutation(format[key], number); } function specialMutationForYears(number) { switch (lastNumber(number)) { case 1: case 3: case 4: case 5: case 9: return number + ' bloaz'; default: return number + ' vloaz'; } } function lastNumber(number) { if (number > 9) { return lastNumber(number % 10); } return number; } function mutation(text, number) { if (number === 2) { return softMutation(text); } return text; } function softMutation(text) { var mutationTable = { 'm': 'v', 'b': 'v', 'd': 'z' }; if (mutationTable[text.charAt(0)] === undefined) { return text; } return mutationTable[text.charAt(0)] + text.substring(1); } return moment.lang('br', { months : "Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split("_"), monthsShort : "Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split("_"), weekdays : "Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split("_"), weekdaysShort : "Sul_Lun_Meu_Mer_Yao_Gwe_Sad".split("_"), weekdaysMin : "Su_Lu_Me_Mer_Ya_Gw_Sa".split("_"), longDateFormat : { LT : "h[e]mm A", L : "DD/MM/YYYY", LL : "D [a viz] MMMM YYYY", LLL : "D [a viz] MMMM YYYY LT", LLLL : "dddd, D [a viz] MMMM YYYY LT" }, calendar : { sameDay : '[Hiziv da] LT', nextDay : '[Warc\'hoazh da] LT', nextWeek : 'dddd [da] LT', lastDay : '[Dec\'h da] LT', lastWeek : 'dddd [paset da] LT', sameElse : 'L' }, relativeTime : { future : "a-benn %s", past : "%s 'zo", s : "un nebeud segondennoù", m : "ur vunutenn", mm : relativeTimeWithMutation, h : "un eur", hh : "%d eur", d : "un devezh", dd : relativeTimeWithMutation, M : "ur miz", MM : relativeTimeWithMutation, y : "ur bloaz", yy : specialMutationForYears }, ordinal : function (number) { var output = (number === 1) ? 'añ' : 'vet'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : bosnian (bs) // author : Nedim Cholich : https://github.com/frontyard // based on (hr) translation by Bojan Marković (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('bs', { months : "januar_februar_mart_april_maj_juni_juli_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[proÅ¡lu] dddd [u] LT'; case 6: return '[proÅ¡le] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[proÅ¡li] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : catalan (ca) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { factory(moment); }(function (moment) { return moment.lang('ca', { months : "Gener_Febrer_Març_Abril_Maig_Juny_Juliol_Agost_Setembre_Octubre_Novembre_Desembre".split("_"), monthsShort : "Gen._Febr._Mar._Abr._Mai._Jun._Jul._Ag._Set._Oct._Nov._Des.".split("_"), weekdays : "Diumenge_Dilluns_Dimarts_Dimecres_Dijous_Divendres_Dissabte".split("_"), weekdaysShort : "Dg._Dl._Dt._Dc._Dj._Dv._Ds.".split("_"), weekdaysMin : "Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextDay : function () { return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextWeek : function () { return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastDay : function () { return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastWeek : function () { return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "fa %s", s : "uns segons", m : "un minut", mm : "%d minuts", h : "una hora", hh : "%d hores", d : "un dia", dd : "%d dies", M : "un mes", MM : "%d mesos", y : "un any", yy : "%d anys" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : czech (cs) // author : petrbela : https://github.com/petrbela (function (factory) { factory(moment); }(function (moment) { var months = "leden_únor_bÅ™ezen_duben_kvÄ›ten_červen_červenec_srpen_září_říjen_listopad_prosinec".split("_"), monthsShort = "led_úno_bÅ™e_dub_kvÄ›_čvn_čvc_srp_zář_říj_lis_pro".split("_"); function plural(n) { return (n > 1) && (n < 5) && (~~(n / 10) !== 1); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár vteÅ™in' : 'pár vteÅ™inami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minuty' : 'minut'); } else { return result + 'minutami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodin'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'den' : 'dnem'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dny' : 'dní'); } else { return result + 'dny'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'mÄ›síc' : 'mÄ›sícem'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'mÄ›síce' : 'mÄ›síců'); } else { return result + 'mÄ›síci'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'let'); } else { return result + 'lety'; } break; } } return moment.lang('cs', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "nedÄ›le_pondÄ›lí_úterý_stÅ™eda_čtvrtek_pátek_sobota".split("_"), weekdaysShort : "ne_po_út_st_čt_pá_so".split("_"), weekdaysMin : "ne_po_út_st_čt_pá_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes v] LT", nextDay: '[zítra v] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v nedÄ›li v] LT'; case 1: case 2: return '[v] dddd [v] LT'; case 3: return '[ve stÅ™edu v] LT'; case 4: return '[ve čtvrtek v] LT'; case 5: return '[v pátek v] LT'; case 6: return '[v sobotu v] LT'; } }, lastDay: '[včera v] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulou nedÄ›li v] LT'; case 1: case 2: return '[minulé] dddd [v] LT'; case 3: return '[minulou stÅ™edu v] LT'; case 4: case 5: return '[minulý] dddd [v] LT'; case 6: return '[minulou sobotu v] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "pÅ™ed %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chuvash (cv) // author : Anatoly Mironov : https://github.com/mirontoli (function (factory) { factory(moment); }(function (moment) { return moment.lang('cv', { months : "кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"), monthsShort : "кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"), weekdays : "вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"), weekdaysShort : "выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"), weekdaysMin : "вр_тн_ыт_юн_кç_эр_шм".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ]", LLL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT", LLLL : "dddd, YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT" }, calendar : { sameDay: '[Паян] LT [сехетре]', nextDay: '[Ыран] LT [сехетре]', lastDay: '[Ĕнер] LT [сехетре]', nextWeek: '[Çитес] dddd LT [сехетре]', lastWeek: '[Иртнĕ] dddd LT [сехетре]', sameElse: 'L' }, relativeTime : { future : function (output) { var affix = /сехет$/i.exec(output) ? "рен" : /çул$/i.exec(output) ? "тан" : "ран"; return output + affix; }, past : "%s каялла", s : "пĕр-ик çеккунт", m : "пĕр минут", mm : "%d минут", h : "пĕр сехет", hh : "%d сехет", d : "пĕр кун", dd : "%d кун", M : "пĕр уйăх", MM : "%d уйăх", y : "пĕр çул", yy : "%d çул" }, ordinal : '%d-мĕш', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Welsh (cy) // author : Robert Allen (function (factory) { factory(moment); }(function (moment) { return moment.lang("cy", { months: "Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr".split("_"), monthsShort: "Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag".split("_"), weekdays: "Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn".split("_"), weekdaysShort: "Sul_Llun_Maw_Mer_Iau_Gwe_Sad".split("_"), weekdaysMin: "Su_Ll_Ma_Me_Ia_Gw_Sa".split("_"), // time formats are the same as en-gb longDateFormat: { LT: "HH:mm", L: "DD/MM/YYYY", LL: "D MMMM YYYY", LLL: "D MMMM YYYY LT", LLLL: "dddd, D MMMM YYYY LT" }, calendar: { sameDay: '[Heddiw am] LT', nextDay: '[Yfory am] LT', nextWeek: 'dddd [am] LT', lastDay: '[Ddoe am] LT', lastWeek: 'dddd [diwethaf am] LT', sameElse: 'L' }, relativeTime: { future: "mewn %s", past: "%s yn &#244;l", s: "ychydig eiliadau", m: "munud", mm: "%d munud", h: "awr", hh: "%d awr", d: "diwrnod", dd: "%d diwrnod", M: "mis", MM: "%d mis", y: "blwyddyn", yy: "%d flynedd" }, // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh ordinal: function (number) { var b = number, output = '', lookup = [ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed ]; if (b > 20) { if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { output = 'fed'; // not 30ain, 70ain or 90ain } else { output = 'ain'; } } else if (b > 0) { output = lookup[b]; } return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : danish (da) // author : Ulrik Nielsen : https://github.com/mrbase (function (factory) { factory(moment); }(function (moment) { return moment.lang('da', { months : "januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "søn_man_tir_ons_tor_fre_lør".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[I dag kl.] LT', nextDay : '[I morgen kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[I gÃ¥r kl.] LT', lastWeek : '[sidste] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "om %s", past : "%s siden", s : "fÃ¥ sekunder", m : "et minut", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dage", M : "en mÃ¥ned", MM : "%d mÃ¥neder", y : "et Ã¥r", yy : "%d Ã¥r" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.lang('de', { months : "Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort : "Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays : "Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"), weekdaysShort : "So._Mo._Di._Mi._Do._Fr._Sa.".split("_"), weekdaysMin : "So_Mo_Di_Mi_Do_Fr_Sa".split("_"), longDateFormat : { LT: "H:mm [Uhr]", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay: "[Heute um] LT", sameElse: "L", nextDay: '[Morgen um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gestern um] LT', lastWeek: '[letzten] dddd [um] LT' }, relativeTime : { future : "in %s", past : "vor %s", s : "ein paar Sekunden", m : processRelativeTime, mm : "%d Minuten", h : processRelativeTime, hh : "%d Stunden", d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : modern greek (el) // author : Aggelos Karalias : https://github.com/mehiel (function (factory) { factory(moment); }(function (moment) { return moment.lang('el', { monthsNominativeEl : "Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"), monthsGenitiveEl : "Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου".split("_"), months : function (momentToFormat, format) { if (/D/.test(format.substring(0, format.indexOf("MMMM")))) { // if there is a day number before 'MMMM' return this._monthsGenitiveEl[momentToFormat.month()]; } else { return this._monthsNominativeEl[momentToFormat.month()]; } }, monthsShort : "Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"), weekdays : "Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"), weekdaysShort : "Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"), weekdaysMin : "Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"), meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'μμ' : 'ΜΜ'; } else { return isLower ? 'πμ' : 'ΠΜ'; } }, longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendarEl : { sameDay : '[Σήμερα {}] LT', nextDay : '[Αύριο {}] LT', nextWeek : 'dddd [{}] LT', lastDay : '[Χθες {}] LT', lastWeek : '[την προηγούμενη] dddd [{}] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendarEl[key], hours = mom && mom.hours(); return output.replace("{}", (hours % 12 === 1 ? "στη" : "στις")); }, relativeTime : { future : "σε %s", past : "%s πριν", s : "δευτερόλεπτα", m : "ένα λεπτό", mm : "%d λεπτά", h : "μία ώρα", hh : "%d ώρες", d : "μία μέρα", dd : "%d μέρες", M : "ένας μήνας", MM : "%d μήνες", y : "ένας χρόνος", yy : "%d χρόνια" }, ordinal : function (number) { return number + 'η'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4st is the first week of the year. } }); })); // moment.js language configuration // language : australian english (en-au) (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-au', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, 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" }, 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; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian english (en-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-ca', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "YYYY-MM-DD", LL : "D MMMM, YYYY", LLL : "D MMMM, YYYY LT", LLLL : "dddd, D MMMM, YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, 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" }, 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; } }); })); // moment.js language configuration // language : great britain english (en-gb) // author : Chris Gedrim : https://github.com/chrisgedrim (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-gb', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, 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" }, 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; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : esperanto (eo) // author : Colin Dean : https://github.com/colindean // komento: Mi estas malcerta se mi korekte traktis akuzativojn en tiu traduko. // Se ne, bonvolu korekti kaj avizi min por ke mi povas lerni! (function (factory) { factory(moment); }(function (moment) { return moment.lang('eo', { months : "januaro_februaro_marto_aprilo_majo_junio_julio_aÅ­gusto_septembro_oktobro_novembro_decembro".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aÅ­g_sep_okt_nov_dec".split("_"), weekdays : "Dimanĉo_Lundo_Mardo_Merkredo_Ä´aÅ­do_Vendredo_Sabato".split("_"), weekdaysShort : "Dim_Lun_Mard_Merk_Ä´aÅ­_Ven_Sab".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Ä´a_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D[-an de] MMMM, YYYY", LLL : "D[-an de] MMMM, YYYY LT", LLLL : "dddd, [la] D[-an de] MMMM, YYYY LT" }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'p.t.m.' : 'P.T.M.'; } else { return isLower ? 'a.t.m.' : 'A.T.M.'; } }, calendar : { sameDay : '[HodiaÅ­ je] LT', nextDay : '[MorgaÅ­ je] LT', nextWeek : 'dddd [je] LT', lastDay : '[HieraÅ­ je] LT', lastWeek : '[pasinta] dddd [je] LT', sameElse : 'L' }, relativeTime : { future : "je %s", past : "antaÅ­ %s", s : "sekundoj", m : "minuto", mm : "%d minutoj", h : "horo", hh : "%d horoj", d : "tago",//ne 'diurno', ĉar estas uzita por proksimumo dd : "%d tagoj", M : "monato", MM : "%d monatoj", y : "jaro", yy : "%d jaroj" }, ordinal : "%da", week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : spanish (es) // author : Julio Napurí : https://github.com/julionc (function (factory) { factory(moment); }(function (moment) { return moment.lang('es', { months : "enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"), monthsShort : "ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_"), weekdays : "domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"), weekdaysShort : "dom._lun._mar._mié._jue._vie._sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "hace %s", s : "unos segundos", m : "un minuto", mm : "%d minutos", h : "una hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un año", yy : "%d años" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : estonian (et) // author : Henry Kehlmann : https://github.com/madhenry (function (factory) { factory(moment); }(function (moment) { function translateSeconds(number, withoutSuffix, key, isFuture) { return (isFuture || withoutSuffix) ? 'paari sekundi' : 'paar sekundit'; } return moment.lang('et', { months : "jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember".split("_"), monthsShort : "jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets".split("_"), weekdays : "pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev".split("_"), weekdaysShort : "P_E_T_K_N_R_L".split("_"), weekdaysMin : "P_E_T_K_N_R_L".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[Täna,] LT', nextDay : '[Homme,] LT', nextWeek : '[Järgmine] dddd LT', lastDay : '[Eile,] LT', lastWeek : '[Eelmine] dddd LT', sameElse : 'L' }, relativeTime : { future : "%s pärast", past : "%s tagasi", s : translateSeconds, m : "minut", mm : "%d minutit", h : "tund", hh : "%d tundi", d : "päev", dd : "%d päeva", M : "kuu", MM : "%d kuud", y : "aasta", yy : "%d aastat" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : euskara (eu) // author : Eneko Illarramendi : https://github.com/eillarra (function (factory) { factory(moment); }(function (moment) { return moment.lang('eu', { months : "urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"), monthsShort : "urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"), weekdays : "igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"), weekdaysShort : "ig._al._ar._az._og._ol._lr.".split("_"), weekdaysMin : "ig_al_ar_az_og_ol_lr".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY[ko] MMMM[ren] D[a]", LLL : "YYYY[ko] MMMM[ren] D[a] LT", LLLL : "dddd, YYYY[ko] MMMM[ren] D[a] LT", l : "YYYY-M-D", ll : "YYYY[ko] MMM D[a]", lll : "YYYY[ko] MMM D[a] LT", llll : "ddd, YYYY[ko] MMM D[a] LT" }, calendar : { sameDay : '[gaur] LT[etan]', nextDay : '[bihar] LT[etan]', nextWeek : 'dddd LT[etan]', lastDay : '[atzo] LT[etan]', lastWeek : '[aurreko] dddd LT[etan]', sameElse : 'L' }, relativeTime : { future : "%s barru", past : "duela %s", s : "segundo batzuk", m : "minutu bat", mm : "%d minutu", h : "ordu bat", hh : "%d ordu", d : "egun bat", dd : "%d egun", M : "hilabete bat", MM : "%d hilabete", y : "urte bat", yy : "%d urte" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Persian Language // author : Ebrahim Byagowi : https://github.com/ebraminio (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': 'Û±', '2': 'Û²', '3': 'Û³', '4': 'Û´', '5': 'Ûµ', '6': 'Û¶', '7': 'Û·', '8': 'Û¸', '9': 'Û¹', '0': 'Û°' }, numberMap = { 'Û±': '1', 'Û²': '2', 'Û³': '3', 'Û´': '4', 'Ûµ': '5', 'Û¶': '6', 'Û·': '7', 'Û¸': '8', 'Û¹': '9', 'Û°': '0' }; return moment.lang('fa', { months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysMin : 'ÛŒ_د_س_Ú†_Ù¾_ج_Ø´'.split('_'), longDateFormat : { LT : 'HH:mm', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY LT', LLLL : 'dddd, D MMMM YYYY LT' }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "قبل از ظهر"; } else { return "بعد از ظهر"; } }, calendar : { sameDay : '[امروز ساعت] LT', nextDay : '[فردا ساعت] LT', nextWeek : 'dddd [ساعت] LT', lastDay : '[دیروز ساعت] LT', lastWeek : 'dddd [پیش] [ساعت] LT', sameElse : 'L' }, relativeTime : { future : 'در %s', past : '%s پیش', s : 'چندین ثانیه', m : 'یک دقیقه', mm : '%d دقیقه', h : 'یک ساعت', hh : '%d ساعت', d : 'یک روز', dd : '%d روز', M : 'یک ماه', MM : '%d ماه', y : 'یک سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/[Û°-Û¹]/g, function (match) { return numberMap[match]; }).replace(/ØŒ/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }).replace(/,/g, 'ØŒ'); }, ordinal : '%dÙ…', week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : finnish (fi) // author : Tarmo Aidantausta : https://github.com/bleadof (function (factory) { factory(moment); }(function (moment) { var numbers_past = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), numbers_future = ['nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', numbers_past[7], numbers_past[8], numbers_past[9]]; function translate(number, withoutSuffix, key, isFuture) { var result = ""; switch (key) { case 's': return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; case 'm': return isFuture ? 'minuutin' : 'minuutti'; case 'mm': result = isFuture ? 'minuutin' : 'minuuttia'; break; case 'h': return isFuture ? 'tunnin' : 'tunti'; case 'hh': result = isFuture ? 'tunnin' : 'tuntia'; break; case 'd': return isFuture ? 'päivän' : 'päivä'; case 'dd': result = isFuture ? 'päivän' : 'päivää'; break; case 'M': return isFuture ? 'kuukauden' : 'kuukausi'; case 'MM': result = isFuture ? 'kuukauden' : 'kuukautta'; break; case 'y': return isFuture ? 'vuoden' : 'vuosi'; case 'yy': result = isFuture ? 'vuoden' : 'vuotta'; break; } result = verbal_number(number, isFuture) + " " + result; return result; } function verbal_number(number, isFuture) { return number < 10 ? (isFuture ? numbers_future[number] : numbers_past[number]) : number; } return moment.lang('fi', { months : "tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"), monthsShort : "tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"), weekdays : "sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"), weekdaysShort : "su_ma_ti_ke_to_pe_la".split("_"), weekdaysMin : "su_ma_ti_ke_to_pe_la".split("_"), longDateFormat : { LT : "HH.mm", L : "DD.MM.YYYY", LL : "Do MMMM[ta] YYYY", LLL : "Do MMMM[ta] YYYY, [klo] LT", LLLL : "dddd, Do MMMM[ta] YYYY, [klo] LT", l : "D.M.YYYY", ll : "Do MMM YYYY", lll : "Do MMM YYYY, [klo] LT", llll : "ddd, Do MMM YYYY, [klo] LT" }, calendar : { sameDay : '[tänään] [klo] LT', nextDay : '[huomenna] [klo] LT', nextWeek : 'dddd [klo] LT', lastDay : '[eilen] [klo] LT', lastWeek : '[viime] dddd[na] [klo] LT', sameElse : 'L' }, relativeTime : { future : "%s päästä", past : "%s sitten", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : "%d.", week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : faroese (fo) // author : Ragnar Johannesen : https://github.com/ragnar123 (function (factory) { factory(moment); }(function (moment) { return moment.lang('fo', { months : "januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"), weekdaysShort : "sun_mán_týs_mik_hós_frí_ley".split("_"), weekdaysMin : "su_má_tý_mi_hó_fr_le".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[Í dag kl.] LT', nextDay : '[Í morgin kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[Í gjár kl.] LT', lastWeek : '[síðstu] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "um %s", past : "%s síðani", s : "fá sekund", m : "ein minutt", mm : "%d minuttir", h : "ein tími", hh : "%d tímar", d : "ein dagur", dd : "%d dagar", M : "ein mánaði", MM : "%d mánaðir", y : "eitt ár", yy : "%d ár" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian french (fr-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { factory(moment); }(function (moment) { return moment.lang('fr-ca', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à ] LT", nextDay: '[Demain à ] LT', nextWeek: 'dddd [à ] LT', lastDay: '[Hier à ] LT', lastWeek: 'dddd [dernier à ] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); } }); })); // moment.js language configuration // language : french (fr) // author : John Fischer : https://github.com/jfroffice (function (factory) { factory(moment); }(function (moment) { return moment.lang('fr', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à ] LT", nextDay: '[Demain à ] LT', nextWeek: 'dddd [à ] LT', lastDay: '[Hier à ] LT', lastWeek: 'dddd [dernier à ] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : galician (gl) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { factory(moment); }(function (moment) { return moment.lang('gl', { months : "Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro".split("_"), monthsShort : "Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"), weekdays : "Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"), weekdaysShort : "Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay : function () { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek : function () { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay : function () { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek : function () { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : function (str) { if (str === "uns segundos") { return "nuns segundos"; } return "en " + str; }, past : "hai %s", s : "uns segundos", m : "un minuto", mm : "%d minutos", h : "unha hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Hebrew (he) // author : Tomer Cohen : https://github.com/tomer // author : Moshe Simantov : https://github.com/DevelopmentIL // author : Tal Ater : https://github.com/TalAter (function (factory) { factory(moment); }(function (moment) { return moment.lang('he', { months : "×™× ×•××¨_פברואר_מרץ_אפריל_מאי_×™×•× ×™_יולי_אוגוסט_ספטמבר_אוקטובר_× ×•×‘×ž×‘×¨_דצמבר".split("_"), monthsShort : "×™× ×•×³_פבר׳_מרץ_אפר׳_מאי_×™×•× ×™_יולי_אוג׳_ספט׳_אוק׳_× ×•×‘×³_דצמ׳".split("_"), weekdays : "ראשון_×©× ×™_שלישי_רביעי_חמישי_שישי_שבת".split("_"), weekdaysShort : "א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"), weekdaysMin : "א_ב_×’_ד_×”_ו_ש".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [ב]MMMM YYYY", LLL : "D [ב]MMMM YYYY LT", LLLL : "dddd, D [ב]MMMM YYYY LT", l : "D/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay : '[היום ב־]LT', nextDay : '[מחר ב־]LT', nextWeek : 'dddd [בשעה] LT', lastDay : '[אתמול ב־]LT', lastWeek : '[ביום] dddd [האחרון בשעה] LT', sameElse : 'L' }, relativeTime : { future : "בעוד %s", past : "×œ×¤× ×™ %s", s : "מספר ×©× ×™×•×ª", m : "דקה", mm : "%d דקות", h : "שעה", hh : function (number) { if (number === 2) { return "שעתיים"; } return number + " שעות"; }, d : "יום", dd : function (number) { if (number === 2) { return "יומיים"; } return number + " ימים"; }, M : "חודש", MM : function (number) { if (number === 2) { return "חודשיים"; } return number + " חודשים"; }, y : "×©× ×”", yy : function (number) { if (number === 2) { return "×©× ×ª×™×™×"; } return number + " ×©× ×™×"; } } }); })); // moment.js language configuration // language : hindi (hi) // author : Mayank Singhal : https://github.com/mayanksinghal (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('hi', { months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split("_"), monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split("_"), weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[कल] LT', nextWeek : 'dddd, LT', lastDay : '[कल] LT', lastWeek : '[पिछले] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s में", past : "%s पहले", s : "कुछ ही क्षण", m : "एक मिनट", mm : "%d मिनट", h : "एक घंटा", hh : "%d घंटे", d : "एक दिन", dd : "%d दिन", M : "एक महीने", MM : "%d महीने", y : "एक वर्ष", yy : "%d वर्ष" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Hindi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. meridiem : function (hour, minute, isLower) { if (hour < 4) { return "रात"; } else if (hour < 10) { return "सुबह"; } else if (hour < 17) { return "दोपहर"; } else if (hour < 20) { return "शाम"; } else { return "रात"; } }, 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. } }); })); // moment.js language configuration // language : hrvatski (hr) // author : Bojan Marković : https://github.com/bmarkovic // based on (sl) translation by Robert SedovÅ¡ek (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('hr', { months : "sječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac".split("_"), monthsShort : "sje._vel._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[proÅ¡lu] dddd [u] LT'; case 6: return '[proÅ¡le] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[proÅ¡li] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hungarian (hu) // author : Adam Brunner : https://github.com/adambrunner (function (factory) { factory(moment); }(function (moment) { var weekEndings = 'vasárnap hétfÅ‘n kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num = number, suffix; switch (key) { case 's': return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'M': return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'MM': return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'y': return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); case 'yy': return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } return ''; } function week(isFuture) { return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } return moment.lang('hu', { months : "január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"), monthsShort : "jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"), weekdays : "vasárnap_hétfÅ‘_kedd_szerda_csütörtök_péntek_szombat".split("_"), weekdaysShort : "vas_hét_kedd_sze_csüt_pén_szo".split("_"), weekdaysMin : "v_h_k_sze_cs_p_szo".split("_"), longDateFormat : { LT : "H:mm", L : "YYYY.MM.DD.", LL : "YYYY. MMMM D.", LLL : "YYYY. MMMM D., LT", LLLL : "YYYY. MMMM D., dddd LT" }, calendar : { sameDay : '[ma] LT[-kor]', nextDay : '[holnap] LT[-kor]', nextWeek : function () { return week.call(this, true); }, lastDay : '[tegnap] LT[-kor]', lastWeek : function () { return week.call(this, false); }, sameElse : 'L' }, relativeTime : { future : "%s múlva", past : "%s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Indonesia (id) // author : Mohammad Satrio Utomo : https://github.com/tyok // reference: http://id.wikisource.org/wiki/Pedoman_Umum_Ejaan_Bahasa_Indonesia_yang_Disempurnakan (function (factory) { factory(moment); }(function (moment) { return moment.lang('id', { months : "Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"), monthsShort : "Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"), weekdays : "Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"), weekdaysShort : "Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"), weekdaysMin : "Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'siang'; } else if (hours < 19) { return 'sore'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Besok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kemarin pukul] LT', lastWeek : 'dddd [lalu pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lalu", s : "beberapa detik", m : "semenit", mm : "%d menit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : icelandic (is) // author : Hinrik Örn Sigurðsson : https://github.com/hinrik (function (factory) { factory(moment); }(function (moment) { function plural(n) { if (n % 100 === 11) { return true; } else if (n % 10 === 1) { return false; } return true; } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; case 'm': return withoutSuffix ? 'mínúta' : 'mínútu'; case 'mm': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); } else if (withoutSuffix) { return result + 'mínúta'; } return result + 'mínútu'; case 'hh': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); } return result + 'klukkustund'; case 'd': if (withoutSuffix) { return 'dagur'; } return isFuture ? 'dag' : 'degi'; case 'dd': if (plural(number)) { if (withoutSuffix) { return result + 'dagar'; } return result + (isFuture ? 'daga' : 'dögum'); } else if (withoutSuffix) { return result + 'dagur'; } return result + (isFuture ? 'dag' : 'degi'); case 'M': if (withoutSuffix) { return 'mánuður'; } return isFuture ? 'mánuð' : 'mánuði'; case 'MM': if (plural(number)) { if (withoutSuffix) { return result + 'mánuðir'; } return result + (isFuture ? 'mánuði' : 'mánuðum'); } else if (withoutSuffix) { return result + 'mánuður'; } return result + (isFuture ? 'mánuð' : 'mánuði'); case 'y': return withoutSuffix || isFuture ? 'ár' : 'ári'; case 'yy': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); } return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); } } return moment.lang('is', { months : "janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"), monthsShort : "jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"), weekdays : "sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"), weekdaysShort : "sun_mán_þri_mið_fim_fös_lau".split("_"), weekdaysMin : "Su_Má_Þr_Mi_Fi_Fö_La".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd, D. MMMM YYYY [kl.] LT" }, calendar : { sameDay : '[í dag kl.] LT', nextDay : '[á morgun kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[í gær kl.] LT', lastWeek : '[síðasta] dddd [kl.] LT', sameElse : 'L' }, relativeTime : { future : "eftir %s", past : "fyrir %s síðan", s : translate, m : translate, mm : translate, h : "klukkustund", hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : italian (it) // author : Lorenzo : https://github.com/aliem // author: Mattia Larentis: https://github.com/nostalgiaz (function (factory) { factory(moment); }(function (moment) { return moment.lang('it', { months : "Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settembre_Ottobre_Novembre_Dicembre".split("_"), monthsShort : "Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"), weekdays : "Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato".split("_"), weekdaysShort : "Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"), weekdaysMin : "D_L_Ma_Me_G_V_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: '[lo scorso] dddd [alle] LT', sameElse: 'L' }, relativeTime : { future : function (s) { return ((/^[0-9].+$/).test(s) ? "tra" : "in") + " " + s; }, past : "%s fa", s : "secondi", m : "un minuto", mm : "%d minuti", h : "un'ora", hh : "%d ore", d : "un giorno", dd : "%d giorni", M : "un mese", MM : "%d mesi", y : "un anno", yy : "%d anni" }, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : japanese (ja) // author : LI Long : https://github.com/baryon (function (factory) { factory(moment); }(function (moment) { return moment.lang('ja', { months : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"), weekdaysShort : "æ—¥_月_火_æ°´_木_金_土".split("_"), weekdaysMin : "æ—¥_月_火_æ°´_木_金_土".split("_"), longDateFormat : { LT : "Ah時m分", L : "YYYY/MM/DD", LL : "YYYYå¹´M月Dæ—¥", LLL : "YYYYå¹´M月Dæ—¥LT", LLLL : "YYYYå¹´M月Dæ—¥LT dddd" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "午前"; } else { return "午後"; } }, calendar : { sameDay : '[今日] LT', nextDay : '[明日] LT', nextWeek : '[来週]dddd LT', lastDay : '[昨日] LT', lastWeek : '[前週]dddd LT', sameElse : 'L' }, relativeTime : { future : "%s後", past : "%s前", s : "æ•°ç§’", m : "1分", mm : "%d分", h : "1時間", hh : "%d時間", d : "1æ—¥", dd : "%dæ—¥", M : "1ヶ月", MM : "%dヶ月", y : "1å¹´", yy : "%då¹´" } }); })); // moment.js language configuration // language : Georgian (ka) // author : Irakli Janiashvili : https://github.com/irakli-janiashvili (function (factory) { factory(moment); }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), 'accusative': 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') }, nounCase = (/D[oD] *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), 'accusative': 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_') }, nounCase = (/(წინა|შემდეგ)/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ka', { months : monthsCaseReplace, monthsShort : "იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ".split("_"), weekdaysMin : "კვ_ორ_სა_ოთ_ხუ_პა_შა".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[დღეს] LT[-ზე]', nextDay : '[ხვალ] LT[-ზე]', lastDay : '[გუშინ] LT[-ზე]', nextWeek : '[შემდეგ] dddd LT[-ზე]', lastWeek : '[წინა] dddd LT-ზე', sameElse : 'L' }, relativeTime : { future : function (s) { return (/(წამი|წუთი|საათი|წელი)/).test(s) ? s.replace(/ი$/, "ში") : s + "ში"; }, past : function (s) { if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { return s.replace(/(ი|ე)$/, "ის წინ"); } if ((/წელი/).test(s)) { return s.replace(/წელი$/, "წლის წინ"); } }, s : "რამდენიმე წამი", m : "წუთი", mm : "%d წუთი", h : "საათი", hh : "%d საათი", d : "დღე", dd : "%d დღე", M : "თვე", MM : "%d თვე", y : "წელი", yy : "%d წელი" }, ordinal : function (number) { if (number === 0) { return number; } if (number === 1) { return number + "-ლი"; } if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { return "მე-" + number; } return number + "-ე"; }, week : { dow : 1, doy : 7 } }); })); // moment.js language configuration // language : korean (ko) // author : Kyungwook, Park : https://github.com/kyungw00k (function (factory) { factory(moment); }(function (moment) { return moment.lang('ko', { months : "1ì›”_2ì›”_3ì›”_4ì›”_5ì›”_6ì›”_7ì›”_8ì›”_9ì›”_10ì›”_11ì›”_12ì›”".split("_"), monthsShort : "1ì›”_2ì›”_3ì›”_4ì›”_5ì›”_6ì›”_7ì›”_8ì›”_9ì›”_10ì›”_11ì›”_12ì›”".split("_"), weekdays : "일요일_월요일_화요일_수요일_목요일_금요일_í† ìš”ì¼".split("_"), weekdaysShort : "일_ì›”_í™”_수_목_금_í† ".split("_"), weekdaysMin : "일_ì›”_í™”_수_목_금_í† ".split("_"), longDateFormat : { LT : "A h시 mmë¶„", L : "YYYY.MM.DD", LL : "YYYYë…„ MMMM D일", LLL : "YYYYë…„ MMMM D일 LT", LLLL : "YYYYë…„ MMMM D일 dddd LT" }, meridiem : function (hour, minute, isUpper) { return hour < 12 ? 'ì˜¤ì „' : '오후'; }, calendar : { sameDay : '오늘 LT', nextDay : '내일 LT', nextWeek : 'dddd LT', lastDay : 'ì–´ì œ LT', lastWeek : '지난주 dddd LT', sameElse : 'L' }, relativeTime : { future : "%s 후", past : "%s ì „", s : "몇초", ss : "%dì´ˆ", m : "일분", mm : "%dë¶„", h : "한시간", hh : "%d시간", d : "하루", dd : "%d일", M : "한달", MM : "%d달", y : "일년", yy : "%dë…„" }, ordinal : '%d일' }); })); // moment.js language configuration // language : Lithuanian (lt) // author : Mindaugas MozÅ«ras : https://github.com/mmozuras (function (factory) { factory(moment); }(function (moment) { var units = { "m" : "minutÄ—_minutÄ—s_minutÄ™", "mm": "minutÄ—s_minučių_minutes", "h" : "valanda_valandos_valandÄ…", "hh": "valandos_valandų_valandas", "d" : "diena_dienos_dienÄ…", "dd": "dienos_dienų_dienas", "M" : "mÄ—nuo_mÄ—nesio_mÄ—nesį", "MM": "mÄ—nesiai_mÄ—nesių_mÄ—nesius", "y" : "metai_metų_metus", "yy": "metai_metų_metus" }, weekDays = "pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_Å¡eÅ¡tadienis_sekmadienis".split("_"); function translateSeconds(number, withoutSuffix, key, isFuture) { if (withoutSuffix) { return "kelios sekundÄ—s"; } else { return isFuture ? "kelių sekundžių" : "kelias sekundes"; } } function translateSingular(number, withoutSuffix, key, isFuture) { return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); } function special(number) { return number % 10 === 0 || (number > 10 && number < 20); } function forms(key) { return units[key].split("_"); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; if (number === 1) { return result + translateSingular(number, withoutSuffix, key[0], isFuture); } else if (withoutSuffix) { return result + (special(number) ? forms(key)[1] : forms(key)[0]); } else { if (isFuture) { return result + forms(key)[1]; } else { return result + (special(number) ? forms(key)[1] : forms(key)[2]); } } } function relativeWeekDay(moment, format) { var nominative = format.indexOf('dddd LT') === -1, weekDay = weekDays[moment.weekday()]; return nominative ? weekDay : weekDay.substring(0, weekDay.length - 2) + "į"; } return moment.lang("lt", { months : "sausio_vasario_kovo_balandžio_gegužės_biržėlio_liepos_rugpjūčio_rugsÄ—jo_spalio_lapkričio_gruodžio".split("_"), monthsShort : "sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"), weekdays : relativeWeekDay, weekdaysShort : "Sek_Pir_Ant_Tre_Ket_Pen_Å eÅ¡".split("_"), weekdaysMin : "S_P_A_T_K_Pn_Å ".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY [m.] MMMM D [d.]", LLL : "YYYY [m.] MMMM D [d.], LT [val.]", LLLL : "YYYY [m.] MMMM D [d.], dddd, LT [val.]", l : "YYYY-MM-DD", ll : "YYYY [m.] MMMM D [d.]", lll : "YYYY [m.] MMMM D [d.], LT [val.]", llll : "YYYY [m.] MMMM D [d.], ddd, LT [val.]" }, calendar : { sameDay : "[Å iandien] LT", nextDay : "[Rytoj] LT", nextWeek : "dddd LT", lastDay : "[Vakar] LT", lastWeek : "[PraÄ—jusį] dddd LT", sameElse : "L" }, relativeTime : { future : "po %s", past : "prieÅ¡ %s", s : translateSeconds, m : translateSingular, mm : translate, h : translateSingular, hh : translate, d : translateSingular, dd : translate, M : translateSingular, MM : translate, y : translateSingular, yy : translate }, ordinal : function (number) { return number + '-oji'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : latvian (lv) // author : Kristaps Karlsons : https://github.com/skakri (function (factory) { factory(moment); }(function (moment) { var units = { 'mm': 'minÅ«ti_minÅ«tes_minÅ«te_minÅ«tes', 'hh': 'stundu_stundas_stunda_stundas', 'dd': 'dienu_dienas_diena_dienas', 'MM': 'mÄ“nesi_mÄ“neÅ¡us_mÄ“nesis_mÄ“neÅ¡i', 'yy': 'gadu_gadus_gads_gadi' }; function format(word, number, withoutSuffix) { var forms = word.split('_'); if (withoutSuffix) { return number % 10 === 1 && number !== 11 ? forms[2] : forms[3]; } else { return number % 10 === 1 && number !== 11 ? forms[0] : forms[1]; } } function relativeTimeWithPlural(number, withoutSuffix, key) { return number + ' ' + format(units[key], number, withoutSuffix); } return moment.lang('lv', { months : "janvāris_februāris_marts_aprÄ«lis_maijs_jÅ«nijs_jÅ«lijs_augusts_septembris_oktobris_novembris_decembris".split("_"), monthsShort : "jan_feb_mar_apr_mai_jÅ«n_jÅ«l_aug_sep_okt_nov_dec".split("_"), weekdays : "svÄ“tdiena_pirmdiena_otrdiena_treÅ¡diena_ceturtdiena_piektdiena_sestdiena".split("_"), weekdaysShort : "Sv_P_O_T_C_Pk_S".split("_"), weekdaysMin : "Sv_P_O_T_C_Pk_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "YYYY. [gada] D. MMMM", LLL : "YYYY. [gada] D. MMMM, LT", LLLL : "YYYY. [gada] D. MMMM, dddd, LT" }, calendar : { sameDay : '[Å odien pulksten] LT', nextDay : '[RÄ«t pulksten] LT', nextWeek : 'dddd [pulksten] LT', lastDay : '[Vakar pulksten] LT', lastWeek : '[Pagājušā] dddd [pulksten] LT', sameElse : 'L' }, relativeTime : { future : "%s vÄ“lāk", past : "%s agrāk", s : "dažas sekundes", m : "minÅ«ti", mm : relativeTimeWithPlural, h : "stundu", hh : relativeTimeWithPlural, d : "dienu", dd : relativeTimeWithPlural, M : "mÄ“nesi", MM : relativeTimeWithPlural, y : "gadu", yy : relativeTimeWithPlural }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : malayalam (ml) // author : Floyd Pink : https://github.com/floydpink (function (factory) { factory(moment); }(function (moment) { return moment.lang('ml', { months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split("_"), monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._à´“à´—._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split("_"), weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split("_"), weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split("_"), weekdaysMin : 'à´žà´¾_തി_ചൊ_ബു_വ്യാ_വെ_à´¶'.split("_"), longDateFormat : { LT : "A h:mm -നു", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[ഇന്ന്] LT', nextDay : '[നാളെ] LT', nextWeek : 'dddd, LT', lastDay : '[ഇന്നലെ] LT', lastWeek : '[കഴിഞ്ഞ] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s കഴിഞ്ഞ്", past : "%s മുൻപ്", s : "അൽപ നിമിഷങ്ങൾ", m : "ഒരു മിനിറ്റ്", mm : "%d മിനിറ്റ്", h : "ഒരു മണിക്കൂർ", hh : "%d മണിക്കൂർ", d : "ഒരു ദിവസം", dd : "%d ദിവസം", M : "ഒരു മാസം", MM : "%d മാസം", y : "ഒരു വർഷം", yy : "%d വർഷം" }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return "രാത്രി"; } else if (hour < 12) { return "രാവിലെ"; } else if (hour < 17) { return "ഉച്ച കഴിഞ്ഞ്"; } else if (hour < 20) { return "വൈകുന്നേരം"; } else { return "രാത്രി"; } } }); })); // moment.js language configuration // language : Marathi (mr) // author : Harshad Kale : https://github.com/kalehv (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('mr', { months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split("_"), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split("_"), weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm वाजता", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[उद्या] LT', nextWeek : 'dddd, LT', lastDay : '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s नंतर", past : "%s पूर्वी", s : "सेकंद", m: "एक मिनिट", mm: "%d मिनिटे", h : "एक तास", hh : "%d तास", d : "एक दिवस", dd : "%d दिवस", M : "एक महिना", MM : "%d महिने", y : "एक वर्ष", yy : "%d वर्षे" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return "रात्री"; } else if (hour < 10) { return "सकाळी"; } else if (hour < 17) { return "दुपारी"; } else if (hour < 20) { return "सायंकाळी"; } else { return "रात्री"; } }, 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. } }); })); // moment.js language configuration // language : Bahasa Malaysia (ms-MY) // author : Weldan Jamili : https://github.com/weldan (function (factory) { factory(moment); }(function (moment) { return moment.lang('ms-my', { months : "Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"), monthsShort : "Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"), weekdays : "Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"), weekdaysShort : "Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"), weekdaysMin : "Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Esok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kelmarin pukul] LT', lastWeek : 'dddd [lepas pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lepas", s : "beberapa saat", m : "seminit", mm : "%d minit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : norwegian bokmÃ¥l (nb) // authors : Espen Hovlandsdal : https://github.com/rexxars // Sigurd Gartmann : https://github.com/sigurdga (function (factory) { factory(moment); }(function (moment) { return moment.lang('nb', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "sø._ma._ti._on._to._fr._lø.".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "H.mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd D. MMMM YYYY [kl.] LT" }, calendar : { sameDay: '[i dag kl.] LT', nextDay: '[i morgen kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[i gÃ¥r kl.] LT', lastWeek: '[forrige] dddd [kl.] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekunder", m : "ett minutt", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dager", M : "en mÃ¥ned", MM : "%d mÃ¥neder", y : "ett Ã¥r", yy : "%d Ã¥r" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : nepali/nepalese // author : suvash : https://github.com/suvash (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('ne', { months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split("_"), monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split("_"), weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split("_"), weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split("_"), weekdaysMin : 'आइ._सो._मङ्_बु._बि._शु._श.'.split("_"), longDateFormat : { LT : "Aको h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem : function (hour, minute, isLower) { if (hour < 3) { return "राती"; } else if (hour < 10) { return "बिहान"; } else if (hour < 15) { return "दिउँसो"; } else if (hour < 18) { return "बेलुका"; } else if (hour < 20) { return "साँझ"; } else { return "राती"; } }, calendar : { sameDay : '[आज] LT', nextDay : '[भोली] LT', nextWeek : '[आउँदो] dddd[,] LT', lastDay : '[हिजो] LT', lastWeek : '[गएको] dddd[,] LT', sameElse : 'L' }, relativeTime : { future : "%sमा", past : "%s अगाडी", s : "केही समय", m : "एक मिनेट", mm : "%d मिनेट", h : "एक घण्टा", hh : "%d घण्टा", d : "एक दिन", dd : "%d दिन", M : "एक महिना", MM : "%d महिना", y : "एक बर्ष", yy : "%d बर्ष" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : dutch (nl) // author : Joris Röling : https://github.com/jjupiter (function (factory) { factory(moment); }(function (moment) { var monthsShortWithDots = "jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_"), monthsShortWithoutDots = "jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_"); return moment.lang('nl', { months : "januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"), monthsShort : function (m, format) { if (/-MMM-/.test(format)) { return monthsShortWithoutDots[m.month()]; } else { return monthsShortWithDots[m.month()]; } }, weekdays : "zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"), weekdaysShort : "zo._ma._di._wo._do._vr._za.".split("_"), weekdaysMin : "Zo_Ma_Di_Wo_Do_Vr_Za".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' }, relativeTime : { future : "over %s", past : "%s geleden", s : "een paar seconden", m : "één minuut", mm : "%d minuten", h : "één uur", hh : "%d uur", d : "één dag", dd : "%d dagen", M : "één maand", MM : "%d maanden", y : "één jaar", yy : "%d jaar" }, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : norwegian nynorsk (nn) // author : https://github.com/mechuwind (function (factory) { factory(moment); }(function (moment) { return moment.lang('nn', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sundag_mÃ¥ndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"), weekdaysShort : "sun_mÃ¥n_tys_ons_tor_fre_lau".split("_"), weekdaysMin : "su_mÃ¥_ty_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[I dag klokka] LT', nextDay: '[I morgon klokka] LT', nextWeek: 'dddd [klokka] LT', lastDay: '[I gÃ¥r klokka] LT', lastWeek: '[FøregÃ¥ende] dddd [klokka] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekund", m : "ett minutt", mm : "%d minutt", h : "en time", hh : "%d timar", d : "en dag", dd : "%d dagar", M : "en mÃ¥nad", MM : "%d mÃ¥nader", y : "ett Ã¥r", yy : "%d Ã¥r" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : polish (pl) // author : Rafal Hirsz : https://github.com/evoL (function (factory) { factory(moment); }(function (moment) { var monthsNominative = "styczeÅ„_luty_marzec_kwiecieÅ„_maj_czerwiec_lipiec_sierpieÅ„_wrzesieÅ„_październik_listopad_grudzieÅ„".split("_"), monthsSubjective = "stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_wrzeÅ›nia_października_listopada_grudnia".split("_"); function plural(n) { return (n % 10 < 5) && (n % 10 > 1) && (~~(n / 10) !== 1); } function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'minuta' : 'minutÄ™'; case 'mm': return result + (plural(number) ? 'minuty' : 'minut'); case 'h': return withoutSuffix ? 'godzina' : 'godzinÄ™'; case 'hh': return result + (plural(number) ? 'godziny' : 'godzin'); case 'MM': return result + (plural(number) ? 'miesiÄ…ce' : 'miesiÄ™cy'); case 'yy': return result + (plural(number) ? 'lata' : 'lat'); } } return moment.lang('pl', { months : function (momentToFormat, format) { if (/D MMMM/.test(format)) { return monthsSubjective[momentToFormat.month()]; } else { return monthsNominative[momentToFormat.month()]; } }, monthsShort : "sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"), weekdays : "niedziela_poniedziaÅ‚ek_wtorek_Å›roda_czwartek_piÄ…tek_sobota".split("_"), weekdaysShort : "nie_pon_wt_Å›r_czw_pt_sb".split("_"), weekdaysMin : "N_Pn_Wt_Åšr_Cz_Pt_So".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[DziÅ› o] LT', nextDay: '[Jutro o] LT', nextWeek: '[W] dddd [o] LT', lastDay: '[Wczoraj o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[W zeszłą niedzielÄ™ o] LT'; case 3: return '[W zeszłą Å›rodÄ™ o] LT'; case 6: return '[W zeszłą sobotÄ™ o] LT'; default: return '[W zeszÅ‚y] dddd [o] LT'; } }, sameElse: 'L' }, relativeTime : { future : "za %s", past : "%s temu", s : "kilka sekund", m : translate, mm : translate, h : translate, hh : translate, d : "1 dzieÅ„", dd : '%d dni', M : "miesiÄ…c", MM : translate, y : "rok", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : brazilian portuguese (pt-br) // author : Caio Ribeiro Pereira : https://github.com/caio-ribeiro-pereira (function (factory) { factory(moment); }(function (moment) { return moment.lang('pt-br', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje à s] LT', nextDay: '[Amanhã à s] LT', nextWeek: 'dddd [à s] LT', lastDay: '[Ontem à s] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [à s] LT' : // Saturday + Sunday '[Última] dddd [à s] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº' }); })); // moment.js language configuration // language : portuguese (pt) // author : Jefferson : https://github.com/jalex79 (function (factory) { factory(moment); }(function (moment) { return moment.lang('pt', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje à s] LT', nextDay: '[Amanhã à s] LT', nextWeek: 'dddd [à s] LT', lastDay: '[Ontem à s] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [à s] LT' : // Saturday + Sunday '[Última] dddd [à s] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : romanian (ro) // author : Vlad Gurdiga : https://github.com/gurdiga // author : Valentin Agachi : https://github.com/avaly (function (factory) { factory(moment); }(function (moment) { return moment.lang('ro', { months : "Ianuarie_Februarie_Martie_Aprilie_Mai_Iunie_Iulie_August_Septembrie_Octombrie_Noiembrie_Decembrie".split("_"), monthsShort : "Ian_Feb_Mar_Apr_Mai_Iun_Iul_Aug_Sep_Oct_Noi_Dec".split("_"), weekdays : "Duminică_Luni_MarÅ£i_Miercuri_Joi_Vineri_Sâmbătă".split("_"), weekdaysShort : "Dum_Lun_Mar_Mie_Joi_Vin_Sâm".split("_"), weekdaysMin : "Du_Lu_Ma_Mi_Jo_Vi_Sâ".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY H:mm", LLLL : "dddd, D MMMM YYYY H:mm" }, calendar : { sameDay: "[azi la] LT", nextDay: '[mâine la] LT', nextWeek: 'dddd [la] LT', lastDay: '[ieri la] LT', lastWeek: '[fosta] dddd [la] LT', sameElse: 'L' }, relativeTime : { future : "peste %s", past : "%s în urmă", s : "câteva secunde", m : "un minut", mm : "%d minute", h : "o oră", hh : "%d ore", d : "o zi", dd : "%d zile", M : "o lună", MM : "%d luni", y : "un an", yy : "%d ani" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : russian (ru) // author : Viktorminator : https://github.com/Viktorminator // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'минута_минуты_минут', 'hh': 'час_часа_часов', 'dd': 'день_дня_дней', 'MM': 'месяц_месяца_месяцев', 'yy': 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), 'accusative': 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = { 'nominative': 'янв_фев_мар_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), 'accusative': 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return monthsShort[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), 'accusative': 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_') }, nounCase = (/\[ ?[Вв] ?(?:прошлую|следующую)? ?\] ?dddd/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ru', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "вс_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "вс_пн_вт_ср_чт_пт_сб".split("_"), monthsParse : [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[й|я]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i], longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY г.", LLL : "D MMMM YYYY г., LT", LLLL : "dddd, D MMMM YYYY г., LT" }, calendar : { sameDay: '[Сегодня в] LT', nextDay: '[Завтра в] LT', lastDay: '[Вчера в] LT', nextWeek: function () { return this.day() === 2 ? '[Во] dddd [в] LT' : '[Ð’] dddd [в] LT'; }, lastWeek: function () { switch (this.day()) { case 0: return '[Ð’ прошлое] dddd [в] LT'; case 1: case 2: case 4: return '[Ð’ прошлый] dddd [в] LT'; case 3: case 5: case 6: return '[Ð’ прошлую] dddd [в] LT'; } }, sameElse: 'L' }, relativeTime : { future : "через %s", past : "%s назад", s : "несколько секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "час", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "месяц", MM : relativeTimeWithPlural, y : "год", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночи"; } else if (hour < 12) { return "утра"; } else if (hour < 17) { return "дня"; } else { return "вечера"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': return number + '-й'; case 'D': return number + '-го'; case 'w': case 'W': return number + '-я'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : slovak (sk) // author : Martin Minka : https://github.com/k2s // based on work of petrbela : https://github.com/petrbela (function (factory) { factory(moment); }(function (moment) { var months = "január_február_marec_apríl_máj_jún_júl_august_september_október_november_december".split("_"), monthsShort = "jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec".split("_"); function plural(n) { return (n > 1) && (n < 5); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minúty' : 'minút'); } else { return result + 'minútami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodín'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dni' : 'dní'); } else { return result + 'dňami'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'mesiace' : 'mesiacov'); } else { return result + 'mesiacmi'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'rokov'); } else { return result + 'rokmi'; } break; } } return moment.lang('sk', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "nedeľa_pondelok_utorok_streda_Å¡tvrtok_piatok_sobota".split("_"), weekdaysShort : "ne_po_ut_st_Å¡t_pi_so".split("_"), weekdaysMin : "ne_po_ut_st_Å¡t_pi_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes o] LT", nextDay: '[zajtra o] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v nedeľu o] LT'; case 1: case 2: return '[v] dddd [o] LT'; case 3: return '[v stredu o] LT'; case 4: return '[vo Å¡tvrtok o] LT'; case 5: return '[v piatok o] LT'; case 6: return '[v sobotu o] LT'; } }, lastDay: '[včera o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulú nedeľu o] LT'; case 1: case 2: return '[minulý] dddd [o] LT'; case 3: return '[minulú stredu o] LT'; case 4: case 5: return '[minulý] dddd [o] LT'; case 6: return '[minulú sobotu o] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "pred %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : slovenian (sl) // author : Robert SedovÅ¡ek : https://github.com/sedovsek (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'ena minuta' : 'eno minuto'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2) { result += 'minuti'; } else if (number === 3 || number === 4) { result += 'minute'; } else { result += 'minut'; } return result; case 'h': return withoutSuffix ? 'ena ura' : 'eno uro'; case 'hh': if (number === 1) { result += 'ura'; } else if (number === 2) { result += 'uri'; } else if (number === 3 || number === 4) { result += 'ure'; } else { result += 'ur'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dni'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2) { result += 'meseca'; } else if (number === 3 || number === 4) { result += 'mesece'; } else { result += 'mesecev'; } return result; case 'yy': if (number === 1) { result += 'leto'; } else if (number === 2) { result += 'leti'; } else if (number === 3 || number === 4) { result += 'leta'; } else { result += 'let'; } return result; } } return moment.lang('sl', { months : "januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota".split("_"), weekdaysShort : "ned._pon._tor._sre._čet._pet._sob.".split("_"), weekdaysMin : "ne_po_to_sr_če_pe_so".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danes ob] LT', nextDay : '[jutri ob] LT', nextWeek : function () { switch (this.day()) { case 0: return '[v] [nedeljo] [ob] LT'; case 3: return '[v] [sredo] [ob] LT'; case 6: return '[v] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[v] dddd [ob] LT'; } }, lastDay : '[včeraj ob] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[prejÅ¡nja] dddd [ob] LT'; case 1: case 2: case 4: case 5: return '[prejÅ¡nji] dddd [ob] LT'; } }, sameElse : 'L' }, relativeTime : { future : "čez %s", past : "%s nazaj", s : "nekaj sekund", m : translate, mm : translate, h : translate, hh : translate, d : "en dan", dd : translate, M : "en mesec", MM : translate, y : "eno leto", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Albanian (sq) // author : Flakërim Ismani : https://github.com/flakerimi // author: Menelion Elensúle: https://github.com/Oire (tests) (function (factory) { factory(moment); }(function (moment) { return moment.lang('sq', { months : "Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor".split("_"), monthsShort : "Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj".split("_"), weekdays : "E Diel_E Hënë_E Marte_E Mërkure_E Enjte_E Premte_E Shtunë".split("_"), weekdaysShort : "Die_Hën_Mar_Mër_Enj_Pre_Sht".split("_"), weekdaysMin : "D_H_Ma_Më_E_P_Sh".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Sot në] LT', nextDay : '[Neser në] LT', nextWeek : 'dddd [në] LT', lastDay : '[Dje në] LT', lastWeek : 'dddd [e kaluar në] LT', sameElse : 'L' }, relativeTime : { future : "në %s", past : "%s me parë", s : "disa seconda", m : "një minut", mm : "%d minutea", h : "një orë", hh : "%d orë", d : "një ditë", dd : "%d ditë", M : "një muaj", MM : "%d muaj", y : "një vit", yy : "%d vite" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : swedish (sv) // author : Jens Alm : https://github.com/ulmus (function (factory) { factory(moment); }(function (moment) { return moment.lang('sv', { months : "januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "söndag_mÃ¥ndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"), weekdaysShort : "sön_mÃ¥n_tis_ons_tor_fre_lör".split("_"), weekdaysMin : "sö_mÃ¥_ti_on_to_fr_lö".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[Idag] LT', nextDay: '[Imorgon] LT', lastDay: '[IgÃ¥r] LT', nextWeek: 'dddd LT', lastWeek: '[Förra] dddd[en] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "för %s sedan", s : "nÃ¥gra sekunder", m : "en minut", mm : "%d minuter", h : "en timme", hh : "%d timmar", d : "en dag", dd : "%d dagar", M : "en mÃ¥nad", MM : "%d mÃ¥nader", y : "ett Ã¥r", yy : "%d Ã¥r" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'e' : (b === 1) ? 'a' : (b === 2) ? 'a' : (b === 3) ? 'e' : 'e'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : thai (th) // author : Kridsada Thanabulpong : https://github.com/sirn (function (factory) { factory(moment); }(function (moment) { return moment.lang('th', { months : "มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม".split("_"), monthsShort : "มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา".split("_"), weekdays : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์".split("_"), weekdaysShort : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์".split("_"), // yes, three characters difference weekdaysMin : "อา._จ._อ._พ._พฤ._ศ._ส.".split("_"), longDateFormat : { LT : "H นาฬิกา m นาที", L : "YYYY/MM/DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY เวลา LT", LLLL : "วันddddที่ D MMMM YYYY เวลา LT" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "ก่อนเที่ยง"; } else { return "หลังเที่ยง"; } }, calendar : { sameDay : '[วันนี้ เวลา] LT', nextDay : '[พรุ่งนี้ เวลา] LT', nextWeek : 'dddd[หน้า เวลา] LT', lastDay : '[เมื่อวานนี้ เวลา] LT', lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT', sameElse : 'L' }, relativeTime : { future : "อีก %s", past : "%sที่แล้ว", s : "ไม่กี่วินาที", m : "1 นาที", mm : "%d นาที", h : "1 ชั่วโมง", hh : "%d ชั่วโมง", d : "1 วัน", dd : "%d วัน", M : "1 เดือน", MM : "%d เดือน", y : "1 ปี", yy : "%d ปี" } }); })); // moment.js language configuration // language : Tagalog/Filipino (tl-ph) // author : Dan Hagman (function (factory) { factory(moment); }(function (moment) { return moment.lang('tl-ph', { months : "Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"), monthsShort : "Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"), weekdays : "Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"), weekdaysShort : "Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"), weekdaysMin : "Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"), longDateFormat : { LT : "HH:mm", L : "MM/D/YYYY", LL : "MMMM D, YYYY", LLL : "MMMM D, YYYY LT", LLLL : "dddd, MMMM DD, YYYY LT" }, calendar : { sameDay: "[Ngayon sa] LT", nextDay: '[Bukas sa] LT', nextWeek: 'dddd [sa] LT', lastDay: '[Kahapon sa] LT', lastWeek: 'dddd [huling linggo] LT', sameElse: 'L' }, relativeTime : { future : "sa loob ng %s", past : "%s ang nakalipas", s : "ilang segundo", m : "isang minuto", mm : "%d minuto", h : "isang oras", hh : "%d oras", d : "isang araw", dd : "%d araw", M : "isang buwan", MM : "%d buwan", y : "isang taon", yy : "%d taon" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : turkish (tr) // authors : Erhan Gundogan : https://github.com/erhangundogan, // Burak YiÄŸit Kaya: https://github.com/BYK (function (factory) { factory(moment); }(function (moment) { var suffixes = { 1: "'inci", 5: "'inci", 8: "'inci", 70: "'inci", 80: "'inci", 2: "'nci", 7: "'nci", 20: "'nci", 50: "'nci", 3: "'üncü", 4: "'üncü", 100: "'üncü", 6: "'ncı", 9: "'uncu", 10: "'uncu", 30: "'uncu", 60: "'ıncı", 90: "'ıncı" }; return moment.lang('tr', { months : "Ocak_Åžubat_Mart_Nisan_Mayıs_Haziran_Temmuz_AÄŸustos_Eylül_Ekim_Kasım_Aralık".split("_"), monthsShort : "Oca_Åžub_Mar_Nis_May_Haz_Tem_AÄŸu_Eyl_Eki_Kas_Ara".split("_"), weekdays : "Pazar_Pazartesi_Salı_ÇarÅŸamba_PerÅŸembe_Cuma_Cumartesi".split("_"), weekdaysShort : "Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"), weekdaysMin : "Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[bugün saat] LT', nextDay : '[yarın saat] LT', nextWeek : '[haftaya] dddd [saat] LT', lastDay : '[dün] LT', lastWeek : '[geçen hafta] dddd [saat] LT', sameElse : 'L' }, relativeTime : { future : "%s sonra", past : "%s önce", s : "birkaç saniye", m : "bir dakika", mm : "%d dakika", h : "bir saat", hh : "%d saat", d : "bir gün", dd : "%d gün", M : "bir ay", MM : "%d ay", y : "bir yıl", yy : "%d yıl" }, ordinal : function (number) { if (number === 0) { // special case for zero return number + "'ıncı"; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (suffixes[a] || suffixes[b] || suffixes[c]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas TamaziÉ£t in Latin (tzm-la) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('tzm-la', { months : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_É£wÅ¡t_Å¡wtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), monthsShort : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_É£wÅ¡t_Å¡wtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), weekdays : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysShort : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysMin : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[asdkh g] LT", nextDay: '[aska g] LT', nextWeek: 'dddd [g] LT', lastDay: '[assant g] LT', lastWeek: 'dddd [g] LT', sameElse: 'L' }, relativeTime : { future : "dadkh s yan %s", past : "yan %s", s : "imik", m : "minuḍ", mm : "%d minuḍ", h : "saÉ›a", hh : "%d tassaÉ›in", d : "ass", dd : "%d ossan", M : "ayowr", MM : "%d iyyirn", y : "asgas", yy : "%d isgasn" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas TamaziÉ£t (tzm) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('tzm', { months : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), monthsShort : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), weekdays : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysShort : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysMin : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[ⴰⵙⴷⵅ â´´] LT", nextDay: '[ⴰⵙⴽⴰ â´´] LT', nextWeek: 'dddd [â´´] LT', lastDay: '[ⴰⵚⴰⵏⵜ â´´] LT', lastWeek: 'dddd [â´´] LT', sameElse: 'L' }, relativeTime : { future : "â´·â´°â´·âµ… âµ™ ⵢⴰⵏ %s", past : "ⵢⴰⵏ %s", s : "ⵉⵎⵉⴽ", m : "ⵎⵉⵏⵓⴺ", mm : "%d ⵎⵉⵏⵓⴺ", h : "ⵙⴰⵄⴰ", hh : "%d ⵜⴰⵙⵙⴰⵄⵉⵏ", d : "ⴰⵙⵙ", dd : "%d oⵙⵙⴰⵏ", M : "â´°âµ¢oⵓⵔ", MM : "%d ⵉⵢⵢⵉⵔⵏ", y : "ⴰⵙⴳⴰⵙ", yy : "%d ⵉⵙⴳⴰⵙⵏ" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : ukrainian (uk) // author : zemlanin : https://github.com/zemlanin // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'хвилина_хвилини_хвилин', 'hh': 'година_години_годин', 'dd': 'день_дні_днів', 'MM': 'місяць_місяці_місяців', 'yy': 'рік_роки_років' }; if (key === 'm') { return withoutSuffix ? 'хвилина' : 'хвилину'; } else if (key === 'h') { return withoutSuffix ? 'година' : 'годину'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_'), 'accusative': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_') }, nounCase = (/D[oD]? *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') }, nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? 'accusative' : ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? 'genitive' : 'nominative'); return weekdays[nounCase][m.day()]; } function processHoursFunction(str) { return function () { return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; }; } return moment.lang('uk', { months : monthsCaseReplace, monthsShort : "січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "нд_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY Ñ€.", LLL : "D MMMM YYYY Ñ€., LT", LLLL : "dddd, D MMMM YYYY Ñ€., LT" }, calendar : { sameDay: processHoursFunction('[Сьогодні '), nextDay: processHoursFunction('[Завтра '), lastDay: processHoursFunction('[Вчора '), nextWeek: processHoursFunction('[У] dddd ['), lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return processHoursFunction('[Минулої] dddd [').call(this); case 1: case 2: case 4: return processHoursFunction('[Минулого] dddd [').call(this); } }, sameElse: 'L' }, relativeTime : { future : "за %s", past : "%s тому", s : "декілька секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "годину", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "місяць", MM : relativeTimeWithPlural, y : "рік", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночі"; } else if (hour < 12) { return "ранку"; } else if (hour < 17) { return "дня"; } else { return "вечора"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return number + '-й'; case 'D': return number + '-го'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : uzbek // author : Sardor Muminov : https://github.com/muminoff (function (factory) { factory(moment); }(function (moment) { return moment.lang('uz', { months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"), monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"), weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"), weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"), weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "D MMMM YYYY, dddd LT" }, calendar : { sameDay : '[Бугун соат] LT [да]', nextDay : '[Эртага] LT [да]', nextWeek : 'dddd [куни соат] LT [да]', lastDay : '[Кеча соат] LT [да]', lastWeek : '[Утган] dddd [куни соат] LT [да]', sameElse : 'L' }, relativeTime : { future : "Якин %s ичида", past : "Бир неча %s олдин", s : "фурсат", m : "бир дакика", mm : "%d дакика", h : "бир соат", hh : "%d соат", d : "бир кун", dd : "%d кун", M : "бир ой", MM : "%d ой", y : "бир йил", yy : "%d йил" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : vietnamese (vn) // author : Bang Nguyen : https://github.com/bangnk (function (factory) { factory(moment); }(function (moment) { return moment.lang('vn', { months : "tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12".split("_"), monthsShort : "Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12".split("_"), weekdays : "chá»§ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy".split("_"), weekdaysShort : "CN_T2_T3_T4_T5_T6_T7".split("_"), weekdaysMin : "CN_T2_T3_T4_T5_T6_T7".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM [năm] YYYY", LLL : "D MMMM [năm] YYYY LT", LLLL : "dddd, D MMMM [năm] YYYY LT", l : "DD/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay: "[Hôm nay lúc] LT", nextDay: '[Ngà y mai lúc] LT', nextWeek: 'dddd [tuần tá»›i lúc] LT', lastDay: '[Hôm qua lúc] LT', lastWeek: 'dddd [tuần rồi lúc] LT', sameElse: 'L' }, relativeTime : { future : "%s tá»›i", past : "%s trước", s : "và i giây", m : "má»™t phút", mm : "%d phút", h : "má»™t giờ", hh : "%d giờ", d : "má»™t ngà y", dd : "%d ngà y", M : "má»™t tháng", MM : "%d tháng", y : "má»™t năm", yy : "%d năm" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chinese // author : suupic : https://github.com/suupic // author : Zeno Zeng : https://github.com/zenozeng (function (factory) { factory(moment); }(function (moment) { return moment.lang('zh-cn', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysMin : "æ—¥_一_二_三_å››_五_å…­".split("_"), longDateFormat : { LT : "Ah点mm", L : "YYYYå¹´MMMDæ—¥", LL : "YYYYå¹´MMMDæ—¥", LLL : "YYYYå¹´MMMDæ—¥LT", LLLL : "YYYYå¹´MMMDæ—¥ddddLT", l : "YYYYå¹´MMMDæ—¥", ll : "YYYYå¹´MMMDæ—¥", lll : "YYYYå¹´MMMDæ—¥LT", llll : "YYYYå¹´MMMDæ—¥ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return "凌晨"; } else if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : function () { return this.minutes() === 0 ? "[今天]Ah[点整]" : "[今天]LT"; }, nextDay : function () { return this.minutes() === 0 ? "[明天]Ah[点整]" : "[明天]LT"; }, lastDay : function () { return this.minutes() === 0 ? "[昨天]Ah[点整]" : "[昨天]LT"; }, nextWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, lastWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, sameElse : 'L' }, ordinal : function (number, period) { switch (period) { case "d": case "D": case "DDD": return number + "æ—¥"; case "M": return number + "月"; case "w": case "W": return number + "周"; default: return number; } }, relativeTime : { future : "%s内", past : "%s前", s : "å‡ ç§’", m : "1分钟", mm : "%d分钟", h : "1小时", hh : "%d小时", d : "1天", dd : "%d天", M : "1个月", MM : "%d个月", y : "1å¹´", yy : "%då¹´" }, week : { // GB/T 7408-1994ã€Šæ•°æ®å…ƒå’Œäº¤æ¢æ ¼å¼Â·ä¿¡æ¯äº¤æ¢Â·æ—¥æœŸå’Œæ—¶é—´è¡¨ç¤ºæ³•ã€‹ä¸ŽISO 8601:1988等效 dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : traditional chinese (zh-tw) // author : Ben : https://github.com/ben-lin (function (factory) { factory(moment); }(function (moment) { return moment.lang('zh-tw', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "週日_週一_週二_週三_週四_週五_週六".split("_"), weekdaysMin : "æ—¥_一_二_三_å››_五_å…­".split("_"), longDateFormat : { LT : "Ah點mm", L : "YYYYå¹´MMMDæ—¥", LL : "YYYYå¹´MMMDæ—¥", LLL : "YYYYå¹´MMMDæ—¥LT", LLLL : "YYYYå¹´MMMDæ—¥ddddLT", l : "YYYYå¹´MMMDæ—¥", ll : "YYYYå¹´MMMDæ—¥", lll : "YYYYå¹´MMMDæ—¥LT", llll : "YYYYå¹´MMMDæ—¥ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, ordinal : function (number, period) { switch (period) { case "d" : case "D" : case "DDD" : return number + "æ—¥"; case "M" : return number + "月"; case "w" : case "W" : return number + "週"; default : return number; } }, relativeTime : { future : "%så…§", past : "%s前", s : "幾秒", m : "一分鐘", mm : "%d分鐘", h : "一小時", hh : "%d小時", d : "一天", dd : "%d天", M : "一個月", MM : "%d個月", y : "一年", yy : "%då¹´" } }); })); moment.lang('es'); /************************************ Exposing Moment ************************************/ function makeGlobal(deprecate) { var warned = false, local_moment = moment; /*global ender:false */ if (typeof ender !== 'undefined') { return; } // 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 if (deprecate) { this.moment = function () { if (!warned && console && console.warn) { warned = true; console.warn( "Accessing Moment through the global scope is " + "deprecated, and will be removed in an upcoming " + "release."); } return local_moment.apply(null, arguments); }; } else { this['moment'] = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; makeGlobal(true); } else if (typeof define === "function" && define.amd) { define("moment", function (require, exports, module) { if (module.config().noGlobal !== true) { // If user provided noGlobal, he is aware of global makeGlobal(module.config().noGlobal === undefined); } return moment; }); } else { makeGlobal(); } }).call(this);
var passport = require('passport'); // route middleware to ensure user is logged in module.exports = function (req, res, next) { //console.log('authMidware has been called..........-->'); if (req.isAuthenticated()) return next(); res.redirect('/login'); }
/** * @file Database * @author Jim Bulkowski <jim.b@paperelectron.com> * @project magnum-di * @license MIT {@link http://opensource.org/licenses/MIT} */ /** * Fake database for Magnum-di examples * @module Database */ module.exports = { User: { users: {Bob: {name: 'Bob', age: 27}, Tom: {name: 'Tom', age: 38}}, find: function(username, cb){ var user = (this.users[username]) ? this.users[username] : null cb(null, user); } } }
import React, { useContext } from 'react'; import PropTypes from 'prop-types'; import { ThemeContext } from '../ThemeContext/ThemeContext'; import SectionMaxWidth from '../SectionMaxWidth/SectionMaxWidth'; import { Styled } from './DetailCallout.styles'; const DetailCallout = ({ children, header }) => { const { colorMode } = useContext(ThemeContext); return ( <Styled.DetailCallout colorMode={colorMode}> <SectionMaxWidth> <Styled.DetailCalloutHeader>{header}</Styled.DetailCalloutHeader> <Styled.DetailCalloutOverview>{children}</Styled.DetailCalloutOverview> </SectionMaxWidth> </Styled.DetailCallout> ); }; DetailCallout.propTypes = { header: PropTypes.oneOfType([PropTypes.node, PropTypes.string]).isRequired, children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node, PropTypes.string]).isRequired, }; export default DetailCallout;
'use strict'; angular.module('angularMaterialAdmin', ['app']) //remove setellizer .config(function(AnalyticsProvider, $stateProvider, $urlRouterProvider, $mdThemingProvider, $authProvider, $locationProvider, $mdIconProvider, socialProvider, $httpProvider, $mdDateLocaleProvider, $mdAriaProvider, $compileProvider) { //UU-XXXXXXX-X should be your tracking code AnalyticsProvider.setAccount('UA-57016004-2'); $mdDateLocaleProvider.formatDate = function(date) { return moment(date).format('DD-MMM-YY'); }; $mdAriaProvider.disableWarnings(); /* Uncomment before buidling for pushing to server */ // $compileProvider.debugInfoEnabled(false); $compileProvider.commentDirectivesEnabled(false); $compileProvider.cssClassDirectivesEnabled(false); // $locationProvider.html5Mode(true); $authProvider.httpInterceptor = false; // Optional: For client-side use (Implicit Grant), set responseType to 'token' (default: 'code') $authProvider.facebook({ clientId: '1250377088376164', url: "http://localhost/app/public/facebook", responseType: 'token', authorizationEndpoint: 'https://www.facebook.com/v2.8/dialog/oauth', scope: ['user_about_me', 'read_custom_friendlists', 'user_friends', 'email', 'user_hometown', 'user_likes'] }); $authProvider.google({ url: "http://localhost/app/public/login", clientId: '702228530885-vi264d7g6v5ivbcmebjfpomr0hmliomd.apps.googleusercontent.com', authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth' }); // $authProvider.linkedin({ // clientId: '81l3qatlqe4l4p', // }); $urlRouterProvider.otherwise('/creativity'); socialProvider.setGoogleKey("702228530885-vi264d7g6v5ivbcmebjfpomr0hmliomd.apps.googleusercontent.com"); // socialProvider.setLinkedInKey("81l3qatlqe4l4p"); socialProvider.setFbKey({ appId: "1250377088376164", apiVersion: "v2.8", responseType: 'token' }); $mdIconProvider .defaultIconSet('assets/svg/mdi.svg'); $mdThemingProvider .theme('default') .primaryPalette('pink', { 'default': '600' }) .accentPalette('pink', { 'default': '500' }) .warnPalette('red'); $mdThemingProvider.theme('dark', 'default') .primaryPalette('pink') .dark('pink'); $mdThemingProvider.theme('pink', 'default') .primaryPalette('pink'); }) .run(function($state, $location, $rootScope, $mdDialog, tokenService, Analytics) { // authManager.checkAuthOnRefresh(); // authManager.redirectWhenUnauthenticated(); console.log('abc'); $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options) { $rootScope.currentState = toState.name; }); localStorage.setItem('evervisited', true); $rootScope.user = {}; // REQUIRED FOR CORDOVA // // angular.element(document).ready(function() { // console.log("Testing if cordova is passed"); // if (window.cordova) { // console.log("Cordova passed!") // document.addEventListener('deviceready', function() { // console.log("Deviceready event has fired, bootstrapping AngularJS."); // // Link the callback function to universalLinks // universalLinks.subscribe(null, function(eventData) { // // do some work // console.log('Did launch application from the link: ' + eventData.url); // var url = eventData.url; // var n = url.indexOf('campusbox.org/dist'); // var result = url.substring(n + 19); // // eventData.url = null; // console.log(result); // $location.url(result); // }); // }, false); // } // }); // // END $rootScope.currentState = $state.current.name; $rootScope.$on('$stateChangeSuccess', function() { $rootScope.currentState = $state.current.name; //If you don't wanna create the service, you can directly write // your function here. // someService.doSomething(); }); $rootScope.openLoginDialog = function(callback) { $mdDialog.show({ controller: 'loginDialogController', templateUrl: 'app/dialogs/auth/loginDialog.html', parent: angular.element(document.body), escapeToClose: true, fullscreen: true, clickOutsideToClose: true, controllerAs: 'dc' }).then(function() { callback(); }, function() { // console.log('else of dialog'); }); }; $rootScope.token = localStorage.getItem('id_token'); if ('serviceWorker' in navigator) { navigator.serviceWorker.register('service-worker.js').then(function() { //Registration was successful }) .catch(function() { //registration failed :( }); } if (localStorage.getItem('id_token') !== null) { $rootScope.authenticated = true; $rootScope.token = localStorage.getItem('id_token'); tokenService.get("userImage") .then(function(response) { $rootScope.user = response; tokenService.get("notifications") .then(function(abc) { $rootScope.notifications = abc; }); }); } else { $rootScope.authenticated = false; } // if (!authManager.isAuthenticated()) { // console.log("sending to login") // $state.go('static.login'); //} });
'use strict'; Template.pickUsername.events({ 'submit form': function (ev) { ev.preventDefault(); var $form = $(ev.target), username = $form.serializeArray()[0].value; if ($form.data('bootstrapValidator').isValid()) { Meteor.call('setUsername', username, function (err) { if (err) { console.error(err); } Router.go('/'); }); } } }); Template.pickUsername.rendered = function () { $('.username-form').bootstrapValidator({ trigger: null, submitButtons: null, fields: { username: { message: 'Bitte gib deine Benutzername an', validators: { notEmpty: { message: 'Bitte gib deine Benutzername an' } } } } } ).on('success.form.bv', function (ev) { ev.preventDefault(); }); };
module.exports = require('./dist/collection.min.js');
var Parser = require("jade/lib/parser.js"); var jade = require("jade/lib/runtime.js"); var esprima = require("esprima"); var _ = require("lodash"); module.exports = function(string, thisVar) { var jadeString = flattenLeftWhitespace(string); var parser = new Parser(jadeString, null, {}); var jadeTree = parser.parse(); if (jadeTree.nodes.length != 1) { throw new Error( "Jade React Transforms must have exactly 1 root node :: \n" + jadeString ); } var jsTree = convertJadeTreeWithThis(jadeTree, thisVar); return jsTree; }; var flattenLeftWhitespace = function(string) { var lines = string.split("\n").filter(function(line) { return line.trim().length != 0; }); var minIndentation = lines.reduce(function(smallest, line) { if (line.trim().length == 0) return smallest; var match = line.match(/^(\s+)/); var indent = match ? match[0].length : 0; return Math.min(smallest, indent); }, 9000); return lines.map(function(line) { return line.slice(minIndentation); }).join("\n"); } var convertJadeTreeWithThis = function(jadeTree, thisVar) { // nesting function declarations to ensure thisVar available to whole // computation without excessive passing around in arguments return convertJadeTree(jadeTree); function convertJadeTree(jadeNode, ix, siblings, nested) { if (jadeNode.nodes) { return convertJadeTree(jadeNode.nodes[0]); } else if (jadeNode.buffer) { // is a variable return { "type": "Identifier", "name": jadeNode.val }; } else if (jadeNode.expr) { var cases = jadeNode.block.nodes.map(function(caseNode) { var sExpr = caseNode.expr == "default" ? null : esprima.parse(caseNode.expr).body[0].expression; return { "type": "SwitchCase", "test": sExpr, "consequent": [{ "type": "ReturnStatement", "argument": convertJadeTree(caseNode.block.nodes[0]), }] } }); var testExpr = esprima.parse(jadeNode.expr).body[0].expression; var switchFunction = { "type": "FunctionExpression", "id": null, "params": [], "defaults": [], "generator": false, "expression": false, "body": { "type": "BlockStatement", "body": [{ "type": "SwitchStatement", "discriminant": testExpr, "cases": cases }] } }; return { "type": "CallExpression", "callee": { "type": "CallExpression", "callee": { "type": "MemberExpression", "computed": false, "object": switchFunction, "property": { "type": "Identifier", "name": "bind", } }, "arguments": [thisVar] }, "arguments": [] }; } else if (jadeNode.obj) { // is an each statement if (jadeNode.block.nodes.length > 1) { console.warn( "React only supports singular DOM Nodes, only the first node will " + "render for: " ); console.warn(jadeNode); } var jsNode = { "type": "CallExpression", "callee": { "type": "MemberExpression", "computed": false, "object": { "type": "Identifier", "name": jadeNode.obj }, "property": { "type": "Identifier", "name": "map" }, }, "arguments": [{ "type": "FunctionExpression", "id": null, "params": [{ "type": "Identifier", "name": jadeNode.val }, { "type": "Identifier", "name": jadeNode.key }], "defaults": [], "generator": false, "expression": false, "body": { "type": "BlockStatement", "body": [{ "type": "ReturnStatement", "argument": convertJadeTree(jadeNode.block.nodes[0]) }] } }, thisVar] }; return jsNode; } else if (jadeNode.val && ( jadeNode.val.slice(0,4) == "if (" || (jadeNode.val.slice(0,9) == "else if (" && nested) || jadeNode.val.slice(0,8) == "unless (" || (jadeNode.val.slice(0,13) == "else unless (" && nested) )) { // is an if or unless statement // jade does not appear to support 'else unless', but if it ever does // we are prepared for it. var stringExpr; if (jadeNode.val.slice(0,4) == "if (") { stringExpr = jadeNode.val.slice(4,-1); } else if (jadeNode.val.slice(0,8) == "unless (") { stringExpr = "!" + jadeNode.val.slice(8,-1); } else if (jadeNode.val.slice(0,9) == "else if (") { stringExpr = jadeNode.val.slice(9,-1); } else if (jadeNode.val.slice(0,13) == "else unless (") { stringExpr = "!" + jadeNode.val.slice(13,-1); } var testExpr = esprima.parse(stringExpr).body[0].expression; var next = siblings[ix + 1]; if ( (next && next.val && next.val.slice(0, 9) == "else if (") || (next && next.val && next.val.slice(0, 13) == "else unless (") ) { var alternate = convertJadeTree(next, ix + 1, siblings, true); } else { var alternate = (next && next.val == "else") ? convertJadeTree(next.block.nodes[0]) : {"type": "Identifier", "name": "null"}; } return { "type": "ConditionalExpression", "test": testExpr, "consequent": convertJadeTree(jadeNode.block.nodes[0]), "alternate": alternate } } else if (jadeNode.val && jadeNode.val.slice(0,4) == "else" ) { return null; } else if (jadeNode.val) { // is a standard string return { "type": "Literal", "value": jadeNode.val }; } else if (jadeNode.call) { // is a mixin var jsNode = { "type": "CallExpression", "callee": { "type": "MemberExpression", "computed": false, "object": { "type": "Identifier", "name": "React", }, "property": { "type": "Identifier", "name": "createElement" }, }, "arguments": [] }; if (jadeNode.args) { var props = esprima.parse(jadeNode.args).body[0].expression; } else { var props = buildPropsFromAttrs(jadeNode.attrs); } if (jadeNode.attributeBlocks && jadeNode.attributeBlocks.length > 0) { props = parseAndAttributes(jadeNode.attributeBlocks, props); } var children = jadeNode.block ? _.compact(jadeNode.block.nodes.map(convertJadeTree)) : []; if (jadeNode.code) { children.unshift(convertJadeTree(jadeNode.code)); } jsNode.arguments = [{ "type": "Identifier", "name": jadeNode.name }, props].concat(children); return jsNode; } else { // is a standard dom node var unescapedContent = false; var jsNode = { "type": "CallExpression", "callee": { "type": "MemberExpression", "computed": false, "object": { "type": "Identifier", "name": "DOM", }, "property": { "type": "Identifier", "name": jadeNode.name, }, }, "arguments": [] }; var props = { "type": "ObjectExpression", "properties": [] }; var props = buildPropsFromAttrs(jadeNode.attrs); if (jadeNode.code && jadeNode.code.buffer && !jadeNode.code.escape) { unescapedContent = true; var children = []; props.properties.push(addUnescapedHTML(jadeNode.code)); } else if ( jadeNode.block.nodes && jadeNode.block.nodes[0] && !jadeNode.block.nodes[0].escape && jadeNode.block.nodes[0].buffer ) { unescapedContent = true; var children = []; props.properties.push(addUnescapedHTML(jadeNode.block.nodes[0])); } else { var children = jadeNode.block ? _.compact(jadeNode.block.nodes.map(convertJadeTree)) : []; if (jadeNode.code) { children.unshift(convertJadeTree(jadeNode.code)); } } if (jadeNode.attributeBlocks && jadeNode.attributeBlocks.length > 0) { props = parseAndAttributes(jadeNode.attributeBlocks, props); } jsNode.arguments = [props].concat(children); return jsNode; } }; function isLiteral(str) { return ( (str[0] == '"' && str[str.length-1] == '"' && str.split('"').length == 3) || (str[0] == "'" && str[str.length-1] == "'" && str.split("'").length == 3) ) }; function parseAndAttributes(andAttr, props) { var props = props || { "type": "ObjectExpression", "properties": [] }; var attrBlocks = andAttr.map(function(block) { return parseAttributeCode(block); }); var isBlankProp = ( props.type == "ObjectExpression" && props.properties.length == 0 ); if (isBlankProp && attrBlocks.length == 1) { return attrBlocks[0]; } var attrProps = { "type": "CallExpression", "callee": { "type": "MemberExpression", "computed": false, "object": { "type": "Identifier", "name": "Object", }, "property": { "type": "Identifier", "name": "assign", }, }, "arguments": [props].concat(attrBlocks) } return attrProps; } function buildPropsFromAttrs(attrs) { var props = { "type": "ObjectExpression", "properties": [] }; var classes = []; var calcClasses = []; attrs.forEach(function(attr) { var literal = isLiteral(attr.val); var val = literal ? eval(attr.val) : attr.val; var safeName = attr.name; if (safeName == "class") safeName = "className"; if (safeName == "for") safeName = "htmlFor"; if (literal && attr.name == "class") { classes.push(val); } else if (!literal && attr.name == "class") { calcClasses.push(val); } else if (literal) { props.properties.push({ "type": "Property", "key": { "type": "Literal", "value": safeName, }, "computed": false, "value": { "type": "Literal", "value": val }, "kind": "init", "method": false, "shorthand": false }); } else { props.properties.push({ "type": "Property", "key": { "type": "Literal", "value": safeName, }, "computed": false, "value": parseAttributeCode(val), "kind": "init", "method": false, "shorthand": false }); } }); if (classes.length > 0 || calcClasses.length > 0) { var classValue, calcClassValue, finalClassValue; if (classes.length > 0) { classValue = { "type": "Literal", "value": classes.join(" ") + " " } } if (calcClasses.length > 0) { calcClassValue = calcClasses.reduceRight(function(accExpr, calcExpr) { if (!accExpr) { return parseAttributeCode(calcExpr) } else { return { "type": "BinaryExpression", "operator": "+", "left": parseAttributeCode(calcExpr), "right": accExpr }; } }, null); } if (classValue && calcClassValue) { finalClassValue = { "type": "BinaryExpression", "operator": "+", "left": classValue, "right": calcClassValue }; } else { finalClassValue = classValue || calcClassValue; } props.properties.push({ "type": "Property", "key": { "type": "Identifier", "name": "className", }, "computed": false, "value": finalClassValue, "method": false, "shorthand": false }); } return props; } function addUnescapedHTML(node) { return { "type": "Property", "key": { "type": "Identifier", "name": "dangerouslySetInnerHTML", }, "computed": false, "value": { "type": "ObjectExpression", "properties": [{ "type": "Property", "key": { "type": "Identifier", "name": "__html", }, "computed": false, "value": parseAttributeCode(node.val), "kind": "init", "method": false, "shorthand": false, }] }, "kind": "init", "method": false, "shorthand": false } }; function parseAttributeCode(attrCode) { if (attrCode[0] == "{" && attrCode[attrCode.length - 1] == "}") { // wrap object literal blocks to ensure esprima parses correctly as // as an expression rather than a block attrCode = "(" + attrCode + ")"; } var element = esprima.parse(attrCode).body[0]; switch (element.type) { case "ExpressionStatement": return replaceThisVar(element.expression); case "BlockStatement": return replaceThisVar(element.body[0]); } } function replaceThisVar(node) { if (!node) return node; switch (node.type) { case "ExpressionStatement": node.expression = replaceThisVar(node.expression); break; case "CallExpression": node.callee = replaceThisVar(node.callee); node.arguments = node.arguments.map(replaceThisVar); break; case "ObjectExpression": node.properties = node.properties.map(replaceThisVar); break; case "Property": node.value = replaceThisVar(node.value); break; case "MemberExpression": node.object = replaceThisVar(node.object); break; case "ArrayExpression": node.elements = node.elements.map(replaceThisVar); break; case "ConditionalExpression": node.test = replaceThisVar(node.test); node.consequent = replaceThisVar(node.consequent); node.alternate = replaceThisVar(node.alternate); break; case "ThrowStatement": case "UpdateExpression": case "UnaryExpression": node.argument = replaceThisVar(node.argument); break; case "LogicalExpression": case "BinaryExpression": case "AssignmentExpression": node.left = replaceThisVar(node.left); node.right = replaceThisVar(node.right); break; case "ThisExpression": return thisVar; } return node; } };
Date; //doc: Creates JavaScript Date instances which let you work with dates and times. new Date; //doc: Creates JavaScript Date instances which let you work with dates and times. var myalias = Date; myalias; //doc: Creates JavaScript Date instances which let you work with dates and times. // This is variable foo. var foo = 10; foo; //doc: This is variable foo. // This function returns a monkey. function makeMonkey() { return "monkey"; } makeMonkey; //doc: This function returns a monkey. var monkeyAlias = makeMonkey; monkeyAlias; //doc: This function returns a monkey. // This is an irrelevant comment. // This describes abc. var abc = 20; abc; //doc: This describes abc. // Quux is a thing. And here are a bunch more sentences that would // make the docstring too long, and are thus wisely stripped by Tern's // brain-dead heuristics. Ayay. function Quux() {} Quux; //doc: Quux is a thing. /* Extra bogus * whitespace is also stripped. */ var baz = "hi"; baz; //doc: Extra bogus whitespace is also stripped. var o = { // Get the name. getName: function() { return this.name; }, // The name name: "Harold" }; o.getName; //doc: Get the name. o.name; //doc: The name
const express = require('express'); const router = express.Router(); router.get('/login', (req, res) => { res.render('index'); }); module.exports = router;
// giveaway $(document).on('ready pjax:end', function () { if ($('#gw_app').length > 0) { window.giveaway_app = new Vue({ el: '#gw_app', data: { history: { history: [], historyOwn: [] }, config: config, user: user, joined: {}, need_refill: config.min_enter }, created: function () { this.refrash_gw(); }, methods: { refrash_gw: function () { var self = this; // get active gw $.getJSON('/' + config.lang + '/giveaway/active_giveaways', function (data) { self.joined = data.joined; $.each(data.giveaways, function (index, item) { $("#timer" + item.id).countdown(item.finish, function (event) { var format = '%H:%M:%S'; if (item.type == "hour") { format = '%M min %S sec'; } if (item.type == "day") { format = '%H hr %M min'; } if (item.type == "week") { format = '%M min %S sec'; if (event.offset.totalHours > 0) { format = '%H hr %M min'; } if (event.offset.totalDays > 0) { format = '%-d day%!d'; } } if (event.type == 'finish') { setTimeout(function () { reload_page(); self.refrash_gw(); }, 5000) } $(this).text( event.strftime(format) ); }); }); }); }, sell: function (item_id) { var self = this; $.ajax({ url: '/' + self.config.lang + '/giveaway/sell', type: "POST", dataType: "json", data: { id: item_id }, success: function (data) { if (data.status == 'success') { if (data.status == 'success') { updateBalance(data.balance); ShowMsg(localization.success, localization.is_sold, 'success', 10000); // self.open_history(); for (var i in self.history.historyOwn) { var curr = self.history.historyOwn[i]; if (curr.id == item_id) { curr.steam_trade_offer_state = 15; curr.state = localization.item_state_15; break; } } } else { ShowMsg(localization.error, localization.sell_error, 'fail', 3000); } } else { ShowMsg(localization.error, localization.sell_error, 'fail', 3000); // data.msgwork } }, error: function () { ShowMsg(localization.error, localization.unknown_error, 'fail', 3000); } }); }, send: function ($item) { var self = this; $item.steam_trade_offer_state = 1; $item.state = localization.sending; $.ajax({ url: '/' + self.config.lang + '/giveaway/send', dataType: "json", type: "POST", data: { id: $item.id }, }).success(function (data) { if (data.status == 'success') { ShowMsg(localization.success, localization.take_item, 'success', 10000); $item.steam_trade_offer_state = 2; $item.state = localization.item_state_2; $item.tradeofferlink = 'https://steamcommunity.com/tradeoffer/' + data.tradeofferid; } else { if (data.type == 'steam' && typeof (data.error_message) == 'string') { if (data.error_message.search('(15)') > 0) { ShowMsg(localization.error, localization['trade_error_15'], 'fail', 10000); } else { ShowMsg(localization.error, data.error_message, 'fail', 10000); } } else { ShowMsg(localization.error, localization[data.error_message], 'fail', 10000); } } }); }, open_history: function (gw_type) { var self = this; // clear array this.history = { history: [], historyOwn: [] }; $.ajax({ url: '/' + self.config.lang + '/giveaway/history/' + gw_type, dataType: "json", method: "POST" }).success(function (data) { if (data.success) { self.history = data; $("#overlay").fadeIn('fast'); $("#giveaway").fadeIn('fast'); $('body').addClass('is-modal'); $('#giveaway .close').one('click', hide_overlay); return false; } else { return ShowMsg(localization.error, localization.unknown_error, 'fail', 3000); } }).error(function () { return ShowMsg(localization.error, localization.unknown_error, 'fail', 3000); }); } } }); } });
/*** * * Note that this localization is alredy included by default. * Simply call Date.setLocale(<code>) * * var locale = Date.getLocale(<code>) will return this object, which * can be tweaked to change the behavior of parsing/formatting in the locales. * * locale.addFormat adds a date format (see this file for examples). * Special tokens in the date format will be parsed out into regex tokens: * * {0} is a reference to an entry in locale.optionals. Output: (?:the)? * {unit} is a reference to all units. Output: (day|week|month|...) * {unit3} is a reference to a specific unit. Output: (hour) * {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week) * {unit?} "?" makes that token optional. Output: (day|week|month)? * * {day} Any reference to tokens in them modifiers array will include all with the same name. Output: (yesterday|today|tomorrow) * * All spaces are optional and will be converted to "\s*" * * Locale arrays months, weekdays, units, numbers, as well as the "src" field for * all entries in the modifiers array follow a special format indicated by a colon: * * minute:|s = minute|minutes * thicke:n|r = thicken|thicker * * Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples * of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in: * * units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays'] * * When matched, the index will be found using: * * units.indexOf(match) % 7; * * Resulting in the correct index with any number of alternates for that entry. * */ Date.setLocale('ru', { futureRelativeFormat: 1, months: ['Январ:я|ь','Феврал:я|ь','Март:а|','Апрел:я|ь','Ма:я|й','Июн:я|ь','Июл:я|ь','Август:а|','Сентябр:я|ь','Октябр:я|ь','Ноябр:я|ь','Декабр:я|ь'], weekdays: ['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'], units: ['миллисекунд:а|у|ы|','секунд:а|у|ы|','минут:а|у|ы|','час:||а|ов','день|день|дня|дней','недел:я|ю|и|ь|е','месяц:||а|ев|е','год|год|года|лет|году'], numbers: ['од:ин|ну','дв:а|е','три','четыре','пять','шесть','семь','восемь','девять','десять'], optionals: ['в|на','года'], outputFormat: '{d} {month} {yyyy} года', pastFormat: '{num} {unit} {sign}', futureFormat: '{sign} {num} {unit}', modifiers: [ { name: 'day', src: 'позавчера', value: -2 }, { name: 'day', src: 'вчера', value: -1 }, { name: 'day', src: 'сегодня', value: 0 }, { name: 'day', src: 'завтра', value: 1 }, { name: 'day', src: 'послезавтра', value: 2 }, { name: 'sign', src: 'назад', value: -1 }, { name: 'sign', src: 'через', value: 1 }, { name: 'shift', src: 'прошло:й|м', value: -1 }, { name: 'shift', src: 'следующе:й|м', value: 1 } ], formats: [ '{num} {unit} {sign}', '{sign} {num} {unit}', '{date} {month} {year?} {1}', '{month} {year}', '{0} {shift} {unit=5-7}' ] });
import Enum from '../../lib/Enum'; import { moduleActionTypes } from '../../enums/moduleActionTypes'; import proxyActionTypes from '../../enums/proxyActionTypes'; export default new Enum( [...Object.keys(moduleActionTypes), ...Object.keys(proxyActionTypes)], 'dateTimeFormat', );
/** * * Block */ import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import styles from './styles.scss'; const renderMsg = msg => <p>{msg}</p>; const Block = ({ children, description, style, title }) => ( <div className="col-md-12"> <div className={styles.ctmBlock} style={style}> <div className={styles.ctmBlockTitle}> <FormattedMessage id={title} /> <FormattedMessage id={description}> {renderMsg} </FormattedMessage> </div> {children} </div> </div> ); Block.defaultProps = { children: null, description: 'app.utils.defaultMessage', style: {}, title: 'app.utils.defaultMessage', }; Block.propTypes = { children: PropTypes.any, description: PropTypes.string, style: PropTypes.object, title: PropTypes.string, }; export default Block;
var HtmlWebpackPlugin = require('html-webpack-plugin'); var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: __dirname + '/app/index.html', filename: 'index.html', inject: 'body' }) module.exports = { entry: [ './app/index.js' ], output: { path: __dirname + '/dist', filename: 'index_bundle.js' }, module: { loaders: [ {test: /\.js$/, exclude: /node_module/, loader: 'babel-loader'}, {test: /\.css$/, loader: 'style-loader!css-loader'} ] }, plugins: [HtmlWebpackPluginConfig] }
define(['src/util/api'], function (API) { return async function loadZips(zipURLs, options = {}) { const JSZip = await API.require('jszip'); const superagent = await API.require('superagent'); const xyParser = await API.require('https://www.lactame.com/lib/xy-parser/1.3.0/xy-parser.min.js'); const SD = await API.require('https://www.lactame.com/lib/spectra-data/3.0.7/spectra-data.min.js'); var jszip = new JSZip(); var spectraDataSet = []; for (let zipURL of zipURLs) { let zipFiles = await superagent.get(zipURL) .withCredentials() .responseType('blob'); var zip = await jszip.loadAsync(zipFiles.body); let filesToProcess = Object.keys(zip.files).filter((filename) => filename.match(/\.[0-9]+$/)); for (const filename of filesToProcess) { let fileData = await zip.files[filename].async('string'); let result = xyParser(fileData, { arrayType: 'xxyy' }); let spectrum = SD.NMR.fromXY(result[0], result[1], { dataType: 'IR', xUnit: 'waveNumber', yUnit: '' }); if (options.filter) options.filter(spectrum.sd); spectrum.sd.info = {}; spectrum.sd.filename = filename.replace(/[0-9 a-z A-Z]+\//, ''); spectraDataSet.push(spectrum); } } return spectraDataSet; }; });
(function () { 'use strict'; angular .module('softvApp') .controller('ordenEjecutadaCtrl', ordenEjecutadaCtrl); ordenEjecutadaCtrl.inject = ['$state', 'ngNotify', '$stateParams', '$uibModal', 'DescargarMaterialFactory', 'ordenesFactory', '$rootScope', '$filter']; function ordenEjecutadaCtrl($state, ngNotify, $stateParams, $uibModal, ordenesFactory, $rootScope, $filter, DescargarMaterialFactory) { var vm = this; vm.showDatosCliente = true; vm.buscarContrato = buscarContrato; vm.fechaEjecucion = new Date(); vm.observaciones = ''; vm.detalleTrabajo = detalleTrabajo; vm.Guardar = Guardar; vm.clv_tecnico = 0; vm.titulo = 'Ejecución de Orden' vm.claveOrden = $stateParams.id; vm.block = true; vm.blockSolicitud = true; vm.MuestraAgenda = MuestraAgenda; vm.blockVista1 = true; vm.blockVista2 = true; vm.blockEjecucionReal = true; vm.blockEjecutada = false; vm.blockPendiente = true; vm.blockVista = false; vm.blockTecnico = false; vm.fechas = fechas; vm.ValidarDescargaMaterialOrden = ValidarDescargaMaterialOrden; vm.soyEjecucion = true; vm.Eliminar = Eliminar; vm.idBitacora = 0; vm.idTecnicoBitacora = 0; vm.SoyRetiro = false; vm.Cancelar = Cancelar; init(vm.claveOrden); function Cancelar() { ordenesFactory.Getsp_BorraArticulosAsignados(vm.claveOrden).then(function (data) { $state.go('home.procesos.ordenes'); }); } function Bloqueo() { if (vm.status == 'E') { vm.blockEjecucion = false; vm.blockVista1 = true; vm.blockVista2 = true; } else if (vm.status == 'V') { vm.blockEjecucion = true; if (vm.Visita1 == null) { vm.blockVista1 = false; vm.blockVista2 = true; } else { vm.blockVista1 = true; vm.blockVista2 = false; } } } function DimeSitengoRetiro() { // 1.-si tengo retiro pero no se ha recibido ninguno // 2.- si tengo retiro y ya se recibio almenos un articulo //3.-No tengo retiro var recibidos = 0; var cuantosRetiro = 0; vm.trabajosTabla.forEach(function (row) { if (row.Descripcion.toLowerCase().includes('rante') || row.Descripcion.toLowerCase().includes('relnb') || row.Descripcion.toLowerCase().includes('rcabl') || row.Descripcion.toLowerCase().includes('rcont') || row.Descripcion.toLowerCase().includes('rapar') || row.Descripcion.toLowerCase().includes('rantx') || row.Descripcion.toLowerCase().includes('riapar') || row.Descripcion.toLowerCase().includes('retca') || row.Descripcion.toLowerCase().includes('rradi') || row.Descripcion.toLowerCase().includes('rrout')) { cuantosRetiro = cuantosRetiro + 1; if (row.recibi == true) { recibidos = recibidos + 1; } } }); if (cuantosRetiro > 0) { vm.SoyRetiro = true; return (recibidos == 0) ? 1 : 2 } else { return 3; } } function init(orden) { ordenesFactory.ConsultaOrdSer(orden).then(function (data) { vm.clv_orden = data.GetDeepConsultaOrdSerResult.Clv_Orden; vm.datosOrden = data.GetDeepConsultaOrdSerResult; vm.contrato = data.GetDeepConsultaOrdSerResult.ContratoCom; vm.Clv_TipSer = data.GetDeepConsultaOrdSerResult.Clv_TipSer; var verificastatus = data.GetDeepConsultaOrdSerResult.STATUS; if (verificastatus == 'E') { $state.go('home.procesos.ordenes'); } vm.Fec_Sol = vm.datosOrden.Fec_Sol; vm.observaciones = vm.datosOrden.Obs; ordenesFactory.consultaTablaServicios(vm.clv_orden).then(function (data) { vm.trabajosTabla = data.GetBUSCADetOrdSerListResult; vm.trabajosTabla.forEach(function (row) { row.recibi = false; }); }); buscarContrato(vm.contrato); vm.status = 'E' FechasOrden(); Bloqueo(); DescargarMaterialFactory.GetchecaBitacoraTecnico(vm.clv_orden, 'O').then(function (data) { if (data.GetchecaBitacoraTecnicoResult != null) { vm.idBitacora = data.GetchecaBitacoraTecnicoResult.idBitacora; vm.idTecnicoBitacora = data.GetchecaBitacoraTecnicoResult.clvTecnico; } ordenesFactory.MuestraRelOrdenesTecnicos(orden).then(function (data) { vm.tecnico = data.GetMuestraRelOrdenesTecnicosListResult; if (vm.idTecnicoBitacora > 0) { for (var a = 0; a < vm.tecnico.length; a++) { if (vm.tecnico[a].CLV_TECNICO == vm.idTecnicoBitacora) { vm.selectedTecnico = vm.tecnico[a]; vm.blockTecnico = true; } } } }); }); }); } function ValidarDescargaMaterialOrden() { if (vm.selectedTecnico != undefined) { DescargaMaterialOrden(); } else { ngNotify.set('Selecciona un técnico y/o Ingresa una fecha de ejecución.', 'error'); } } function DescargaMaterialOrden() { var options = {}; options.ClvOrden = vm.clv_orden; options.SctTecnico = vm.selectedTecnico; options.Tipo_Descargar = "O"; options.Detalle = false; var modalInstance = $uibModal.open({ animation: vm.animationsEnabled, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/ModalDescargaMaterial.html', controller: 'ModalDescargaMaterialCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { options: function () { return options; } } }); } function buscarContrato(event) { if (vm.contrato == null || vm.contrato == '' || vm.contrato == undefined) { ngNotify.set('Coloque un contrato válido', 'error'); return; } if (!vm.contrato.includes('-')) { ngNotify.set('Coloque un contrato válido', 'error'); return; } ordenesFactory.getContratoReal(vm.contrato).then(function (data) { vm.contratoBueno = data.GetuspBuscaContratoSeparado2ListResult[0].ContratoBueno; datosContrato(data.GetuspBuscaContratoSeparado2ListResult[0].ContratoBueno); }); } $rootScope.$on('cliente_select', function (e, contrato) { vm.contrato = contrato.CONTRATO; vm.contratoBueno = contrato.ContratoBueno; datosContrato(contrato.ContratoBueno); }); $rootScope.$on('detalle_orden', function (e, detalle) { vm.clv_detalle = detalle; }); $rootScope.$on('actualiza_tablaServicios', function () { actualizarTablaServicios(); }); function actualizarTablaServicios() { ordenesFactory.consultaTablaServicios(vm.clv_orden).then(function (data) { vm.trabajosTabla = data.GetBUSCADetOrdSerListResult; }); } function datosContrato(contrato) { ordenesFactory.serviciosCliente(contrato).then(function (data) { vm.servicios = data.GetDameSerDelCliFacListResult; }); ordenesFactory.buscarCliPorContrato(contrato).then(function (data) { vm.datosCli = data.GetDeepBUSCLIPORCONTRATO_OrdSerResult; }); } function detalleTrabajo(trabajo, x) { if (vm.selectedTecnico == undefined) { ngNotify.set('Selecciona a un técnico.', 'warn'); return; } var items = {}; items.contrato = vm.contratoBueno; if (x.Descripcion.toLowerCase().includes('ipaqu') || x.Descripcion.toLowerCase().includes('bpaqu') || x.Descripcion.toLowerCase().includes('dpaqu') || x.Descripcion.toLowerCase().includes('rpaqu') || x.Descripcion.toLowerCase().includes('ipaqut') || x.Descripcion.toLowerCase().includes('bpaqt') || x.Descripcion.toLowerCase().includes('dpaqt') || x.Descripcion.toLowerCase().includes('rpaqt') || x.Descripcion.toLowerCase().includes('bpaad') || x.Descripcion.toLowerCase().includes('bsedi')) { items.clv_detalle_orden = x.Clave; items.clv_orden = x.Clv_Orden; items.descripcion = x.Descripcion.toLowerCase(); items.servicio = vm.Clv_TipSer; items.Detalle = false; var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/bajaServicios.html', controller: 'BajaServiciosCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, size: 'md', resolve: { items: function () { return items; } } }); } else if ( x.Descripcion.toLowerCase().includes('camdo') || x.Descripcion.toLowerCase().includes('cadig') || x.Descripcion.toLowerCase().includes('canet') ) { ordenesFactory.consultaCambioDomicilio(x.Clave, vm.clv_orden, vm.contratoBueno).then(function (data) { console.log(data); var items = { clv_detalle_orden: x.Clave, clv_orden: vm.clv_orden, contrato: vm.contratoBueno, isUpdate: (data.GetDeepCAMDOResult == null) ? false : true, datosCamdo: data.GetDeepCAMDOResult, Detalle: true }; var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/facturacion/modalCambioDomicilio.html', controller: 'CambioDomicilioOrdenesCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, size: 'md', resolve: { items: function () { return items; } } }); }); } else if ( x.Descripcion.toLowerCase().includes('iante') || x.Descripcion.toLowerCase().includes('inlnb') || x.Descripcion.toLowerCase().includes('iapar') || x.Descripcion.toLowerCase().includes('iantx') || x.Descripcion.toLowerCase().includes('inups') || x.Descripcion.toLowerCase().includes('itrip') || x.Descripcion.toLowerCase().includes('iradi') || x.Descripcion.toLowerCase().includes('irout') || x.Descripcion.toLowerCase().includes('icabm') || x.Descripcion.toLowerCase().includes('ecabl') || x.Descripcion.toLowerCase().includes('econt') ) { vm.NOM = x.Descripcion.split(' '); var items_ = { 'Op': 'M', 'Trabajo': vm.NOM[0], 'Contrato': vm.contratoBueno, 'ClvTecnico': vm.selectedTecnico.CLV_TECNICO, 'Clave': x.Clave, 'ClvOrden': x.Clv_Orden, 'Detalle': false }; var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/ModalAsignaAparato.html', controller: 'ModalAsignaAparatoCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, size: 'md', resolve: { items: function () { return items_; } } }); } else if ( x.Descripcion.toLowerCase().includes('rante') || x.Descripcion.toLowerCase().includes('relnb') || x.Descripcion.toLowerCase().includes('rcabl') || x.Descripcion.toLowerCase().includes('rcont') || x.Descripcion.toLowerCase().includes('rapar') || x.Descripcion.toLowerCase().includes('rantx') || x.Descripcion.toLowerCase().includes('riapar') || x.Descripcion.toLowerCase().includes('retca') || x.Descripcion.toLowerCase().includes('rradi') || x.Descripcion.toLowerCase().includes('rrout') ) { vm.TrabajoRetiro = true; } else if ( x.Descripcion.toLowerCase().includes('ccabm') || x.Descripcion.toLowerCase().includes('cantx') ) { vm.NOM = x.Descripcion.split(' '); var items_ = { 'Op': 'M', 'Trabajo': vm.NOM[0], 'Contrato': vm.contratoBueno, 'ClvTecnico': vm.selectedTecnico.CLV_TECNICO, 'Clave': x.Clave, 'ClvOrden': x.Clv_Orden }; var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/ModalAsignaAparato.html', controller: 'ModalCambioAparatoCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, size: 'md', resolve: { items: function () { return items_; } } }); }else if( x.Descripcion.toLowerCase().includes('isnet') || x.Descripcion.toLowerCase().includes('isdig') || x.Descripcion.toLowerCase().includes('isdtv') ){ var items_ = { 'clv_orden': x.Clv_Orden, 'Clv_Tecnico': vm.selectedTecnico.CLV_TECNICO, 'Detalle': false }; var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/ModalInstalaServicio.html', controller: 'ModalInstalaServicioCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, size: 'lg', resolve: { items: function () { return items_; } } }); } else { console.log('este trabajo no esta implementado'); } } function fechas() { FechasOrden(); Bloqueo(); } function toDate(dateStr) { var parts = dateStr.split("/"); return new Date(parts[2], parts[1] - 1, parts[0]); } function ValidaFecha(fechaIngresada, fechasolicitud) { var _fechaHoy = new Date(); var _fechaIngresada = toDate(fechaIngresada); var _fechasolicitud = toDate(fechasolicitud); if ((_fechaIngresada > _fechasolicitud && _fechaIngresada < _fechaHoy) || _fechasolicitud.toDateString() === _fechaIngresada.toDateString()) { return true; } else { return false; } } function MuestraAgenda() { var options = {}; options.clv_queja_orden = vm.clv_orden; options.opcion = 1; var modalInstance = $uibModal.open({ animation: vm.animationsEnabled, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/ModalAgendaQueja.html', controller: 'ModalAgendaQuejaCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, size: 'sm', resolve: { options: function () { return options; } } }); } function FechasOrden() { vm.Fec_Eje = (vm.datosOrden.Fec_Eje == '' || vm.datosOrden.Fec_Eje === '01/01/1900') ? '' : vm.datosOrden.Fec_Eje; vm.Visita1 = (vm.datosOrden.Visita1 == '' || vm.datosOrden.Visita1 === '01/01/1900') ? '' : vm.datosOrden.Visita1; vm.Visita2 = (vm.datosOrden.Visita2 == '' || vm.datosOrden.Visita2 === '01/01/1900') ? '' : vm.datosOrden.Visita2; } function Guardar(redirect) { if (vm.status == 'E') { if (ValidaFecha(vm.Fec_Eje, vm.Fec_Sol) == false) { ngNotify.set('La fecha de ejecución no puede ser menor a la fecha de solicitud ni mayor a la fecha actual', 'warn'); return; } } else if (vm.status == 'V') { if (vm.Visita1 != null && vm.Visita1 != undefined && (vm.Visita2 == undefined || vm.Visita2 == null)) { if (ValidaFecha(vm.Visita1, vm.Fec_Sol) == false) { ngNotify.set('La fecha de visita 1 no puede ser menor a la fecha de solicitud ni mayor a la fecha actual', 'warn'); return; } if (vm.Visita1 != null && vm.Visita1 != undefined && (vm.Visita2 != undefined || vm.Visita2 != null)) { if (ValidaFecha(vm.Visita2, vm.Fec_Sol) == false) { ngNotify.set('La fecha de visita 2 no puede ser menor a la fecha de solicitud ni mayor a la fecha actual', 'warn'); return; } } } } console.log(DimeSitengoRetiro()); if (DimeSitengoRetiro() == 1) { ngNotify.set('Necesita recibir al menos un artículo para generar la orden ', 'warn'); return; } if (DimeSitengoRetiro() == 2) { var ApaNoEntregados = []; vm.trabajosTabla.forEach(function (row) { if (row.Descripcion.toLowerCase().includes('rante') || row.Descripcion.toLowerCase().includes('relnb') || row.Descripcion.toLowerCase().includes('rcabl') || row.Descripcion.toLowerCase().includes('rcont') || row.Descripcion.toLowerCase().includes('rapar') || row.Descripcion.toLowerCase().includes('rantx') || row.Descripcion.toLowerCase().includes('riapar') || row.Descripcion.toLowerCase().includes('retca') || row.Descripcion.toLowerCase().includes('rradi') || row.Descripcion.toLowerCase().includes('rrout')) { if (row.recibi == false) { ApaNoEntregados.push(row); } } }); ordenesFactory.GetSP_InsertaTbl_NoEntregados(ApaNoEntregados).then(function (response) { console.log(response); }); } EjecutaOrden(redirect); } function GuardaDetalle(redirect) { ordenesFactory.AddNueRelOrdenUsuario(vm.clv_orden).then(function (data) { var obj = { 'ClvOrden': vm.clv_orden, 'ClvTipSer': vm.Clv_TipSer, 'Contrato': vm.contratoBueno, 'FecSol': vm.Fec_Sol, 'FecEje': (vm.Fec_Eje == null || vm.Fec_Eje == undefined) ? '' : vm.Fec_Eje, 'Visita1': (vm.Visita1 == null || vm.Visita1 == undefined) ? '' : vm.Visita1, 'Visita2': (vm.Visita2 == null || vm.Visita2 == undefined) ? '' : vm.Visita2, 'Status': vm.status, 'ClvTecnico': vm.selectedTecnico.CLV_TECNICO, 'Impresa': 1, 'ClvFactura': 0, 'Obs': vm.observaciones, 'ListadeArticulos': '' }; ordenesFactory.MODORDSER(obj).then(function (response) { console.log(response); console.log("prueba mike"); if (response.GetDeepMODORDSERResult.Msj != null) { console.log("Error"); ngNotify.set(response.GetDeepMODORDSERResult.Msj, 'error'); } else { console.log("well done"); ordenesFactory.PreejecutaOrden(vm.clv_orden).then(function (details) { ordenesFactory.GetDeepSP_GuardaOrdSerAparatos(vm.clv_orden).then(function (result) { var descripcion = 'Se generó la'; ordenesFactory.AddSP_LLena_Bitacora_Ordenes(descripcion, vm.clv_orden).then(function (data) { ordenesFactory.Imprime_Orden(vm.clv_orden).then(function (data) { if (data.GetDeepImprime_OrdenResult.Imprime == 1) { ngNotify.set('La orden es de proceso automático por lo cual no se imprimió', 'warn'); if (redirect) { $state.go('home.procesos.ordenes') } } else { if (redirect) { $state.go('home.procesos.ordenes') } ngNotify.set('La orden se ha ejecutado correctamente', 'success'); } }) }); }); }); } }); }); } function ImprimeOrden(clv_orden) { var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/modalReporteOrdSer.html', controller: 'modalReporteOrdeSerCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, class: 'modal-backdrop fade', size: 'lg', resolve: { clv_orden: function () { return clv_orden; } } }); } function Eliminar() { ordenesFactory.Getsp_validaEliminarOrden().then(function (data) { if (data.Getsp_validaEliminarOrdenserResult.Activo == 1) { ModalConfirmDelete(vm.clv_orden, vm.contratoBueno); } else { ngNotify.set('No tiene permisos para eliminar la orden', 'error'); } }); } function ModalConfirmDelete(clv_orden, contratoBueno){ var options = {}; options.clv_orden = clv_orden; options.contratoBueno = contratoBueno; var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/modalEliminarOrdSer.html', controller: 'modalEliminarOrdSerCtrl', controllerAs: 'ctrl', backdrop: 'static', keyboard: false, class: 'modal-backdrop fade', size: 'sm', resolve: { options: function () { return options; } } }); } function EjecutaOrden(redirect) { if (vm.status == 'P') { ngNotify.set('Marque la opción ejecutada o visita para continuar', 'error'); return; } ordenesFactory.GetSP_ValidaGuardaOrdSerAparatos(vm.clv_orden, 'M', vm.status, 0, vm.selectedTecnico.CLV_TECNICO).then(function (data) { if (data.GetSP_ValidaGuardaOrdSerAparatosResult != '') { ngNotify.set(data.GetSP_ValidaGuardaOrdSerAparatosResult, 'warn'); return; } else { ordenesFactory.GetValidaOrdSerManuales(vm.clv_orden).then(function (response) { ordenesFactory.GetValida_DetOrden(vm.clv_orden).then(function (response) { if (response.GetValida_DetOrdenResult.Validacion == 0) { ngNotify.set('Se requiere tener datos en el detalle de la orden', 'error'); return; } else { ordenesFactory.GetCheca_si_tiene_camdo(vm.clv_orden).then(function (camdo) { if (camdo.GetCheca_si_tiene_camdoResult.Error > 0) { ngNotify.set('Se requiere que capture el nuevo domicilio', 'error'); } else { ordenesFactory.GetChecaMotivoCanServ(vm.clv_orden).then(function (result) { if (result.GetChecaMotivoCanServResult.Res == 1) { var ClvOrden = vm.clv_orden; var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: 'views/procesos/modalMotivoCancelacion.html', controller: 'modalMotivoCanCtrl', controllerAs: '$ctrl', backdrop: 'static', keyboard: false, class: 'modal-backdrop fade', size: 'md', resolve: { ClvOrden: function () { return ClvOrden; } } }); } else { GuardaDetalle(redirect); } }); } }); } }); }); } }); } } })();
"use strict"; import React, {Component} from 'react'; import { AsyncStorage, Alert, StyleSheet, View, ScrollView, } from 'react-native'; import {GoogleSignin} from 'react-native-google-signin'; import CONFIG from './../config'; import _, {LANGUAGES} from './../i18n'; import CloudStorage from './../CloudStorage'; import Items from './../Items'; import { Layout, Button, ButtonPicker, } from './../components'; import Scene from './Scene'; export class SettingsScene extends Scene { constructor(props, context, updater) { super(props, context, updater); this.hardwareBackPress = () => this.navigationPop(); this.state = { hasPlayServices: false, language: CONFIG.LANGUAGE, hqPreview: CONFIG.HQ_PREVIEW, includeIconsInProgress: CONFIG.INCLUDE_ICONS_IN_PROGRESS, profile: CONFIG.PROFILE || null, }; } componentWillMount() { let configure = () => { GoogleSignin.configure(CONFIG.GOOGLE_SIGNIN).then(() => { this.setState({ hasPlayServices: true, }); }); }; if (CONFIG.PLATFORM === 'android') { GoogleSignin.hasPlayServices({autoResolve: true,}).then(configure()).catch(error => null); } else { configure(); } } setLanguage(language) { this.setState({ language: language, }, () => { CONFIG.set('LANGUAGE', language).then(() => { this.forceUpdate(); }); }); } switchHQPreview() { let values = [true, 'WIFI', false], index, value; index = values.indexOf(this.state.hqPreview); if ((index + 1) > (values.length - 1)) { index = 0; } else { index++; } value = values[index]; CONFIG.set('HQ_PREVIEW', value).then(() => { this.setState({ hqPreview: value, }); }); } toggleIncludeIcons() { CONFIG.set('INCLUDE_ICONS_IN_PROGRESS', !this.state.includeIconsInProgress).then(() => { this.setState({ includeIconsInProgress: !this.state.includeIconsInProgress, }); }); } cloudSynchronization() { if (!this.state.hasPlayServices) { return; } if (this.state.profile) { Alert.alert(_('SETTINGS__CLOUD_SYNCHRONIZATION_TITLE'), `${ _('SETTINGS__CONNECTED_ACCOUNT')}: ${this.state.profile.name}`, [ {text: _('BUTTON__CANCEL'), onPress: () => null, style: 'cancel'}, {text: _('BUTTON__TURN_OFF'), onPress: async () => { if (CONFIG.NETWORK === 'NONE') { Alert.alert(_('ERROR__NO_INTERNET_CONNECTION'), ''); return; } await CloudStorage.remove('/items'); GoogleSignin.revokeAccess().then(() => { CONFIG.remove(['SETTINGS__CLOUD_SYNCHRONIZATION_TITLE', 'PROFILE',]).then(() => { this.setState({ profile: null, }, () => Items.initialize()); }); }).catch(error => console.log(error)); }}, ]); return; } Alert.alert(_('SETTINGS__CLOUD_SYNCHRONIZATION_TITLE'), _('SETTINGS__CLOUD_SYNCHRONIZATION_CONFIRM'), [ {text: _('BUTTON__CANCEL'), onPress: () => null, style: 'cancel'}, {text: _('BUTTON__SIGN_IN'), onPress: () => { if (CONFIG.NETWORK === 'NONE') { Alert.alert(_('ERROR__NO_INTERNET_CONNECTION'), ''); return; } GoogleSignin.signIn().then(user => { let profile = { id: user.id, name: user.name, }; CONFIG.set({ CLOUD_SYNCHRONIZATION: true, PROFILE: profile, }).then(() => { this.setState({ profile: profile, }, () => Items.initialize()); }); }).catch(error => console.log(error)); }}, ]); } eraseData() { Alert.alert(_('SETTINGS__CLEARING_DATA_TITLE'), _('SETTINGS__CLEARING_DATA_CONFIRM'), [ {text: _('BUTTON__CANCEL'), onPress: () => null, style: 'cancel'}, {text: _('BUTTON__CLEAR'), onPress: () => { AsyncStorage.removeItem('TIPS_SHOWN'); Items.clear(); }}, ]); } render() { let languages = [], btnHQPreviewTitle = `${_('SETTINGS__HQ_PREVIEW')}`, btnSync, btnSyncTitle = _('BUTTON__CLOUD_SYNCHRONIZATION'); for (let i in LANGUAGES) if (LANGUAGES.hasOwnProperty(i)) { languages.push({label: LANGUAGES[i].name.toUpperCase(), value: i}); } switch (this.state.hqPreview) { case true: btnHQPreviewTitle += `: ${_('SETTINGS__IS_ON')}`; break; case 'WIFI': btnHQPreviewTitle += `: ${_('SETTINGS__WIFI_ONLY')}`; break; case false: btnHQPreviewTitle += `: ${_('SETTINGS__IS_OFF')}`; break; } if (this.state.hasPlayServices) { if (this.state.profile) { btnSyncTitle += `: ${_('SETTINGS__IS_ON')}` ; } else { btnSyncTitle += `: ${_('SETTINGS__IS_OFF')}` ; } btnSync = ( <View style={styles.section}> <Button title={btnSyncTitle.toUpperCase()} onPress={() => this.cloudSynchronization()} /> </View> ); } return ( <Layout toolbarTitle={_('SETTINGS__SETTINGS_TITLE')} onToolbarIconPress={() => this.navigationPop()} styles={styles.container} > <View style={styles.top}/> <ScrollView style={styles.center} contentContainerStyle={styles.centerContentContainerStyle}> <View style={styles.section}> <ButtonPicker values={languages} selectedValue={this.state.language} onValueChange={language => this.setLanguage(language)} title={_('SETTINGS__LANGUAGE').toUpperCase()} /> </View> <View style={styles.section}> <Button title={btnHQPreviewTitle} onPress={() => this.switchHQPreview()} /> </View> <View style={styles.section}> <Button title={`${_('SETTINGS__INCLUDE_ICONS_IN_PROGRESS')}: ${this.state.includeIconsInProgress ? _('SETTINGS__IS_ON') : _('SETTINGS__IS_OFF')}`.toUpperCase()} onPress={() => this.toggleIncludeIcons()} /> </View> {btnSync} <View style={styles.section}> <Button title={_('BUTTON__CLEAR_DATA').toUpperCase()} onPress={() => this.eraseData()} color={CONFIG.COLORS.RED} /> </View> </ScrollView> <View style={styles.bottom}/> </Layout> ); } } const styles = StyleSheet.create({ container: { }, top: { paddingHorizontal: 8, }, center: { flex: 1, }, centerContentContainerStyle: { paddingHorizontal: 8, }, bottom: { paddingHorizontal: 8, }, section: { paddingVertical: 8, }, text: { color: '#F5F5F5', }, });
/* * Verse Websocket Asynchronous Module * * The MIT License (MIT) * * Copyright (c) 2013-2014 Jiri Vrany, Jiri Hnidek * * 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. * */ /* globals define */ define(['command'], function(command) { 'use strict'; var node, commands, routines; //command codes = opCodes commands = { 32: 'NODE_CREATE', 33: 'NODE_DESTROY', 34: 'NODE_SUBSCRIBE', 35: 'NODE_UNSUBSCRIBE', 37: 'NODE_LINK', 38: 'NODE_PERMISSIONS', 39: 'NODE_UMASK', 40: 'NODE_OWNER', 41: 'NODE_LOCK', 42: 'NODE_UNLOCK', 43: 'NODE_PRIORITY' }; /* * routines - parsing functions for node commands from server */ routines = { 32: function getNodeCreate(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], SHARE: receivedView.getUint8(bufferPosition + 2), USER_ID: receivedView.getUint16(bufferPosition + 3), PARENT_ID: receivedView.getUint32(bufferPosition + 5), NODE_ID: receivedView.getUint32(bufferPosition + 9), CUSTOM_TYPE: receivedView.getUint16(bufferPosition + 13) }; }, 33: function getNodeDestroy(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], NODE_ID: receivedView.getUint32(bufferPosition + 2) }; }, 34: function getNodeSubscribe(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], NODE_ID: receivedView.getUint32(bufferPosition + 2), VERSION: receivedView.getUint32(bufferPosition + 6), CRC32: receivedView.getUint32(bufferPosition + 10) }; }, 35: function getNodeUnsubscribe(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], NODE_ID: receivedView.getUint32(bufferPosition + 2), VERSION: receivedView.getUint32(bufferPosition + 6), CRC32: receivedView.getUint32(bufferPosition + 10) }; }, 37: function getNodeLink(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], SHARE: receivedView.getUint8(bufferPosition + 2), PARENT_NODE_ID: receivedView.getUint32(bufferPosition + 3), CHILD_NODE_ID: receivedView.getUint32(bufferPosition + 7) }; }, 38: function getNodePermissions(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], SHARE: receivedView.getUint8(bufferPosition + 2), USER_ID: receivedView.getUint16(bufferPosition + 3), PERMISSIONS: receivedView.getUint8(bufferPosition + 5), NODE_ID: receivedView.getUint32(bufferPosition + 6) }; }, 39: function getNodeUmask(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], PERMISSIONS: receivedView.getUint8(bufferPosition + 2) }; }, 40: function getNodeOwner(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], SHARE: receivedView.getUint8(bufferPosition + 2), USER_ID: receivedView.getUint16(bufferPosition + 3), NODE_ID: receivedView.getUint32(bufferPosition + 5) }; }, 41: function getNodeLock(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], SHARE: receivedView.getUint8(bufferPosition + 2), AVATAR_ID: receivedView.getUint32(bufferPosition + 3), NODE_ID: receivedView.getUint32(bufferPosition + 7) }; }, 42: function getNodeUnlock(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], SHARE: receivedView.getUint8(bufferPosition + 2), AVATAR_ID: receivedView.getUint32(bufferPosition + 3), NODE_ID: receivedView.getUint32(bufferPosition + 7) }; }, 43: function getNodePriority(opCode, receivedView, bufferPosition) { return { CMD: commands[opCode], SHARE: receivedView.getUint8(bufferPosition + 2), PRIORITY: receivedView.getUint8(bufferPosition + 3), NODE_ID: receivedView.getUint32(bufferPosition + 4) }; } }; node = { /* * method for getting values of node */ getNodeValues: function getNodeValues(opCode, receivedView, bufferPosition, length) { var result = routines[opCode](opCode, receivedView, bufferPosition, length); return result; }, /* * create node command * @param user_id - ID of current user * @param avatar_id - ID of current avatar * @param custom_type - custom type of node */ create: function(user_id, avatar_id, custom_type) { var cmd, view; cmd = command.template(15, 32); view = new DataView(cmd); view.setUint8(2, 0); view.setUint16(3, user_id); view.setUint32(5, avatar_id); view.setUint32(9, 4294967295); view.setUint16(13, custom_type); return cmd; }, /* * destroy node command * @param node_id - ID of node to be destroyed */ destroy: function(node_id) { var cmd, view; cmd = command.template(6, 33); view = new DataView(cmd); view.setUint32(2, node_id); return cmd; }, /* * subscribe node commad * @param id - node id */ subscribe: function(node_id) { var cmd, view; cmd = command.template(14, 34); view = new DataView(cmd); view.setUint32(2, node_id); view.setUint32(6, 0); view.setUint32(10, 0); return cmd; }, /* * unsubscribe node commad * @param id - node id */ unsubscribe: function(node_id) { var cmd, view; cmd = command.template(14, 35); view = new DataView(cmd); view.setUint32(2, node_id); view.setUint32(6, 0); view.setUint32(10, 0); return cmd; }, /* * link two nodes * @param parent_id - node ID of parent node * @param child_id - node ID of child node */ link: function(parent_node_id, child_node_id) { var cmd, view; cmd = command.template(11, 37); view = new DataView(cmd); view.setUint8(2, 0); // share view.setUint32(3, parent_node_id); view.setUint32(7, child_node_id); return cmd; }, /* * permission of node * @param node_id * @param user_id * @param permission */ perm: function(node_id, user_id, permission) { var cmd, view; cmd = command.template(10, 38); view = new DataView(cmd); view.setUint8(2, 0); // share view.setUint16(3, user_id); view.setUint8(5, permission); view.setUint32(6, node_id); return cmd; }, /* * set umask of new node * @param permission */ umask: function(permission) { var cmd, view; cmd = command.template(3, 39); view = new DataView(cmd); view.setUint8(2, permission); return cmd; }, /* * set new node owner * @param node_id - ID of node * @param user_id - ID of new owner */ owner: function(node_id, user_id) { var cmd, view; cmd = command.template(9, 40); view = new DataView(cmd); view.setUint8(2, 0); // share view.setUint16(3, user_id); view.setUint32(5, node_id); return cmd; }, /* * lock node * @param avatar_id - ID of your avatar * @param node_id - ID of node */ lock: function(avatar_id, node_id) { var cmd, view; cmd = command.template(11, 41); view = new DataView(cmd); view.setUint8(2, 0); // share view.setUint32(3, avatar_id); view.setUint32(7, node_id); return cmd; }, /* * unlock node * @param avatar_id - ID of your avatar * @param node_id - ID of node */ unlock: function(avatar_id, node_id) { var cmd, view; cmd = command.template(11, 42); view = new DataView(cmd); view.setUint8(2, 0); // share view.setUint32(3, avatar_id); view.setUint32(7, node_id); return cmd; }, /* * set priority of node * @param node_id - ID of node * @param priority - new priority of node */ prio: function(node_id, priority) { var cmd, view; cmd = command.template(8, 43); view = new DataView(cmd); view.setUint8(2, 0); // share view.setUint8(3, priority); view.setUint32(4, node_id); return cmd; } }; return node; });
/** * Chunk an array into pieces based on itemsPerChunk. * You can use this to paginate an array of data. */ $.extend({ chunk: (data, itemsPerChunk) => { let ret = [] let pages = Math.floor(data.length / itemsPerChunk) if (data.length % pages) pages++ let temp = 0 for (let i = 0; i < pages; i++) { if (temp === data.length) break const thing = data.slice(temp, itemsPerChunk + temp) ret.push(thing) temp += itemsPerChunk } return ret } })
module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: 10, }, }, ], '@babel/preset-typescript', '@babel/preset-react', ], plugins: ['@babel/plugin-proposal-class-properties'], compact: false, };
version https://git-lfs.github.com/spec/v1 oid sha256:eeff9c5665590e117c68718dc9df044d760c211c6c9943dedf556033d16134d9 size 558294
version https://git-lfs.github.com/spec/v1 oid sha256:c34f8081961fc0eb3779e71334ae8785b432a95fb1ccfee056010aa90c747d21 size 6514
'use strict'; var React = require('react-native'); var { Image, StyleSheet, Text, TouchableHighlight, View, } = React; var Buzzer = React.createClass({ render: function() { var { buzzer } = this.props.data; return ( <TouchableHighlight style={styles.button} underlayColor='transparent'> <View style={styles.container}> <Image source={buzzer.image.source} style={{ width: buzzer.image.width, height: buzzer.image.height, }} /> <Text style={styles.helpText}>Click Anywhere to Buzz</Text> </View> </TouchableHighlight> ) } }); var styles = StyleSheet.create({ button: { flex: 1, padding: 0, }, container: { alignItems: 'center', backgroundColor: '#FFFFFF', flex: 1, justifyContent: 'center', }, helpText: { fontSize: 20, color: '#AAAAAA', marginTop: 30, } }) module.exports = Buzzer;
/* global expect jest test */ import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import UserCard from '../../../components/user/UserCard'; jest.dontMock('../../../components/user/UserCard'); describe('UserCard Component', () => { test('should match the user card snapshot', () => { const onClick = jest.fn(); const Role = { title: '', description: '' }; const component = shallow( <UserCard firstName={'Eguono'} id={3} lastName={'Efe'} email={'efe@gmail.com'} onClick={onClick} Role={Role} createdAt={'today'} />); const tree = toJson(component); expect(tree).toMatchSnapshot(); }); });
import Buff from './Buff'; export default class SlowDebuff extends Buff { /** * @class SlowDebuff * @description A debuff that increases the time between actions */ constructor(dungeon, duration, factor = 1, modifier = 0, name = 'Slowed') { super(dungeon); this._duration = duration; this._factor = factor; this._modifier = modifier; this._name = name; } getProperties() { return { delayFactor: this.getDelayFactor(), delayModifier: this.getDelayModifier() }; } getDuration() { return this._duration; } getDelayFactor() { return this._factor; } getDelayModifier() { return this._modifier; } getName() { return this._name; } isNegative() { return true; } timestep() { } }
const path = require('path'); const fixPath = require('fix-path'); const os = require('os'); module.exports = (shepherd) => { shepherd.pathsAgama = () => { switch (os.platform()) { case 'darwin': fixPath(); shepherd.agamaDir = `${process.env.HOME}/Library/Application Support/Agama`; break; case 'linux': shepherd.agamaDir = `${process.env.HOME}/.agama`; break; case 'win32': shepherd.agamaDir = `${process.env.APPDATA}/Agama`; shepherd.agamaDir = path.normalize(shepherd.agamaDir); break; } } shepherd.pathsDaemons = () => { switch (os.platform()) { case 'darwin': fixPath(); shepherd.agamaTestDir = `${process.env.HOME}/Library/Application Support/Agama/test`, shepherd.komododBin = path.join(__dirname, '../../assets/bin/osx/komodod'), shepherd.komodocliBin = path.join(__dirname, '../../assets/bin/osx/komodo-cli'), shepherd.komodoDir = shepherd.appConfig.dataDir.length ? shepherd.appConfig.dataDir : `${process.env.HOME}/Library/Application Support/Komodo`, shepherd.zcashdBin = '/Applications/ZCashSwingWalletUI.app/Contents/MacOS/zcashd', shepherd.zcashcliBin = '/Applications/ZCashSwingWalletUI.app/Contents/MacOS/zcash-cli', shepherd.zcashDir = `${process.env.HOME}/Library/Application Support/Zcash`, shepherd.zcashParamsDir = `${process.env.HOME}/Library/Application Support/ZcashParams`, shepherd.chipsBin = path.join(__dirname, '../../assets/bin/osx/chipsd'), shepherd.chipscliBin = path.join(__dirname, '../../assets/bin/osx/chips-cli'), shepherd.chipsDir = `${process.env.HOME}/Library/Application Support/Chips`, shepherd.coindRootDir = path.join(__dirname, '../../assets/bin/osx/dex/coind'), shepherd.mmBin = path.join(__dirname, '../../node_modules/marketmaker/bin/darwin/x64/marketmaker'); break; case 'linux': shepherd.agamaTestDir = `${process.env.HOME}/.agama/test`, shepherd.komododBin = path.join(__dirname, '../../assets/bin/linux64/komodod'), shepherd.komodocliBin = path.join(__dirname, '../../assets/bin/linux64/komodo-cli'), shepherd.komodoDir = shepherd.appConfig.dataDir.length ? shepherd.appConfig.dataDir : `${process.env.HOME}/.komodo`, shepherd.zcashParamsDir = `${process.env.HOME}/.zcash-params`, shepherd.chipsBin = path.join(__dirname, '../../assets/bin/linux64/chipsd'), shepherd.chipscliBin = path.join(__dirname, '../../assets/bin/linux64/chips-cli'), shepherd.chipsDir = `${process.env.HOME}/.chips`, shepherd.coindRootDir = path.join(__dirname, '../../assets/bin/linux64/dex/coind'), shepherd.mmBin = path.join(__dirname, '../../node_modules/marketmaker/bin/linux/x64/marketmaker'); break; case 'win32': shepherd.agamaTestDir = `${process.env.APPDATA}/Agama/test`; shepherd.agamaTestDir = path.normalize(shepherd.agamaTestDir); shepherd.komododBin = path.join(__dirname, '../../assets/bin/win64/komodod.exe'), shepherd.komododBin = path.normalize(shepherd.komododBin), shepherd.komodocliBin = path.join(__dirname, '../../assets/bin/win64/komodo-cli.exe'), shepherd.komodocliBin = path.normalize(shepherd.komodocliBin), shepherd.komodoDir = shepherd.appConfig.dataDir.length ? shepherd.appConfig.dataDir : `${process.env.APPDATA}/Komodo`, shepherd.komodoDir = path.normalize(shepherd.komodoDir); shepherd.chipsBin = path.join(__dirname, '../../assets/bin/win64/chipsd.exe'), shepherd.chipsBin = path.normalize(shepherd.chipsBin), shepherd.chipscliBin = path.join(__dirname, '../../assets/bin/win64/chips-cli.exe'), shepherd.chipscliBin = path.normalize(shepherd.chipscliBin), shepherd.chipsDir = `${process.env.APPDATA}/Chips`, shepherd.chipsDir = path.normalize(shepherd.chipsDir); shepherd.zcashParamsDir = `${process.env.APPDATA}/ZcashParams`; shepherd.zcashParamsDir = path.normalize(shepherd.zcashParamsDir); shepherd.coindRootDir = path.join(__dirname, '../../assets/bin/osx/dex/coind'); shepherd.coindRootDir = path.normalize(shepherd.coindRootDir); shepherd.mmBin = path.join(__dirname, '../../node_modules/marketmaker/bin/win32/x64/marketmaker.exe'); shepherd.mmBin = path.normalize(shepherd.mmBin); break; } } return shepherd; };
"use strict";define("settings/select",function(){var e=null;var t;function n(t,n){for(var a=0;a<n.length;a+=1){var r=n[a];var i=r.text||r.value;delete r.text;t.append($(e.helper.createElement("option",r)).text(i))}}t={types:["select"],use:function(){e=this},create:function(t,a,r){var i=$(e.helper.createElement("select"));n(i,r["data-options"]);delete r["data-options"];return i},init:function(e){var t=e.data("options");if(t!=null){n(e,t)}},set:function(e,t){e.val(t||"")},get:function(e,t,n){var a=e.val();if(n||a){return a}}};return t}); //# sourceMappingURL=public/src/modules/settings/select.js.map
var Firebase = require('firebase') var _ = require('lodash') module.exports = function ($firebase, $q, mnFirebaseConstants) { var playersSync = $firebase(new Firebase(mnFirebaseConstants.ROOT_REF).child(mnFirebaseConstants.PLAYERS)) var addPlayer = function (playersArray, playerName) { // TODO: Use isNameUnique and promises so all names are unique. if(!isNameUnique(playersArray, playerName)) { return $q(function (resolve, reject) { reject('The name "' + playerName + '" was already taken.') }) } return playersArray.$inst().$set(playerName, { isCheckedIn: false, isAssignedToGroup: false }) } var setPlayerIsCheckedIn = function (playersArray, playerName, isCheckedIn) { return playersArray.$inst().$update(playerName, { isCheckedIn: isCheckedIn }) } // TODO: Solve promise solution in the for-loop. var setPlayersIsAssignedToGroup = function (playersArray, playerNames, isAssignedToGroup) { for(var i = 0; i < playerNames.length; i++) { setPlayerIsAssignedToGroup(playersArray, playerNames[i], isAssignedToGroup) } } var setPlayerIsAssignedToGroup = function (playersArray, playerName, isAssignedToGroup) { return playersArray.$inst().$update(playerName, { isAssignedToGroup: isAssignedToGroup }) } var removePlayer = function (playersArray, playerName) { return playersArray.$inst().$remove(playerName) } var getPlayersById = function (playersId) { return $firebase(playersSync.$ref().child(playersId)).$asArray().$loaded() } var isNameUnique = function (playersArray, playerName) { return playersArray.$indexFor(playerName) === -1 } var createPlayersArray = function (tournamentId) { return playersSync.$set(tournamentId, false) } return { getPlayersById: getPlayersById, createPlayersArray: createPlayersArray, addPlayer: addPlayer, setPlayerIsCheckedIn: setPlayerIsCheckedIn, setPlayersIsAssignedToGroup: setPlayersIsAssignedToGroup, setPlayerIsAssignedToGroup: setPlayerIsAssignedToGroup, removePlayer: removePlayer } }
var stylZ=(function(window,undefined){// 'Z_' is an alias for 'styleZ' console.clear();//testing console var stylZ=function(el,index){ var ele;/*this variable turns into elemz to work inside functions*/ if( arguments[0] && !arguments[1]){ //No 2nd argument passed/no index passed or asterisk if(arguments[0] && el.charAt(0)==='#'){ console.log('id');//id ele=document.getElementById(el.substring(1));// remove 1st character '#' }else if(arguments[0] && el.charAt(0)==='.'){ console.log('class - 1st occurence');//class ele=document.querySelector(el);//1st Class occurence - don't use substring to remove '.' since querySelector needs it }else if(arguments[0] && el.charAt(0)!=='#' && el.charAt(0)!=='.' && el.charAt(0)!=='*'){ console.log('tagname only-first occurence'); ele=document.getElementsByTagName(el)[0]; } } else{if(arguments[0] && arguments[0]!=='*' && arguments[1] && arguments[1]!=='*' && el.charAt(0)!=='#' && el.charAt(0)!=='.'){ console.log('tagname and index');//tagname and index ele=document.getElementsByTagName(el)[index];//index }else if(arguments[0] && arguments[0]!=='*' && arguments[1] && arguments[1]==='*'){ console.log('id, class, or tagname - first occurence'); ele=document.querySelectorAll(el)[0]; }else if(arguments[0] && arguments[0]==='*' && arguments[1] && arguments[1]==='*'){ console.log('ALL elements on page-- all by getElementsByTagName(\'*\') - need loop here'); //document.getElementsByTagName('*')[i];//make loop code }else if(arguments[0] && arguments[0]==='*' && arguments[1] && arguments[1]==='**'){ console.log('ALL elements on page-- all by querySelectorAll(\'*\') - need loop here'); //document.querySelectorAll('*')[i];//make loop code } } elemz=ele; elz=ele.style;/*get ele from if/else statement-tried to make it a function already-couldn't figure out how to extract/return ele outside of function.*/ var f=Function,/*https://github.com/jed/140bytes/wiki/Byte-saving-techniques*/ //zss=function(prop,val){elz[prop]=val;return this;}, zss=f('prop','val','elz[prop]=val;return this'),/*zss=css*/ //z_dno=f('elz.display="none';return this'), z_dno=f('elz.display="none";return this'), z_din=f('elz.display="inline";return this'), z_dib=f('elz.display="inline-block";return this'), z_dbl=f('elz.display="block";return this'), z_clr=f('val','elz.clear=val;return this'), z_clrn=f('elz.clear="none";return this'), z_clrl=f('elz.clear="left";return this'), z_clrr=f('elz.clear="right";return this'), z_clrb=f('elz.clear="both";return this'), z_clrini=f('elz.clear="initial";return this'), z_clrinh=f('elz.clear="inherit";return this'), z_btm=f('val','elz.bottom=val;return this'), z_f=f('val','elz.font=val;return this'), z_ff=f('val','elz.fontFamily=val;return this'), z_fvn=f('elz.fontVariant="normal";return this'), z_fvs=f('elz.fontVariant="small-caps";return this'), z_fvin=f('elz.fontVariant="initial";return this'), z_fvih=f('elz.fontVariant="inherit";return this'), z_c=f('val','elz.color=val;return this'), z_o=f('val','elz.opacity=val;elz.filter="alpha(opacity=\'+val*100+\')";return this'), z_bg=f('val','elz.background=val;return this'), z_bgc=f('val','elz.backgroundColor=val;return this'), z_bgi=f('val','elz.backgroundImage=\'url("\'+val+\'")\';/*default x-y repeat*/return this'), z_bgir=f('if(arguments[0])elz.backgroundImage=\'url("\'+val+\'")\';elz.backgroundRepeat="repeat";return this'),/*doesnt like being broken into separate lines*/ z_bgix=f('val','if(arguments[0])elz.backgroundImage=\'url("\'+val+\'")\';elz.backgroundRepeat="repeat-x";return this'), z_bgiy=f('val','if(arguments[0])elz.backgroundImage=\'url("\'+val+\'")\';elz.backgroundRepeat="repeat-y";return this'), z_bgin=f('val','if(arguments[0])elz.backgroundImage=\'url("\'+val+\'")\';elz.backgroundRepeat="no-repeat";return this'), z_bgino=f('elz.backgroundImage="none";return this'), z_bgini=f('elz.backgroundImage="initial";return this'), z_bginh=f('elz.backgroundImage="inherit";return this'), z_bgr=f('val','elz.backgroundRepeat=val;return this'), z_bgrr=f('elz.backgroundRepeat="repeat";return this'), z_bgrx=f('elz.backgroundRepeat="repeat-x";return this'), z_bgry=f('elz.backgroundRepeat="repeat-y";return this'), z_bgrn=f('elz.backgroundRepeat="no-repeat";return this'), z_bgri=f('elz.backgroundRepeat="initial";return this'), z_bgp=f('val','elz.backgroundPosition=val;return this'), z_bgplt=f('elz.backgroundPosition="left top";return this'), z_bgplc=f('elz.backgroundPosition="left center";return this'), z_bgplb=f('elz.backgroundPosition="left bottom";return this'), z_bgprt=f('elz.backgroundPosition="right top";return this'), z_bgprc=f('elz.backgroundPosition="right center";return this'), z_bgprb=f('elz.backgroundPosition="right bottom";return this'), z_bgpct=f('elz.backgroundPosition="center top";return this'), z_bgpcc=f('elz.backgroundPosition="center center";return this'), z_bgpcb=f('elz.backgroundPosition="center bottom";return this'), z_bgpini=f('elz.backgroundPosition="initial";return this'), z_bgpinh=f('elz.backgroundPosition="inherit";return this'), z_bga=f('val','elz.backgroundAttachment=val;return this'), z_bgas=f('elz.backgroundAttachment="scroll";return this'), z_bgaf=f('elz.backgroundAttachment="fixed";return this'), z_bgal=f('elz.backgroundAttachment="local";return this'), z_bgaini=f('elz.backgroundAttachment="initial";return this'), z_bgainh=f('elz.backgroundAttachment="inherit";return this'), z_bm=f('val','elz.backgroundBlendMode=val;return this'),/*(CSS3 - noIE) - normal|multiply|screen|overlay|darken|lighten|color-dodge|saturation|color|luminosity*/ z_bmn=f('elz.backgroundBlendMode="normal";return this'), z_bmm=f('elz.backgroundBlendMode="multiply";return this'), z_bmscr=f('elz.backgroundBlendMode="screen";return this'), z_bmo=f('elz.backgroundBlendMode="overlay";return this'), z_bmd=f('elz.backgroundBlendMode="darken";return this'), z_bml=f('elz.backgroundBlendMode="lighten";return this'), z_bmcd=f('elz.backgroundBlendMode="color-dodge";return this'), z_bmsat=f('elz.backgroundBlendMode="saturation";return this'), z_bmlum=f('elz.backgroundBlendMode="luminosity";return this'), z_bclp=f('val','elz.backgroundClip=val;return this'),/*(CSS3 - IE9+) - border-box|padding-box|content-box|initial|inherit*/ z_bclpb=f('elz.backgroundClip="border-box";return this'), z_bclpp=f('elz.backgroundClip="padding-box";return this'), z_bclpc=f('val','elz.backgroundClip="content-box";return this'), z_bclpi=f('val','elz.backgroundClip="initial";return this'), z_bclpih=f('val','elz.backgroundClip="inherit";return this'), z_ori=f('val','elz.backgroundOrigin=val;return this'),/*(CSS3 - IE9+) - padding-box|border-box|content-box|initial|inherit*/ z_orip=f('elz.backgroundOrigin="padding-box";return this'), z_orib=f('elz.backgroundOrigin="border-box";return this'), z_oric=f('elz.backgroundOrigin="content-box";return this'), z_orin=f('elz.backgroundOrigin="initial";return this'), z_orih=f('elz.backgroundOrigin="inherit";return this'), z_ol=f('val','elz.outline=val;return this'), z_olini=f('elz.outline="initial";return this'), z_olinh=f('elz.outline="inherit";return this'), z_olc=f('val','elz.outlineColor=val;return this'), z_olci=f('elz.outlineColor="invert";return this'), z_olcini=f('elz.outlineColor="initial";return this'), z_olcinh=f('elz.outlineColor="inherit";return this'), z_ols=f('val','elz.outlineStyle=val;return this'), /*maybe abbreviate the outline.style list too*/ z_olw=f('val','elz.outlineWidth=val;return this'), z_olwtn=f('elz.outlineWidth="thin";return this'), z_olwm=f('elz.outlineWidth="medium";return this'), z_olwtk=f('elz.outlineWidth="thick";return this'), z_olwl=f('len','elz.outlineWidth=len;return this'), z_olwini=f('elz.outlineWidth="initial";return this'), z_olwinh=f('elz.outlineWidth="inherit";return this'), z_b=f('val','elz.border=val;return this'), z_bt=f('val','elz.borderTop=val;return this'), z_br=f('val','elz.borderRight=val;return this'), z_bb=f('val','elz.borderBottom=val;return this'), z_bl=f('val','elz.borderLeft=val;return this'), z_bc=f('val','elz.borderColor=val;/*color|transparent|initial|inherit - up to 4 values*/return this'), z_btc=f('val','elz.borderTopColor=val;return this'), z_brc=f('val','elz.borderRightColor=val;return this'), z_bbc=f('val','elz.borderBottomColor=val;return this'), z_blc=f('val','elz.borderLeftColor=val;return this'), z_bs=f('val','elz.borderStyle=val;/*none|hidden|dotted|dash|solid|double|groove|ridge|inset|outset|initial|inherit*/return this'), z_bts=f('val','elz.borderTopStyle=val;return this'), z_brs=f('val','elz.borderRightStyle=val;return this'), z_bbs=f('val','elz.borderBottomStyle=val;return this'), z_bls=f('val','elz.borderLeftStyle=val;return this'), z_bw=f('val','elz.borderWidth=val;return this'), z_btw=f('val','elz.borderTopWidth=val;return this'), z_brw=f('val','elz.borderRightWidth=val;return this'), z_bbw=f('val','elz.borderBottomWidth=val;return this'), z_blw=f('val','elz.borderLeftWidth=val;return this'), z_bcl=f('val','elz.borderCollapse=val;/*separate|collapse|initial|inherit*/return this'), z_bsp=f('val','elz.borderSpacing=val;/*has no effect if borderCollapse is set to "collapse"*/return this'), z_p=f('val','elz.padding=val;return this'), z_pt=f('val','elz.paddingTop=val;return this'), z_pr=f('val','elz.paddingRight=val;return this'), z_pb=f('val','elz.paddingBottom=val;return this'), z_pl=f('val','elz.paddingLeft=val;return this'), z_m=f('val','elz.margin=val;return this'), z_mt=f('val','elz.marginTop=val;return this'), z_mr=f('val','elz.marginRight=val;return this'), z_mb=f('val','elz.marginBottom=val;return this'), z_ml=f('val','elz.marginLeft=val;return this'), z_wb=f('val','elz.wordBreak=val;return this'),/*normal|break-all|keep-all|initial|inherit*/ z_ws=f('val','elz.whiteSpace=val;return this'),/*normal|nowrap|pre|initial|inherit*/ z_wsp=f('val','elz.wordSpacing=val;return this'),/*normal|length|initial|inherit - number can be positive, or negative*/ z_w=f('val','elz.width=val;return this'),/*auto|length|%|initial|inherit*/ z_h=f('val','elz.height=val;return this'),/*auto|length|%|initial|inherit*/ z_zi=f('val','elz.zIndex=val;return this'),/*auto|number|initial|inherit - number can be positive, or negative*/ z_iH=f('val','elemz.innerHTML=val;return this'), z_oH=f('val','elemz.outerHTML=val;return this'), z_tC=f('val','var valz=ele.textContent||ele.innerText;valz=val;return this'),/*make sure this line is correct*/ z_iT=f('val','elemz.innerText=val;return this'),/*<IE9*/ z_oT=f('val','elemz.outerText=val;return this'), //z_iAE=function(pos,element){var elmnt=document.createElement(element);elemz.insertAdjacentElement(pos,elmnt);return this'), z_iAE=f('pos','element','var elmnt=document.createElement(element);elemz.insertAdjacentElement(pos,elmnt);return this'), z_iAEbb=f('element','var elmnt=document.createElement(element);elemz.insertAdjacentElement("beforebegin",elmnt);return this'), z_iAEab=f('element','var elmnt=document.createElement(element);elemz.insertAdjacentElement("afterbegin",elmnt);return this'), z_iAEbe=f('element','var elmnt=document.createElement(element);elemz.insertAdjacentElement("beforeend",elmnt);return this'), z_iAEae=f('element','var elmnt=document.createElement(element);elemz.insertAdjacentElement("afterend",elmnt);return this'), z_iAH=f('pos','element','elemz.insertAdjacentHTML(pos,element);return this'), z_iAHbb=f('element','elemz.insertAdjacentHTML("beforebegin",element);return this'), z_iAHab=f('element','elemz.insertAdjacentHTML("afterbegin",element);return this'), z_iAHbe=f('element','elemz.insertAdjacentHTML("beforeend",element);return this'), z_iAHae=f('element','elemz.insertAdjacentHTML("afterend",element);return this'); return {/*To-do list--Return one function ONLY... that is equivalent to this whole object being returned*/ zss:zss, z_dno:z_dno, z_din:z_din, z_dib:z_dib, z_dbl:z_dbl, z_clr:z_clr, z_clrn:z_clrn, z_clrl:z_clrl, z_clrr:z_clrr, z_clrb:z_clrb, z_clrini:z_clrini, z_clrinh:z_clrinh, z_btm:z_btm, z_f:z_f, z_ff:z_ff, z_fvn:z_fvn, z_fvs:z_fvs, z_fvin:z_fvin, z_fvih:z_fvih, /*text color*/ z_c:z_c, z_o:z_o, /*background*/ z_bg:z_bg, z_bgc:z_bgc, z_bgi:z_bgi, z_bgir:z_bgir, z_bgix:z_bgix, z_bgiy:z_bgiy, z_bgin:z_bgin, z_bgino:z_bgino, z_bgini:z_bgini, z_bginh:z_bginh, z_bgr:z_bgr, z_bgrr:z_bgrr, z_bgrx:z_bgrx, z_bgry:z_bgry, z_bgrn:z_bgrn, z_bgri:z_bgri, z_bgp:z_bgp, z_bgplt:z_bgplt, z_bgplc:z_bgplc, z_bgplb:z_bgplb, z_bgprt:z_bgprt, z_bgprc:z_bgprc, z_bgprb:z_bgprb, z_bgpct:z_bgpct, z_bgpcc:z_bgpcc, z_bgpcb:z_bgpcb, z_bgpini:z_bgpini, z_bgpinh:z_bgpinh, z_bga:z_bga, z_bgas:z_bgas, z_bgaf:z_bgaf, z_bgal:z_bgal, z_bgaini:z_bgaini, z_bgainh:z_bgainh, z_bm:z_bm, z_bmn:z_bmn, z_bmm:z_bmm, z_bmscr:z_bmscr, z_bmo:z_bmo, z_bmd:z_bmd, z_bml:z_bml, z_bmcd:z_bmcd, z_bmsat:z_bmsat, z_bmlum:z_bmlum, z_bclp:z_bclp, z_bclpb:z_bclpb, z_bclpp:z_bclpp, z_bclpc:z_bclpc, z_bclpi:z_bclpi, z_bclpih:z_bclpih, z_ori:z_ori, z_orip:z_orip, z_orib:z_orib, z_oric:z_oric, z_orin:z_orin, z_orih:z_orih, /*outline & border*/ z_ol:z_ol, z_olini:z_olini, z_olinh:z_olinh, z_olc:z_olc, z_olci:z_olci, z_olcini:z_olcini, z_olcinh:z_olcinh, z_ols:z_ols, z_olw:z_olw, z_olwtn:z_olwtn, z_olwm:z_olwm, z_olwtk:z_olwtk, z_olwl:z_olwl, z_olwini:z_olwini, z_olwinh:z_olwinh, z_b:z_b, z_bt:z_bt, z_br:z_br, z_bb:z_bb, z_bl:z_bl, z_bc:z_bc, z_btc:z_btc, z_brc:z_brc, z_bbc:z_bbc, z_blc:z_blc, z_bs:z_bs, z_bts:z_bts, z_brs:z_brs, z_bbs:z_bbs, z_bls:z_bls, z_bw:z_bw, z_btw:z_btw, z_brw:z_brw, z_bbw:z_bbw, z_blw:z_blw, z_bcl:z_bcl, z_bsp:z_bsp, z_p:z_p, z_pt:z_pt, z_pr:z_pr, z_pb:z_pb, z_pl:z_pl, z_m:z_m, z_mt:z_mt, z_mr:z_mr, z_mb:z_mb, z_ml:z_ml, z_wb:z_wb, z_ws:z_ws, z_wsp:z_wsp, /*width & height*/ z_w:z_w, z_h:z_h, /*zIndex*/ z_zi:z_zi, /*innerHTML, textContent, innerText ,insertAdjacentElement, insertAdjacentHTML*/ z_iH:z_iH, z_oH:z_oH, z_tC:z_tC, z_iT:z_iT, z_oT:z_oT, z_iAE:z_iAE, z_iAEbb:z_iAEbb, z_iAEab:z_iAEab, z_iAEae:z_iAEae, z_iAEbe:z_iAEbe, z_iAH:z_iAH, z_iAHbb:z_iAHbb, z_iAHae:z_iAHae, z_iAHbe:z_iAHbe }; }; var ZZ_=window.stylZ=window.Z_=stylZ;/*stylZ=Z_*/ return ZZ_; })(window);
// (function () { // 'use strict'; // angular.module('yapp') // .factory('authService', function ($state, $localStorage, $http) { // return { // isLogged: false, // tokenStillValid: false, // check: check, // decodeToken: decodeToken, // logout: logout // }; // function check() { // /*jshint validthis: true */ // if ($localStorage.token && $localStorage.user) { // var decoded = decodeToken($localStorage.token); // if (!(decoded && checkExpire(decoded.exp))) { // logout(); // return; // } // this.isLogged = true; // } else { // this.isLogged = false; // } // } // function urlBase64Decode(str) { // var output = str.replace(/-/g, '+').replace(/_/g, '/'); // switch (output.length % 4) { // case 0: // { // break; // } // case 2: // { // output += '=='; // break; // } // case 3: // { // output += '='; // break; // } // default: // { // throw 'Illegal base64url string!'; // } // } // return decodeURIComponent(escape(window.atob(output))); // } // function decodeToken(token) { // /*jshint validthis: true */ // var parts = token.split('.'); // if (parts.length !== 3) { // console.log('not a token'); // return false; // } // var decoded = urlBase64Decode(parts[1]); // if (!decoded) { // console.log('error while decoding'); // return false; // } // return JSON.parse(decoded); // } // function checkExpire(exp) { // return Math.round(new Date().getTime() / 1000) <= exp; // } // function logout() { // /*jshint validthis: true */ // var self = this; // $http.post('//localhost:9000/logout').then(function () { // self.isLogged = false; // $localStorage.$reset(); // $state.go('login'); // }, function (err) { // console.log(err); // }); // } // }); // })();
export const ic_subject_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M14 17H4v2h10v-2zm6-8H4v2h16V9zM4 15h16v-2H4v2zM4 5v2h16V5H4z"},"children":[]}]};
/* meld v0.1 unobtrusive templating engine that runs on nodejs (jsdom+jquery) and browsers (jquery). prompted by weld.js; syntax by hquery Copyright Chew Choon Keat 2011 Released under the MIT License */ (function(context, $) { /* find all elements matching object's attribute key and set each innerText with attribute value */ function default_callback(index, ele, object) { if (typeof(object) == "string") { return ele.text(object); } else for (name in object) { if (!object.hasOwnProperty(name)) continue; var value = object[name]; if (typeof(value) == "object") { ele.meld('.' + name, value); } else { ele.find('.' + name).text(value); } } } /* return meld function, optionally tied to a root element */ function build_meld_fn(root) { return function(selector, data, callback) { var selected = $(selector, root||this); var ref = selected.first().clone(); if (ref.length == 0) return; if (!callback) callback = default_callback; var parents = selected.parent(); selected.remove(); return parents.each(function(pi, parent) { $.each(data, function(ri, object) { callback(ri, ref.clone().appendTo(parent), object); }); }); } } $.fn.meld = build_meld_fn(); context.meld = build_meld_fn(context.document); })(window, jQuery);
import React from 'react'; const Blog = () => <div>TODO - Blogging comes here</div> export default Blog;
uni.observe("component:upload:loaded", function(comp) { var controller = comp.controller, view = comp.view, 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">' + _('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; target = $(this); id = target.attr('id'); if (!id) { id = plupload.guid(); target.attr('id', id); } uploader = new plupload.Uploader($.extend({ dragdrop : true, container : id }, 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'; } $('#' + file.id).attr('class', actionClass).find('a').css('display', 'block'); } 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).text('Uploaded ' + uploader.total.uploaded + '/' + uploader.files.length + ' files'); } 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).text(_('Add files.')); } else { $('span.plupload_add_text', target).text(uploader.total.queued + ' files 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>'); } } uploader.bind("UploadFile", function(up, file) { $('#' + file.id).addClass('plupload_current_file'); }); uploader.bind('Init', function(up, res) { renderUI(id, target); // Enable rename support if (!settings.unique_names && settings.rename) { $('#' + id + '_filelist div.plupload_file_name span', target).live('click', 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.text(file.name); targetInput.blur(); } }); }); } $('a.plupload_add', target).attr('id', id + '_browse'); up.settings.browse_button = id + '_browse'; // Enable drag/drop if (up.features.dragdrop && up.settings.dragdrop) { up.settings.drop_element = id + '_filelist'; $('#' + id + '_filelist').append('<li class="plupload_droptext">' + _("Drag files here.") + '</li>'); } $('#' + 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.init(); 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 to large: ") + file.name); } if (err.code == plupload.FILE_EXTENSION_ERROR) { alert(_("Error: Invalid file extension: ") + file.name); } $('#' + file.id).attr('class', 'plupload_failed').find('a').css('display', 'block').attr('title', message); } }); 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).text('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'); } }); uploader.bind('QueueChanged', updateList); 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(); 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(); } }); // Call setup function if (settings.setup) { settings.setup(uploader); } }); return this; } else { // Get uploader instance for specified element return uploaders[$(this[0]).attr('id')]; } }; var uploader = view.find("form").pluploadQueue({ // General settings runtimes : 'html5', url : '/photo-asset/image/upload?create-thumb=yes', flash_swf_url : '', max_file_size : '10mb', //chunk_size : '1mb', //resize : {width : 800, height : 640, quality : 100}, unique_names : false, dragdrop : true, browse_button : "__uploader__button__", multiple_queues : true, // Specify what files to browse for filters : [{ title : "Image files", extensions : uni.data.getProperty("validUploadTypes") }], init : { "FileUploaded" : function(ob, file, resp) { var s = uni.spawn(uni.json.parse(resp.response).$).createSubjectFacade(), // Get the image path. // imLoc = s.find("@key", "raw-image", "item.field").$[0].$, // Build a file object, which extracts further info from the image path, such // as the image thumbnail. Also pass in the #getJson method, to which the // augment:image listener will pass the full item #id of the photo-asset // to which this image belongs. At that point, we fire off a notice // that this image is uploaded, which should get picked up by any UI // observers waiting to display the newly uploaded image. // im = uni.fire("image:augment", { image: imLoc, getJson: function(itemOb) { uni.fire("file:uploaded", { itemId : s.get("item.@id"), itemOb : itemOb, view : view, fileOb : file, imLoc : imLoc, imOb : im }); } }).$; }, "UploadProgress" : function() { uni.fire("upload:fileProgress", {}); }, "Error" : function() { uni.fire("upload:fileError", {}); } } }); });
define([ 'backbone', 'jquery', 'underscore' ], function( Backbone, $, _ ) { return Backbone.Model.extend({ defaults : { 'data' : '', 'algorithm' : 'sha1', 'hashed' : null, 'error' : null }, initialize : function() { this.syncing = false; this.resync = false; this.listenTo(this, 'change:data change:algorithm', this.hash); this.listenTo(this, 'sync', this.update); this.listenTo(this, 'error', this.error); }, url : function() { return '/hash/' + this.get('algorithm'); }, syncFile : function(formData) { var self = this; $.ajax({ 'url' : '/hash/' + this.get('algorithm'), 'type' : 'POST', 'xhr' : function() { var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { myXhr.upload.addEventListener('progress', function(e) { self.trigger('uploadProgress', e); }); } return myXhr; }, 'data' : formData, 'success' : _.bind(this.update, this, this), 'error' : function(xhr) { self.error(self, xhr); }, contentType: false, processData: false }); }, hash : function() { /* * May be called with data === false, don't do anything * in that case. It is used to force a change in the model * which FormData doesn't trigger */ this.resync = false; if (this.syncing) { this.resync = true; return; } this.syncing = true; if (typeof this.get('data') === 'string') { this.save(); } else if (this.get('data') instanceof FormData) { this.syncFile(this.get('data')); } }, update : function(model, response) { this.set('hashed', response); this.set('error', null); this.syncing = false; if (true === this.resync) { this.hash(); return; } this.trigger('syncFinished'); }, error : function(model, xhr) { this.syncing = false; this.trigger('syncFinished'); this.set('hashed', null); this.set('error', null); // Set to null to trigger a change if ('error' === xhr.statusText) { /* No response from server */ this.set('error', { 'code' : 'ServerUnavailable', 'message' : 'Unable to contact the server.' }); } else { this.set('error', JSON.parse(xhr.responseText)); } } }); });
var async = require('async'), fs = require('graceful-fs'), colors = require('colors'), _ = require('lodash'); module.exports = function(args, callback){ var config = hexo.config.deploy, log = hexo.log, extend = hexo.extend, deployers = extend.deployer.list(); if (!config){ var help = ''; help += 'You should configure deployment settings in _config.yml first!\n\n'; help += 'Available Types:\n'; help += ' ' + Object.keys(deployers).join(', ') + '\n\n'; help += 'For more help, you can check the online docs: ' + 'http://hexo.io/'.underline; console.log(help); return callback(); } if (!Array.isArray(config)) config = [config]; var generate = function(callback){ if (args.g || args.generate){ hexo.call('generate', callback); } else { fs.exists(hexo.public_dir, function(exist){ if (exist) return callback(); hexo.call('generate', callback); }); } }; var onDeployStarted = function() { /** * Fired before deployment. * * @event deployBefore * @for Hexo */ hexo.emit('deployBefore'); }; var onDeployFinished = function(err) { /** * Fired after deployment. * * @event deployAfter * @param {Error} err * @for Hexo */ hexo.emit('deployAfter', err); callback(err); }; generate(function(err){ if (err) return callback(err); onDeployStarted(); async.each(config, function(item, next){ var type = item.type; if (!deployers.hasOwnProperty(type)){ log.e('Deployer not found: ' + type); return next(); } else { log.i('Start deploying: ' + type); } deployers[type](_.extend({}, item, args), function(err){ if (err) return next(err); log.i('Deploy done: ' + type); next(); }); }, onDeployFinished); }); };
/*LEWD-BOT*/ // Initialization 'use strict'; var Botkit = require('./lib/Botkit.js'); var _ = require('lodash'); var os = require('os'); var controller = Botkit.slackbot({debug: false}); var bot = controller.spawn({token: process.env.token}).startRTM(); // Constants var lewdTerms = [ 'ass', 'beach', 'bikini', 'boobs', 'booty', 'bounce', 'bounce break', 'bra', 'breasts', 'camgirl', 'chick', 'cowgirl', 'girl', 'hot', 'jiggle', 'jiggly', 'lewdPerson', 'lingerie', 'naked', 'nipples', 'nude', 'panties', 'pawg', 'rack', 'sexy', 'slutty', 'swimsuit', 'thong', 'tits', 'twerk', 'wild', 'wooty', 'yoga' ]; var lewdCelebList = [ 'alison brie', 'celebrity', 'kate upton', 'lindsay lohan', 'megan fox', 'model', 'sasha gray', 'scarlet johanson', 'super model' ]; var lewdCommandList = { 'salute': 'nbc police salute', 'keyboard': 'ron jeremy keyboard', 'celery man': 'celery man', 'tayne': 'nude tayne' }; var lewdHype = [ 'LEWD HYPE :dickbutt:', 'HYPETRAIN :snowsplode: :eggplant: ' ]; // Listeners controller.hears('^lewdme!$', 'ambient', function(bot, message) {return getLewdGiphy(bot, message)}); controller.hears('^lewdme! (.*)$', 'ambient', function(bot, message) {return getSpecificGiphy(bot, message)}); // Functions function getSpecificGiphy(bot, message) { var command = message.match[1]; var searchTerms = lewdCommandList[command]; if (_.isEmpty(searchTerms)) { bot.reply(message, 'Invalid Lewd Command.'); } else { var src = {response_url: 'http://api.giphy.com/v1/gifs/search?q=' + searchTerms + '&api_key=dc6zaTOxFJmzC&limit=125', channel: message.channel}; bot.replyPublicDelayed(src, {}, function(res) {return getSpecificGiphyCallback(res, message)}); } } function getSpecificGiphyCallback(res, message) { var gif = res.data[0]; bot.reply(message, isValidGif(gif) ? getGifURL(gif) : 'No image available.'); } function getLewdGiphy(bot, message) { var searchTerms = getLewdTerms(); var offset = _.random(0, 500); var src = {response_url: 'http://api.giphy.com/v1/gifs/search?q=' + searchTerms + '&api_key=dc6zaTOxFJmzC&limit=125&rating=r&offset=' + offset, channel: message.channel}; bot.replyPublicDelayed(src, {}, function(res) {return getLewdGiphyCallback(res, message, searchTerms)}); } function getLewdGiphyCallback(res, message, searchTerms) { var gifs = getLewdestGifs(res.data); var num = _.random(0, (gifs.length || 100) - 1) var gif = gifs[num]; if (isValidGif(gif)) { getHype(message); bot.reply(message, 'Search: ' + searchTerms); bot.reply(message, getGifURL(gif)); } else { getLewdGiphy(bot, message); } } function getLewdTerms() { var maxTermCount = 5; var randomNumMax = lewdTerms.length - 1; var searchTerms = []; var lewdPerson = ''; while(searchTerms.length < maxTermCount) { searchTerms = getRandomTerm(searchTerms, maxTermCount, randomNumMax); } if(_.includes(searchTerms, 'lewdPerson')) { var personNum = _.random(0, lewdCelebList.length - 1); lewdPerson = lewdCelebList[personNum]; } return searchTerms.join(' ').replace('lewdPerson', lewdPerson); } function getRandomTerm(searchTerms, maxTermCount, randomNumMax) { var num = _.random(0, randomNumMax) var term = lewdTerms[num]; if (!_.includes(searchTerms, term)) { searchTerms.push(term) } return searchTerms; } function getLewdestGifs(data) { var lewdest = _.filter(data, {rating: 'r'}); if (!lewdest.length) { lewdest = _.filter(data, {rating: 'pg-13'}); } return lewdest.length ? lewdest : data; } function getGifURL(gif) { return gif.images.fixed_height.url || gif.images.fixed_width.url } function isValidGif(gif) { return _.isObject(gif) && gif.images && (gif.images.fixed_height || gif.images.fixed_width); } function getHype(message) { var hypeRoll = _.random(1, 100); var hypeHit = 50; if (_.isEqual(hypeRoll, hypeHit)) { var hypeNum = _.random(0, lewdHype.length - 1) var hypeMessage = lewdHype[hypeNum]; var hypeTrain = _.repeat(hypeMessage, 52); bot.reply(message, hypeTrain); } }
/*#inport <forEach.js>*/ /*#inport <types.js>*/ /*#inport <extend.js>*/ /*#inport 'watch.js'*/ var bindingTypes = { '*': function attrAndProp(name) { var attrName = snakeCase(name); return { configurable: false, get: function() { return this.getAttribute(attrName); }, set: function(value) { this.setAttribute(attrName, value); } } }, '=': function prop(name) { var storage, $trackers = []; return { get: function(fn) { if(isFunction(fn)) { $trackers.push(fn); } return storage; }, set: function(value) { $watch.$digest($trackers, value, storage); storage = value; } }; } }; function propertyMap(bmap) { var bindings = {}; forEach(bmap, function(value, type) { if( bindingTypes[type] ) { if( isArray(value) ) { forEach(value, function(name) { bindings[name] = bindingTypes[type](name); }); } else { bindings[value] = bindingTypes[type](value); } } else if( bindingTypes[type[0]] ) { bindings[type.substr(1)] = {value: value}; } }); return bindings; }; function Attribute(element) { this.$$element = element; this.$$observers = {}; forEach(element.attributes, function(attr) { this[camelCase(attr.name)] = attr.value; }, this); }; Attribute.prototype = { $observer: function(attrName, fn) { (this.$$observers[attrName] = (this.$$observers[attrName] || [])).push(fn); }, $digest: function(attrName, newValue, oldValue) { if(this.$$observers[attrName]) { $watch.$digest(this.$$observers[attrName], newValue, oldValue); } }, $get: function(attrName) { return this.$$element.getAttribute(attrName); }, $set: function(name, value) { var attrName = snakeCase(name); if( this[name] !== value ) { this.$digest(name, value, this[name]); this.$$element.setAttribute(attrName, value); } }, $dispatch: function(eventName, detail) { return this.$$element.dispatchEvent( new CustomEvent(eventName, detail) ); }, // Extract the info from data-* attributes $data: function() {} };
/******************************************************************************* * Simple script to submit forms * Copyright (c) 2013 Romain TOUZÉ ******************************************************************************/ /*jslint browser: true*/ var fieldsAreValid = function () { 'use strict'; console.debug('in fieldsAreValid'); var username = document.getElementById('id_username'), email = document.getElementById('id_email'), password = document.getElementById('id_password'), password_check = document.getElementById('id_password_check'), invalidEmail = function () { var emailVal; if (email) { emailVal = email.value; return !emailVal.trim().toLowerCase().match(/^\w+@\w+\.[a-z]+$/); } return false; }, invalidPassword = function () { return password.value.trim() === '' || password.value !== password_check.value; }, showError = function (inputNode, message) { window.alert(message); inputNode.style.borderColor = 'red'; inputNode.style.borderWidth = '3px'; }; if (username.value.trim() === '') { /* TODO attention, ce n'est pas internationnalisé...*/ showError(username, 'Please enter a username.'); return false; } if (invalidEmail()) { showError(email, 'Please enter a valid email.'); return false; } if (invalidPassword()) { showError(password, 'Entered password is empty or not the same as your second entry.'); return false; } return true; }; $(function () { $('#submit_link').click( function (event) { 'use strict'; event.preventDefault(); if (fieldsAreValid()) { console.debug('connard! tu valides ou quoi???'); $('#signin_form').submit(); } }); });