code
stringlengths
2
1.05M
/*! * froala_editor v2.7.2 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2017 Froala Labs */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof module === 'object' && module.exports) { // Node/CommonJS module.exports = function( root, jQuery ) { if ( jQuery === undefined ) { // require('jQuery') returns a factory that requires window to // build a jQuery instance, we normalize how we use modules // that require this pattern but the window provided is a noop // if it's defined (how jquery works) if ( typeof window !== 'undefined' ) { jQuery = require('jquery'); } else { jQuery = require('jquery')(root); } } return factory(jQuery); }; } else { // Browser globals factory(window.jQuery); } }(function ($) { /** * Spanish */ $.FE.LANGUAGE['es'] = { translation: { // Place holder "Type something": "Escriba algo", // Basic formatting "Bold": "Negrita", "Italic": "It\u00e1lica", "Underline": "Subrayado", "Strikethrough": "Tachado", // Main buttons "Insert": "Insertar", "Delete": "Borrar", "Cancel": "Cancelar", "OK": "Ok", "Back": "Atr\u00e1s", "Remove": "Quitar", "More": "M\u00e1s", "Update": "Actualizaci\u00f3n", "Style": "Estilo", // Font "Font Family": "Familia de fuentes", "Font Size": "Tama\u00f1o de fuente", // Colors "Colors": "Colores", "Background": "Fondo", "Text": "Texto", "HEX Color": "Color hexadecimal", // Paragraphs "Paragraph Format": "Formato de p\u00e1rrafo", "Normal": "Normal", "Code": "C\u00f3digo", "Heading 1": "Encabezado 1", "Heading 2": "Encabezado 2", "Heading 3": "Encabezado 3", "Heading 4": "Encabezado 4", // Style "Paragraph Style": "Estilo de p\u00e1rrafo", "Inline Style": "Estilo en l\u00ednea", // Alignment "Align": "Alinear", "Align Left": "Alinear a la izquierda", "Align Center": "Alinear al centro", "Align Right": "Alinear a la derecha", "Align Justify": "Justificar", "None": "Ninguno", // Lists "Ordered List": "Lista ordenada", "Unordered List": "Lista desordenada", // Indent "Decrease Indent": "Reducir sangr\u00eda", "Increase Indent": "Aumentar sangr\u00eda", // Links "Insert Link": "Insertar enlace", "Open in new tab": "Abrir en una nueva pesta\u00F1a", "Open Link": "Abrir enlace", "Edit Link": "Editar enlace", "Unlink": "Quitar enlace", "Choose Link": "Elegir enlace", // Images "Insert Image": "Insertar imagen", "Upload Image": "Cargar imagen", "By URL": "Por URL", "Browse": "Examinar", "Drop image": "Soltar la imagen", "or click": "o haga clic en", "Manage Images": "Administrar im\u00e1genes", "Loading": "Cargando", "Deleting": "Borrado", "Tags": "Etiquetas", "Are you sure? Image will be deleted.": "\u00bfEst\u00e1 seguro? Imagen ser\u00e1 borrada.", "Replace": "Reemplazar", "Uploading": "Carga", "Loading image": "Cargando imagen", "Display": "Mostrar", "Inline": "En l\u00ednea", "Break Text": "Romper texto", "Alternate Text": "Texto alternativo", "Change Size": "Cambiar tama\u00f1o", "Width": "Ancho", "Height": "Altura", "Something went wrong. Please try again.": "Algo sali\u00f3 mal. Por favor, vuelva a intentarlo.", "Image Caption": "Captura de imagen", "Advanced Edit": "Edición avanzada", // Video "Insert Video": "Insertar video", "Embedded Code": "C\u00f3digo incrustado", "Paste in a video URL": "Pegar en una URL de video", "Drop video": "Soltar video", "Your browser does not support HTML5 video.": "Su navegador no es compatible con video html5.", "Upload Video": "Subir video", // Tables "Insert Table": "Insertar tabla", "Table Header": "Encabezado de la tabla", "Remove Table": "Retire la tabla", "Table Style": "Estilo de tabla", "Horizontal Align": "Alinear horizontal", "Row": "Fila", "Insert row above": "Insertar fila antes", "Insert row below": "Insertar fila despu\u00e9s", "Delete row": "Eliminar fila", "Column": "Columna", "Insert column before": "Insertar columna antes", "Insert column after": "Insertar columna despu\u00e9s", "Delete column": "Eliminar columna", "Cell": "Celda", "Merge cells": "Combinar celdas", "Horizontal split": "Divisi\u00f3n horizontal", "Vertical split": "Divisi\u00f3n vertical", "Cell Background": "Fondo de la celda", "Vertical Align": "Alinear vertical", "Top": "Cima", "Middle": "Medio", "Bottom": "Del fondo", "Align Top": "Alinear a la parte superior", "Align Middle": "Alinear media", "Align Bottom": "Alinear abajo", "Cell Style": "Estilo de celda", // Files "Upload File": "Subir archivo", "Drop file": "Soltar archivo", // Emoticons "Emoticons": "Emoticones", "Grinning face": "Sonriendo cara", "Grinning face with smiling eyes": "Sonriendo cara con ojos sonrientes", "Face with tears of joy": "Cara con l\u00e1grimas de alegr\u00eda", "Smiling face with open mouth": "Cara sonriente con la boca abierta", "Smiling face with open mouth and smiling eyes": "Cara sonriente con la boca abierta y los ojos sonrientes", "Smiling face with open mouth and cold sweat": "Cara sonriente con la boca abierta y el sudor fr\u00edo", "Smiling face with open mouth and tightly-closed eyes": "Cara sonriente con la boca abierta y los ojos fuertemente cerrados", "Smiling face with halo": "Cara sonriente con halo", "Smiling face with horns": "Cara sonriente con cuernos", "Winking face": "Gui\u00f1o de la cara", "Smiling face with smiling eyes": "Cara sonriente con ojos sonrientes", "Face savoring delicious food": "Care saborear una deliciosa comida", "Relieved face": "Cara Aliviado", "Smiling face with heart-shaped eyes": "Cara sonriente con los ojos en forma de coraz\u00f3n", "Smiling face with sunglasses": "Cara sonriente con gafas de sol", "Smirking face": "Sonriendo cara", "Neutral face": "Cara neutral", "Expressionless face": "Rostro inexpresivo", "Unamused face": "Cara no divertido", "Face with cold sweat": "Cara con sudor fr\u00edo", "Pensive face": "Rostro pensativo", "Confused face": "Cara confusa", "Confounded face": "Cara Averg\u00fc\u00e9ncense", "Kissing face": "Besar la cara", "Face throwing a kiss": "Cara lanzando un beso", "Kissing face with smiling eyes": "Besar a cara con ojos sonrientes", "Kissing face with closed eyes": "Besar a cara con los ojos cerrados", "Face with stuck out tongue": "Cara con la lengua pegada", "Face with stuck out tongue and winking eye": "Cara con pegado a la lengua y los ojos gui\u00f1o", "Face with stuck out tongue and tightly-closed eyes": "Cara con la lengua pegada a y los ojos fuertemente cerrados", "Disappointed face": "Cara decepcionado", "Worried face": "Cara de preocupaci\u00f3n", "Angry face": "Cara enojada", "Pouting face": "Que pone mala cara", "Crying face": "Cara llorando", "Persevering face": "Perseverar cara", "Face with look of triumph": "Cara con expresi\u00f3n de triunfo", "Disappointed but relieved face": "Decepcionado pero el rostro aliviado", "Frowning face with open mouth": "Con el ce\u00f1o fruncido la cara con la boca abierta", "Anguished face": "Rostro angustiado", "Fearful face": "Cara Temeroso", "Weary face": "Rostro cansado", "Sleepy face": "Rostro so\u00f1oliento", "Tired face": "Rostro cansado", "Grimacing face": "Haciendo una mueca cara", "Loudly crying face": "Llorando en voz alta la cara", "Face with open mouth": "Cara con la boca abierta", "Hushed face": "Cara callada", "Face with open mouth and cold sweat": "Cara con la boca abierta y el sudor frío", "Face screaming in fear": "Cara gritando de miedo", "Astonished face": "Cara asombrosa", "Flushed face": "Cara enrojecida", "Sleeping face": "Rostro dormido", "Dizzy face": "Cara Mareado", "Face without mouth": "Cara sin boca", "Face with medical mask": "Cara con la m\u00e1scara m\u00e9dica", // Line breaker "Break": "Romper", // Math "Subscript": "Sub\u00edndice", "Superscript": "Super\u00edndice", // Full screen "Fullscreen": "Pantalla completa", // Horizontal line "Insert Horizontal Line": "Insertar l\u00ednea horizontal", // Clear formatting "Clear Formatting": "Quitar el formato", // Undo, redo "Undo": "Deshacer", "Redo": "Rehacer", // Select all "Select All": "Seleccionar todo", // Code view "Code View": "Vista de c\u00f3digo", // Quote "Quote": "Cita", "Increase": "Aumentar", "Decrease": "Disminuci\u00f3n", // Quick Insert "Quick Insert": "Inserci\u00f3n r\u00e1pida", // Spcial Characters "Special Characters": "Caracteres especiales", "Latin": "Latín", "Greek": "Griego", "Cyrillic": "Cirílico", "Punctuation": "Puntuación", "Currency": "Moneda", "Arrows": "Flechas", "Math": "Mates", "Misc": "Misc", // Print. "Print": "Impresión", // Spell Checker. "Spell Checker": "Corrector ortográfico", // Help "Help": "Ayuda", "Shortcuts": "Atajos", "Inline Editor": "Editor en línea", "Show the editor": "Mostrar al editor", "Common actions": "Acciones comunes", "Copy": "Dupdo", "Cut": "Cortar", "Paste": "Pegar", "Basic Formatting": "Formato básico", "Increase quote level": "Aumentar el nivel de cotización", "Decrease quote level": "Disminuir el nivel de cotización", "Image / Video": "Imagen / video", "Resize larger": "Redimensionar más grande", "Resize smaller": "Redimensionar más pequeño", "Table": "Mesa", "Select table cell": "Celda de tabla select", "Extend selection one cell": "Ampliar la selección una celda", "Extend selection one row": "Ampliar la selección una fila", "Navigation": "Navegación", "Focus popup / toolbar": "Focus popup / toolbar", "Return focus to previous position": "Volver al foco a la posición anterior", // Embed.ly "Embed URL": "URL de inserción", "Paste in a URL to embed": "Pegar en una url para incrustar", // Word Paste. "The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?": "El contenido pegado viene de un documento de Microsoft Word. ¿Quieres mantener el formato o limpiarlo?", "Keep": "Guardar", "Clean": "Limpiar", "Word Paste Detected": "Palabra detectada" }, direction: "ltr" }; }));
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v14.1.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Events = (function () { function Events() { } /** Everything has changed with the columns. Either complete new set of columns set, or user called setState()*/ Events.EVENT_COLUMN_EVERYTHING_CHANGED = 'columnEverythingChanged'; /** User has set in new columns. */ Events.EVENT_NEW_COLUMNS_LOADED = 'newColumnsLoaded'; /** The pivot mode flag was changed */ Events.EVENT_COLUMN_PIVOT_MODE_CHANGED = 'columnPivotModeChanged'; /** A row group column was added, removed or order changed. */ Events.EVENT_COLUMN_ROW_GROUP_CHANGED = 'columnRowGroupChanged'; /** A pivot column was added, removed or order changed. */ Events.EVENT_COLUMN_PIVOT_CHANGED = 'columnPivotChanged'; /** The list of grid columns has changed. */ Events.EVENT_GRID_COLUMNS_CHANGED = 'gridColumnsChanged'; /** A value column was added, removed or agg function was changed. */ Events.EVENT_COLUMN_VALUE_CHANGED = 'columnValueChanged'; /** A column was moved */ Events.EVENT_COLUMN_MOVED = 'columnMoved'; /** One or more columns was shown / hidden */ Events.EVENT_COLUMN_VISIBLE = 'columnVisible'; /** One or more columns was pinned / unpinned*/ Events.EVENT_COLUMN_PINNED = 'columnPinned'; /** A column group was opened / closed */ Events.EVENT_COLUMN_GROUP_OPENED = 'columnGroupOpened'; /** One or more columns was resized. If just one, the column in the event is set. */ Events.EVENT_COLUMN_RESIZED = 'columnResized'; /** The list of displayed columns has changed, can result from columns open / close, column move, pivot, group, etc */ Events.EVENT_DISPLAYED_COLUMNS_CHANGED = 'displayedColumnsChanged'; /** The list of virtual columns has changed, results from viewport changing */ Events.EVENT_VIRTUAL_COLUMNS_CHANGED = 'virtualColumnsChanged'; /** A row group was opened / closed */ Events.EVENT_ROW_GROUP_OPENED = 'rowGroupOpened'; /** The client has set new data into the grid */ Events.EVENT_ROW_DATA_CHANGED = 'rowDataChanged'; /** The client has updated data for the grid */ Events.EVENT_ROW_DATA_UPDATED = 'rowDataUpdated'; /** The client has set new floating data into the grid */ Events.EVENT_PINNED_ROW_DATA_CHANGED = 'pinnedRowDataChanged'; /** Range selection has changed */ Events.EVENT_RANGE_SELECTION_CHANGED = 'rangeSelectionChanged'; /** Model was updated - grid updates the drawn rows when this happens */ Events.EVENT_MODEL_UPDATED = 'modelUpdated'; Events.EVENT_CELL_CLICKED = 'cellClicked'; Events.EVENT_CELL_DOUBLE_CLICKED = 'cellDoubleClicked'; Events.EVENT_CELL_CONTEXT_MENU = 'cellContextMenu'; Events.EVENT_CELL_VALUE_CHANGED = 'cellValueChanged'; Events.EVENT_ROW_VALUE_CHANGED = 'rowValueChanged'; Events.EVENT_CELL_FOCUSED = 'cellFocused'; Events.EVENT_ROW_SELECTED = 'rowSelected'; Events.EVENT_SELECTION_CHANGED = 'selectionChanged'; Events.EVENT_CELL_MOUSE_OVER = 'cellMouseOver'; Events.EVENT_CELL_MOUSE_OUT = 'cellMouseOut'; /** 2 events for filtering. The grid LISTENS for filterChanged and afterFilterChanged */ Events.EVENT_FILTER_CHANGED = 'filterChanged'; /** Filter was change but not applied. Only useful if apply buttons are used in filters. */ Events.EVENT_FILTER_MODIFIED = 'filterModified'; Events.EVENT_SORT_CHANGED = 'sortChanged'; /** A row was removed from the dom, for any reason. Use to clean up resources (if any) used by the row. */ Events.EVENT_VIRTUAL_ROW_REMOVED = 'virtualRowRemoved'; Events.EVENT_ROW_CLICKED = 'rowClicked'; Events.EVENT_ROW_DOUBLE_CLICKED = 'rowDoubleClicked'; /** Gets called once after the grid has finished initialising. */ Events.EVENT_GRID_READY = 'gridReady'; /** Width of height of the main grid div has changed. Grid listens for this and does layout of grid if it's * changed, so always filling the space it was given. */ Events.EVENT_GRID_SIZE_CHANGED = 'gridSizeChanged'; /** The indexes of the rows rendered has changed, eg user has scrolled to a new vertical position. */ Events.EVENT_VIEWPORT_CHANGED = 'viewportChanged'; /** A column drag has started, either resizing a column or moving a column. */ Events.EVENT_DRAG_STARTED = 'dragStarted'; /** A column drag has stopped */ Events.EVENT_DRAG_STOPPED = 'dragStopped'; Events.EVENT_ROW_EDITING_STARTED = 'rowEditingStarted'; Events.EVENT_ROW_EDITING_STOPPED = 'rowEditingStopped'; Events.EVENT_CELL_EDITING_STARTED = 'cellEditingStarted'; Events.EVENT_CELL_EDITING_STOPPED = 'cellEditingStopped'; /** Main body of grid has scrolled, either horizontally or vertically */ Events.EVENT_BODY_SCROLL = 'bodyScroll'; /** The displayed page for pagination has changed. For example the data was filtered or sorted, * or the user has moved to a different page. */ Events.EVENT_PAGINATION_CHANGED = 'paginationChanged'; /** Only used by React, Angular 2+, Web Components, Aurelia and VueJS ag-Grid components * (not used if doing plain JavaScript or Angular 1.x). If the grid receives changes due * to bound properties, this event fires after the grid has finished processing the change. */ Events.EVENT_COMPONENT_STATE_CHANGED = 'componentStateChanged'; /** All items from here down are used internally by the grid, not intended for external use. */ // not documented, either experimental, or we just don't want users using an ddepending on them Events.EVENT_BODY_HEIGHT_CHANGED = 'bodyHeightChanged'; Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED = 'displayedColumnsWidthChanged'; Events.EVENT_SCROLL_VISIBILITY_CHANGED = 'scrollVisibilityChanged'; Events.EVENT_COLUMN_HOVER_CHANGED = 'columnHoverChanged'; Events.EVENT_FLASH_CELLS = 'flashCells'; // these are used for server side group and agg - only used by CS with Viewport Row Model - intention is // to design these better around server side functions and then release to general public when fully working with // all the row models. Events.EVENT_COLUMN_ROW_GROUP_CHANGE_REQUEST = 'columnRowGroupChangeRequest'; Events.EVENT_COLUMN_PIVOT_CHANGE_REQUEST = 'columnPivotChangeRequest'; Events.EVENT_COLUMN_VALUE_CHANGE_REQUEST = 'columnValueChangeRequest'; Events.EVENT_COLUMN_AGG_FUNC_CHANGE_REQUEST = 'columnAggFuncChangeRequest'; return Events; }()); exports.Events = Events;
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v14.1.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var csvCreator_1 = require("./csvCreator"); var rowRenderer_1 = require("./rendering/rowRenderer"); var headerRenderer_1 = require("./headerRendering/headerRenderer"); var filterManager_1 = require("./filter/filterManager"); var columnController_1 = require("./columnController/columnController"); var selectionController_1 = require("./selectionController"); var gridOptionsWrapper_1 = require("./gridOptionsWrapper"); var gridPanel_1 = require("./gridPanel/gridPanel"); var valueService_1 = require("./valueService/valueService"); var eventService_1 = require("./eventService"); var constants_1 = require("./constants"); var context_1 = require("./context/context"); var gridCore_1 = require("./gridCore"); var sortController_1 = require("./sortController"); var focusedCellController_1 = require("./focusedCellController"); var gridCell_1 = require("./entities/gridCell"); var utils_1 = require("./utils"); var cellRendererFactory_1 = require("./rendering/cellRendererFactory"); var cellEditorFactory_1 = require("./rendering/cellEditorFactory"); var paginationProxy_1 = require("./rowModels/paginationProxy"); var immutableService_1 = require("./rowModels/inMemory/immutableService"); var valueCache_1 = require("./valueService/valueCache"); var alignedGridsService_1 = require("./alignedGridsService"); var pinnedRowModel_1 = require("./rowModels/pinnedRowModel"); var GridApi = (function () { function GridApi() { } GridApi.prototype.init = function () { switch (this.rowModel.getType()) { case constants_1.Constants.ROW_MODEL_TYPE_IN_MEMORY: this.inMemoryRowModel = this.rowModel; break; case constants_1.Constants.ROW_MODEL_TYPE_INFINITE: this.infinitePageRowModel = this.rowModel; break; case constants_1.Constants.ROW_MODEL_TYPE_ENTERPRISE: this.enterpriseRowModel = this.rowModel; break; } }; /** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */ GridApi.prototype.__getAlignedGridService = function () { return this.alignedGridsService; }; GridApi.prototype.getDataAsCsv = function (params) { return this.csvCreator.getDataAsCsv(params); }; GridApi.prototype.exportDataAsCsv = function (params) { this.csvCreator.exportDataAsCsv(params); }; GridApi.prototype.getDataAsExcel = function (params) { if (!this.excelCreator) { console.warn('ag-Grid: Excel export is only available in ag-Grid Enterprise'); } return this.excelCreator.getDataAsExcelXml(params); }; GridApi.prototype.exportDataAsExcel = function (params) { if (!this.excelCreator) { console.warn('ag-Grid: Excel export is only available in ag-Grid Enterprise'); } this.excelCreator.exportDataAsExcel(params); }; GridApi.prototype.setEnterpriseDatasource = function (datasource) { if (this.gridOptionsWrapper.isRowModelEnterprise()) { // should really have an IEnterpriseRowModel interface, so we are not casting to any this.rowModel.setDatasource(datasource); } else { console.warn("ag-Grid: you can only use an enterprise datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_ENTERPRISE + "'"); } }; GridApi.prototype.setDatasource = function (datasource) { if (this.gridOptionsWrapper.isRowModelInfinite()) { this.rowModel.setDatasource(datasource); } else { console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_INFINITE + "'"); } }; GridApi.prototype.setViewportDatasource = function (viewportDatasource) { if (this.gridOptionsWrapper.isRowModelViewport()) { // this is bad coding, because it's using an interface that's exposed in the enterprise. // really we should create an interface in the core for viewportDatasource and let // the enterprise implement it, rather than casting to 'any' here this.rowModel.setViewportDatasource(viewportDatasource); } else { console.warn("ag-Grid: you can only use a viewport datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIEWPORT + "'"); } }; GridApi.prototype.setRowData = function (rowData) { if (this.gridOptionsWrapper.isRowModelDefault()) { if (this.gridOptionsWrapper.isDeltaRowDataMode()) { var _a = this.immutableService.createTransactionForRowData(rowData), transaction = _a[0], orderIdMap = _a[1]; this.inMemoryRowModel.updateRowData(transaction, orderIdMap); } else { this.selectionController.reset(); this.inMemoryRowModel.setRowData(rowData); } } else { console.log('cannot call setRowData unless using normal row model'); } }; // DEPRECATED GridApi.prototype.setFloatingTopRowData = function (rows) { console.warn('ag-Grid: since v12, api.setFloatingTopRowData() is now api.setPinnedTopRowData()'); this.setPinnedTopRowData(rows); }; // DEPRECATED GridApi.prototype.setFloatingBottomRowData = function (rows) { console.warn('ag-Grid: since v12, api.setFloatingBottomRowData() is now api.setPinnedBottomRowData()'); this.setPinnedBottomRowData(rows); }; // DEPRECATED GridApi.prototype.getFloatingTopRowCount = function () { console.warn('ag-Grid: since v12, api.getFloatingTopRowCount() is now api.getPinnedTopRowCount()'); return this.getPinnedTopRowCount(); }; // DEPRECATED GridApi.prototype.getFloatingBottomRowCount = function () { console.warn('ag-Grid: since v12, api.getFloatingBottomRowCount() is now api.getPinnedBottomRowCount()'); return this.getPinnedBottomRowCount(); }; // DEPRECATED GridApi.prototype.getFloatingTopRow = function (index) { console.warn('ag-Grid: since v12, api.getFloatingTopRow() is now api.getPinnedTopRow()'); return this.getPinnedTopRow(index); }; // DEPRECATED GridApi.prototype.getFloatingBottomRow = function (index) { console.warn('ag-Grid: since v12, api.getFloatingBottomRow() is now api.getPinnedBottomRow()'); return this.getPinnedBottomRow(index); }; GridApi.prototype.setPinnedTopRowData = function (rows) { this.pinnedRowModel.setPinnedTopRowData(rows); }; GridApi.prototype.setPinnedBottomRowData = function (rows) { this.pinnedRowModel.setPinnedBottomRowData(rows); }; GridApi.prototype.getPinnedTopRowCount = function () { return this.pinnedRowModel.getPinnedTopRowCount(); }; GridApi.prototype.getPinnedBottomRowCount = function () { return this.pinnedRowModel.getPinnedBottomRowCount(); }; GridApi.prototype.getPinnedTopRow = function (index) { return this.pinnedRowModel.getPinnedTopRow(index); }; GridApi.prototype.getPinnedBottomRow = function (index) { return this.pinnedRowModel.getPinnedBottomRow(index); }; GridApi.prototype.setColumnDefs = function (colDefs) { this.columnController.setColumnDefs(colDefs); }; GridApi.prototype.expireValueCache = function () { this.valueCache.expire(); }; GridApi.prototype.getVerticalPixelRange = function () { return this.gridPanel.getVerticalPixelRange(); }; GridApi.prototype.refreshToolPanel = function () { if (this.toolPanel) { this.toolPanel.refresh(); } }; GridApi.prototype.refreshCells = function (params) { if (params === void 0) { params = {}; } if (Array.isArray(params)) { // the old version of refreshCells() took an array of rowNodes for the first argument console.warn('since ag-Grid v11.1, refreshCells() now takes parameters, please see the documentation.'); return; } this.rowRenderer.refreshCells(params); }; GridApi.prototype.redrawRows = function (params) { if (params === void 0) { params = {}; } if (params && params.rowNodes) { this.rowRenderer.redrawRows(params.rowNodes); } else { this.rowRenderer.redrawAfterModelUpdate(); } }; GridApi.prototype.timeFullRedraw = function (count) { if (count === void 0) { count = 1; } var iterationCount = 0; var totalProcessing = 0; var totalReflow = 0; var that = this; doOneIteration(); function doOneIteration() { var start = (new Date()).getTime(); that.rowRenderer.redrawAfterModelUpdate(); var endProcessing = (new Date()).getTime(); setTimeout(function () { var endReflow = (new Date()).getTime(); var durationProcessing = endProcessing - start; var durationReflow = endReflow - endProcessing; console.log('duration: processing = ' + durationProcessing + 'ms, reflow = ' + durationReflow + 'ms'); iterationCount++; totalProcessing += durationProcessing; totalReflow += durationReflow; if (iterationCount < count) { // wait for 1s between tests setTimeout(doOneIteration, 1000); } else { finish(); } }, 0); } function finish() { console.log('tests complete. iteration count = ' + iterationCount); console.log('average processing = ' + (totalProcessing / iterationCount) + 'ms'); console.log('average reflow = ' + (totalReflow / iterationCount) + 'ms'); } }; // *** deprecated GridApi.prototype.refreshView = function () { console.warn('ag-Grid: since v11.1, refreshView() is deprecated, please call redrawRows() instead'); this.redrawRows(); }; // *** deprecated GridApi.prototype.refreshRows = function (rowNodes) { console.warn('since ag-Grid v11.1, refreshRows() is deprecated, please use refreshCells({rowNodes: rows}) or redrawRows({rowNodes: rows}) instead'); this.refreshCells({ rowNodes: rowNodes }); }; // *** deprecated GridApi.prototype.rowDataChanged = function (rows) { console.log('ag-Grid: rowDataChanged is deprecated, either call refreshView() to refresh everything, or call rowNode.setRowData(newData) to set value on a particular node'); this.redrawRows(); }; // *** deprecated GridApi.prototype.softRefreshView = function () { console.warn('ag-Grid: since v11.1, softRefreshView() is deprecated, call refreshCells(params) instead.'); this.refreshCells({ volatile: true }); }; // *** deprecated GridApi.prototype.refreshGroupRows = function () { console.warn('ag-Grid: since v11.1, refreshGroupRows() is no longer supported, call refreshCells() instead. ' + 'Because refreshCells() now does dirty checking, it will only refresh cells that have changed, so it should ' + 'not be necessary to only refresh the group rows.'); this.refreshCells(); }; GridApi.prototype.setFunctionsReadOnly = function (readOnly) { this.gridOptionsWrapper.setProperty('functionsReadOnly', readOnly); }; GridApi.prototype.refreshHeader = function () { this.headerRenderer.refreshHeader(); }; GridApi.prototype.isAnyFilterPresent = function () { return this.filterManager.isAnyFilterPresent(); }; GridApi.prototype.isAdvancedFilterPresent = function () { return this.filterManager.isAdvancedFilterPresent(); }; GridApi.prototype.isQuickFilterPresent = function () { return this.filterManager.isQuickFilterPresent(); }; GridApi.prototype.getModel = function () { return this.rowModel; }; GridApi.prototype.onGroupExpandedOrCollapsed = function (deprecated_refreshFromIndex) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('ag-Grid: cannot call onGroupExpandedOrCollapsed unless using normal row model'); } if (utils_1.Utils.exists(deprecated_refreshFromIndex)) { console.log('ag-Grid: api.onGroupExpandedOrCollapsed - refreshFromIndex parameter is not longer used, the grid will refresh all rows'); } // we don't really want the user calling this if one one rowNode was expanded, instead they should be // calling rowNode.setExpanded(boolean) - this way we do a 'keepRenderedRows=false' so that the whole // grid gets refreshed again - otherwise the row with the rowNodes that were changed won't get updated, // and thus the expand icon in the group cell won't get 'opened' or 'closed'. this.inMemoryRowModel.refreshModel({ step: constants_1.Constants.STEP_MAP }); }; GridApi.prototype.refreshInMemoryRowModel = function (step) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call refreshInMemoryRowModel unless using normal row model'); } var paramsStep = constants_1.Constants.STEP_EVERYTHING; var stepsMapped = { group: constants_1.Constants.STEP_EVERYTHING, filter: constants_1.Constants.STEP_FILTER, map: constants_1.Constants.STEP_MAP, aggregate: constants_1.Constants.STEP_AGGREGATE, sort: constants_1.Constants.STEP_SORT, pivot: constants_1.Constants.STEP_PIVOT }; if (utils_1.Utils.exists(step)) { paramsStep = stepsMapped[step]; } if (utils_1.Utils.missing(paramsStep)) { console.error("ag-Grid: invalid step " + step + ", available steps are " + Object.keys(stepsMapped).join(', ')); return; } var modelParams = { step: paramsStep, keepRenderedRows: true, animate: true, keepEditingRows: true }; this.inMemoryRowModel.refreshModel(modelParams); }; GridApi.prototype.getRowNode = function (id) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.warn('ag-Grid: cannot call getRowNode unless using normal row model'); return; } return this.inMemoryRowModel.getRowNode(id); }; GridApi.prototype.expandAll = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.warn('ag-Grid: cannot call expandAll unless using normal row model'); return; } this.inMemoryRowModel.expandOrCollapseAll(true); }; GridApi.prototype.collapseAll = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.warn('ag-Grid: cannot call collapseAll unless using normal row model'); return; } this.inMemoryRowModel.expandOrCollapseAll(false); }; GridApi.prototype.addVirtualRowListener = function (eventName, rowIndex, callback) { if (typeof eventName !== 'string') { console.log('ag-Grid: addVirtualRowListener is deprecated, please use addRenderedRowListener.'); } this.addRenderedRowListener(eventName, rowIndex, callback); }; GridApi.prototype.addRenderedRowListener = function (eventName, rowIndex, callback) { if (eventName === 'virtualRowSelected') { console.log('ag-Grid: event virtualRowSelected is deprecated, to register for individual row ' + 'selection events, add a listener directly to the row node.'); } this.rowRenderer.addRenderedRowListener(eventName, rowIndex, callback); }; GridApi.prototype.setQuickFilter = function (newFilter) { this.filterManager.setQuickFilter(newFilter); }; GridApi.prototype.selectIndex = function (index, tryMulti, suppressEvents) { console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } this.selectionController.selectIndex(index, tryMulti); }; GridApi.prototype.deselectIndex = function (index, suppressEvents) { if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } this.selectionController.deselectIndex(index); }; GridApi.prototype.selectNode = function (node, tryMulti, suppressEvents) { if (tryMulti === void 0) { tryMulti = false; } if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } node.setSelectedParams({ newValue: true, clearSelection: !tryMulti }); }; GridApi.prototype.deselectNode = function (node, suppressEvents) { if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } node.setSelectedParams({ newValue: false }); }; GridApi.prototype.selectAll = function () { this.selectionController.selectAllRowNodes(); }; GridApi.prototype.deselectAll = function () { this.selectionController.deselectAllRowNodes(); }; GridApi.prototype.selectAllFiltered = function () { this.selectionController.selectAllRowNodes(true); }; GridApi.prototype.deselectAllFiltered = function () { this.selectionController.deselectAllRowNodes(true); }; GridApi.prototype.recomputeAggregates = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call recomputeAggregates unless using normal row model'); } this.inMemoryRowModel.refreshModel({ step: constants_1.Constants.STEP_AGGREGATE }); }; GridApi.prototype.sizeColumnsToFit = function () { if (this.gridOptionsWrapper.isForPrint()) { console.warn('ag-grid: sizeColumnsToFit does not work when forPrint=true'); return; } this.gridPanel.sizeColumnsToFit(); }; GridApi.prototype.showLoadingOverlay = function () { this.gridPanel.showLoadingOverlay(); }; GridApi.prototype.showNoRowsOverlay = function () { this.gridPanel.showNoRowsOverlay(); }; GridApi.prototype.hideOverlay = function () { this.gridPanel.hideOverlay(); }; GridApi.prototype.isNodeSelected = function (node) { console.log('ag-Grid: no need to call api.isNodeSelected(), just call node.isSelected() instead'); return node.isSelected(); }; GridApi.prototype.getSelectedNodesById = function () { console.error('ag-Grid: since version 3.4, getSelectedNodesById no longer exists, use getSelectedNodes() instead'); return null; }; GridApi.prototype.getSelectedNodes = function () { return this.selectionController.getSelectedNodes(); }; GridApi.prototype.getSelectedRows = function () { return this.selectionController.getSelectedRows(); }; GridApi.prototype.getBestCostNodeSelection = function () { return this.selectionController.getBestCostNodeSelection(); }; GridApi.prototype.getRenderedNodes = function () { return this.rowRenderer.getRenderedNodes(); }; GridApi.prototype.ensureColIndexVisible = function (index) { console.warn('ag-Grid: ensureColIndexVisible(index) no longer supported, use ensureColumnVisible(colKey) instead.'); }; GridApi.prototype.ensureColumnVisible = function (key) { this.gridPanel.ensureColumnVisible(key); }; // Valid values for position are bottom, middle and top GridApi.prototype.ensureIndexVisible = function (index, position) { if (position === void 0) { position = 'top'; } this.gridPanel.ensureIndexVisible(index, position); }; // Valid values for position are bottom, middle and top GridApi.prototype.ensureNodeVisible = function (comparator, position) { if (position === void 0) { position = 'top'; } this.gridCore.ensureNodeVisible(comparator, position); }; GridApi.prototype.forEachLeafNode = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNode unless using normal row model'); } this.inMemoryRowModel.forEachLeafNode(callback); }; GridApi.prototype.forEachNode = function (callback) { this.rowModel.forEachNode(callback); }; GridApi.prototype.forEachNodeAfterFilter = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilter unless using normal row model'); } this.inMemoryRowModel.forEachNodeAfterFilter(callback); }; GridApi.prototype.forEachNodeAfterFilterAndSort = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilterAndSort unless using normal row model'); } this.inMemoryRowModel.forEachNodeAfterFilterAndSort(callback); }; GridApi.prototype.getFilterApiForColDef = function (colDef) { console.warn('ag-grid API method getFilterApiForColDef deprecated, use getFilterApi instead'); return this.getFilterInstance(colDef); }; GridApi.prototype.getFilterInstance = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return this.filterManager.getFilterComponent(column).resolveNow(null, function (filterComp) { return filterComp; }); } }; GridApi.prototype.getFilterApi = function (key) { console.warn('ag-Grid: getFilterApi is deprecated, use getFilterInstance instead'); return this.getFilterInstance(key); }; GridApi.prototype.destroyFilter = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return this.filterManager.destroyFilter(column); } }; GridApi.prototype.getColumnDef = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return column.getColDef(); } else { return null; } }; GridApi.prototype.onFilterChanged = function () { this.filterManager.onFilterChanged(); }; GridApi.prototype.onSortChanged = function () { this.sortController.onSortChanged(); }; GridApi.prototype.setSortModel = function (sortModel) { this.sortController.setSortModel(sortModel); }; GridApi.prototype.getSortModel = function () { return this.sortController.getSortModel(); }; GridApi.prototype.setFilterModel = function (model) { this.filterManager.setFilterModel(model); }; GridApi.prototype.getFilterModel = function () { return this.filterManager.getFilterModel(); }; GridApi.prototype.getFocusedCell = function () { return this.focusedCellController.getFocusedCell(); }; GridApi.prototype.clearFocusedCell = function () { return this.focusedCellController.clearFocusedCell(); }; GridApi.prototype.setFocusedCell = function (rowIndex, colKey, floating) { this.focusedCellController.setFocusedCell(rowIndex, colKey, floating, true); }; GridApi.prototype.setHeaderHeight = function (headerHeight) { this.gridOptionsWrapper.setProperty(gridOptionsWrapper_1.GridOptionsWrapper.PROP_HEADER_HEIGHT, headerHeight); this.doLayout(); }; GridApi.prototype.setGroupHeaderHeight = function (headerHeight) { this.gridOptionsWrapper.setProperty(gridOptionsWrapper_1.GridOptionsWrapper.PROP_GROUP_HEADER_HEIGHT, headerHeight); this.doLayout(); }; GridApi.prototype.setFloatingFiltersHeight = function (headerHeight) { this.gridOptionsWrapper.setProperty(gridOptionsWrapper_1.GridOptionsWrapper.PROP_FLOATING_FILTERS_HEIGHT, headerHeight); this.doLayout(); }; GridApi.prototype.setPivotGroupHeaderHeight = function (headerHeight) { this.gridOptionsWrapper.setProperty(gridOptionsWrapper_1.GridOptionsWrapper.PROP_PIVOT_GROUP_HEADER_HEIGHT, headerHeight); this.doLayout(); }; GridApi.prototype.setPivotHeaderHeight = function (headerHeight) { this.gridOptionsWrapper.setProperty(gridOptionsWrapper_1.GridOptionsWrapper.PROP_PIVOT_HEADER_HEIGHT, headerHeight); this.doLayout(); }; GridApi.prototype.showToolPanel = function (show) { this.gridCore.showToolPanel(show); }; GridApi.prototype.isToolPanelShowing = function () { return this.gridCore.isToolPanelShowing(); }; GridApi.prototype.doLayout = function () { this.gridCore.doLayout(); }; GridApi.prototype.resetRowHeights = function () { if (utils_1.Utils.exists(this.inMemoryRowModel)) { this.inMemoryRowModel.resetRowHeights(); } }; GridApi.prototype.setGroupRemoveSingleChildren = function (value) { this.gridOptionsWrapper.setProperty(gridOptionsWrapper_1.GridOptionsWrapper.PROP_GROUP_REMOVE_SINGLE_CHILDREN, value); }; GridApi.prototype.setGroupRemoveLowestSingleChildren = function (value) { this.gridOptionsWrapper.setProperty(gridOptionsWrapper_1.GridOptionsWrapper.PROP_GROUP_REMOVE_LOWEST_SINGLE_CHILDREN, value); }; GridApi.prototype.onRowHeightChanged = function () { if (utils_1.Utils.exists(this.inMemoryRowModel)) { this.inMemoryRowModel.onRowHeightChanged(); } }; GridApi.prototype.getValue = function (colKey, rowNode) { var column = this.columnController.getPrimaryColumn(colKey); if (utils_1.Utils.missing(column)) { column = this.columnController.getGridColumn(colKey); } if (utils_1.Utils.missing(column)) { return null; } else { return this.valueService.getValue(column, rowNode); } }; GridApi.prototype.addEventListener = function (eventType, listener) { var async = this.gridOptionsWrapper.useAsyncEvents(); this.eventService.addEventListener(eventType, listener, async); }; GridApi.prototype.addGlobalListener = function (listener) { var async = this.gridOptionsWrapper.useAsyncEvents(); this.eventService.addGlobalListener(listener, async); }; GridApi.prototype.removeEventListener = function (eventType, listener) { this.eventService.removeEventListener(eventType, listener); }; GridApi.prototype.removeGlobalListener = function (listener) { this.eventService.removeGlobalListener(listener); }; GridApi.prototype.dispatchEvent = function (event) { this.eventService.dispatchEvent(event); }; GridApi.prototype.destroy = function () { this.context.destroy(); }; GridApi.prototype.resetQuickFilter = function () { this.rowModel.forEachNode(function (node) { return node.quickFilterAggregateText = null; }); }; GridApi.prototype.getRangeSelections = function () { if (this.rangeController) { return this.rangeController.getCellRanges(); } else { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); return null; } }; GridApi.prototype.camelCaseToHumanReadable = function (camelCase) { return utils_1.Utils.camelCaseToHumanText(camelCase); }; GridApi.prototype.addRangeSelection = function (rangeSelection) { if (!this.rangeController) { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); } this.rangeController.addRange(rangeSelection); }; GridApi.prototype.clearRangeSelection = function () { if (!this.rangeController) { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); } this.rangeController.clearSelection(); }; GridApi.prototype.copySelectedRowsToClipboard = function (includeHeader, columnKeys) { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copySelectedRowsToClipboard(includeHeader, columnKeys); }; GridApi.prototype.copySelectedRangeToClipboard = function (includeHeader) { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copySelectedRangeToClipboard(includeHeader); }; GridApi.prototype.copySelectedRangeDown = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copyRangeDown(); }; GridApi.prototype.showColumnMenuAfterButtonClick = function (colKey, buttonElement) { var column = this.columnController.getPrimaryColumn(colKey); this.menuFactory.showMenuAfterButtonClick(column, buttonElement); }; GridApi.prototype.showColumnMenuAfterMouseClick = function (colKey, mouseEvent) { var column = this.columnController.getPrimaryColumn(colKey); this.menuFactory.showMenuAfterMouseEvent(column, mouseEvent); }; GridApi.prototype.tabToNextCell = function () { return this.rowRenderer.tabToNextCell(false); }; GridApi.prototype.tabToPreviousCell = function () { return this.rowRenderer.tabToNextCell(true); }; GridApi.prototype.stopEditing = function (cancel) { if (cancel === void 0) { cancel = false; } this.rowRenderer.stopEditing(cancel); }; GridApi.prototype.startEditingCell = function (params) { var column = this.columnController.getGridColumn(params.colKey); if (!column) { console.warn("ag-Grid: no column found for " + params.colKey); return; } var gridCellDef = { rowIndex: params.rowIndex, floating: null, column: column }; var gridCell = new gridCell_1.GridCell(gridCellDef); this.gridPanel.ensureIndexVisible(params.rowIndex); this.rowRenderer.startEditingCell(gridCell, params.keyPress, params.charPress); }; GridApi.prototype.addAggFunc = function (key, aggFunc) { if (this.aggFuncService) { this.aggFuncService.addAggFunc(key, aggFunc); } }; GridApi.prototype.addAggFuncs = function (aggFuncs) { if (this.aggFuncService) { this.aggFuncService.addAggFuncs(aggFuncs); } }; GridApi.prototype.clearAggFuncs = function () { if (this.aggFuncService) { this.aggFuncService.clear(); } }; GridApi.prototype.updateRowData = function (rowDataTransaction) { var res = null; if (this.inMemoryRowModel) { res = this.inMemoryRowModel.updateRowData(rowDataTransaction); } else if (this.infinitePageRowModel) { this.infinitePageRowModel.updateRowData(rowDataTransaction); } else { console.error('ag-Grid: updateRowData() only works with InMemoryRowModel and InfiniteRowModel.'); } // do change detection for all present cells if (!this.gridOptionsWrapper.isSuppressChangeDetection()) { this.rowRenderer.refreshCells(); } return res; }; GridApi.prototype.insertItemsAtIndex = function (index, items, skipRefresh) { if (skipRefresh === void 0) { skipRefresh = false; } console.warn('ag-Grid: insertItemsAtIndex() is deprecated, use updateRowData(transaction) instead.'); this.updateRowData({ add: items, addIndex: index, update: null, remove: null }); }; GridApi.prototype.removeItems = function (rowNodes, skipRefresh) { if (skipRefresh === void 0) { skipRefresh = false; } console.warn('ag-Grid: removeItems() is deprecated, use updateRowData(transaction) instead.'); var dataToRemove = rowNodes.map(function (rowNode) { return rowNode.data; }); this.updateRowData({ add: null, addIndex: null, update: null, remove: dataToRemove }); }; GridApi.prototype.addItems = function (items, skipRefresh) { if (skipRefresh === void 0) { skipRefresh = false; } console.warn('ag-Grid: addItems() is deprecated, use updateRowData(transaction) instead.'); this.updateRowData({ add: items, addIndex: null, update: null, remove: null }); }; GridApi.prototype.refreshVirtualPageCache = function () { console.warn('ag-Grid: refreshVirtualPageCache() is now called refreshInfiniteCache(), please call refreshInfiniteCache() instead'); this.refreshInfiniteCache(); }; GridApi.prototype.refreshInfinitePageCache = function () { console.warn('ag-Grid: refreshInfinitePageCache() is now called refreshInfiniteCache(), please call refreshInfiniteCache() instead'); this.refreshInfiniteCache(); }; GridApi.prototype.refreshInfiniteCache = function () { if (this.infinitePageRowModel) { this.infinitePageRowModel.refreshCache(); } else { console.warn("ag-Grid: api.refreshInfiniteCache is only available when rowModelType='infinite'."); } }; GridApi.prototype.purgeVirtualPageCache = function () { console.warn('ag-Grid: purgeVirtualPageCache() is now called purgeInfiniteCache(), please call purgeInfiniteCache() instead'); this.purgeInfinitePageCache(); }; GridApi.prototype.purgeInfinitePageCache = function () { console.warn('ag-Grid: purgeInfinitePageCache() is now called purgeInfiniteCache(), please call purgeInfiniteCache() instead'); this.purgeInfiniteCache(); }; GridApi.prototype.purgeInfiniteCache = function () { if (this.infinitePageRowModel) { this.infinitePageRowModel.purgeCache(); } else { console.warn("ag-Grid: api.purgeInfiniteCache is only available when rowModelType='infinite'."); } }; GridApi.prototype.purgeEnterpriseCache = function (route) { if (this.enterpriseRowModel) { this.enterpriseRowModel.purgeCache(route); } else { console.warn("ag-Grid: api.purgeEnterpriseCache is only available when rowModelType='enterprise'."); } }; GridApi.prototype.getVirtualRowCount = function () { console.warn('ag-Grid: getVirtualRowCount() is now called getInfiniteRowCount(), please call getInfiniteRowCount() instead'); return this.getInfiniteRowCount(); }; GridApi.prototype.getInfiniteRowCount = function () { if (this.infinitePageRowModel) { return this.infinitePageRowModel.getVirtualRowCount(); } else { console.warn("ag-Grid: api.getVirtualRowCount is only available when rowModelType='virtual'."); } }; GridApi.prototype.isMaxRowFound = function () { if (this.infinitePageRowModel) { return this.infinitePageRowModel.isMaxRowFound(); } else { console.warn("ag-Grid: api.isMaxRowFound is only available when rowModelType='virtual'."); } }; GridApi.prototype.setVirtualRowCount = function (rowCount, maxRowFound) { console.warn('ag-Grid: setVirtualRowCount() is now called setInfiniteRowCount(), please call setInfiniteRowCount() instead'); this.setInfiniteRowCount(rowCount, maxRowFound); }; GridApi.prototype.setInfiniteRowCount = function (rowCount, maxRowFound) { if (this.infinitePageRowModel) { this.infinitePageRowModel.setVirtualRowCount(rowCount, maxRowFound); } else { console.warn("ag-Grid: api.setVirtualRowCount is only available when rowModelType='virtual'."); } }; GridApi.prototype.getVirtualPageState = function () { console.warn('ag-Grid: getVirtualPageState() is now called getCacheBlockState(), please call getCacheBlockState() instead'); return this.getCacheBlockState(); }; GridApi.prototype.getInfinitePageState = function () { console.warn('ag-Grid: getInfinitePageState() is now called getCacheBlockState(), please call getCacheBlockState() instead'); return this.getCacheBlockState(); }; GridApi.prototype.getCacheBlockState = function () { if (this.infinitePageRowModel) { return this.infinitePageRowModel.getBlockState(); } else if (this.enterpriseRowModel) { return this.enterpriseRowModel.getBlockState(); } else { console.warn("ag-Grid: api.getCacheBlockState() is only available when rowModelType='infinite' or rowModelType='enterprise'."); } }; GridApi.prototype.checkGridSize = function () { this.gridPanel.setBodyAndHeaderHeights(); }; GridApi.prototype.getFirstRenderedRow = function () { console.log('in ag-Grid v12, getFirstRenderedRow() was renamed to getFirstDisplayedRow()'); return this.getFirstDisplayedRow(); }; GridApi.prototype.getFirstDisplayedRow = function () { return this.rowRenderer.getFirstVirtualRenderedRow(); }; GridApi.prototype.getLastRenderedRow = function () { console.log('in ag-Grid v12, getLastRenderedRow() was renamed to getLastDisplayedRow()'); return this.getLastDisplayedRow(); }; GridApi.prototype.getLastDisplayedRow = function () { return this.rowRenderer.getLastVirtualRenderedRow(); }; GridApi.prototype.getDisplayedRowAtIndex = function (index) { return this.rowModel.getRow(index); }; GridApi.prototype.getDisplayedRowCount = function () { return this.rowModel.getRowCount(); }; GridApi.prototype.paginationIsLastPageFound = function () { return this.paginationProxy.isLastPageFound(); }; GridApi.prototype.paginationGetPageSize = function () { return this.paginationProxy.getPageSize(); }; GridApi.prototype.paginationSetPageSize = function (size) { this.gridOptionsWrapper.setProperty('paginationPageSize', size); }; GridApi.prototype.paginationGetCurrentPage = function () { return this.paginationProxy.getCurrentPage(); }; GridApi.prototype.paginationGetTotalPages = function () { return this.paginationProxy.getTotalPages(); }; GridApi.prototype.paginationGetRowCount = function () { return this.paginationProxy.getTotalRowCount(); }; GridApi.prototype.paginationGoToNextPage = function () { this.paginationProxy.goToNextPage(); }; GridApi.prototype.paginationGoToPreviousPage = function () { this.paginationProxy.goToPreviousPage(); }; GridApi.prototype.paginationGoToFirstPage = function () { this.paginationProxy.goToFirstPage(); }; GridApi.prototype.paginationGoToLastPage = function () { this.paginationProxy.goToLastPage(); }; GridApi.prototype.paginationGoToPage = function (page) { this.paginationProxy.goToPage(page); }; __decorate([ context_1.Autowired('immutableService'), __metadata("design:type", immutableService_1.ImmutableService) ], GridApi.prototype, "immutableService", void 0); __decorate([ context_1.Autowired('csvCreator'), __metadata("design:type", csvCreator_1.CsvCreator) ], GridApi.prototype, "csvCreator", void 0); __decorate([ context_1.Optional('excelCreator'), __metadata("design:type", Object) ], GridApi.prototype, "excelCreator", void 0); __decorate([ context_1.Autowired('gridCore'), __metadata("design:type", gridCore_1.GridCore) ], GridApi.prototype, "gridCore", void 0); __decorate([ context_1.Autowired('rowRenderer'), __metadata("design:type", rowRenderer_1.RowRenderer) ], GridApi.prototype, "rowRenderer", void 0); __decorate([ context_1.Autowired('headerRenderer'), __metadata("design:type", headerRenderer_1.HeaderRenderer) ], GridApi.prototype, "headerRenderer", void 0); __decorate([ context_1.Autowired('filterManager'), __metadata("design:type", filterManager_1.FilterManager) ], GridApi.prototype, "filterManager", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], GridApi.prototype, "columnController", void 0); __decorate([ context_1.Autowired('selectionController'), __metadata("design:type", selectionController_1.SelectionController) ], GridApi.prototype, "selectionController", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], GridApi.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata("design:type", gridPanel_1.GridPanel) ], GridApi.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('valueService'), __metadata("design:type", valueService_1.ValueService) ], GridApi.prototype, "valueService", void 0); __decorate([ context_1.Autowired('alignedGridsService'), __metadata("design:type", alignedGridsService_1.AlignedGridsService) ], GridApi.prototype, "alignedGridsService", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], GridApi.prototype, "eventService", void 0); __decorate([ context_1.Autowired('pinnedRowModel'), __metadata("design:type", pinnedRowModel_1.PinnedRowModel) ], GridApi.prototype, "pinnedRowModel", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], GridApi.prototype, "context", void 0); __decorate([ context_1.Autowired('rowModel'), __metadata("design:type", Object) ], GridApi.prototype, "rowModel", void 0); __decorate([ context_1.Autowired('sortController'), __metadata("design:type", sortController_1.SortController) ], GridApi.prototype, "sortController", void 0); __decorate([ context_1.Autowired('paginationProxy'), __metadata("design:type", paginationProxy_1.PaginationProxy) ], GridApi.prototype, "paginationProxy", void 0); __decorate([ context_1.Autowired('focusedCellController'), __metadata("design:type", focusedCellController_1.FocusedCellController) ], GridApi.prototype, "focusedCellController", void 0); __decorate([ context_1.Optional('rangeController'), __metadata("design:type", Object) ], GridApi.prototype, "rangeController", void 0); __decorate([ context_1.Optional('clipboardService'), __metadata("design:type", Object) ], GridApi.prototype, "clipboardService", void 0); __decorate([ context_1.Optional('aggFuncService'), __metadata("design:type", Object) ], GridApi.prototype, "aggFuncService", void 0); __decorate([ context_1.Autowired('menuFactory'), __metadata("design:type", Object) ], GridApi.prototype, "menuFactory", void 0); __decorate([ context_1.Autowired('cellRendererFactory'), __metadata("design:type", cellRendererFactory_1.CellRendererFactory) ], GridApi.prototype, "cellRendererFactory", void 0); __decorate([ context_1.Autowired('cellEditorFactory'), __metadata("design:type", cellEditorFactory_1.CellEditorFactory) ], GridApi.prototype, "cellEditorFactory", void 0); __decorate([ context_1.Autowired('valueCache'), __metadata("design:type", valueCache_1.ValueCache) ], GridApi.prototype, "valueCache", void 0); __decorate([ context_1.Optional('toolPanel'), __metadata("design:type", Object) ], GridApi.prototype, "toolPanel", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], GridApi.prototype, "init", null); GridApi = __decorate([ context_1.Bean('gridApi') ], GridApi); return GridApi; }()); exports.GridApi = GridApi;
/* PowerPoint specific API library */ /* Version: 15.0.4420.1017 Build Time: 03/31/2014 */ /* Copyright (c) Microsoft Corporation. All rights reserved. */ /* Your use of this file is governed by the Microsoft Services Agreement http://go.microsoft.com/fwlink/?LinkId=266419. */ OSF.ClientMode={ ReadWrite: 0, ReadOnly: 1 } OSF.DDA.RichInitializationReason={ 1: Microsoft.Office.WebExtension.InitializationReason.Inserted, 2: Microsoft.Office.WebExtension.InitializationReason.DocumentOpened }; Microsoft.Office.WebExtension.FileType={ Text: "text", Compressed: "compressed" }; OSF.DDA.RichClientSettingsManager={ read: function OSF_DDA_RichClientSettingsManager$Read(onCalling, onReceiving) { var keys=[]; var values=[]; if (onCalling) { onCalling(); } window.external.GetContext().GetSettings().Read(keys, values); if (onReceiving) { onReceiving(); } var serializedSettings={}; for (var index=0; index < keys.length; index++) { serializedSettings[keys[index]]=values[index]; } return serializedSettings; }, write: function OSF_DDA_RichClientSettingsManager$Write(serializedSettings, overwriteIfStale, onCalling, onReceiving) { var keys=[]; var values=[]; for (var key in serializedSettings) { keys.push(key); values.push(serializedSettings[key]); } if (onCalling) { onCalling(); } window.external.GetContext().GetSettings().Write(keys, values); if (onReceiving) { onReceiving(); } } }; OSF.DDA.DispIdHost.getRichClientDelegateMethods=function (actionId) { var delegateMethods={}; delegateMethods[OSF.DDA.DispIdHost.Delegates.ExecuteAsync]=OSF.DDA.SafeArray.Delegate.executeAsync; delegateMethods[OSF.DDA.DispIdHost.Delegates.RegisterEventAsync]=OSF.DDA.SafeArray.Delegate.registerEventAsync; delegateMethods[OSF.DDA.DispIdHost.Delegates.UnregisterEventAsync]=OSF.DDA.SafeArray.Delegate.unregisterEventAsync; function getSettingsExecuteMethod(hostDelegateMethod) { return function (args) { var status, response; try { response=hostDelegateMethod(args.hostCallArgs, args.onCalling, args.onReceiving); status=OSF.DDA.ErrorCodeManager.errorCodes.ooeSuccess; } catch (ex) { status=OSF.DDA.ErrorCodeManager.errorCodes.ooeInternalError; response={ name : Strings.OfficeOM.L_InternalError, message : ex }; } if (args.onComplete) { args.onComplete(status, response); } }; } function readSerializedSettings(hostCallArgs, onCalling, onReceiving) { return OSF.DDA.RichClientSettingsManager.read(onCalling, onReceiving); } function writeSerializedSettings(hostCallArgs, onCalling, onReceiving) { return OSF.DDA.RichClientSettingsManager.write( hostCallArgs[OSF.DDA.SettingsManager.SerializedSettings], hostCallArgs[Microsoft.Office.WebExtension.Parameters.OverwriteIfStale], onCalling, onReceiving ); } switch (actionId) { case OSF.DDA.AsyncMethodNames.RefreshAsync.id: delegateMethods[OSF.DDA.DispIdHost.Delegates.ExecuteAsync]=getSettingsExecuteMethod(readSerializedSettings); break; case OSF.DDA.AsyncMethodNames.SaveAsync.id: delegateMethods[OSF.DDA.DispIdHost.Delegates.ExecuteAsync]=getSettingsExecuteMethod(writeSerializedSettings); break; default: break; } return delegateMethods; } OSF.DDA.File=function OSF_DDA_File(handle, fileSize, sliceSize) { OSF.OUtil.defineEnumerableProperties(this, { "size": { value: fileSize }, "sliceCount": { value: Math.ceil(fileSize / sliceSize) } }); var privateState={}; privateState[OSF.DDA.FileProperties.Handle]=handle; privateState[OSF.DDA.FileProperties.SliceSize]=sliceSize; var am=OSF.DDA.AsyncMethodNames; OSF.DDA.DispIdHost.addAsyncMethods( this, [ am.GetDocumentCopyChunkAsync, am.ReleaseDocumentCopyAsync ], privateState ); } OSF.DDA.FileSliceOffset="fileSliceoffset"; OSF.DDA.CustomXmlParts=function OSF_DDA_CustomXmlParts() { this._eventDispatches=[]; var am=OSF.DDA.AsyncMethodNames; OSF.DDA.DispIdHost.addAsyncMethods(this, [ am.AddDataPartAsync, am.GetDataPartByIdAsync, am.GetDataPartsByNameSpaceAsync ]); }; OSF.DDA.CustomXmlPart=function OSF_DDA_CustomXmlPart(customXmlParts, id, builtIn) { OSF.OUtil.defineEnumerableProperties(this, { "builtIn": { value: builtIn }, "id": { value: id }, "namespaceManager": { value: new OSF.DDA.CustomXmlPrefixMappings(id) } }); var am=OSF.DDA.AsyncMethodNames; OSF.DDA.DispIdHost.addAsyncMethods(this, [ am.DeleteDataPartAsync, am.GetPartNodesAsync, am.GetPartXmlAsync ]); var customXmlPartEventDispatches=customXmlParts._eventDispatches; var dispatch=customXmlPartEventDispatches[id]; if (!dispatch) { var et=Microsoft.Office.WebExtension.EventType; dispatch=new OSF.EventDispatch([ et.DataNodeDeleted, et.DataNodeInserted, et.DataNodeReplaced ]); customXmlPartEventDispatches[id]=dispatch; } OSF.DDA.DispIdHost.addEventSupport(this, dispatch); }; OSF.DDA.CustomXmlPrefixMappings=function OSF_DDA_CustomXmlPrefixMappings(partId) { var am=OSF.DDA.AsyncMethodNames; OSF.DDA.DispIdHost.addAsyncMethods( this, [ am.AddDataPartNamespaceAsync, am.GetDataPartNamespaceAsync, am.GetDataPartPrefixAsync ], partId ); }; OSF.DDA.CustomXmlNode=function OSF_DDA_CustomXmlNode(handle, nodeType, ns, baseName) { OSF.OUtil.defineEnumerableProperties(this, { "baseName": { value: baseName }, "namespaceUri": { value: ns }, "nodeType": { value: nodeType } }); var am=OSF.DDA.AsyncMethodNames; OSF.DDA.DispIdHost.addAsyncMethods( this, [ am.GetRelativeNodesAsync, am.GetNodeValueAsync, am.GetNodeXmlAsync, am.SetNodeValueAsync, am.SetNodeXmlAsync ], handle ); }; OSF.DDA.NodeInsertedEventArgs=function OSF_DDA_NodeInsertedEventArgs(newNode, inUndoRedo) { OSF.OUtil.defineEnumerableProperties(this, { "type": { value: Microsoft.Office.WebExtension.EventType.DataNodeInserted }, "newNode": { value: newNode }, "inUndoRedo": { value: inUndoRedo } }); }; OSF.DDA.NodeReplacedEventArgs=function OSF_DDA_NodeReplacedEventArgs(oldNode, newNode, inUndoRedo) { OSF.OUtil.defineEnumerableProperties(this, { "type": { value: Microsoft.Office.WebExtension.EventType.DataNodeReplaced }, "oldNode": { value: oldNode }, "newNode": { value: newNode }, "inUndoRedo": { value: inUndoRedo } }); }; OSF.DDA.NodeDeletedEventArgs=function OSF_DDA_NodeDeletedEventArgs(oldNode, oldNextSibling, inUndoRedo) { OSF.OUtil.defineEnumerableProperties(this, { "type": { value: Microsoft.Office.WebExtension.EventType.DataNodeDeleted }, "oldNode": { value: oldNode }, "oldNextSibling": { value: oldNextSibling }, "inUndoRedo": { value: inUndoRedo } }); }; OSF.OUtil.redefineList(Microsoft.Office.WebExtension.FileType, { Compressed: "compressed" }); OSF.OUtil.redefineList(Microsoft.Office.WebExtension.CoercionType, { Text: "text" }); OSF.OUtil.redefineList(Microsoft.Office.WebExtension.EventType, { DocumentSelectionChanged: "documentSelectionChanged" }); OSF.OUtil.redefineList(Microsoft.Office.WebExtension.ValueFormat, { Unformatted: "unformatted" }); OSF.OUtil.redefineList(Microsoft.Office.WebExtension.FilterType, { All: "all" }); delete Microsoft.Office.WebExtension.BindingType; delete Microsoft.Office.WebExtension.select; OSF.OUtil.setNamespace("SafeArray", OSF.DDA); OSF.DDA.SafeArray.Response={ Status: 0, Payload: 1 }; OSF.DDA.SafeArray.UniqueArguments={ Offset: "offset", Run: "run", BindingSpecificData: "bindingSpecificData", MergedCellGuid: "{66e7831f-81b2-42e2-823c-89e872d541b3}" }; OSF.OUtil.setNamespace("Delegate", OSF.DDA.SafeArray); OSF.DDA.SafeArray.Delegate.SpecialProcessor=function OSF_DDA_SafeArray_Delegate_SpecialProcessor() { function _2DVBArrayToJaggedArray(vbArr) { var ret; try { var rows=vbArr.ubound(1); var cols=vbArr.ubound(2); vbArr=vbArr.toArray(); if (rows==1 && cols==1) { ret=[vbArr]; } else { ret=[]; for (var row=0; row < rows; row++) { var rowArr=[]; for (var col=0; col < cols; col++) { var datum=vbArr[row * cols+col]; if (datum !=OSF.DDA.SafeArray.UniqueArguments.MergedCellGuid) { rowArr.push(datum); } } if (rowArr.length > 0) { ret.push(rowArr); } } } } catch (ex) { } return ret; } var complexTypes=[ OSF.DDA.PropertyDescriptors.FileProperties, OSF.DDA.PropertyDescriptors.FileSliceProperties, OSF.DDA.PropertyDescriptors.BindingProperties, OSF.DDA.SafeArray.UniqueArguments.BindingSpecificData, OSF.DDA.SafeArray.UniqueArguments.Offset, OSF.DDA.SafeArray.UniqueArguments.Run, OSF.DDA.PropertyDescriptors.Subset, OSF.DDA.PropertyDescriptors.DataPartProperties, OSF.DDA.PropertyDescriptors.DataNodeProperties, OSF.DDA.EventDescriptors.BindingSelectionChangedEvent, OSF.DDA.EventDescriptors.DataNodeInsertedEvent, OSF.DDA.EventDescriptors.DataNodeReplacedEvent, OSF.DDA.EventDescriptors.DataNodeDeletedEvent, OSF.DDA.DataNodeEventProperties.OldNode, OSF.DDA.DataNodeEventProperties.NewNode, OSF.DDA.DataNodeEventProperties.NextSiblingNode ]; var dynamicTypes={}; dynamicTypes[Microsoft.Office.WebExtension.Parameters.Data]=(function () { var tableRows=0; var tableHeaders=1; return { toHost: function OSF_DDA_SafeArray_Delegate_SpecialProcessor_Data$toHost(data) { if (typeof data !="string" && data[OSF.DDA.TableDataProperties.TableRows] !==undefined) { var tableData=[]; tableData[tableRows]=data[OSF.DDA.TableDataProperties.TableRows]; tableData[tableHeaders]=data[OSF.DDA.TableDataProperties.TableHeaders]; data=tableData; } return data; }, fromHost: function OSF_DDA_SafeArray_Delegate_SpecialProcessor_Data$fromHost(hostArgs) { var ret; if (hostArgs.toArray) { var dimensions=hostArgs.dimensions(); if(dimensions===2) { ret=_2DVBArrayToJaggedArray(hostArgs); } else { var array=hostArgs.toArray(); if(array.length===2 && ((array[0] !=null && array[0].toArray) || (array[1] !=null && array[1].toArray))) { ret={}; ret[OSF.DDA.TableDataProperties.TableRows]=_2DVBArrayToJaggedArray(array[tableRows]); ret[OSF.DDA.TableDataProperties.TableHeaders]=_2DVBArrayToJaggedArray(array[tableHeaders]); } else { ret=array; } } } else { ret=hostArgs; } return ret; } } })(); OSF.DDA.SafeArray.Delegate.SpecialProcessor.uber.constructor.call(this, complexTypes, dynamicTypes); this.pack=function OSF_DDA_SafeArray_Delegate_SpecialProcessor$pack(param, arg) { var value; if (this.isDynamicType(param)) { value=dynamicTypes[param].toHost(arg); } else { value=arg; } return value; }; this.unpack=function OSF_DDA_SafeArray_Delegate_SpecialProcessor$unpack(param, arg) { var value; if (this.isComplexType(param) || OSF.DDA.ListType.isListType(param)) { try { value=arg.toArray(); } catch (ex) { value=arg || {}; } } else if (this.isDynamicType(param)) { value=dynamicTypes[param].fromHost(arg); } else { value=arg; } return value; }; } OSF.OUtil.extend(OSF.DDA.SafeArray.Delegate.SpecialProcessor, OSF.DDA.SpecialProcessor); OSF.DDA.SafeArray.Delegate.ParameterMap=(function () { var parameterMap=new OSF.DDA.HostParameterMap(new OSF.DDA.SafeArray.Delegate.SpecialProcessor()); var ns; var self=parameterMap.self; function createObject(properties) { var obj=null; if (properties) { obj={}; var len=properties.length; for (var i=0; i < len; i++) { obj[properties[i].name]=properties[i].value; } } return obj; } function define(definition) { var args={}; var toHost=createObject(definition.toHost); if (definition.invertible) { args.map=toHost; } else if (definition.canonical) { args.toHost=args.fromHost=toHost; } else { args.toHost=toHost; args.fromHost=createObject(definition.fromHost); } parameterMap.setMapping(definition.type, args); } ns=OSF.DDA.FileProperties; define({ type: OSF.DDA.PropertyDescriptors.FileProperties, fromHost: [ { name: ns.Handle, value: 0 }, { name: ns.FileSize, value: 1 } ] }); define({ type: OSF.DDA.PropertyDescriptors.FileSliceProperties, fromHost: [ { name: Microsoft.Office.WebExtension.Parameters.Data, value: 0 }, { name: ns.SliceSize, value: 1} ] }); ns=OSF.DDA.BindingProperties; define({ type: OSF.DDA.PropertyDescriptors.BindingProperties, fromHost: [ { name: ns.Id, value: 0 }, { name: ns.Type, value: 1 }, { name: OSF.DDA.SafeArray.UniqueArguments.BindingSpecificData, value: 2 } ] }); define({ type: OSF.DDA.SafeArray.UniqueArguments.BindingSpecificData, fromHost: [ { name: ns.RowCount, value: 0 }, { name: ns.ColumnCount, value: 1 }, { name: ns.HasHeaders, value: 2 } ] }); ns=OSF.DDA.SafeArray.UniqueArguments; define({ type: OSF.DDA.PropertyDescriptors.Subset, toHost: [ { name: ns.Offset, value: 0 }, { name: ns.Run, value: 1 } ], canonical: true }); ns=Microsoft.Office.WebExtension.Parameters; define({ type: OSF.DDA.SafeArray.UniqueArguments.Offset, toHost: [ { name: ns.StartRow, value: 0 }, { name: ns.StartColumn, value: 1 } ], canonical: true }); define({ type: OSF.DDA.SafeArray.UniqueArguments.Run, toHost: [ { name: ns.RowCount, value: 0 }, { name: ns.ColumnCount, value: 1 } ], canonical: true }); ns=OSF.DDA.DataPartProperties; define({ type: OSF.DDA.PropertyDescriptors.DataPartProperties, fromHost: [ { name: ns.Id, value: 0 }, { name: ns.BuiltIn, value: 1 } ] }); ns=OSF.DDA.DataNodeProperties; define({ type: OSF.DDA.PropertyDescriptors.DataNodeProperties, fromHost: [ { name: ns.Handle, value: 0 }, { name: ns.BaseName, value: 1 }, { name: ns.NamespaceUri, value: 2 }, { name: ns.NodeType, value: 3 } ] }); define({ type: OSF.DDA.EventDescriptors.BindingSelectionChangedEvent, fromHost: [ { name: OSF.DDA.PropertyDescriptors.BindingProperties, value: 0 }, { name: OSF.DDA.PropertyDescriptors.Subset, value: 1 } ] }); ns=OSF.DDA.DataNodeEventProperties; define({ type: OSF.DDA.EventDescriptors.DataNodeInsertedEvent, fromHost: [ { name: ns.InUndoRedo, value: 0 }, { name: ns.NewNode, value: 1 } ] }); define({ type: OSF.DDA.EventDescriptors.DataNodeReplacedEvent, fromHost: [ { name: ns.InUndoRedo, value: 0 }, { name: ns.OldNode, value: 1 }, { name: ns.NewNode, value: 2 } ] }); define({ type: OSF.DDA.EventDescriptors.DataNodeDeletedEvent, fromHost: [ { name: ns.InUndoRedo, value: 0 }, { name: ns.OldNode, value: 1 }, { name: ns.NextSiblingNode, value: 2 } ] }); define({ type: ns.OldNode, fromHost: [ { name: OSF.DDA.PropertyDescriptors.DataNodeProperties, value: self } ] }); define({ type: ns.NewNode, fromHost: [ { name: OSF.DDA.PropertyDescriptors.DataNodeProperties, value: self } ] }); define({ type: ns.NextSiblingNode, fromHost: [ { name: OSF.DDA.PropertyDescriptors.DataNodeProperties, value: self } ] }); ns=Microsoft.Office.WebExtension.AsyncResultStatus; define({ type: OSF.DDA.PropertyDescriptors.AsyncResultStatus, fromHost: [ { name: ns.Succeeded, value: 0 }, { name: ns.Failed, value: 1 } ] }); ns=Microsoft.Office.WebExtension.CoercionType; define({ type: Microsoft.Office.WebExtension.Parameters.CoercionType, toHost: [ { name: ns.Text, value: 0 }, { name: ns.Matrix, value: 1 }, { name: ns.Table, value: 2 }, { name: ns.Html, value: 3 }, { name: ns.Ooxml, value: 4 } ] }); ns=Microsoft.Office.WebExtension.FileType; if (ns) { define({ type: Microsoft.Office.WebExtension.Parameters.FileType, toHost: [ { name: ns.Text, value: 0 }, { name: ns.Compressed, value: 5 } ] }); } ns=Microsoft.Office.WebExtension.BindingType; if (ns) { define({ type: Microsoft.Office.WebExtension.Parameters.BindingType, toHost: [ { name: ns.Text, value: 0 }, { name: ns.Matrix, value: 1 }, { name: ns.Table, value: 2 } ], invertible: true }); } ns=Microsoft.Office.WebExtension.ValueFormat; define({ type: Microsoft.Office.WebExtension.Parameters.ValueFormat, toHost: [ { name: ns.Unformatted, value: 0 }, { name: ns.Formatted, value: 1 } ] }); ns=Microsoft.Office.WebExtension.FilterType; define({ type: Microsoft.Office.WebExtension.Parameters.FilterType, toHost: [ { name: ns.All, value: 0 }, { name: ns.OnlyVisible, value: 1 } ] }); ns=Microsoft.Office.WebExtension.Parameters; var cns=OSF.DDA.MethodDispId; define({ type: cns.dispidGetSelectedDataMethod, fromHost: [ { name: ns.Data, value: self } ], toHost: [ { name: ns.CoercionType, value: 0 }, { name: ns.ValueFormat, value: 1 }, { name: ns.FilterType, value: 2 } ] }); define({ type: cns.dispidSetSelectedDataMethod, toHost: [ { name: ns.CoercionType, value: 0 }, { name: ns.Data, value: 1 } ] }); define({ type: cns.dispidGetDocumentCopyMethod, toHost: [{ name: ns.FileType, value: 0}], fromHost: [ { name: OSF.DDA.PropertyDescriptors.FileProperties, value: self } ] }); define({ type: cns.dispidGetDocumentCopyChunkMethod, toHost: [ { name: OSF.DDA.FileProperties.Handle, value: 0 }, { name: OSF.DDA.FileSliceOffset, value: 1 }, { name: OSF.DDA.FileProperties.SliceSize, value: 2 } ], fromHost: [ { name: OSF.DDA.PropertyDescriptors.FileSliceProperties, value: self } ] }); define({ type: cns.dispidReleaseDocumentCopyMethod, toHost: [{ name: OSF.DDA.FileProperties.Handle, value: 0}] }); define({ type: cns.dispidAddBindingFromSelectionMethod, fromHost: [ { name: OSF.DDA.PropertyDescriptors.BindingProperties, value: self } ], toHost: [ { name: ns.Id, value: 0 }, { name: ns.BindingType, value: 1 } ] }); define({ type: cns.dispidAddBindingFromPromptMethod, fromHost: [ { name: OSF.DDA.PropertyDescriptors.BindingProperties, value: self } ], toHost: [ { name: ns.Id, value: 0 }, { name: ns.BindingType, value: 1 }, { name: ns.PromptText, value: 2 } ] }); define({ type: cns.dispidAddBindingFromNamedItemMethod, fromHost: [ { name: OSF.DDA.PropertyDescriptors.BindingProperties, value: self } ], toHost: [ { name: ns.ItemName, value: 0 }, { name: ns.Id, value: 1 }, { name: ns.BindingType, value: 2 }, { name: ns.FailOnCollision, value: 3 } ] }); define({ type: cns.dispidReleaseBindingMethod, toHost: [ { name: ns.Id, value: 0 } ] }); define({ type: cns.dispidGetBindingMethod, fromHost: [ { name: OSF.DDA.PropertyDescriptors.BindingProperties, value: self } ], toHost: [ { name: ns.Id, value: 0 } ] }); define({ type: cns.dispidGetAllBindingsMethod, fromHost: [ { name: OSF.DDA.ListDescriptors.BindingList, value: self } ] }); define({ type: cns.dispidGetBindingDataMethod, fromHost: [ { name: ns.Data, value: self } ], toHost: [ { name: ns.Id, value: 0 }, { name: ns.CoercionType, value: 1 }, { name: ns.ValueFormat, value: 2 }, { name: ns.FilterType, value: 3 }, { name: OSF.DDA.PropertyDescriptors.Subset, value: 4 } ] }); define({ type: cns.dispidSetBindingDataMethod, toHost: [ { name: ns.Id, value: 0 }, { name: ns.CoercionType, value: 1 }, { name: ns.Data, value: 2 }, { name: OSF.DDA.SafeArray.UniqueArguments.Offset, value: 3 } ] }); define({ type: cns.dispidAddRowsMethod, toHost: [ { name: ns.Id, value: 0 }, { name: ns.Data, value: 1 } ] }); define({ type: cns.dispidAddColumnsMethod, toHost: [ { name: ns.Id, value: 0 }, { name: ns.Data, value: 1 } ] }); define({ type: cns.dispidClearAllRowsMethod, toHost: [ { name: ns.Id, value: 0 } ] }); define({ type: cns.dispidLoadSettingsMethod, fromHost: [ { name: OSF.DDA.SettingsManager.SerializedSettings, value: self } ] }); define({ type: cns.dispidSaveSettingsMethod, toHost: [ { name: OSF.DDA.SettingsManager.SerializedSettings, value: OSF.DDA.SettingsManager.SerializedSettings }, { name: Microsoft.Office.WebExtension.Parameters.OverwriteIfStale, value: Microsoft.Office.WebExtension.Parameters.OverwriteIfStale } ] }); define({ type: cns.dispidAddDataPartMethod, fromHost: [ { name: OSF.DDA.PropertyDescriptors.DataPartProperties, value: self } ], toHost: [ { name: ns.Xml, value: 0 } ] }); define({ type: cns.dispidGetDataPartByIdMethod, fromHost: [ { name: OSF.DDA.PropertyDescriptors.DataPartProperties, value: self } ], toHost: [ { name: ns.Id, value: 0 } ] }); define({ type: cns.dispidGetDataPartsByNamespaceMethod, fromHost: [ { name: OSF.DDA.ListDescriptors.DataPartList, value: self } ], toHost: [ { name: ns.Namespace, value: 0 } ] }); define({ type: cns.dispidGetDataPartXmlMethod, fromHost: [ { name: ns.Data, value: self} ], toHost: [ { name: ns.Id, value: 0 } ] }); define({ type: cns.dispidGetDataPartNodesMethod, fromHost: [ { name: OSF.DDA.ListDescriptors.DataNodeList, value: self } ], toHost: [ { name: ns.Id, value: 0 }, { name: ns.XPath, value: 1 } ] }); define({ type: cns.dispidDeleteDataPartMethod, toHost: [ { name: ns.Id, value: 0 } ] }); define({ type: cns.dispidGetDataNodeValueMethod, fromHost: [ { name: ns.Data, value: self} ], toHost: [ { name: OSF.DDA.DataNodeProperties.Handle, value: 0 } ] }); define({ type: cns.dispidGetDataNodeXmlMethod, fromHost: [ { name: ns.Data, value: self} ], toHost: [ { name: OSF.DDA.DataNodeProperties.Handle, value: 0 } ] }); define({ type: cns.dispidGetDataNodesMethod, fromHost: [ { name: OSF.DDA.ListDescriptors.DataNodeList, value: self } ], toHost: [ { name: OSF.DDA.DataNodeProperties.Handle, value: 0 }, { name: ns.XPath, value: 1 } ] }); define({ type: cns.dispidSetDataNodeValueMethod, toHost: [ { name: OSF.DDA.DataNodeProperties.Handle, value: 0 }, { name: ns.Data, value: 1 } ] }); define({ type: cns.dispidSetDataNodeXmlMethod, toHost: [ { name: OSF.DDA.DataNodeProperties.Handle, value: 0 }, { name: ns.Xml, value: 1 } ] }); define({ type: cns.dispidAddDataNamespaceMethod, toHost: [ { name: OSF.DDA.DataPartProperties.Id, value: 0 }, { name: ns.Prefix, value: 1 }, { name: ns.Namespace, value: 2 } ] }); define({ type: cns.dispidGetDataUriByPrefixMethod, fromHost: [ { name: ns.Data, value: self} ], toHost: [ { name: OSF.DDA.DataPartProperties.Id, value: 0 }, { name: ns.Prefix, value: 1 } ] }); define({ type: cns.dispidGetDataPrefixByUriMethod, fromHost: [ { name: ns.Data, value: self} ], toHost: [ { name: OSF.DDA.DataPartProperties.Id, value: 0 }, { name: ns.Namespace, value: 1 } ] }); define({ type: cns.dispidGetSelectedTaskMethod, fromHost: [ { name: ns.TaskId, value: self } ] }); define({ type: cns.dispidGetTaskMethod, fromHost: [ { name: "taskName", value: 0 }, { name: "wssTaskId", value: 1 }, { name: "resourceNames", value: 2 } ], toHost: [ { name: ns.TaskId, value: 0 } ] }); define({ type: cns.dispidGetTaskFieldMethod, fromHost: [ { name: ns.FieldValue, value: self } ], toHost: [ { name: ns.TaskId, value: 0 }, { name: ns.FieldId, value: 1 }, { name: ns.GetRawValue, value: 2 } ] }); define({ type: cns.dispidGetWSSUrlMethod, fromHost: [ { name: ns.ServerUrl, value: 0 }, { name: ns.ListName, value: 1 } ] }); define({ type: cns.dispidGetSelectedResourceMethod, fromHost: [ { name: ns.ResourceId, value: self } ] }); define({ type: cns.dispidGetResourceFieldMethod, fromHost: [ { name: ns.FieldValue, value: self } ], toHost: [ { name: ns.ResourceId, value: 0 }, { name: ns.FieldId, value: 1 }, { name: ns.GetRawValue, value: 2 } ] }); define({ type: cns.dispidGetProjectFieldMethod, fromHost: [ { name: ns.FieldValue, value: self } ], toHost: [ { name: ns.FieldId, value: 0 }, { name: ns.GetRawValue, value: 1 } ] }); define({ type: cns.dispidGetSelectedViewMethod, fromHost: [ { name: ns.ViewType, value: 0 }, { name: ns.ViewName, value: 1 } ] }); cns=OSF.DDA.EventDispId define({ type: cns.dispidDocumentSelectionChangedEvent }); define({ type: cns.dispidBindingSelectionChangedEvent, fromHost: [ {name: OSF.DDA.EventDescriptors.BindingSelectionChangedEvent, value: self} ] }); define({ type: cns.dispidBindingDataChangedEvent, fromHost: [{ name: OSF.DDA.PropertyDescriptors.BindingProperties, value: self}] }); define({ type: cns.dispidSettingsChangedEvent }); define({ type: cns.dispidDataNodeAddedEvent, fromHost: [{ name: OSF.DDA.EventDescriptors.DataNodeInsertedEvent, value: self}] }); define({ type: cns.dispidDataNodeReplacedEvent, fromHost: [{ name: OSF.DDA.EventDescriptors.DataNodeReplacedEvent, value: self}] }); define({ type: cns.dispidDataNodeDeletedEvent, fromHost: [{ name: OSF.DDA.EventDescriptors.DataNodeDeletedEvent, value: self}] }); define({ type: cns.dispidTaskSelectionChangedEvent }); define({ type: cns.dispidResourceSelectionChangedEvent }); define({ type: cns.dispidViewSelectionChangedEvent }); return parameterMap; })(); OSF.DDA.SafeArray.Delegate._onException=function OSF_DDA_SafeArray_Delegate$OnException(ex, args) { var status; var number=ex.number; if (number) { switch (number) { case -2146828218: status=OSF.DDA.ErrorCodeManager.errorCodes.ooeNoCapability; break; case -2146827850: default: status=OSF.DDA.ErrorCodeManager.errorCodes.ooeInternalError; break; } } if (args.onComplete) { args.onComplete(status || OSF.DDA.ErrorCodeManager.errorCodes.ooeInternalError); } } OSF.DDA.SafeArray.Delegate.executeAsync=function OSF_DDA_SafeArray_Delegate$ExecuteAsync(args) { try { if (args.onCalling) { args.onCalling(); } function toArray(args) { var arrArgs=args; if (OSF.OUtil.isArray(args)) { var len=arrArgs.length; for (var i=0; i < len; i++) { arrArgs[i]=toArray(arrArgs[i]); } } else if (OSF.OUtil.isDate(args)) { arrArgs=args.getVarDate(); } else if (typeof args==="object" && !OSF.OUtil.isArray(args)) { arrArgs=[]; for (var index in args) { if (!OSF.OUtil.isFunction(args[index])) { arrArgs[index]=toArray(args[index]); } } } return arrArgs; } var startTime=(new Date()).getTime(); window.external.Execute( args.dispId, toArray(args.hostCallArgs), function OSF_DDA_SafeArrayFacade$Execute_OnResponse(hostResponseArgs) { if (args.onReceiving) { args.onReceiving(); } var result=hostResponseArgs.toArray(); var status=result[OSF.DDA.SafeArray.Response.Status]; if (args.onComplete) { var payload; if (status==OSF.DDA.ErrorCodeManager.errorCodes.ooeSuccess) { if (result.length > 2) { payload=[]; for (var i=1; i < result.length; i++) payload[i - 1]=result[i]; } else { payload=result[OSF.DDA.SafeArray.Response.Payload]; } } else { payload=result[OSF.DDA.SafeArray.Response.Payload]; } args.onComplete(status, payload); } if (OSF.AppTelemetry) { OSF.AppTelemetry.onMethodDone(args.dispId, args.hostCallArgs, Math.abs((new Date()).getTime() - startTime), status); } } ); } catch (ex) { OSF.DDA.SafeArray.Delegate._onException(ex, args); } }; OSF.DDA.SafeArray.Delegate._getOnAfterRegisterEvent=function OSF_DDA_SafeArrayDelegate$GetOnAfterRegisterEvent(register, args) { var startTime=(new Date()).getTime(); return function OSF_DDA_SafeArrayDelegate$OnAfterRegisterEvent(hostResponseArgs) { if (args.onReceiving) { args.onReceiving(); } var status=hostResponseArgs.toArray ? hostResponseArgs.toArray()[OSF.DDA.SafeArray.Response.Status] : hostResponseArgs; if (args.onComplete) { args.onComplete(status) } if (OSF.AppTelemetry) { OSF.AppTelemetry.onRegisterDone(register, args.dispId, Math.abs((new Date()).getTime() - startTime), status); } } } OSF.DDA.SafeArray.Delegate.registerEventAsync=function OSF_DDA_SafeArray_Delegate$RegisterEventAsync(args) { if (args.onCalling) { args.onCalling(); } var callback=OSF.DDA.SafeArray.Delegate._getOnAfterRegisterEvent(true, args); try { window.external.RegisterEvent( args.dispId, args.targetId, function OSF_DDA_SafeArrayDelegate$RegisterEventAsync_OnEvent(eventDispId, payload) { if (args.onEvent) { args.onEvent(payload); } if (OSF.AppTelemetry) { OSF.AppTelemetry.onEventDone(args.dispId); } }, callback ); } catch (ex) { OSF.DDA.SafeArray.Delegate._onException(ex, args); } }; OSF.DDA.SafeArray.Delegate.unregisterEventAsync=function OSF_DDA_SafeArray_Delegate$UnregisterEventAsync(args) { if (args.onCalling) { args.onCalling(); } var callback=OSF.DDA.SafeArray.Delegate._getOnAfterRegisterEvent(false, args); try { window.external.UnregisterEvent( args.dispId, args.targetId, callback ); } catch (ex) { OSF.DDA.SafeArray.Delegate._onException(ex, args); } }; OSF.DDA.PowerPointDocument=function OSF_DDA_PowerPointDocument(officeAppContext, settings) { OSF.DDA.PowerPointDocument.uber.constructor.call(this, officeAppContext, settings); OSF.DDA.DispIdHost.addAsyncMethods(this, [ OSF.DDA.AsyncMethodNames.GetSelectedDataAsync, OSF.DDA.AsyncMethodNames.SetSelectedDataAsync, OSF.DDA.AsyncMethodNames.GetDocumentCopyAsync ]); OSF.DDA.DispIdHost.addEventSupport(this, new OSF.EventDispatch([Microsoft.Office.WebExtension.EventType.DocumentSelectionChanged])); OSF.OUtil.finalizeProperties(this); }; OSF.OUtil.extend(OSF.DDA.PowerPointDocument, OSF.DDA.Document);
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : (factory(global.jQuery)); }(this, (function ($) { 'use strict'; $.fn.datepicker.languages['fr-FR'] = { format: 'dd/mm/yyyy', days: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], daysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], daysMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], weekStart: 1, months: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], monthsShort: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jun', 'Jui', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'] }; })));
if (typeof define !== 'function') { var define = require('amdefine')(module); } define([ 'duino' ], function(duino) { /** * RGB Lights Plugin. This plugin is able to control a strip of RGB LEDs connected to an Arduino or GPIO Pins * * @author https://github.com/ConnorRoberts * @class RGBLights * @param {Object} app The express application * @constructor */ var RGBLights = function(app) { this.name = 'RGBLights'; this.collection = 'RGBLight'; this.icon = 'icon-eye-open'; this.app = app; this.id = this.name.toLowerCase(); this.board = new duino.Board(); this.pins = {}; this.pluginHelper = app.get('plugin helper'); this.values = {}; var that = this; app.get('sockets').on('connection', function(socket) { socket.on('rgblights', function(data) { that.picker(data); }); }); }; /** * Is called if the user has picked a color from the colourwheel * * @method picker * @param {Object} data The data of the colourwheel * @param {String} data.id The id of the element * @oaram {String} data.hex The hex value of the color * @oaram {Object} data.pins Splitted integer values for RGB * @oaram {String} data.pins.R The value for RED * @oaram {String} data.pins.G The value for GREEN * @oaram {String} data.pins.B The value for BLUE */ RGBLights.prototype.picker = function(data) { var that = this; this.pluginHelper.findItem(that.collection, data.id, function(err, item, collection) { if ((!err) && (item)) { // Inform clients over websockets that.app.get('sockets').emit('rgblights-changed', data); // Write the RGB values to the Arduino that.board.analogWrite(item.pins.R, data.R); // Red Pin that.board.analogWrite(item.pins.G, data.G); // Green Pin that.board.analogWrite(item.pins.B, data.B); // Blue Pin } else { console.log(err); } }); }; /** * Manipulate the items array before render * * @method beforeRender * @param {Array} items An array containing the items to be rendered * @param {Function} callback The callback method to execute after manipulation * @param {String} callback.err null if no error occured, otherwise the error * @param {Object} callback.result The manipulated items */ RGBLights.prototype.beforeRender = function(items, callback) { var that = this; items.forEach(function(item) { item.value = that.values[item._id] ? that.values[item._id] : 0; }); return callback(null, items); }; var exports = RGBLights; return exports; });
import { react } from "babel-types"; import * as t from "babel-types"; let referenceVisitor = { ReferencedIdentifier(path, state) { if (path.isJSXIdentifier() && react.isCompatTag(path.node.name)) { return; } // direct references that we need to track to hoist this to the highest scope we can let binding = path.scope.getBinding(path.node.name); if (!binding) return; // this binding isn't accessible from the parent scope so we can safely ignore it // eg. it's in a closure etc if (binding !== state.scope.getBinding(path.node.name)) return; if (binding.constant) { state.bindings[path.node.name] = binding; } else { for (let violationPath of (binding.constantViolations: Array)) { state.breakOnScopePaths = state.breakOnScopePaths.concat(violationPath.getAncestry()); } } } }; export default class PathHoister { constructor(path, scope) { this.breakOnScopePaths = []; this.bindings = {}; this.scopes = []; this.scope = scope; this.path = path; } isCompatibleScope(scope) { for (let key in this.bindings) { let binding = this.bindings[key]; if (!scope.bindingIdentifierEquals(key, binding.identifier)) { return false; } } return true; } getCompatibleScopes() { let scope = this.path.scope; do { if (this.isCompatibleScope(scope)) { this.scopes.push(scope); } else { break; } if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { break; } } while (scope = scope.parent); } getAttachmentPath() { let scopes = this.scopes; let scope = scopes.pop(); if (!scope) return; if (scope.path.isFunction()) { if (this.hasOwnParamBindings(scope)) { // should ignore this scope since it's ourselves if (this.scope === scope) return; // needs to be attached to the body return scope.path.get("body").get("body")[0]; } else { // doesn't need to be be attached to this scope return this.getNextScopeStatementParent(); } } else if (scope.path.isProgram()) { return this.getNextScopeStatementParent(); } } getNextScopeStatementParent() { let scope = this.scopes.pop(); if (scope) return scope.path.getStatementParent(); } hasOwnParamBindings(scope) { for (let name in this.bindings) { if (!scope.hasOwnBinding(name)) continue; let binding = this.bindings[name]; if (binding.kind === "param") return true; } return false; } run() { let node = this.path.node; if (node._hoisted) return; node._hoisted = true; this.path.traverse(referenceVisitor, this); this.getCompatibleScopes(); let attachTo = this.getAttachmentPath(); if (!attachTo) return; // don't bother hoisting to the same function as this will cause multiple branches to be evaluated more than once leading to a bad optimisation if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; let uid = attachTo.scope.generateUidIdentifier("ref"); attachTo.insertBefore([ t.variableDeclaration("var", [ t.variableDeclarator(uid, this.path.node) ]) ]); let parent = this.path.parentPath; if (parent.isJSXElement() && this.path.container === parent.node.children) { // turning the `span` in `<div><span /></div>` to an expression so we need to wrap it with // an expression container uid = t.JSXExpressionContainer(uid); } this.path.replaceWith(uid); } }
var expect = require('expect.js'); var eio = require('../'); var wsSupport = require('has-cors'); var uagent = navigator.userAgent; var isOldSimulator = ~uagent.indexOf('iPhone OS 4') || ~uagent.indexOf('iPhone OS 5'); var isIE11 = !!navigator.userAgent.match(/Trident.*rv[ :]*11\./); // ws doesn't work at all in sauce labs var isAndroid = navigator.userAgent.match(/Android/i); describe('connection', function() { this.timeout(20000); it('should connect to localhost', function(done){ var socket = new eio.Socket(); socket.on('open', function () { socket.on('message', function (data) { expect(data).to.equal('hi'); socket.close(); done(); }); }); }); it('should receive multibyte utf-8 strings with polling', function(done) { var socket = new eio.Socket(); socket.on('open', function () { socket.send('cash money €€€'); socket.on('message', function (data) { if ('hi' == data) return; expect(data).to.be('cash money €€€'); socket.close(); done(); }); }); }); it('should receive emoji', function(done) { var socket = new eio.Socket(); socket.on('open', function () { socket.send('\uD800-\uDB7F\uDB80-\uDBFF\uDC00-\uDFFF\uE000-\uF8FF'); socket.on('message', function (data) { if ('hi' == data) return; expect(data).to.be('\uD800-\uDB7F\uDB80-\uDBFF\uDC00-\uDFFF\uE000-\uF8FF'); socket.close(); done(); }); }); }); it('should not send packets if socket closes', function(done) { var socket = new eio.Socket(); socket.on('open', function() { var noPacket = true; socket.on('packetCreate', function() { noPacket = false; }); socket.close(); socket.send('hi'); setTimeout(function() { expect(noPacket).to.be(true); done(); }, 1200); }); }); // no `Worker` on old IE if (global.Worker) { it('should work in a worker', function(done){ var worker = new Worker('/test/support/worker.js'); worker.onmessage = function(e){ expect(e.data); done(); }; }); } it('should not connect at all when JSONP forced and disabled', function(done) { var socket = eio.Socket({ transports: ['polling'], forceJSONP: true, jsonp: false }); socket.on('error', function(msg) { expect(msg).to.be('No transports available'); done(); }); }); if (wsSupport && !isOldSimulator && !isAndroid && !isIE11) { it('should connect with ws when JSONP forced and disabled', function(done) { var socket = eio.Socket({ transports: ['polling', 'websocket'], forceJSONP: true, jsonp: false }); socket.on('open', function() { expect(socket.transport.name).to.be('websocket'); socket.close(); done(); }); }); it('should defer close when upgrading', function(done) { var socket = new eio.Socket(); socket.on('open', function() { var upgraded = false; socket.on('upgrade', function() { upgraded = true; }).on('upgrading', function() { socket.on('close', function() { expect(upgraded).to.be(true); done(); }); socket.close(); }); }); }); it('should close on upgradeError if closing is deferred', function(done) { var socket = new eio.Socket(); socket.on('open', function() { var upgradeError = false; socket.on('upgradeError', function() { upgradeError = true; }).on('upgrading', function() { socket.on('close', function() { expect(upgradeError).to.be(true); done(); }); socket.close(); socket.transport.onError('upgrade error'); }); }); }); it('should not send packets if closing is deferred', function(done) { var socket = new eio.Socket(); socket.on('open', function() { var noPacket = true; socket.on('upgrading', function() { socket.on('packetCreate', function() { noPacket = false; }); socket.close(); socket.send('hi'); }); setTimeout(function() { expect(noPacket).to.be(true); done(); }, 1200); }); }); it('should send all buffered packets if closing is deferred', function(done) { var socket = new eio.Socket(); socket.on('open', function() { socket.on('upgrading', function() { socket.send('hi'); socket.close(); }).on('close', function() { expect(socket.writeBuffer).to.have.length(0); done(); }); }); }); } });
// DATA_TEMPLATE: empty_table oTest.fnStart( "oLanguage.sInfoPostFix" ); $(document).ready( function () { /* Check the default */ var oTable = $('#example').dataTable( { "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumns": [ { "mData": "engine" }, { "mData": "browser" }, { "mData": "platform" }, { "mData": "version" }, { "mData": "grade" } ] } ); var oSettings = oTable.fnSettings(); oTest.fnWaitTest( "Info post fix language is '' (blank) by default", null, function () { return oSettings.oLanguage.sInfoPostFix == ""; } ); oTest.fnTest( "Width no post fix, the basic info shows", null, function () { return document.getElementById('example_info').innerHTML = "Showing 1 to 10 of 57 entries"; } ); oTest.fnWaitTest( "Info post fix language can be defined", function () { oSession.fnRestore(); oTable = $('#example').dataTable( { "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumnDefs": [ { "mData": "engine", "aTargets": [0] }, { "mData": "browser", "aTargets": [1] }, { "mData": "platform", "aTargets": [2] }, { "mData": "version", "aTargets": [3] }, { "mData": "grade", "aTargets": [4] } ], "oLanguage": { "sInfoPostFix": "unit test" } } ); oSettings = oTable.fnSettings(); }, function () { return oSettings.oLanguage.sInfoPostFix == "unit test"; } ); oTest.fnTest( "Info empty language default is in the DOM", null, function () { return document.getElementById('example_info').innerHTML = "Showing 1 to 10 of 57 entries unit test"; } ); oTest.fnWaitTest( "Macros have no effect in the post fix", function () { oSession.fnRestore(); oTable = $('#example').dataTable( { "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumnDefs": [ { "mData": "engine", "aTargets": [0] }, { "mData": "browser", "aTargets": [1] }, { "mData": "platform", "aTargets": [2] }, { "mData": "version", "aTargets": [3] }, { "mData": "grade", "aTargets": [4] } ], "oLanguage": { "sInfoPostFix": "unit _START_ _END_ _TOTAL_ test" } } ); }, function () { return document.getElementById('example_info').innerHTML = "Showing 1 to 10 of 57 entries unit _START_ _END_ _TOTAL_ test"; } ); oTest.fnWaitTest( "Post fix is applied after fintering info", function () { oSession.fnRestore(); oTable = $('#example').dataTable( { "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumnDefs": [ { "mData": "engine", "aTargets": [0] }, { "mData": "browser", "aTargets": [1] }, { "mData": "platform", "aTargets": [2] }, { "mData": "version", "aTargets": [3] }, { "mData": "grade", "aTargets": [4] } ], "oLanguage": { "sInfoPostFix": "unit test" } } ); oTable.fnFilter("nothinghere"); }, function () { return document.getElementById('example_info').innerHTML = "Showing 0 to 0 of 0 entries unit (filtered from 57 total entries) test"; } ); oTest.fnComplete(); } );
/* * 用于屏蔽页面上的所有flash */ var flashText = '<div style="text-shadow:0 0 2px #eee;letter-spacing:-1px;background:#eee;font-weight:bold;padding:0;font-family:arial,sans-serif;font-size:30px;color:#ccc;width:152px;height:52px;border:4px solid #ccc;border-radius:12px;position:absolute;top:50%;left:50%;margin:-30px 0 0 -80px;text-align:center;line-height:52px;">Flash</div>'; var count = 0; var flashBlocks = {}; //点击时间触发 var click2ShowFlash = function(e){ var index = this.getAttribute('data-flash-index'); var flash = flashBlocks[index]; flash.setAttribute('data-flash-show','isshow'); this.parentNode.insertBefore(flash, this); this.parentNode.removeChild(this); this.removeEventListener('click', click2ShowFlash, false); }; var createAPlaceHolder = function(flash, width, height){ var index = count++; var style = document.defaultView.getComputedStyle(flash, null); var positionType = style.position; positionType = positionType === 'static' ? 'relative' : positionType; var margin = style['margin']; var display = style['display'] == 'inline' ? 'inline-block' : style['display']; var style = [ '', 'width:' + width +'px', 'height:' + height +'px', 'position:' + positionType, 'margin:' + margin, 'display:' + display, 'margin:0', 'padding:0', 'border:0', 'border-radius:1px', 'cursor:pointer', 'background:-webkit-linear-gradient(top, rgba(240,240,240,1)0%,rgba(220,220,220,1)100%)', '' ] flashBlocks[index] = flash; var placeHolder = document.createElement('div'); placeHolder.setAttribute('title', '&#x70B9;&#x6211;&#x8FD8;&#x539F;Flash'); placeHolder.setAttribute('data-flash-index', '' + index); flash.parentNode.insertBefore(placeHolder, flash); flash.parentNode.removeChild(flash); placeHolder.addEventListener('click', click2ShowFlash, false); placeHolder.style.cssText += style.join(';'); placeHolder.innerHTML = flashText; return placeHolder; }; var parseFlash = function(target){ if(target instanceof HTMLObjectElement) { if(target.innerHTML.trim() == '') return; if(target.getAttribute("classid") && !/^java:/.test(target.getAttribute("classid"))) return; } else if(!(target instanceof HTMLEmbedElement)) return; var width = target.offsetWidth; var height = target.offsetHeight; if(width > 160 && height > 60){ createAPlaceHolder(target, width, height); } }; var handleBeforeLoadEvent = function(e){ var target = e.target if(target.getAttribute('data-flash-show') == 'isshow') return; parseFlash(target); }; module.exports = function() { var embeds = document.getElementsByTagName('embed'); var objects = document.getElementsByTagName('object'); for(var i=0,len=objects.length; i<len; i++) objects[i] && parseFlash(objects[i]); for(var i=0,len=embeds.length; i<len; i++) embeds[i] && parseFlash(embeds[i]); } // document.addEventListener("beforeload", handleBeforeLoadEvent, true);
'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed /** @module ember @submodule ember-runtime */ // using ember-metal/lib/main here to ensure that ember-debug is setup // if present import Ember from 'ember-metal'; import { assert, runInDebug } from 'ember-metal/debug'; import isEnabled from 'ember-metal/features'; import merge from 'ember-metal/merge'; // NOTE: this object should never be included directly. Instead use `Ember.Object`. // We only define this separately so that `Ember.Set` can depend on it. import { get } from 'ember-metal/property_get'; import { guidFor, apply } from 'ember-metal/utils'; import { generateGuid, GUID_KEY_PROPERTY, makeArray } from 'ember-metal/utils'; import { meta } from 'ember-metal/meta'; import { finishChains } from 'ember-metal/chains'; import { sendEvent } from 'ember-metal/events'; import { IS_BINDING, Mixin, REQUIRED } from 'ember-metal/mixin'; import EmberError from 'ember-metal/error'; import ActionHandler from 'ember-runtime/mixins/action_handler'; import { defineProperty } from 'ember-metal/properties'; import { Binding } from 'ember-metal/binding'; import { ComputedProperty, computed } from 'ember-metal/computed'; import InjectedProperty from 'ember-metal/injected_property'; import run from 'ember-metal/run_loop'; import { destroy } from 'ember-metal/watching'; import { K } from 'ember-metal/core'; import { validatePropertyInjections } from 'ember-runtime/inject'; var schedule = run.schedule; var applyMixin = Mixin._apply; var finishPartial = Mixin.finishPartial; var reopen = Mixin.prototype.reopen; var hasCachedComputedProperties = false; function makeCtor() { // Note: avoid accessing any properties on the object since it makes the // method a lot faster. This is glue code so we want it to be as fast as // possible. var wasApplied = false; var initMixins, initProperties; var Class = function() { if (!wasApplied) { Class.proto(); // prepare prototype... } if (arguments.length > 0) { initProperties = [arguments[0]]; } this.__defineNonEnumerable(GUID_KEY_PROPERTY); var m = meta(this); var proto = m.proto; m.proto = this; if (initMixins) { // capture locally so we can clear the closed over variable var mixins = initMixins; initMixins = null; apply(this, this.reopen, mixins); } if (initProperties) { // capture locally so we can clear the closed over variable var props = initProperties; initProperties = null; var concatenatedProperties = this.concatenatedProperties; var mergedProperties = this.mergedProperties; for (var i = 0, l = props.length; i < l; i++) { var properties = props[i]; assert( 'Ember.Object.create no longer supports mixing in other ' + 'definitions, use .extend & .create seperately instead.', !(properties instanceof Mixin) ); if (typeof properties !== 'object' && properties !== undefined) { throw new EmberError('Ember.Object.create only accepts objects.'); } if (!properties) { continue; } var keyNames = Object.keys(properties); for (var j = 0, ll = keyNames.length; j < ll; j++) { var keyName = keyNames[j]; var value = properties[keyName]; if (IS_BINDING.test(keyName)) { m.writeBindings(keyName, value); } var possibleDesc = this[keyName]; var desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined; assert( 'Ember.Object.create no longer supports defining computed ' + 'properties. Define computed properties using extend() or reopen() ' + 'before calling create().', !(value instanceof ComputedProperty) ); assert( 'Ember.Object.create no longer supports defining methods that call _super.', !(typeof value === 'function' && value.toString().indexOf('._super') !== -1) ); assert( '`actions` must be provided at extend time, not at create time, ' + 'when Ember.ActionHandler is used (i.e. views, controllers & routes).', !((keyName === 'actions') && ActionHandler.detect(this)) ); if (concatenatedProperties && concatenatedProperties.length > 0 && concatenatedProperties.indexOf(keyName) >= 0) { var baseValue = this[keyName]; if (baseValue) { if ('function' === typeof baseValue.concat) { value = baseValue.concat(value); } else { value = makeArray(baseValue).concat(value); } } else { value = makeArray(value); } } if (mergedProperties && mergedProperties.length && mergedProperties.indexOf(keyName) >= 0) { var originalValue = this[keyName]; value = merge(originalValue, value); } if (desc) { desc.set(this, keyName, value); } else { if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) { this.setUnknownProperty(keyName, value); } else { if (isEnabled('mandatory-setter')) { defineProperty(this, keyName, null, value); // setup mandatory setter } else { this[keyName] = value; } } } } } } finishPartial(this, m); var length = arguments.length; if (length === 0) { this.init(); } else if (length === 1) { this.init(arguments[0]); } else { // v8 bug potentially incorrectly deopts this function: https://code.google.com/p/v8/issues/detail?id=3709 // we may want to keep this around till this ages out on mobile var args = new Array(length); for (var x = 0; x < length; x++) { args[x] = arguments[x]; } this.init.apply(this, args); } m.proto = proto; finishChains(this); sendEvent(this, 'init'); }; Class.toString = Mixin.prototype.toString; Class.willReopen = function() { if (wasApplied) { Class.PrototypeMixin = Mixin.create(Class.PrototypeMixin); } wasApplied = false; }; Class._initMixins = function(args) { initMixins = args; }; Class._initProperties = function(args) { initProperties = args; }; Class.proto = function() { var superclass = Class.superclass; if (superclass) { superclass.proto(); } if (!wasApplied) { wasApplied = true; Class.PrototypeMixin.applyPartial(Class.prototype); } return this.prototype; }; return Class; } /** @class CoreObject @namespace Ember @public */ var CoreObject = makeCtor(); CoreObject.toString = function() { return 'Ember.CoreObject'; }; CoreObject.PrototypeMixin = Mixin.create({ reopen(...args) { applyMixin(this, args, true); return this; }, /** An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition. Example: ```javascript App.Person = Ember.Object.extend({ init: function() { alert('Name is ' + this.get('name')); } }); var steve = App.Person.create({ name: "Steve" }); // alerts 'Name is Steve'. ``` NOTE: If you do override `init` for a framework class like `Ember.View`, be sure to call `this._super.apply(this, arguments)` in your `init` declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application. @method init @public */ init() {}, __defineNonEnumerable(property) { Object.defineProperty(this, property.name, property.descriptor); //this[property.name] = property.descriptor.value; }, /** Defines the properties that will be concatenated from the superclass (instead of overridden). By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the `classNames` property of `Ember.View`. Here is some sample code showing the difference between a concatenated property and a normal one: ```javascript App.BarView = Ember.View.extend({ someNonConcatenatedProperty: ['bar'], classNames: ['bar'] }); App.FooBarView = App.BarView.extend({ someNonConcatenatedProperty: ['foo'], classNames: ['foo'] }); var fooBarView = App.FooBarView.create(); fooBarView.get('someNonConcatenatedProperty'); // ['foo'] fooBarView.get('classNames'); // ['ember-view', 'bar', 'foo'] ``` This behavior extends to object creation as well. Continuing the above example: ```javascript var view = App.FooBarView.create({ someNonConcatenatedProperty: ['baz'], classNames: ['baz'] }) view.get('someNonConcatenatedProperty'); // ['baz'] view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ``` Adding a single property that is not an array will just add it in the array: ```javascript var view = App.FooBarView.create({ classNames: 'baz' }) view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ``` Using the `concatenatedProperties` property, we can tell Ember to mix the content of the properties. In `Ember.View` the `classNameBindings` and `attributeBindings` properties are also concatenated, in addition to `classNames`. This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual concatenated property (to not mislead your users to think they can override the property in a subclass). @property concatenatedProperties @type Array @default null @public */ concatenatedProperties: null, /** Destroyed object property flag. if this property is `true` the observers and bindings were already removed by the effect of calling the `destroy()` method. @property isDestroyed @default false @public */ isDestroyed: false, /** Destruction scheduled flag. The `destroy()` method has been called. The object stays intact until the end of the run loop at which point the `isDestroyed` flag is set. @property isDestroying @default false @public */ isDestroying: false, /** Destroys an object by setting the `isDestroyed` flag and removing its metadata, which effectively destroys observers and bindings. If you try to set a property on a destroyed object, an exception will be raised. Note that destruction is scheduled for the end of the run loop and does not happen immediately. It will set an isDestroying flag immediately. @method destroy @return {Ember.Object} receiver @public */ destroy() { if (this.isDestroying) { return; } this.isDestroying = true; schedule('actions', this, this.willDestroy); schedule('destroy', this, this._scheduledDestroy); return this; }, /** Override to implement teardown. @method willDestroy @public */ willDestroy: K, /** Invoked by the run loop to actually destroy the object. This is scheduled for execution by the `destroy` method. @private @method _scheduledDestroy */ _scheduledDestroy() { if (this.isDestroyed) { return; } destroy(this); this.isDestroyed = true; }, bind(to, from) { if (!(from instanceof Binding)) { from = Binding.from(from); } from.to(to).connect(this); return from; }, /** Returns a string representation which attempts to provide more information than Javascript's `toString` typically does, in a generic way for all Ember objects. ```javascript App.Person = Em.Object.extend() person = App.Person.create() person.toString() //=> "<App.Person:ember1024>" ``` If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass: ```javascript Student = App.Person.extend() student = Student.create() student.toString() //=> "<(subclass of App.Person):ember1025>" ``` If the method `toStringExtension` is defined, its return value will be included in the output. ```javascript App.Teacher = App.Person.extend({ toStringExtension: function() { return this.get('fullName'); } }); teacher = App.Teacher.create() teacher.toString(); //=> "<App.Teacher:ember1026:Tom Dale>" ``` @method toString @return {String} string representation @public */ toString() { var hasToStringExtension = typeof this.toStringExtension === 'function'; var extension = hasToStringExtension ? ':' + this.toStringExtension() : ''; var ret = '<' + this.constructor.toString() + ':' + guidFor(this) + extension + '>'; this.toString = makeToString(ret); return ret; } }); CoreObject.PrototypeMixin.ownerConstructor = CoreObject; function makeToString(ret) { return function() { return ret; }; } CoreObject.__super__ = null; var ClassMixinProps = { ClassMixin: REQUIRED, PrototypeMixin: REQUIRED, isClass: true, isMethod: false, /** Creates a new subclass. ```javascript App.Person = Ember.Object.extend({ say: function(thing) { alert(thing); } }); ``` This defines a new subclass of Ember.Object: `App.Person`. It contains one method: `say()`. You can also create a subclass from any existing class by calling its `extend()` method. For example, you might want to create a subclass of Ember's built-in `Ember.View` class: ```javascript App.PersonView = Ember.View.extend({ tagName: 'li', classNameBindings: ['isAdministrator'] }); ``` When defining a subclass, you can override methods but still access the implementation of your parent class by calling the special `_super()` method: ```javascript App.Person = Ember.Object.extend({ say: function(thing) { var name = this.get('name'); alert(name + ' says: ' + thing); } }); App.Soldier = App.Person.extend({ say: function(thing) { this._super(thing + ", sir!"); }, march: function(numberOfHours) { alert(this.get('name') + ' marches for ' + numberOfHours + ' hours.'); } }); var yehuda = App.Soldier.create({ name: "Yehuda Katz" }); yehuda.say("Yes"); // alerts "Yehuda Katz says: Yes, sir!" ``` The `create()` on line #17 creates an *instance* of the `App.Soldier` class. The `extend()` on line #8 creates a *subclass* of `App.Person`. Any instance of the `App.Person` class will *not* have the `march()` method. You can also pass `Mixin` classes to add additional properties to the subclass. ```javascript App.Person = Ember.Object.extend({ say: function(thing) { alert(this.get('name') + ' says: ' + thing); } }); App.SingingMixin = Mixin.create({ sing: function(thing){ alert(this.get('name') + ' sings: la la la ' + thing); } }); App.BroadwayStar = App.Person.extend(App.SingingMixin, { dance: function() { alert(this.get('name') + ' dances: tap tap tap tap '); } }); ``` The `App.BroadwayStar` class contains three methods: `say()`, `sing()`, and `dance()`. @method extend @static @param {Mixin} [mixins]* One or more Mixin classes @param {Object} [arguments]* Object containing values to use within the new class @public */ extend() { var Class = makeCtor(); var proto; Class.ClassMixin = Mixin.create(this.ClassMixin); Class.PrototypeMixin = Mixin.create(this.PrototypeMixin); Class.ClassMixin.ownerConstructor = Class; Class.PrototypeMixin.ownerConstructor = Class; reopen.apply(Class.PrototypeMixin, arguments); Class.superclass = this; Class.__super__ = this.prototype; proto = Class.prototype = Object.create(this.prototype); proto.constructor = Class; generateGuid(proto); meta(proto).proto = proto; // this will disable observers on prototype Class.ClassMixin.apply(Class); return Class; }, /** Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with. ```javascript App.Person = Ember.Object.extend({ helloWorld: function() { alert("Hi, my name is " + this.get('name')); } }); var tom = App.Person.create({ name: 'Tom Dale' }); tom.helloWorld(); // alerts "Hi, my name is Tom Dale". ``` `create` will call the `init` function if defined during `Ember.AnyObject.extend` If no arguments are passed to `create`, it will not set values to the new instance during initialization: ```javascript var noName = App.Person.create(); noName.helloWorld(); // alerts undefined ``` NOTE: For performance reasons, you cannot declare methods or computed properties during `create`. You should instead declare methods and computed properties when using `extend`. @method create @static @param [arguments]* @public */ create(...args) { var C = this; if (args.length > 0) { this._initProperties(args); } return new C(); }, /** Augments a constructor's prototype with additional properties and functions: ```javascript MyObject = Ember.Object.extend({ name: 'an object' }); o = MyObject.create(); o.get('name'); // 'an object' MyObject.reopen({ say: function(msg){ console.log(msg); } }) o2 = MyObject.create(); o2.say("hello"); // logs "hello" o.say("goodbye"); // logs "goodbye" ``` To add functions and properties to the constructor itself, see `reopenClass` @method reopen @public */ reopen() { this.willReopen(); reopen.apply(this.PrototypeMixin, arguments); return this; }, /** Augments a constructor's own properties and functions: ```javascript MyObject = Ember.Object.extend({ name: 'an object' }); MyObject.reopenClass({ canBuild: false }); MyObject.canBuild; // false o = MyObject.create(); ``` In other words, this creates static properties and functions for the class. These are only available on the class and not on any instance of that class. ```javascript App.Person = Ember.Object.extend({ name : "", sayHello : function() { alert("Hello. My name is " + this.get('name')); } }); App.Person.reopenClass({ species : "Homo sapiens", createPerson: function(newPersonsName){ return App.Person.create({ name:newPersonsName }); } }); var tom = App.Person.create({ name : "Tom Dale" }); var yehuda = App.Person.createPerson("Yehuda Katz"); tom.sayHello(); // "Hello. My name is Tom Dale" yehuda.sayHello(); // "Hello. My name is Yehuda Katz" alert(App.Person.species); // "Homo sapiens" ``` Note that `species` and `createPerson` are *not* valid on the `tom` and `yehuda` variables. They are only valid on `App.Person`. To add functions and properties to instances of a constructor by extending the constructor's prototype see `reopen` @method reopenClass @public */ reopenClass() { reopen.apply(this.ClassMixin, arguments); applyMixin(this, arguments, false); return this; }, detect(obj) { if ('function' !== typeof obj) { return false; } while (obj) { if (obj === this) { return true; } obj = obj.superclass; } return false; }, detectInstance(obj) { return obj instanceof this; }, /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ```javascript person: function() { var personId = this.get('personId'); return App.Person.create({ id: personId }); }.property().meta({ type: App.Person }) ``` Once you've done this, you can retrieve the values saved to the computed property from your class like this: ```javascript MyClass.metaForProperty('person'); ``` This will return the original hash that was passed to `meta()`. @static @method metaForProperty @param key {String} property name @private */ metaForProperty(key) { var proto = this.proto(); var possibleDesc = proto[key]; var desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined; assert( 'metaForProperty() could not find a computed property ' + 'with key \'' + key + '\'.', !!desc && desc instanceof ComputedProperty ); return desc._meta || {}; }, _computedProperties: computed(function() { hasCachedComputedProperties = true; var proto = this.proto(); var property; var properties = []; for (var name in proto) { property = proto[name]; if (property && property.isDescriptor) { properties.push({ name: name, meta: property._meta }); } } return properties; }).readOnly(), /** Iterate over each computed property for the class, passing its name and any associated metadata (see `metaForProperty`) to the callback. @static @method eachComputedProperty @param {Function} callback @param {Object} binding @private */ eachComputedProperty(callback, binding) { var property, name; var empty = {}; var properties = get(this, '_computedProperties'); for (var i = 0, length = properties.length; i < length; i++) { property = properties[i]; name = property.name; callback.call(binding || this, property.name, property.meta || empty); } } }; function injectedPropertyAssertion() { assert('Injected properties are invalid', validatePropertyInjections(this)); } runInDebug(function() { /** Provides lookup-time type validation for injected properties. @private @method _onLookup */ ClassMixinProps._onLookup = injectedPropertyAssertion; }); /** Returns a hash of property names and container names that injected properties will lookup on the container lazily. @method _lazyInjections @return {Object} Hash of all lazy injected property keys to container names @private */ ClassMixinProps._lazyInjections = function() { var injections = {}; var proto = this.proto(); var key, desc; for (key in proto) { desc = proto[key]; if (desc instanceof InjectedProperty) { injections[key] = desc.type + ':' + (desc.name || key); } } return injections; }; var ClassMixin = Mixin.create(ClassMixinProps); ClassMixin.ownerConstructor = CoreObject; CoreObject.ClassMixin = ClassMixin; ClassMixin.apply(CoreObject); CoreObject.reopen({ didDefineProperty(proto, key, value) { if (hasCachedComputedProperties === false) { return; } if (value instanceof Ember.ComputedProperty) { var cache = Ember.meta(this.constructor).readableCache(); if (cache && cache._computedProperties !== undefined) { cache._computedProperties = undefined; } } } }); export default CoreObject;
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("build/docs/examples/example-example89/index-jquery.html"); }); var colorSpan = element(by.css('span')); it('should check ng-style', function() { expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); element(by.css('input[value=\'set color\']')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); element(by.css('input[value=clear]')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); }); });
/* YUI 3.5.0 (build 5089) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('button-group', function(Y) { /** * A Widget to create groups of buttons * * @module button-group * @since 3.5.0 */ var CONTENT_BOX = "contentBox", SELECTOR = "button, input[type=button], input[type=reset], input[type=submit]", CLICK_EVENT = "click", CLASS_NAMES = Y.ButtonCore.CLASS_NAMES; /** * Creates a ButtonGroup * * @class ButtonGroup * @extends Widget * @param config {Object} Configuration object * @constructor */ function ButtonGroup() { ButtonGroup.superclass.constructor.apply(this, arguments); } /* ButtonGroup extends Widget */ Y.ButtonGroup = Y.extend(ButtonGroup, Y.Widget, { /** * @method renderUI * @description Creates a visual representation of the widget based on existing parameters. * @public */ renderUI: function() { this.getButtons().plug(Y.Plugin.Button); }, /** * @method bindUI * @description Hooks up events for the widget * @public */ bindUI: function() { var group = this, cb = group.get(CONTENT_BOX); cb.delegate(CLICK_EVENT, group._handleClick, SELECTOR, group); }, /** * @method getButtons * @description Returns all buttons inside this this button group * @public */ getButtons: function() { var cb = this.get(CONTENT_BOX); return cb.all(SELECTOR); }, /** * @method getSelectedButtons * @description Returns all Y.Buttons instances that are selected * @public */ getSelectedButtons: function() { var group = this, selected = [], buttons = group.getButtons(), selectedClass = ButtonGroup.CLASS_NAMES.SELECTED; buttons.each(function(node){ if (node.hasClass(selectedClass)){ selected.push(node); } }); return selected; }, /** * @method getSelectedValues * @description Returns the values of all Y.Button instances that are selected * @public */ getSelectedValues: function() { var group = this, value, values = [], selected = group.getSelectedButtons(), selectedClass = ButtonGroup.CLASS_NAMES.SELECTED; Y.Array.each(selected, function(node){ if (node.hasClass(selectedClass)){ value = node.getContent(); values.push(value); } }); return values; }, /** * @method _handleClick * @description A delegated click handler for when any button is clicked in the content box * @param e {Object} An event object * @private */ _handleClick: function(e){ var buttons, clickedNode = e.target, group = this, type = group.get('type'), selectedClass = ButtonGroup.CLASS_NAMES.SELECTED, isSelected = clickedNode.hasClass(selectedClass); // TODO: Anything for 'push' groups? if (type === 'checkbox') { clickedNode.toggleClass(selectedClass, !isSelected); group.fire('selectionChange', {originEvent: e}); } else if (type === 'radio') { if (!isSelected) { buttons = group.getButtons(); // Todo: getSelectedButtons()? Need it to return an arraylist then. buttons.removeClass(selectedClass); clickedNode.addClass(selectedClass); group.fire('selectionChange', {originEvent: e}); } } } }, { // Y.ButtonGroup static properties /** * The identity of the widget. * * @property NAME * @type {String} * @default 'buttongroup' * @readOnly * @protected * @static */ NAME: 'buttongroup', /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { type: { writeOnce: 'initOnly', value: 'radio' } }, /** * List of class names to use for ButtonGroups * * @property CLASS_NAMES * @type {Object} * @static */ CLASS_NAMES: CLASS_NAMES }); }, '3.5.0' ,{requires:['button-plugin', 'cssbutton', 'widget']});
/* eslint consistent-return: 0, no-else-return: 0*/ import * as types from 'types'; export function dismissMessage() { return { type: types.DISMISS_MESSAGE }; }
Clazz.declarePackage ("JSV.api"); Clazz.declareInterface (JSV.api, "JSVFileHelper");
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v13.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../../context/context"); var gridOptionsWrapper_1 = require("../../gridOptionsWrapper"); var filterService_1 = require("../../rowNodes/filterService"); var FilterStage = (function () { function FilterStage() { } FilterStage.prototype.execute = function (params) { var rowNode = params.rowNode; if (this.gridOptionsWrapper.isEnableServerSideFilter()) { this.filterService.filter(rowNode, false); } else { this.filterService.filterAccordingToColumnState(rowNode); } }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], FilterStage.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('filterService'), __metadata("design:type", filterService_1.FilterService) ], FilterStage.prototype, "filterService", void 0); FilterStage = __decorate([ context_1.Bean('filterStage') ], FilterStage); return FilterStage; }()); exports.FilterStage = FilterStage;
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/jax/output/HTML-CSS/imageFonts.js * * Implements the image fallback fonts for the HTML-CSS OutputJax. * * --------------------------------------------------------------------- * * Copyright (c) 2009-2017 The MathJax Consortium * * 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. */ (function (HUB,HTMLCSS,AJAX) { var VERSION = "2.7.2"; HUB.Register.LoadHook(HTMLCSS.fontDir + "/fontdata.js",function () { HTMLCSS.Augment({ allowWebFonts: false, imgDir: HTMLCSS.webfontDir+"/png", imgPacked: (MathJax.isPacked ? "" : "/unpacked"), imgSize: ['050','060','071','085',100,120,141,168,200,238,283,336,400,476], imgBaseIndex: 4, // set by initImg() imgSizeForEm: {}, // cache of indexes by em-size imgSizeForScale: {}, // cache of indexes by scale for a given em-size imgZoom: 1, // set by initImg for each equation handleImg: function (span,font,c,n,text) { if (text.length) {this.addText(span,text)} var orig = c[5].orig; if (!orig) {orig = c[5].orig = [c[0],c[1],c[2],c[3],c[4]]} var bscale = this.imgZoom; if (!span.scale) {span.scale = 1} var index = this.imgIndex(span.scale*bscale); if (index == this.imgEmWidth.length-1 && this.em*span.scale*bscale/this.imgEmWidth[index] > 1.1) {bscale = this.imgEmWidth[index]/(this.em*span.scale)} var factor = this.imgEmWidth[index]/(this.em*(span.scale||1)*bscale); c[0] = orig[0]*factor; c[1] = orig[1]*factor; c[2] = orig[2]*factor; c[3] = orig[3]*factor; c[4] = orig[4]*factor; var dir = this.imgDir+"/"+font.directory+"/"+this.imgSize[index]; var chr = n.toString(16).toUpperCase(); while (chr.length < 4) {chr = "0"+chr}; var file = dir+"/"+chr+".png"; var img = c[5].img[index]; var style = {width:Math.floor(img[0]/bscale+.5)+"px", height:Math.floor(img[1]/bscale+.5)+"px"}; if (img[2]) {style.verticalAlign = Math.floor(-img[2]/bscale+.5)+"px"} if (c[3] < 0) {style.marginLeft = this.Em(c[3]/1000)} if (c[4] != c[2]) {style.marginRight = this.Em((c[2]-c[4])/1000)} if (this.msieIE6) { style.filter = "progid:DXImageTransform.Microsoft." + "AlphaImageLoader(src='"+AJAX.urlRev(file)+"', sizingMethod='scale')"; file = this.directory+"/blank.gif" } this.addElement(span,"img",{src:AJAX.urlRev(file), style:style, isMathJax:true}); return ""; }, defineImageData: function (def) { for (var font in def) {if (def.hasOwnProperty(font)) { var FONT = HTMLCSS.FONTDATA.FONTS[font]; if (FONT) { font = def[font]; for (var n in font) {if (font.hasOwnProperty(n) && FONT[n]) {FONT[n][5] = {img: font[n]}}} } }} }, initImg: function (span) { if (this.imgSizeForEm[this.em]) {this.imgBaseIndex = this.imgSizeForEm[this.em]} for (var i = 0, m = this.imgEmWidth.length-1; i < m; i++) {if (this.em <= this.imgEmWidth[i]) break} if (i && this.imgEmWidth[i] - this.em > this.em - this.imgEmWidth[i-1]) {i--} this.imgSizeForEm[this.em] = this.imgBaseIndex = i; this.imgZoom = this.imgBrowserZoom(); }, imgIndex: function (scale) { if (!scale) {return this.imgBaseIndex} if (!this.imgSizeForScale[this.em]) {this.imgSizeForScale[this.em] = {}} if (this.imgSizeForScale[this.em][scale]) {return this.imgSizeForScale[this.em][scale]} var em = this.em * scale; for (var i = 0, m = this.imgEmWidth.length-1; i < m; i++) {if (em <= this.imgEmWidth[i]) break} if (i && this.imgEmWidth[i] - em > em - this.imgEmWidth[i-1]) {i--} this.imgSizeForScale[this.em][scale] = i; return i; }, imgBrowserZoom: function () {return 1} }); HUB.Browser.Select({ Firefox: function (browser) { var ZDIV = HTMLCSS.addElement(document.body,"div",{ style: { display:"none", visibility:"hidden", overflow:"scroll", position:"absolute", top:0, left: 0, width:"200px", height:"200px", padding:0, border:0, margin:0 } }); var ZFRAME = HTMLCSS.addElement(ZDIV,"div",{ style: { position:"absolute", left:0, top:0, right:0, bottom:0, padding:0, border:0, margin:0 } }); HTMLCSS.Augment({ imgSpaceBug: true, imgSpace: "\u00A0", imgZoomLevel: (browser.isMac ? {50:.3, 30:.5, 22:.67, 19:.8, 16:.9, 15:1, 13:1.1, 12:1.2, 11:1.33, 10:1.5, 9:1.7, 7:2, 6:2.4, 5:3, 0:15} : {56:.3, 34:.5, 25:.67, 21:.8, 19:.9, 17:1, 15:1.1, 14:1.2, 13:1.33, 11:1.5, 10:1.7, 8:2, 7:2.4, 6:3, 0:17} ), imgZoomDiv: ZDIV, imgBrowserZoom: function () { var size = this.imgZoomLevel; ZDIV.style.display = ""; var ratio = (ZDIV.offsetWidth-ZFRAME.offsetWidth); ratio = (size[ratio] ? size[ratio] : size[0]/ratio); ZDIV.style.display = "none"; return ratio; } }); }, Safari: function (browser) { // for iPhone and iTouch // var webkit = (navigator.appVersion+"AppleWebKit/530").match(/AppleWebKit\/(\d+)/)[1]; HTMLCSS.Augment({ // imgHeightBug: (!browser.isMac || webkit > 525), // imgDepthBug: (!browser.isMac || webkit > 525), imgBrowserZoom: function () {return 3} }); }, Chrome: function (browser) { HTMLCSS.Augment({ imgHeightBug: true, imgBrowserZoom: function () {return 3} }); }, Opera: function (browser) { HTMLCSS.Augment({ imgSpaceBug: true, imgSpace: "\u00A0\u00A0", imgDoc: (document.compatMode == "BackCompat" ? document.body : document.documentElement), imgBrowserZoom: function () { if (browser.isMac) {return 3} // Mac Opera scales very nicely var H = this.imgDoc.clientHeight, d = Math.floor(15*H/window.innerHeight); if (this.imgDoc.clientWidth < this.imgDoc.scrollWidth-d) {H += d} return parseFloat((window.innerHeight/H).toFixed(1)); } }); } }); var GETWIDTHS = function () { var img = HTMLCSS.FONTDATA.FONTS["MathJax_Main"][0x2014][5].img; // em-dash HTMLCSS.imgEmWidth = []; for (var i = 0, m = img.length; i < m; i++) {HTMLCSS.imgEmWidth[i] = img[i][0]} }; var IMGDIR = HTMLCSS.imgDir + HTMLCSS.imgPacked; MathJax.Callback.Queue( ["Require",AJAX,IMGDIR+"/imagedata.js"], GETWIDTHS, ["loadComplete",AJAX,HTMLCSS.directory+"/imageFonts.js"] ); }); })(MathJax.Hub,MathJax.OutputJax["HTML-CSS"],MathJax.Ajax);
'use strict'; module.exports = function (t, a, d) { var x = {}, y = {}, z = {}, p, r; t.call(function (arg1, arg2) { return [this, arg1, arg2]; }, 100).call(x, y, z)(function (arg) { p = y; r = arg; }).done(); a.not(p, y, "Not yet"); setTimeout(function () { a.not(p, y, "After a while"); setTimeout(function () { a(p, y, "Timed"); a.deep(r, [x, y, z], "Result"); d(); }, 70); }, 50); };
import {createStore, compose, applyMiddleware} from 'redux'; import thunkMiddleware from 'redux-thunk'; import rootReducer from '../reducers'; export default function configureStore(initialState) { const middlewares = [ // Add other middleware on this line... // thunk middleware can also accept an extra argument to be passed to each thunk action // https://github.com/gaearon/redux-thunk#injecting-a-custom-argument thunkMiddleware, ]; return createStore(rootReducer, initialState, compose( applyMiddleware(...middlewares) ) ); }
var expansions = require("npm-expansions") var clickCount = -1 var updateExpansion = function(event) { if (event) event.preventDefault() if (++clickCount > 10) { return window.location = "https://github.com/npm/npm-expansions" } var expansion = expansions[Math.floor(Math.random() * expansions.length)]; $("#npm-expansions").text(expansion) } $(function() { updateExpansion() $("#npm-expansions").on('click', updateExpansion) })
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ function ContextDependencyTemplateAsId() {} module.exports = ContextDependencyTemplateAsId; ContextDependencyTemplateAsId.prototype.apply = function(dep, source, outputOptions, requestShortener) { var comment = ""; if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; if(dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { if(dep.valueRange) { source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + ""); } else { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve"); } } else { var content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } };
define("dojo/store/DataStore", ["../_base/lang", "../_base/declare", "../_base/Deferred", "../_base/array", "./util/QueryResults" ], function(lang,declare,Deferred,array,QueryResults) { // module: // dojo/store/DataStore // summary: // TODOC return declare("dojo.store.DataStore", null, { target: "", constructor: function(options){ // summary: // This is an adapter for using Dojo Data stores with an object store consumer. // You can provide a Dojo data store and use this adapter to interact with it through // the Dojo object store API // options: Object? // This provides any configuration information that will be mixed into the store, // including a reference to the Dojo data store under the property "store". lang.mixin(this, options); if(!"idProperty" in options){ var idAttribute; try{ idAttribute = this.store.getIdentityAttributes(); }catch(e){ // some store are not requiring an item instance to give us the ID attributes // but some other do and throw errors in that case. } // if no idAttribute we have implicit id this.idProperty = (!idAttribute || !idAttributes[0]) || this.idProperty; } var features = this.store.getFeatures(); // check the feature set and null out any methods that shouldn't be available if(!features["dojo.data.api.Read"]){ this.get = null; } if(!features["dojo.data.api.Identity"]){ this.getIdentity = null; } if(!features["dojo.data.api.Write"]){ this.put = this.add = null; } }, // idProperty: String // The object property to use to store the identity of the store items. idProperty: "id", // store: // The object store to convert to a data store store: null, _objectConverter: function(callback){ var store = this.store; var idProperty = this.idProperty; return function(item){ var object = {}; var attributes = store.getAttributes(item); for(var i = 0; i < attributes.length; i++){ object[attributes[i]] = store.getValue(item, attributes[i]); } if(!(idProperty in object)){ object[idProperty] = store.getIdentity(item); } return callback(object); }; }, get: function(id, options){ // summary: // Retrieves an object by it's identity. This will trigger a fetchItemByIdentity // id: Object? // The identity to use to lookup the object var returnedObject, returnedError; var deferred = new Deferred(); this.store.fetchItemByIdentity({ identity: id, onItem: this._objectConverter(function(object){ deferred.resolve(returnedObject = object); }), onError: function(error){ deferred.reject(returnedError = error); } }); if(returnedObject){ // if it was returned synchronously return returnedObject; } if(returnedError){ throw returnedError; } return deferred.promise; }, put: function(object, options){ // summary: // Stores an object by its identity. // object: Object // The object to store. // options: Object? // Additional metadata for storing the data. Includes a reference to an id // that the object may be stored with (i.e. { id: "foo" }). var id = options && typeof options.id != "undefined" || this.getIdentity(object); var store = this.store; var idProperty = this.idProperty; if(typeof id == "undefined"){ store.newItem(object); }else{ store.fetchItemByIdentity({ identity: id, onItem: function(item){ if(item){ for(var i in object){ if(i != idProperty && // don't copy id properties since they are immutable and should be omitted for implicit ids store.getValue(item, i) != object[i]){ store.setValue(item, i, object[i]); } } }else{ store.newItem(object); } } }); } }, remove: function(id){ // summary: // Deletes an object by its identity. // id: Object // The identity to use to delete the object var store = this.store; this.store.fetchItemByIdentity({ identity: id, onItem: function(item){ store.deleteItem(item); } }); }, query: function(query, options){ // summary: // Queries the store for objects. // query: Object // The query to use for retrieving objects from the store // options: Object? // Optional options object as used by the underlying dojo.data Store. // returns: dojo.store.util.QueryResults // A query results object that can be used to iterate over results. var fetchHandle; var deferred = new Deferred(function(){ fetchHandle.abort && fetchHandle.abort(); }); deferred.total = new Deferred(); var converter = this._objectConverter(function(object){return object;}); fetchHandle = this.store.fetch(lang.mixin({ query: query, onBegin: function(count){ deferred.total.resolve(count); }, onComplete: function(results){ deferred.resolve(array.map(results, converter)); }, onError: function(error){ deferred.reject(error); } }, options)); return QueryResults(deferred); }, getIdentity: function(object){ // summary: // Fetch the identity for the given object. // object: Object // The data object to get the identity from. // returns: Number // The id of the given object. return object[this.idProperty]; } }); });
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pastefromword', 'nb', { confirmCleanup: 'Teksten du limer inn ser ut til å være kopiert fra Word. Vil du renske den før du limer den inn?', error: 'Det var ikke mulig å renske den innlimte teksten på grunn av en intern feil', title: 'Lim inn fra Word', toolbar: 'Lim inn fra Word' } );
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * */ 'use strict'; exports.__esModule = true; exports.default = void 0; var _EventSubscription3 = _interopRequireDefault(require("./_EventSubscription")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * EmitterSubscription represents a subscription with listener and context data. */ var EmitterSubscription = /*#__PURE__*/function (_EventSubscription2) { _inheritsLoose(EmitterSubscription, _EventSubscription2); /** * @param {EventEmitter} emitter - The event emitter that registered this * subscription * @param {EventSubscriptionVendor} subscriber - The subscriber that controls * this subscription * @param {function} listener - Function to invoke when the specified event is * emitted * @param {*} context - Optional context object to use when invoking the * listener */ function EmitterSubscription(emitter, subscriber, listener, context) { var _this; _this = _EventSubscription2.call(this, subscriber) || this; _this.emitter = emitter; _this.listener = listener; _this.context = context; return _this; } /** * Removes this subscription from the emitter that registered it. * Note: we're overriding the `remove()` method of _EventSubscription here * but deliberately not calling `super.remove()` as the responsibility * for removing the subscription lies with the EventEmitter. */ var _proto = EmitterSubscription.prototype; _proto.remove = function remove() { this.emitter.removeSubscription(this); }; return EmitterSubscription; }(_EventSubscription3.default); var _default = EmitterSubscription; exports.default = _default; module.exports = exports.default;
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var punycode = require('punycode'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a puny coded representation of "domain". // It only converts the part of the domain name that // has non ASCII characters. I.e. it dosent matter if // you call it with a domain that already is in ASCII. var domainArray = this.hostname.split('.'); var newOut = []; for (var i = 0; i < domainArray.length; ++i) { var s = domainArray[i]; newOut.push(s.match(/[^A-Za-z0-9_-]/) ? 'xn--' + punycode.encode(s) : s); } this.hostname = newOut.join('.'); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); Object.keys(this).forEach(function(k) { result[k] = this[k]; }, this); // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative Object.keys(relative).forEach(function(k) { if (k !== 'protocol') result[k] = relative[k]; }); //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { Object.keys(relative).forEach(function(k) { result[k] = relative[k]; }); result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last == '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; function isString(arg) { return typeof arg === "string"; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isNull(arg) { return arg === null; } function isNullOrUndefined(arg) { return arg == null; }
/*! algoliasearch 3.3.2 | © 2014, 2015 Algolia SAS | github.com/algolia/algoliasearch-client-js */ (function(C){var c;"undefined"!==typeof window?c=window:"undefined"!==typeof self&&(c=self);c.ALGOLIA_MIGRATION_LAYER=C()})(function(){return function c(h,e,m){function g(d,k){if(!e[d]){if(!h[d]){var p="function"==typeof require&&require;if(!k&&p)return p(d,!0);if(b)return b(d,!0);p=Error("Cannot find module '"+d+"'");throw p.code="MODULE_NOT_FOUND",p;}p=e[d]={exports:{}};h[d][0].call(p.exports,function(b){var k=h[d][1][b];return g(k?k:b)},p,p.exports,c,h,e,m)}return e[d].exports}for(var b="function"== typeof require&&require,k=0;k<m.length;k++)g(m[k]);return g}({1:[function(c,h,e){function m(b,d){for(var g in d)b.setAttribute(g,d[g])}function g(b,d){b.onload=function(){this.onerror=this.onload=null;d(null,b)};b.onerror=function(){this.onerror=this.onload=null;d(Error("Failed to load "+this.src),b)}}function b(b,d){b.onreadystatechange=function(){if("complete"==this.readyState||"loaded"==this.readyState)this.onreadystatechange=null,d(null,b)}}h.exports=function(k,d,c){var p=document.head||document.getElementsByTagName("head")[0], e=document.createElement("script");"function"===typeof d&&(c=d,d={});d=d||{};c=c||function(){};e.type=d.type||"text/javascript";e.charset=d.charset||"utf8";e.async="async"in d?!!d.async:!0;e.src=k;d.attrs&&m(e,d.attrs);d.text&&(e.text=""+d.text);("onload"in e?g:b)(e,c);e.onload||g(e,c);p.appendChild(e)}},{}],2:[function(c,h,e){h.exports=function(e){e=new RegExp("cdn\\.jsdelivr\\.net/algoliasearch/latest/"+e.replace(".","\\.")+"(?:\\.min)?\\.js$");for(var g=document.getElementsByTagName("script"), b=!1,k=0,d=g.length;k<d;k++)if(g[k].src&&e.test(g[k].src)){b=!0;break}return b}},{}],3:[function(c,h,e){(function(e){function g(b){return function(){var k="AlgoliaSearch: loaded V2 script using "+b;e.console&&e.console.log&&e.console.log(k)}}h.exports=function(b){var k=c(1);b="//cdn.jsdelivr.net/algoliasearch/2/"+b+".min.js";e.console&&(e.console.warn?e.console.warn("-- AlgoliaSearch `latest` warning --\nWarning, you are using the `latest` version string from jsDelivr to load the AlgoliaSearch library.\nUsing `latest` is no more recommended, you should load //cdn.jsdelivr.net/algoliasearch/2/algoliasearch.min.js\n\nAlso, we updated the AlgoliaSearch JavaScript client to V3. If you want to upgrade,\nplease read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n-- /AlgoliaSearch `latest` warning --"): e.console.log&&e.console.log("-- AlgoliaSearch `latest` warning --\nWarning, you are using the `latest` version string from jsDelivr to load the AlgoliaSearch library.\nUsing `latest` is no more recommended, you should load //cdn.jsdelivr.net/algoliasearch/2/algoliasearch.min.js\n\nAlso, we updated the AlgoliaSearch JavaScript client to V3. If you want to upgrade,\nplease read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n-- /AlgoliaSearch `latest` warning --")); try{document.write("<script>window.ALGOLIA_SUPPORTS_DOCWRITE = true\x3c/script>"),!0===e.ALGOLIA_SUPPORTS_DOCWRITE?(document.write('<script src="'+b+'">\x3c/script>'),g("document.write")()):k(b,g("DOMElement"))}catch(d){k(b,g("DOMElement"))}}}).call(this,"undefined"!==typeof global?global:"undefined"!==typeof self?self:"undefined"!==typeof window?window:{})},{1:1}],4:[function(c,h,e){(function(e){h.exports=function(){e.AlgoliaSearch=function(){throw Error("-- AlgoliaSearch V2 => V3 error --\nYou are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\nPlease read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n-- /AlgoliaSearch V2 => V3 error --"); };e.AlgoliaSearchHelper=function(){throw Error("-- AlgoliaSearch V2 => V3 error --\nYou are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\nPlease read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n-- /AlgoliaSearch V2 => V3 error --");};AlgoliaExplainResults=function(){throw Error("-- AlgoliaSearch V2 => V3 error --\nYou are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\nPlease read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n-- /AlgoliaSearch V2 => V3 error --"); }}}).call(this,"undefined"!==typeof global?global:"undefined"!==typeof self?self:"undefined"!==typeof window?window:{})},{}],5:[function(c,h,e){h=c(2);e=c(3);c=c(4);h("algoliasearch")?e("algoliasearch"):c()},{2:2,3:3,4:4}]},{},[5])(5)}); (function(C){"object"===typeof exports&&"undefined"!==typeof module?module.exports=C():"function"===typeof define&&define.amd?define([],C):("undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:this).algoliasearch=C()})(function(){return function c(h,e,m){function g(d,k){if(!e[d]){if(!h[d]){var p="function"==typeof require&&require;if(!k&&p)return p(d,!0);if(b)return b(d,!0);p=Error("Cannot find module '"+d+"'");throw p.code="MODULE_NOT_FOUND",p;}p=e[d]= {exports:{}};h[d][0].call(p.exports,function(b){var k=h[d][1][b];return g(k?k:b)},p,p.exports,c,h,e,m)}return e[d].exports}for(var b="function"==typeof require&&require,k=0;k<m.length;k++)g(m[k]);return g}({1:[function(c,h,e){function m(){if(!k){k=!0;for(var d,e=b.length;e;){d=b;b=[];for(var g=-1;++g<e;)d[g]();e=b.length}k=!1}}function g(){}c=h.exports={};var b=[],k=!1;c.nextTick=function(d){b.push(d);k||setTimeout(m,0)};c.title="browser";c.browser=!0;c.env={};c.argv=[];c.version="";c.versions={}; c.on=g;c.addListener=g;c.once=g;c.off=g;c.removeListener=g;c.removeAllListeners=g;c.emit=g;c.binding=function(d){throw Error("process.binding is not supported");};c.cwd=function(){return"/"};c.chdir=function(d){throw Error("process.chdir is not supported");};c.umask=function(){return 0}},{}],2:[function(c,h,e){h.exports=function(e,b,k,d){k=k||"=";var c={};if("string"!==typeof e||0===e.length)return c;var p=/\+/g;e=e.split(b||"&");b=1E3;d&&"number"===typeof d.maxKeys&&(b=d.maxKeys);d=e.length;0<b&& d>b&&(d=b);for(b=0;b<d;++b){var n=e[b].replace(p,"%20"),h=n.indexOf(k),r;0<=h?(r=n.substr(0,h),n=n.substr(h+1)):(r=n,n="");r=decodeURIComponent(r);n=decodeURIComponent(n);Object.prototype.hasOwnProperty.call(c,r)?m(c[r])?c[r].push(n):c[r]=[c[r],n]:c[r]=n}return c};var m=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],3:[function(c,h,e){function m(d,b){if(d.map)return d.map(b);for(var e=[],k=0;k<d.length;k++)e.push(b(d[k],k));return e}var g=function(d){switch(typeof d){case "string":return d; case "boolean":return d?"true":"false";case "number":return isFinite(d)?d:"";default:return""}};h.exports=function(d,e,c,h){e=e||"&";c=c||"=";null===d&&(d=void 0);return"object"===typeof d?m(k(d),function(k){var h=encodeURIComponent(g(k))+c;return b(d[k])?m(d[k],function(a){return h+encodeURIComponent(g(a))}).join(e):h+encodeURIComponent(g(d[k]))}).join(e):h?encodeURIComponent(g(h))+c+encodeURIComponent(g(d)):""};var b=Array.isArray||function(d){return"[object Array]"===Object.prototype.toString.call(d)}, k=Object.keys||function(d){var b=[],e;for(e in d)Object.prototype.hasOwnProperty.call(d,e)&&b.push(e);return b}},{}],4:[function(c,h,e){e.decode=e.parse=c(2);e.encode=e.stringify=c(3)},{2:2,3:3}],5:[function(c,h,e){function m(){var b;try{b=g.debug}catch(d){}return b}e=h.exports=c(6);e.log=function(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)};e.formatArgs=function(){var b=arguments,d=this.useColors;b[0]=(d?"%c":"")+this.namespace+(d? " %c":" ")+b[0]+(d?"%c ":" ")+"+"+e.humanize(this.diff);if(!d)return b;var d="color: "+this.color,b=[b[0],d,"color: inherit"].concat(Array.prototype.slice.call(b,1)),c=0,g=0;b[0].replace(/%[a-z%]/g,function(b){"%%"!==b&&(c++,"%c"===b&&(g=c))});b.splice(g,0,d);return b};e.save=function(b){try{null==b?g.removeItem("debug"):g.debug=b}catch(d){}};e.load=m;e.useColors=function(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)|| navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)};var g;if("undefined"!==typeof chrome&&"undefined"!==typeof chrome.storage)g=chrome.storage.local;else a:{try{g=window.localStorage;break a}catch(b){}g=void 0}e.colors="lightseagreen forestgreen goldenrod dodgerblue darkorchid crimson".split(" ");e.formatters.j=function(b){return JSON.stringify(b)};e.enable(m())},{6:6}],6:[function(c,h,e){e=h.exports=function(b){function k(){}function d(){var b=+new Date;d.diff= b-(g||b);d.prev=g;g=d.curr=b;null==d.useColors&&(d.useColors=e.useColors());null==d.color&&d.useColors&&(d.color=e.colors[m++%e.colors.length]);var c=Array.prototype.slice.call(arguments);c[0]=e.coerce(c[0]);"string"!==typeof c[0]&&(c=["%o"].concat(c));var k=0;c[0]=c[0].replace(/%([a-z%])/g,function(b,a){if("%%"===b)return b;k++;var f=e.formatters[a];"function"===typeof f&&(b=f.call(d,c[k]),c.splice(k,1),k--);return b});"function"===typeof e.formatArgs&&(c=e.formatArgs.apply(d,c));(d.log||e.log|| console.log.bind(console)).apply(d,c)}k.enabled=!1;d.enabled=!0;var c=e.enabled(b)?d:k;c.namespace=b;return c};e.coerce=function(b){return b instanceof Error?b.stack||b.message:b};e.disable=function(){e.enable("")};e.enable=function(b){e.save(b);for(var c=(b||"").split(/[\s,]+/),d=c.length,g=0;g<d;g++)c[g]&&(b=c[g].replace(/\*/g,".*?"),"-"===b[0]?e.skips.push(new RegExp("^"+b.substr(1)+"$")):e.names.push(new RegExp("^"+b+"$")))};e.enabled=function(b){var c,d;c=0;for(d=e.skips.length;c<d;c++)if(e.skips[c].test(b))return!1; c=0;for(d=e.names.length;c<d;c++)if(e.names[c].test(b))return!0;return!1};e.humanize=c(7);e.names=[];e.skips=[];e.formatters={};var m=0,g},{7:7}],7:[function(c,h,e){function m(b){if(b=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(b)){var c=parseFloat(b[1]);switch((b[2]||"ms").toLowerCase()){case "years":case "year":case "yrs":case "yr":case "y":return 315576E5*c;case "days":case "day":case "d":return 864E5*c;case "hours":case "hour":case "hrs":case "hr":case "h":return 36E5* c;case "minutes":case "minute":case "mins":case "min":case "m":return 6E4*c;case "seconds":case "second":case "secs":case "sec":case "s":return 1E3*c;case "milliseconds":case "millisecond":case "msecs":case "msec":case "ms":return c}}}function g(b,c,d){if(!(b<c))return b<1.5*c?Math.floor(b/c)+" "+d:Math.ceil(b/c)+" "+d+"s"}h.exports=function(b,c){c=c||{};return"string"==typeof b?m(b):c.long?g(b,864E5,"day")||g(b,36E5,"hour")||g(b,6E4,"minute")||g(b,1E3,"second")||b+" ms":864E5<=b?Math.round(b/864E5)+ "d":36E5<=b?Math.round(b/36E5)+"h":6E4<=b?Math.round(b/6E4)+"m":1E3<=b?Math.round(b/1E3)+"s":b+"ms"}},{}],8:[function(c,h,e){(function(c,e){(function(){function b(a){return"function"===typeof a}function k(){return function(){c.nextTick(n)}}function d(){var a=0,f=new I(n),b=document.createTextNode("");f.observe(b,{characterData:!0});return function(){b.data=a=++a%2}}function v(){var a=new MessageChannel;a.port1.onmessage=n;return function(){a.port2.postMessage(0)}}function p(){return function(){setTimeout(n, 1)}}function n(){for(var a=0;a<z;a+=2)(0,B[a])(B[a+1]),B[a]=void 0,B[a+1]=void 0;z=0}function x(){}function r(a,f,b,l){try{a.call(f,b,l)}catch(d){return d}}function a(a,f,b){D(function(a){var d=!1,c=r(b,f,function(b){d||(d=!0,f!==b?l(a,b):u(a,b))},function(f){d||(d=!0,t(a,f))},"Settle: "+(a._label||" unknown promise"));!d&&c&&(d=!0,t(a,c))},a)}function f(a,f){1===f._state?u(a,f._result):2===a._state?t(a,f._result):E(f,void 0,function(f){l(a,f)},function(f){t(a,f)})}function l(l,d){if(l===d)t(l,new TypeError("You cannot resolve a promise with itself")); else if("function"===typeof d||"object"===typeof d&&null!==d)if(d.constructor===l.constructor)f(l,d);else{var c;try{c=d.then}catch(e){F.error=e,c=F}c===F?t(l,F.error):void 0===c?u(l,d):b(c)?a(l,d,c):u(l,d)}else u(l,d)}function q(a){a._onerror&&a._onerror(a._result);G(a)}function u(a,f){void 0===a._state&&(a._result=f,a._state=1,0!==a._subscribers.length&&D(G,a))}function t(a,f){void 0===a._state&&(a._state=2,a._result=f,D(q,a))}function E(a,f,b,l){var d=a._subscribers,c=d.length;a._onerror=null;d[c]= f;d[c+1]=b;d[c+2]=l;0===c&&a._state&&D(G,a)}function G(a){var f=a._subscribers,b=a._state;if(0!==f.length){for(var l,d,c=a._result,e=0;e<f.length;e+=3)l=f[e],d=f[e+b],l?J(b,l,d,c):d(c);a._subscribers.length=0}}function K(){this.error=null}function J(a,f,d,c){var e=b(d),q,g,k,h;if(e){try{q=d(c)}catch(p){H.error=p,q=H}q===H?(h=!0,g=q.error,q=null):k=!0;if(f===q){t(f,new TypeError("A promises callback cannot return that same promise."));return}}else q=c,k=!0;void 0===f._state&&(e&&k?l(f,q):h?t(f,g): 1===a?u(f,q):2===a&&t(f,q))}function N(a,f){try{f(function(f){l(a,f)},function(f){t(a,f)})}catch(b){t(a,b)}}function w(a,f,b,l){this._instanceConstructor=a;this.promise=new a(x,l);this._abortOnReject=b;this._validateInput(f)?(this._input=f,this._remaining=this.length=f.length,this._init(),0===this.length?u(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&u(this.promise,this._result))):t(this.promise,this._validationError())}function y(a){this._id=O++;this._result= this._state=void 0;this._subscribers=[];if(x!==a){if(!b(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof y))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");N(this,a)}}var L=Array.isArray?Array.isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)},z=0,D=function(a,f){B[z]=a;B[z+1]=f;z+=2;2===z&&M()},A= "undefined"!==typeof window?window:{},I=A.MutationObserver||A.WebKitMutationObserver,A="undefined"!==typeof Uint8ClampedArray&&"undefined"!==typeof importScripts&&"undefined"!==typeof MessageChannel,B=Array(1E3),M;M="undefined"!==typeof c&&"[object process]"==={}.toString.call(c)?k():I?d():A?v():p();var F=new K,H=new K;w.prototype._validateInput=function(a){return L(a)};w.prototype._validationError=function(){return Error("Array Methods must be provided an Array")};w.prototype._init=function(){this._result= Array(this.length)};w.prototype._enumerate=function(){for(var a=this.length,f=this.promise,b=this._input,l=0;void 0===f._state&&l<a;l++)this._eachEntry(b[l],l)};w.prototype._eachEntry=function(a,f){var b=this._instanceConstructor;"object"===typeof a&&null!==a?a.constructor===b&&void 0!==a._state?(a._onerror=null,this._settledAt(a._state,f,a._result)):this._willSettleAt(b.resolve(a),f):(this._remaining--,this._result[f]=this._makeResult(1,f,a))};w.prototype._settledAt=function(a,f,b){var l=this.promise; void 0===l._state&&(this._remaining--,this._abortOnReject&&2===a?t(l,b):this._result[f]=this._makeResult(a,f,b));0===this._remaining&&u(l,this._result)};w.prototype._makeResult=function(a,f,b){return b};w.prototype._willSettleAt=function(a,f){var b=this;E(a,void 0,function(a){b._settledAt(1,f,a)},function(a){b._settledAt(2,f,a)})};var O=0;y.all=function(a,f){return(new w(this,a,!0,f)).promise};y.race=function(a,f){function b(a){l(c,a)}function d(a){t(c,a)}var c=new this(x,f);if(!L(a))return t(c,new TypeError("You must pass an array to race.")), c;for(var e=a.length,q=0;void 0===c._state&&q<e;q++)E(this.resolve(a[q]),void 0,b,d);return c};y.resolve=function(a,f){if(a&&"object"===typeof a&&a.constructor===this)return a;var b=new this(x,f);l(b,a);return b};y.reject=function(a,f){var b=new this(x,f);t(b,a);return b};y.prototype={constructor:y,then:function(a,f){var b=this._state;if(1===b&&!a||2===b&&!f)return this;var l=new this.constructor(x),d=this._result;if(b){var c=arguments[b-1];D(function(){J(b,l,c,d)})}else E(this,l,a,f);return l},"catch":function(a){return this.then(null, a)}};A={Promise:y,polyfill:function(){var a;a="undefined"!==typeof e?e:"undefined"!==typeof window&&window.document?window:self;"Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var f;new a.Promise(function(a){f=a});return b(f)}()||(a.Promise=y)}};"undefined"!==typeof h&&h.exports?h.exports=A:"undefined"!==typeof this&&(this.ES6Promise=A)}).call(this)}).call(this,c(1),"undefined"!==typeof global?global:"undefined"!==typeof self?self:"undefined"!== typeof window?window:{})},{1:1}],9:[function(c,h,e){var m=Object.prototype.hasOwnProperty,g=Object.prototype.toString,b=c(10),k=function(b){if(!b||"[object Object]"!==g.call(b))return!1;var c=m.call(b,"constructor"),e=b.constructor&&b.constructor.prototype&&m.call(b.constructor.prototype,"isPrototypeOf");if(b.constructor&&!c&&!e)return!1;for(var k in b);return void 0===k||m.call(b,k)};h.exports=function v(){var c,e,g,h,a,f=arguments[0],l=1,q=arguments.length,u=!1;if("boolean"===typeof f)u=f,f=arguments[1]|| {},l=2;else if("object"!==typeof f&&"function"!==typeof f||null==f)f={};for(;l<q;++l)if(c=arguments[l],null!=c)for(e in c)g=f[e],h=c[e],f!==h&&(u&&h&&(k(h)||(a=b(h)))?(a?(a=!1,g=g&&b(g)?g:[]):g=g&&k(g)?g:{},f[e]=v(u,g,h)):void 0!==h&&(f[e]=h));return f}},{10:10}],10:[function(c,h,e){h.exports=Array.isArray||function(c){return"[object Array]"==Object.prototype.toString.call(c)}},{}],11:[function(c,h,e){var m=Object.prototype.hasOwnProperty,g=Object.prototype.toString;h.exports=function(b,c,d){if("[object Function]"!== g.call(c))throw new TypeError("iterator must be a function");var e=b.length;if(e===+e)for(var h=0;h<e;h++)c.call(d,b[h],h,b);else for(h in b)m.call(b,h)&&c.call(d,b[h],h,b)}},{}],12:[function(c,h,e){h.exports="function"===typeof Object.create?function(c,e){c.super_=e;c.prototype=Object.create(e.prototype,{constructor:{value:c,enumerable:!1,writable:!0,configurable:!0}})}:function(c,e){c.super_=e;var b=function(){};b.prototype=e.prototype;c.prototype=new b;c.prototype.constructor=c}},{}],13:[function(c, h,e){(function(e){function g(a,f,l){var d=c(9);if(!a)throw Error("algoliasearch: Please provide an application ID. Usage: algoliasearch(applicationID, apiKey, opts)");if(!f)throw Error("algoliasearch: Please provide an API key. Usage: algoliasearch(applicationID, apiKey, opts)");this.applicationID=a;this.apiKey=f;a=[this.applicationID+"-1.algolianet.com",this.applicationID+"-2.algolianet.com",this.applicationID+"-3.algolianet.com"];this.hosts={read:[],write:[]};this.hostIndex={read:0,write:0};l=l|| {};f=l.protocol||"https:";var e=void 0===l.timeout?2E3:l.timeout;/:$/.test(f)||(f+=":");if("http:"!==l.protocol&&"https:"!==l.protocol)throw Error("algoliasearch: protocol must be `http:` or `https:` (was `"+l.protocol+"`)");l.hosts?(this.hosts.read=d([],l.hosts),this.hosts.write=d([],l.hosts)):(this.hosts.read=[this.applicationID+"-dsn.algolia.net"].concat(a),this.hosts.write=[this.applicationID+".algolia.net"].concat(a));this.hosts.read=b(this.hosts.read,k(f));this.hosts.write=b(this.hosts.write, k(f));this.requestTimeout=e;this.extraHeaders=[];this.cache={};this._ua=l._ua;this._useCache=void 0===l._useCache?!0:l._useCache;this._setTimeout=l._setTimeout;x("init done, %j",this)}function b(a,f){for(var b=[],c=0;c<a.length;++c)b.push(f(a[c],c));return b}function k(a){return function(f){return a+"//"+f.toLowerCase()}}function d(){throw Error("algoliasearch: Not implemented in this environment.\nIf you feel this is a mistake, write to support@algolia.com");}function v(a,f){var b=a.toLowerCase().replace(".", "").replace("()","");return"algoliasearch: `"+a+"` was replaced by `"+f+"`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#"+b}function p(a,f){f(a,0)}function n(a,f){var b=!1;return function(){b||(console.log(f),b=!0);return a.apply(this,arguments)}}h.exports=g;"development"===e.env.NODE_ENV&&c(5).enable("algoliasearch*");var x=c(5)("algoliasearch"),r=c(11);g.prototype={deleteIndex:function(a,f){return this._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(a), hostType:"write",callback:f})},moveIndex:function(a,f,b){f={operation:"move",destination:f};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(a)+"/operation",body:f,hostType:"write",callback:b})},copyIndex:function(a,f,b){f={operation:"copy",destination:f};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(a)+"/operation",body:f,hostType:"write",callback:b})},getLogs:function(a,f,b){if(0===arguments.length||"function"===typeof a)b=a,a=0,f=10;else if(1=== arguments.length||"function"===typeof f)b=f,f=10;return this._jsonRequest({method:"GET",url:"/1/logs?offset="+a+"&length="+f,hostType:"read",callback:b})},listIndexes:function(a,f){var b="";void 0===a||"function"===typeof a?f=a:b="?page="+a;return this._jsonRequest({method:"GET",url:"/1/indexes"+b,hostType:"read",callback:f})},initIndex:function(a){return new this.Index(this,a)},listUserKeys:function(a){return this._jsonRequest({method:"GET",url:"/1/keys",hostType:"read",callback:a})},getUserKeyACL:function(a, f){return this._jsonRequest({method:"GET",url:"/1/keys/"+a,hostType:"read",callback:f})},deleteUserKey:function(a,f){return this._jsonRequest({method:"DELETE",url:"/1/keys/"+a,hostType:"write",callback:f})},addUserKey:function(a,f,b){if(1===arguments.length||"function"===typeof f)b=f,f=null;var c={acl:a};f&&(c.validity=f.validity,c.maxQueriesPerIPPerHour=f.maxQueriesPerIPPerHour,c.maxHitsPerQuery=f.maxHitsPerQuery,c.indexes=f.indexes);return this._jsonRequest({method:"POST",url:"/1/keys",body:c,hostType:"write", callback:b})},addUserKeyWithValidity:n(function(a,f,b){return this.addUserKey(a,f,b)},v("client.addUserKeyWithValidity()","client.addUserKey()")),updateUserKey:function(a,f,b,c){if(2===arguments.length||"function"===typeof b)c=b,b=null;var d={acl:f};b&&(d.validity=b.validity,d.maxQueriesPerIPPerHour=b.maxQueriesPerIPPerHour,d.maxHitsPerQuery=b.maxHitsPerQuery,d.indexes=b.indexes);return this._jsonRequest({method:"PUT",url:"/1/keys/"+a,body:d,hostType:"write",callback:c})},setSecurityTags:function(a){if("[object Array]"=== Object.prototype.toString.call(a)){for(var f=[],b=0;b<a.length;++b)if("[object Array]"===Object.prototype.toString.call(a[b])){for(var c=[],d=0;d<a[b].length;++d)c.push(a[b][d]);f.push("("+c.join(",")+")")}else f.push(a[b]);a=f.join(",")}this.securityTags=a},setUserToken:function(a){this.userToken=a},startQueriesBatch:n(function(){this._batch=[]},v("client.startQueriesBatch()","client.search()")),addQueryInBatch:n(function(a,f,b){this._batch.push({indexName:a,query:f,params:b})},v("client.addQueryInBatch()", "client.search()")),clearCache:function(){this.cache={}},sendQueriesBatch:n(function(a){return this.search(this._batch,a)},v("client.sendQueriesBatch()","client.search()")),setRequestTimeout:function(a){a&&(this.requestTimeout=parseInt(a,10))},search:function(a,f){var c=this,d={requests:b(a,function(a){var f="";void 0!==a.query&&(f+="query="+encodeURIComponent(a.query));return{indexName:a.indexName,params:c._getSearchParams(a.params,f)}})};return this._jsonRequest({cache:this.cache,method:"POST", url:"/1/indexes/*/queries",body:d,hostType:"read",callback:f})},destroy:d,enableRateLimitForward:d,disableRateLimitForward:d,useSecuredAPIKey:d,disableSecuredAPIKey:d,generateSecuredApiKey:d,Index:function(a,f){this.indexName=f;this.as=a;this.typeAheadValueOption=this.typeAheadArgs=null;this.cache={}},setExtraHeader:function(a,f){this.extraHeaders.push({name:a.toLowerCase(),value:f})},_sendQueriesBatch:function(a,f){return this._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/*/queries", body:a,hostType:"read",fallback:{method:"GET",url:"/1/indexes/*",body:{params:function(){for(var f="",b=0;b<a.requests.length;++b)var c="/1/indexes/"+encodeURIComponent(a.requests[b].indexName)+"?"+a.requests[b].params,f=f+(b+"="+encodeURIComponent(c)+"&");return f}()}},callback:f})},_jsonRequest:function(a){function f(c,m){function p(){g.hostIndex[a.hostType]=++g.hostIndex[a.hostType]%g.hosts[a.hostType].length;h+=1;m.timeout=g.requestTimeout*(h+1);return f(c,m)}var n;g._useCache&&(n=a.url);g._useCache&& d&&(n+="_body_"+m.body);if(g._useCache&&e&&void 0!==e[n])return b("serving response from cache"),g._promise.resolve(e[n]);if(h>=g.hosts[a.hostType].length){if(!a.fallback||!g._request.fallback||k)return g._promise.reject(Error("Cannot connect to the AlgoliaSearch API. Send an email to support@algolia.com to report and resolve the issue."));h=0;m.method=a.fallback.method;m.url=a.fallback.url;m.jsonBody=a.fallback.body;m.jsonBody&&(m.body=JSON.stringify(a.fallback.body));m.timeout=g.requestTimeout* (h+1);g.hostIndex[a.hostType]=0;k=g.useFallback=!0;return f(g._request.fallback,m)}return c.call(g,g.hosts[a.hostType][g.hostIndex[a.hostType]]+m.url,{body:d,jsonBody:a.body,method:m.method,headers:g._computeRequestHeaders(),timeout:m.timeout,debug:b}).then(function(a){if(a instanceof Error)return b("error: %s",a.message),p();b("received response: %j",a);var f=a&&a.body&&a.body.message&&a.body.status||a.statusCode||a&&a.body&&200,c=200===f||201===f,f=!c&&4!==Math.floor(f/100)&&1!==Math.floor(f/100); g._useCache&&c&&e&&(e[n]=a.body);return c?a.body:f?p():g._promise.reject(Error(a.body&&a.body.message||"Unknown error"))},function(d){b("error: %s, stack: %s",d.message,d.stack);g.useFallback?(g.hostIndex[a.hostType]=++g.hostIndex[a.hostType]%g.hosts[a.hostType].length,h+=1):h=g.hosts[a.hostType].length;return f(c,m)})}var b=c(5)("algoliasearch:"+a.url),d,e=a.cache,g=this,h=0,k=!1;void 0!==a.body&&(d=JSON.stringify(a.body));b("request start");var m=g.useFallback&&a.fallback,n=m?a.fallback:a,m=f(m? g._request.fallback:g._request,{url:n.url,method:n.method,body:d,jsonBody:a.body,timeout:g.requestTimeout*(h+1)});if(a.callback)m.then(function(f){p(function(){a.callback(null,f)},g._setTimeout||setTimeout)},function(f){p(function(){a.callback(f)},g._setTimeout||setTimeout)});else return m},_getSearchParams:function(a,f){if(this._isUndefined(a)||null===a)return f;for(var b in a)null!==b&&a.hasOwnProperty(b)&&(f+=""===f?"":"&",f+=b+"="+encodeURIComponent("[object Array]"===Object.prototype.toString.call(a[b])? JSON.stringify(a[b]):a[b]));return f},_isUndefined:function(a){return void 0===a},_computeRequestHeaders:function(){var a={"x-algolia-api-key":this.apiKey,"x-algolia-application-id":this.applicationID,"x-user-agent":this._ua};this.userToken&&(a["x-algolia-usertoken"]=this.userToken);this.securityTags&&(a["x-algolia-tagfilters"]=this.securityTags);this.extraHeaders&&r(this.extraHeaders,function(b){a[b.name]=b.value});return a}};g.prototype.Index.prototype={clearCache:function(){this.cache={}},addObject:function(a, b,c){if(1===arguments.length||"function"===typeof b)c=b,b=void 0;return this.as._jsonRequest({method:void 0!==b?"PUT":"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+(void 0!==b?"/"+encodeURIComponent(b):""),body:a,hostType:"write",callback:c})},addObjects:function(a,b){for(var c={requests:[]},d=0;d<a.length;++d)c.requests.push({action:"addObject",body:a[d]});return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/batch",body:c,hostType:"write", callback:b})},getObject:function(a,b,c){if(1===arguments.length||"function"===typeof b)c=b,b=void 0;var d="";if(void 0!==b)for(var d="?attributes=",e=0;e<b.length;++e)0!==e&&(d+=","),d+=b[e];return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/"+encodeURIComponent(a)+d,hostType:"read",callback:c})},getObjects:function(a,f){var c=this,d={requests:b(a,function(a){return{indexName:c.indexName,objectID:a}})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/*/objects", hostType:"read",body:d,callback:f})},partialUpdateObject:function(a,b){return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/"+encodeURIComponent(a.objectID)+"/partial",body:a,hostType:"write",callback:b})},partialUpdateObjects:function(a,b){for(var c={requests:[]},d=0;d<a.length;++d)c.requests.push({action:"partialUpdateObject",objectID:a[d].objectID,body:a[d]});return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+ "/batch",body:c,hostType:"write",callback:b})},saveObject:function(a,b){return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/"+encodeURIComponent(a.objectID),body:a,hostType:"write",callback:b})},saveObjects:function(a,b){for(var c={requests:[]},d=0;d<a.length;++d)c.requests.push({action:"updateObject",objectID:a[d].objectID,body:a[d]});return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/batch",body:c,hostType:"write", callback:b})},deleteObject:function(a,b){if("function"===typeof a||"string"!==typeof a&&"number"!==typeof a){var c=Error("Cannot delete an object without an objectID");b=a;return"function"===typeof b?b(c):this.as._promise.reject(c)}return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/"+encodeURIComponent(a),hostType:"write",callback:b})},deleteObjects:function(a,f){var c={requests:b(a,function(a){return{action:"deleteObject",objectID:a,body:{objectID:a}}})}; return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/batch",body:c,hostType:"write",callback:f})},deleteByQuery:function(a,f,c){function d(a){return g.waitTask(a.taskID)}function e(){return g.deleteByQuery(a,f)}var g=this,h=g.as;if(1===arguments.length||"function"===typeof f)c=f,f={};f.attributesToRetrieve="objectID";f.hitsPerPage=1E3;this.clearCache();var k=this.search(a,f).then(function(a){if(0===a.nbHits)return a;a=b(a.hits,function(a){return a.objectID}); return g.deleteObjects(a).then(d).then(e)});if(!c)return k;k.then(function(){p(function(){c(null)},h._setTimeout||setTimeout)},function(a){p(function(){c(a)},h._setTimeout||setTimeout)})},search:function(a,b,c){if("function"===typeof a&&"object"===typeof b||"object"===typeof c)throw Error("algoliasearch: index.search usage is index.search(query, params, cb)");if(0===arguments.length||"function"===typeof a)c=a,a="";else if(1===arguments.length||"function"===typeof b)c=b,b=void 0;if("object"===typeof a&& null!==a)b=a,a=void 0;else if(void 0===a||null===a)a="";var d="";void 0!==a&&(d+="query="+encodeURIComponent(a));void 0!==b&&(d=this.as._getSearchParams(b,d));return this._search(d,c)},browse:function(a,b,c){if(1===arguments.length||"function"===typeof b)c=b,b=void 0;var d="?page="+a;this.as._isUndefined(b)||(d+="&hitsPerPage="+b);return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/browse"+d,hostType:"read",callback:c})},ttAdapter:function(a){var b=this; return function(c,d){b.search(c,a,function(a,b){a?d(a):d(b.hits)})}},waitTask:function(a,b){var c=this,d=c.as,e=this.as._jsonRequest({method:"GET",hostType:"read",url:"/1/indexes/"+encodeURIComponent(c.indexName)+"/task/"+a}).then(function(b){return"published"!==b.status?c.as._promise.delay(100).then(function(){return c.waitTask(a)}):b});if(!b)return e;e.then(function(a){p(function(){b(null,a)},d._setTimeout||setTimeout)},function(a){p(function(){b(a)},d._setTimeout||setTimeout)})},clearIndex:function(a){return this.as._jsonRequest({method:"POST", url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/clear",hostType:"write",callback:a})},getSettings:function(a){return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/settings",hostType:"read",callback:a})},setSettings:function(a,b){return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/settings",hostType:"write",body:a,callback:b})},listUserKeys:function(a){return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+ encodeURIComponent(this.indexName)+"/keys",hostType:"read",callback:a})},getUserKeyACL:function(a,b){return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys/"+a,hostType:"read",callback:b})},deleteUserKey:function(a,b){return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys/"+a,hostType:"write",callback:b})},addUserKey:function(a,b,c){if(1===arguments.length||"function"===typeof b)c=b,b=null;var d={acl:a}; b&&(d.validity=b.validity,d.maxQueriesPerIPPerHour=b.maxQueriesPerIPPerHour,d.maxHitsPerQuery=b.maxHitsPerQuery);return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys",body:d,hostType:"write",callback:c})},addUserKeyWithValidity:n(function(a,b,c){return this.addUserKey(a,b,c)},v("index.addUserKeyWithValidity()","index.addUserKey()")),updateUserKey:function(a,b,c,d){if(2===arguments.length||"function"===typeof c)d=c,c=null;var e={acl:b};c&&(e.validity= c.validity,e.maxQueriesPerIPPerHour=c.maxQueriesPerIPPerHour,e.maxHitsPerQuery=c.maxHitsPerQuery);return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys/"+a,body:e,hostType:"write",callback:d})},_search:function(a,b){return this.as._jsonRequest({cache:this.cache,method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/query",body:{params:a},hostType:"read",fallback:{method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName),body:{params:a}}, callback:b})},as:null,indexName:null,typeAheadArgs:null,typeAheadValueOption:null}}).call(this,c(1))},{1:1,11:11,5:5,9:9}],14:[function(c,h,e){h.exports=function(c,b,e){function d(){b.debug("JSONP: success");u||a||(u=!0,r||(b.debug("JSONP: Fail. Script loaded but did not call the callback"),p(),e(Error("Failed to load JSONP script"))))}function h(){"loaded"!==this.readyState&&"complete"!==this.readyState||d()}function p(){clearTimeout(t);l.onload=null;l.onreadystatechange=null;l.onerror=null;f.removeChild(l); try{delete window[q],delete window[q+"_loaded"]}catch(a){window[q]=null,window[q+"_loaded"]=null}}function n(){b.debug("JSONP: Script timeout");a=!0;p();e(Error("Timeout - Could not connect to endpoint "+c))}function x(){b.debug("JSONP: Script error");u||a||(p(),e(Error("Failed to load JSONP script")))}if("GET"!==b.method)e(Error("Method "+b.method+" "+c+" is not supported by JSONP."));else{b.debug("JSONP: start");var r=!1,a=!1;m+=1;var f=document.getElementsByTagName("head")[0],l=document.createElement("script"), q="algoliaJSONP_"+m,u=!1;window[q]=function(b){try{delete window[q]}catch(c){window[q]=void 0}a||(r=!0,p(),e(null,{body:b}))};c+="&callback="+q;b.jsonBody&&b.jsonBody.params&&(c+="&"+b.jsonBody.params);var t=setTimeout(n,b.timeout);l.onreadystatechange=h;l.onload=d;l.onerror=x;l.async=!0;l.defer=!0;l.src=c;f.appendChild(l)}};var m=0},{}],15:[function(c,h,e){(function(e){function g(a,d,e){var h=c(9),k=c(16);e=h(!0,{},e)||{};void 0===e.protocol&&(e.protocol=k());e._ua=g.ua;return new b(a,d,e)}function b(){v.apply(this, arguments)}h.exports=g;var k=c(12),d=e.Promise||c(8).Promise,v=c(13),p=c(17),n=c(14);g.version=c(18);g.ua="Algolia for vanilla JavaScript "+g.version;var x="XDomainRequest"in window,r="withCredentials"in new XMLHttpRequest,a="timeout"in new XMLHttpRequest;k(b,v);b.prototype._request=function(b,c){return new d(function(d,e){function g(){if(!w){a||clearTimeout(v);var b=null;try{b=JSON.parse(n.responseText)}catch(c){}d({body:b,statusCode:n.status})}}function h(b){w||(a||clearTimeout(v),e(Error("Could not connect to host, error was:"+ b)))}function k(){a||(w=!0,n.abort());d(Error("Timeout - Could not connect to endpoint "+b))}if(r||x){b=p(b,c.headers);var m=c.body,n=r?new XMLHttpRequest:new XDomainRequest,v,w;n instanceof XMLHttpRequest?n.open(c.method,b,!0):n.open(c.method,b);r&&m&&"GET"!==c.method&&n.setRequestHeader("content-type","application/x-www-form-urlencoded");n.onprogress=function(){};n.onload=g;n.onerror=h;a?(n.timeout=c.timeout,n.ontimeout=k):v=setTimeout(k,c.timeout);n.send(m)}else e(Error("CORS not supported"))})}; b.prototype._request.fallback=function(a,b){a=p(a,b.headers);return new d(function(c,d){n(a,b,function(a,b){a?d(a):c(b)})})};b.prototype._promise={reject:function(a){return d.reject(a)},resolve:function(a){return d.resolve(a)},delay:function(a){return new d(function(b){setTimeout(b,a)})}}}).call(this,"undefined"!==typeof global?global:"undefined"!==typeof self?self:"undefined"!==typeof window?window:{})},{12:12,13:13,14:14,16:16,17:17,18:18,8:8,9:9}],16:[function(c,h,e){(function(c){h.exports=function(){var e= c.document.location.protocol;"http:"!==e&&"https:"!==e&&(e="http:");return e}}).call(this,"undefined"!==typeof global?global:"undefined"!==typeof self?self:"undefined"!==typeof window?window:{})},{}],17:[function(c,h,e){h.exports=function(c,b){c=/\?/.test(c)?c+"&":c+"?";return c+m.encode(b)};var m=c(4)},{4:4}],18:[function(c,h,e){h.exports="3.3.2"},{}]},{},[15])(15)});
/* http://keith-wood.name/datepick.html Norwegian localisation for jQuery Datepicker. Written by Naimdjon Takhirov (naimdjon@gmail.com). */ (function($) { $.datepick.regional['no'] = { monthNames: ['Januar','Februar','Mars','April','Mai','Juni', 'Juli','August','September','Oktober','November','Desember'], monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jun', 'Jul','Aug','Sep','Okt','Nov','Des'], dayNamesShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'], dayNames: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'], dayNamesMin: ['Sø','Ma','Ti','On','To','Fr','Lø'], dateFormat: 'yyyy-mm-dd', firstDay: 0, renderer: $.datepick.defaultRenderer, prevText: '&laquo;Forrige', prevStatus: '', prevJumpText: '&#x3c;&#x3c;', prevJumpStatus: '', nextText: 'Neste&raquo;', nextStatus: '', nextJumpText: '&#x3e;&#x3e;', nextJumpStatus: '', currentText: 'I dag', currentStatus: '', todayText: 'I dag', todayStatus: '', clearText: 'Tøm', clearStatus: '', closeText: 'Lukk', closeStatus: '', yearStatus: '', monthStatus: '', weekText: 'Uke', weekStatus: '', dayStatus: 'D, M d', defaultStatus: '', isRTL: false }; $.datepick.setDefaults($.datepick.regional['no']); })(jQuery);
var convert = require('./convert'); module.exports = convert(require('../object'));
/** * @license * Video.js 6.0.0-RC.2 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> * * Includes vtt.js <https://github.com/mozilla/vtt.js> * Available under Apache License Version 2.0 * <https://github.com/mozilla/vtt.js/blob/master/LICENSE> */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file big-play-button.js */ /** * The initial play button that shows before the video has played. The hiding of the * `BigPlayButton` get done via CSS and `Player` states. * * @extends Button */ var BigPlayButton = function (_Button) { _inherits(BigPlayButton, _Button); function BigPlayButton() { _classCallCheck(this, BigPlayButton); return _possibleConstructorReturn(this, _Button.apply(this, arguments)); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. Always returns 'vjs-big-play-button'. */ BigPlayButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; }; /** * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent} * for more detailed information on what a click can be. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ BigPlayButton.prototype.handleClick = function handleClick(event) { var playPromise = this.player_.play(); var cb = this.player_.getChild('controlBar'); var playToggle = cb && cb.getChild('playToggle'); if (!playToggle) { this.player_.focus(); return; } if (playPromise) { playPromise.then(function () { return playToggle.focus(); }); } else { this.setTimeout(function () { playToggle.focus(); }, 1); } }; return BigPlayButton; }(_button2['default']); /** * The text that should display over the `BigPlayButton`s controls. Added to for localization. * * @type {string} * @private */ BigPlayButton.prototype.controlText_ = 'Play Video'; _component2['default'].registerComponent('BigPlayButton', BigPlayButton); exports['default'] = BigPlayButton; },{"2":2,"5":5}],2:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _obj = _dereq_(91); 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; } /** * @file button.js */ /** * Base class for all buttons. * * @extends ClickableComponent */ var Button = function (_ClickableComponent) { _inherits(Button, _ClickableComponent); function Button() { _classCallCheck(this, Button); return _possibleConstructorReturn(this, _ClickableComponent.apply(this, arguments)); } /** * Create the `Button`s DOM element. * * @param {string} [tag="button"] * The element's node type. This argument is IGNORED: no matter what * is passed, it will always create a `button` element. * * @param {Object} [props={}] * An object of properties that should be set on the element. * * @param {Object} [attributes={}] * An object of attributes that should be set on the element. * * @return {Element} * The element that gets created. */ Button.prototype.createEl = function createEl(tag) { var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; tag = 'button'; props = (0, _obj.assign)({ innerHTML: '<span aria-hidden="true" class="vjs-icon-placeholder"></span>', className: this.buildCSSClass() }, props); // Add attributes for button element attributes = (0, _obj.assign)({ // Necessary since the default button type is "submit" 'type': 'button', // let the screen reader user know that the text of the button may change 'aria-live': 'polite' }, attributes); var el = _component2['default'].prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; }; /** * Add a child `Component` inside of this `Button`. * * @param {string|Component} child * The name or instance of a child to add. * * @param {Object} [options={}] * The key/value store of options that will get passed to children of * the child. * * @return {Component} * The `Component` that gets added as a child. When using a string the * `Component` will get created by this process. * * @deprecated since version 5 */ Button.prototype.addChild = function addChild(child) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var className = this.constructor.name; _log2['default'].warn('Adding an actionable (user controllable) child to a Button (' + className + ') is not supported; use a ClickableComponent instead.'); // Avoid the error message generated by ClickableComponent's addChild method return _component2['default'].prototype.addChild.call(this, child, options); }; /** * Enable the `Button` element so that it can be activated or clicked. Use this with * {@link Button#disable}. */ Button.prototype.enable = function enable() { _ClickableComponent.prototype.enable.call(this); this.el_.removeAttribute('disabled'); }; /** * Enable the `Button` element so that it cannot be activated or clicked. Use this with * {@link Button#enable}. */ Button.prototype.disable = function disable() { _ClickableComponent.prototype.disable.call(this); this.el_.setAttribute('disabled', 'disabled'); }; /** * This gets called when a `Button` has focus and `keydown` is triggered via a key * press. * * @param {EventTarget~Event} event * The event that caused this function to get called. * * @listens keydown */ Button.prototype.handleKeyPress = function handleKeyPress(event) { // Ignore Space (32) or Enter (13) key operation, which is handled by the browser for a button. if (event.which === 32 || event.which === 13) { return; } // Pass keypress handling up for unsupported keys _ClickableComponent.prototype.handleKeyPress.call(this, event); }; return Button; }(_clickableComponent2['default']); _component2['default'].registerComponent('Button', Button); exports['default'] = Button; },{"3":3,"5":5,"89":89,"91":91}],3:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _events = _dereq_(84); var Events = _interopRequireWildcard(_events); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _obj = _dereq_(91); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file button.js */ /** * Clickable Component which is clickable or keyboard actionable, * but is not a native HTML button. * * @extends Component */ var ClickableComponent = function (_Component) { _inherits(ClickableComponent, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ClickableComponent(player, options) { _classCallCheck(this, ClickableComponent); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.emitTapEvents(); _this.enable(); return _this; } /** * Create the `Component`s DOM element. * * @param {string} [tag=div] * The element's node type. * * @param {Object} [props={}] * An object of properties that should be set on the element. * * @param {Object} [attributes={}] * An object of attributes that should be set on the element. * * @return {Element} * The element that gets created. */ ClickableComponent.prototype.createEl = function createEl() { var tag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div'; var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; props = (0, _obj.assign)({ innerHTML: '<span aria-hidden="true" class="vjs-icon-placeholder"></span>', className: this.buildCSSClass(), tabIndex: 0 }, props); if (tag === 'button') { _log2['default'].error('Creating a ClickableComponent with an HTML element of ' + tag + ' is not supported; use a Button instead.'); } // Add ARIA attributes for clickable element which is not a native HTML button attributes = (0, _obj.assign)({ 'role': 'button', // let the screen reader user know that the text of the element may change 'aria-live': 'polite' }, attributes); this.tabIndex_ = props.tabIndex; var el = _Component.prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; }; /** * Create a control text element on this `Component` * * @param {Element} [el] * Parent element for the control text. * * @return {Element} * The control text element that gets created. */ ClickableComponent.prototype.createControlTextEl = function createControlTextEl(el) { this.controlTextEl_ = Dom.createEl('span', { className: 'vjs-control-text' }); if (el) { el.appendChild(this.controlTextEl_); } this.controlText(this.controlText_, el); return this.controlTextEl_; }; /** * Get or set the localize text to use for the controls on the `Component`. * * @param {string} [text] * Control text for element. * * @param {Element} [el=this.el()] * Element to set the title on. * * @return {string} * - The control text when getting */ ClickableComponent.prototype.controlText = function controlText(text) { var el = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.el(); if (!text) { return this.controlText_ || 'Need Text'; } var localizedText = this.localize(text); this.controlText_ = text; this.controlTextEl_.innerHTML = localizedText; if (!this.nonIconControl) { // Set title attribute if only an icon is shown el.setAttribute('title', localizedText); } }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ClickableComponent.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this); }; /** * Enable this `Component`s element. */ ClickableComponent.prototype.enable = function enable() { this.removeClass('vjs-disabled'); this.el_.setAttribute('aria-disabled', 'false'); if (typeof this.tabIndex_ !== 'undefined') { this.el_.setAttribute('tabIndex', this.tabIndex_); } this.on('tap', this.handleClick); this.on('click', this.handleClick); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); }; /** * Disable this `Component`s element. */ ClickableComponent.prototype.disable = function disable() { this.addClass('vjs-disabled'); this.el_.setAttribute('aria-disabled', 'true'); if (typeof this.tabIndex_ !== 'undefined') { this.el_.removeAttribute('tabIndex'); } this.off('tap', this.handleClick); this.off('click', this.handleClick); this.off('focus', this.handleFocus); this.off('blur', this.handleBlur); }; /** * This gets called when a `ClickableComponent` gets: * - Clicked (via the `click` event, listening starts in the constructor) * - Tapped (via the `tap` event, listening starts in the constructor) * - The following things happen in order: * 1. {@link ClickableComponent#handleFocus} is called via a `focus` event on the * `ClickableComponent`. * 2. {@link ClickableComponent#handleFocus} adds a listener for `keydown` on using * {@link ClickableComponent#handleKeyPress}. * 3. `ClickableComponent` has not had a `blur` event (`blur` means that focus was lost). The user presses * the space or enter key. * 4. {@link ClickableComponent#handleKeyPress} calls this function with the `keydown` * event as a parameter. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click * @abstract */ ClickableComponent.prototype.handleClick = function handleClick(event) {}; /** * This gets called when a `ClickableComponent` gains focus via a `focus` event. * Turns on listening for `keydown` events. When they happen it * calls `this.handleKeyPress`. * * @param {EventTarget~Event} event * The `focus` event that caused this function to be called. * * @listens focus */ ClickableComponent.prototype.handleFocus = function handleFocus(event) { Events.on(_document2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; /** * Called when this ClickableComponent has focus and a key gets pressed down. By * default it will call `this.handleClick` when the key is space or enter. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ ClickableComponent.prototype.handleKeyPress = function handleKeyPress(event) { // Support Space (32) or Enter (13) key operation to fire a click event if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleClick(event); } else if (_Component.prototype.handleKeyPress) { // Pass keypress handling up for unsupported keys _Component.prototype.handleKeyPress.call(this, event); } }; /** * Called when a `ClickableComponent` loses focus. Turns off the listener for * `keydown` events. Which Stops `this.handleKeyPress` from getting called. * * @param {EventTarget~Event} event * The `blur` event that caused this function to be called. * * @listens blur */ ClickableComponent.prototype.handleBlur = function handleBlur(event) { Events.off(_document2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; return ClickableComponent; }(_component2['default']); _component2['default'].registerComponent('ClickableComponent', ClickableComponent); exports['default'] = ClickableComponent; },{"5":5,"83":83,"84":84,"86":86,"89":89,"91":91,"97":97}],4:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file close-button.js */ /** * The `CloseButton` is a `{@link Button}` that fires a `close` event when * it gets clicked. * * @extends Button */ var CloseButton = function (_Button) { _inherits(CloseButton, _Button); /** * Creates an instance of the this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CloseButton(player, options) { _classCallCheck(this, CloseButton); var _this = _possibleConstructorReturn(this, _Button.call(this, player, options)); _this.controlText(options && options.controlText || _this.localize('Close')); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ CloseButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-close-button ' + _Button.prototype.buildCSSClass.call(this); }; /** * This gets called when a `CloseButton` gets clicked. See * {@link ClickableComponent#handleClick} for more information on when this will be * triggered * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click * @fires CloseButton#close */ CloseButton.prototype.handleClick = function handleClick(event) { /** * Triggered when the a `CloseButton` is clicked. * * @event CloseButton#close * @type {EventTarget~Event} * * @property {boolean} [bubbles=false] * set to false so that the close event does not * bubble up to parents if there is no listener */ this.trigger({ type: 'close', bubbles: false }); }; return CloseButton; }(_button2['default']); _component2['default'].registerComponent('CloseButton', CloseButton); exports['default'] = CloseButton; },{"2":2,"5":5}],5:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = 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 _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _evented = _dereq_(51); var _evented2 = _interopRequireDefault(_evented); var _stateful = _dereq_(52); var _stateful2 = _interopRequireDefault(_stateful); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _domData = _dereq_(82); var DomData = _interopRequireWildcard(_domData); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _guid = _dereq_(88); var Guid = _interopRequireWildcard(_guid); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _toTitleCase = _dereq_(94); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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"); } } /** * Player Component - Base class for all UI objects * * @file component.js */ /** * Base class for all UI Components. * Components are UI objects which represent both a javascript object and an element * in the DOM. They can be children of other components, and can have * children themselves. * * Components can also use methods from {@link EventTarget} */ var Component = function () { /** * A callback that is called when a component is ready. Does not have any * paramters and any callback value will be ignored. * * @callback Component~ReadyCallback * @this Component */ /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. # * @param {Object[]} [options.children] * An array of children objects to intialize this component with. Children objects have * a name property that will be used if more than one component of the same type needs to be * added. * * @param {Component~ReadyCallback} [ready] * Function that gets called when the `Component` is ready. */ function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = (0, _mergeOptions2['default'])({}, this.options_); // Updated options with supplied options options = this.options_ = (0, _mergeOptions2['default'])(this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } // Make this an evented object and use `el_`, if available, as its event bus (0, _evented2['default'])(this, { eventBusKey: this.el_ ? 'el_' : null }); (0, _stateful2['default'])(this, this.constructor.defaultState); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } /** * Dispose of the `Component` and all child components. * * @fires Component#dispose */ Component.prototype.dispose = function dispose() { /** * Triggered when a `Component` is disposed. * * @event Component#dispose * @type {EventTarget~Event} * * @property {boolean} [bubbles=false] * set to false so that the close event does not * bubble up */ this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } DomData.removeData(this.el_); this.el_ = null; }; /** * Return the {@link Player} that the `Component` has attached to. * * @return {Player} * The player that this `Component` has attached to. */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects with new options. * > Note: When both `obj` and `options` contain properties whose values are objects. * The two properties get merged using {@link module:mergeOptions} * * @param {Object} obj * The object that contains new options. * * @return {Object} * A new object of `this.options_` and `obj` merged together. * * @deprecated since version 5 */ Component.prototype.options = function options(obj) { _log2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = (0, _mergeOptions2['default'])(this.options_, obj); return this.options_; }; /** * Get the `Component`s DOM element * * @return {Element} * The DOM element for this `Component`. */ Component.prototype.el = function el() { return this.el_; }; /** * Create the `Component`s DOM element. * * @param {string} [tagName] * Element's DOM node type. e.g. 'div' * * @param {Object} [properties] * An object of properties that should be set. * * @param {Object} [attributes] * An object of attributes that should be set. * * @return {Element} * The element that gets created. */ Component.prototype.createEl = function createEl(tagName, properties, attributes) { return Dom.createEl(tagName, properties, attributes); }; /** * Localize a string given the string in english. * * @param {string} string * The string to localize. * * @return {string} * The localized string or if no localization exists the english string. */ Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the `Component`s DOM element. This is where children get inserted. * This will usually be the the same as the element returned in {@link Component#el}. * * @return {Element} * The content element for this `Component`. */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get this `Component`s ID * * @return {string} * The id of this `Component` */ Component.prototype.id = function id() { return this.id_; }; /** * Get the `Component`s name. The name gets used to reference the `Component` * and is set during registration. * * @return {string} * The name of this `Component`. */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * * @return {Array} * The children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns the child `Component` with the given `id`. * * @param {string} id * The id of the child `Component` to get. * * @return {Component|undefined} * The child `Component` with the given `id` or undefined. */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns the child `Component` with the given `name`. * * @param {string} name * The name of the child `Component` to get. * * @return {Component|undefined} * The child `Component` with the given `name` or undefined. */ Component.prototype.getChild = function getChild(name) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); return this.childNameIndex_[name]; }; /** * Add a child `Component` inside the current `Component`. * * * @param {string|Component} child * The name or instance of a child to add. * * @param {Object} [options={}] * The key/value store of options that will get passed to children of * the child. * * @param {number} [index=this.children_.length] * The index to attempt to add a child into. * * @return {Component} * The `Component` that gets added as a child. When using a string the * `Component` will get created by this process. */ Component.prototype.addChild = function addChild(child) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.children_.length; var component = void 0; var componentName = void 0; // If child is a string, create component with options if (typeof child === 'string') { componentName = (0, _toTitleCase2['default'])(child); var componentClassName = options.componentClass || componentName; // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); if (!ComponentClass) { throw new Error('Component ' + componentClassName + ' does not exist'); } // data stored directly on the videojs object may be // misidentified as a component to retain // backwards-compatibility with 4.x. check to make sure the // component class can be instantiated. if (typeof ComponentClass !== 'function') { return null; } component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.splice(index, 0, component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && component.name(); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { var childNodes = this.contentEl().children; var refNode = childNodes[index] || null; this.contentEl().insertBefore(component.el(), refNode); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child `Component` from this `Component`s list of children. Also removes * the child `Component`s element from this `Component`s element. * * @param {Component} component * The child `Component` to remove. */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child `Component`s based upon options. */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { (function () { // `this` is `parent` var parentOptions = _this.options_; var handleAdd = function handleAdd(child) { var name = child.name; var opts = child.opts; // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // Allow options to be passed as a simple boolean if no configuration // is necessary. if (opts === true) { opts = {}; } // We also want to pass the original player options // to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each var newChild = _this.addChild(name, opts); if (newChild) { _this[name] = newChild; } }; // Allow for an array of children details to passed in the options var workingChildren = void 0; var Tech = Component.getComponent('Tech'); if (Array.isArray(children)) { workingChildren = children; } else { workingChildren = Object.keys(children); } workingChildren // children that are in this.options_ but also in workingChildren would // give us extra children we do not want. So, we want to filter them out. .concat(Object.keys(_this.options_).filter(function (child) { return !workingChildren.some(function (wchild) { if (typeof wchild === 'string') { return child === wchild; } return child === wchild.name; }); })).map(function (child) { var name = void 0; var opts = void 0; if (typeof child === 'string') { name = child; opts = children[name] || _this.options_[name] || {}; } else { name = child.name; opts = child; } return { name: name, opts: opts }; }).filter(function (child) { // we have to make sure that child.name isn't in the techOrder since // techs are registerd as Components but can't aren't compatible // See https://github.com/videojs/video.js/issues/2772 var c = Component.getComponent(child.opts.componentClass || (0, _toTitleCase2['default'])(child.name)); return c && !Tech.isTech(c); }).forEach(handleAdd); })(); } }; /** * Builds the default DOM class name. Should be overriden by sub-components. * * @return {string} * The DOM class name for this object. * * @abstract */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Bind a listener to the component's ready state. * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.ready = function ready(fn) { var sync = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (fn) { if (this.isReady_) { if (sync) { fn.call(this); } else { // Call the function asynchronously by default for consistency this.setTimeout(fn, 1); } } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } }; /** * Trigger all the ready listeners for this `Component`. * * @fires Component#ready */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; // Reset Ready Queue this.readyQueue_ = []; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); } // Allow for using event listeners also /** * Triggered when a `Component` is ready. * * @event Component#ready * @type {EventTarget~Event} */ this.trigger('ready'); }, 1); }; /** * Find a single DOM element matching a `selector`. This can be within the `Component`s * `contentEl()` or another custom context. * * @param {string} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|string} [context=this.contentEl()] * A DOM element within which to query. Can also be a selector string in * which case the first matching element will get used as context. If * missing `this.contentEl()` gets used. If `this.contentEl()` returns * nothing it falls back to `document`. * * @return {Element|null} * the dom element that was found, or null * * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors) */ Component.prototype.$ = function $(selector, context) { return Dom.$(selector, context || this.contentEl()); }; /** * Finds all DOM element matching a `selector`. This can be within the `Component`s * `contentEl()` or another custom context. * * @param {string} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|string} [context=this.contentEl()] * A DOM element within which to query. Can also be a selector string in * which case the first matching element will get used as context. If * missing `this.contentEl()` gets used. If `this.contentEl()` returns * nothing it falls back to `document`. * * @return {NodeList} * a list of dom elements that were found * * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors) */ Component.prototype.$$ = function $$(selector, context) { return Dom.$$(selector, context || this.contentEl()); }; /** * Check if a component's element has a CSS class name. * * @param {string} classToCheck * CSS class name to check. * * @return {boolean} * - True if the `Component` has the class. * - False if the `Component` does not have the class` */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasClass(this.el_, classToCheck); }; /** * Add a CSS class name to the `Component`s element. * * @param {string} classToAdd * CSS class name to add */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addClass(this.el_, classToAdd); }; /** * Remove a CSS class name from the `Component`s element. * * @param {string} classToRemove * CSS class name to remove */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeClass(this.el_, classToRemove); }; /** * Add or remove a CSS class name from the component's element. * - `classToToggle` gets added when {@link Component#hasClass} would return false. * - `classToToggle` gets removed when {@link Component#hasClass} would return true. * * @param {string} classToToggle * The class to add or remove based on (@link Component#hasClass} * * @param {boolean|Dom~predicate} [predicate] * An {@link Dom~predicate} function or a boolean */ Component.prototype.toggleClass = function toggleClass(classToToggle, predicate) { Dom.toggleClass(this.el_, classToToggle, predicate); }; /** * Show the `Component`s element if it is hidden by removing the * 'vjs-hidden' class name from it. */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); }; /** * Hide the `Component`s element if it is currently showing by adding the * 'vjs-hidden` class name to it. */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); }; /** * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing' * class name to it. Used during fadeIn/fadeOut. * * @private */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); }; /** * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing' * class name from it. Used during fadeIn/fadeOut. * * @private */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); }; /** * Get the value of an attribute on the `Component`s element. * * @param {string} attribute * Name of the attribute to get the value from. * * @return {string|null} * - The value of the attribute that was asked for. * - Can be an empty string on some browsers if the attribute does not exist * or has no value * - Most browsers will return null if the attibute does not exist or has * no value. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute} */ Component.prototype.getAttribute = function getAttribute(attribute) { return Dom.getAttribute(this.el_, attribute); }; /** * Set the value of an attribute on the `Component`'s element * * @param {string} attribute * Name of the attribute to set. * * @param {string} value * Value to set the attribute to. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute} */ Component.prototype.setAttribute = function setAttribute(attribute, value) { Dom.setAttribute(this.el_, attribute, value); }; /** * Remove an attribute from the `Component`s element. * * @param {string} attribute * Name of the attribute to remove. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute} */ Component.prototype.removeAttribute = function removeAttribute(attribute) { Dom.removeAttribute(this.el_, attribute); }; /** * Get or set the width of the component based upon the CSS styles. * See {@link Component#dimension} for more detailed information. * * @param {number|string} [num] * The width that you want to set postfixed with '%', 'px' or nothing. * * @param {boolean} [skipListeners] * Skip the componentresize event trigger * * @return {number|string} * The width when getting, zero if there is no width. Can be a string * postpixed with '%' or 'px'. */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component based upon the CSS styles. * See {@link Component#dimension} for more detailed information. * * @param {number|string} [num] * The height that you want to set postfixed with '%', 'px' or nothing. * * @param {boolean} [skipListeners] * Skip the componentresize event trigger * * @return {number|string} * The width when getting, zero if there is no width. Can be a string * postpixed with '%' or 'px'. */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both the width and height of the `Component` element at the same time. * * @param {number|string} width * Width to set the `Component`s element to. * * @param {number|string} height * Height to set the `Component`s element to. */ Component.prototype.dimensions = function dimensions(width, height) { // Skip componentresize listeners on width for optimization this.width(width, true); this.height(height); }; /** * Get or set width or height of the `Component` element. This is the shared code * for the {@link Component#width} and {@link Component#height}. * * Things to know: * - If the width or height in an number this will return the number postfixed with 'px'. * - If the width/height is a percent this will return the percent postfixed with '%' * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/} * for more information * - If you want the computed style of the component, use {@link Component#currentWidth} * and {@link {Component#currentHeight} * * @fires Component#componentresize * * @param {string} widthOrHeight 8 'width' or 'height' * * @param {number|string} [num] 8 New dimension * * @param {boolean} [skipListeners] * Skip componentresize event trigger * * @return {number} * The dimension when getting or 0 if unset */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { /** * Triggered when a component is resized. * * @event Component#componentresize * @type {EventTarget~Event} */ this.trigger('componentresize'); } return; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + (0, _toTitleCase2['default'])(widthOrHeight)], 10); }; /** * Get the width or the height of the `Component` elements computed style. Uses * `window.getComputedStyle`. * * @param {string} widthOrHeight * A string containing 'width' or 'height'. Whichever one you want to get. * * @return {number} * The dimension that gets asked for or 0 if nothing was set * for that dimension. */ Component.prototype.currentDimension = function currentDimension(widthOrHeight) { var computedWidthOrHeight = 0; if (widthOrHeight !== 'width' && widthOrHeight !== 'height') { throw new Error('currentDimension only accepts width or height value'); } if (typeof _window2['default'].getComputedStyle === 'function') { var computedStyle = _window2['default'].getComputedStyle(this.el_); computedWidthOrHeight = computedStyle.getPropertyValue(widthOrHeight) || computedStyle[widthOrHeight]; } // remove 'px' from variable and parse as integer computedWidthOrHeight = parseFloat(computedWidthOrHeight); // if the computed value is still 0, it's possible that the browser is lying // and we want to check the offset values. // This code also runs on IE8 and wherever getComputedStyle doesn't exist. if (computedWidthOrHeight === 0) { var rule = 'offset' + (0, _toTitleCase2['default'])(widthOrHeight); computedWidthOrHeight = this.el_[rule]; } return computedWidthOrHeight; }; /** * An object that contains width and height values of the `Component`s * computed style. Uses `window.getComputedStyle`. * * @typedef {Object} Component~DimensionObject * * @property {number} width * The width of the `Component`s computed style. * * @property {number} height * The height of the `Component`s computed style. */ /** * Get an object that contains width and height values of the `Component`s * computed style. * * @return {Component~DimensionObject} * The dimensions of the components element */ Component.prototype.currentDimensions = function currentDimensions() { return { width: this.currentDimension('width'), height: this.currentDimension('height') }; }; /** * Get the width of the `Component`s computed style. Uses `window.getComputedStyle`. * * @return {number} width * The width of the `Component`s computed style. */ Component.prototype.currentWidth = function currentWidth() { return this.currentDimension('width'); }; /** * Get the height of the `Component`s computed style. Uses `window.getComputedStyle`. * * @return {number} height * The height of the `Component`s computed style. */ Component.prototype.currentHeight = function currentHeight() { return this.currentDimension('height'); }; /** * Set the focus to this component */ Component.prototype.focus = function focus() { this.el_.focus(); }; /** * Remove the focus from this component */ Component.prototype.blur = function blur() { this.el_.blur(); }; /** * Emit a 'tap' events when touch event support gets detected. This gets used to * support toggling the controls through a tap on the video. They get enabled * because every sub-component would have extra overhead otherwise. * * @private * @fires Component#tap * @listens Component#touchstart * @listens Component#touchmove * @listens Component#touchleave * @listens Component#touchcancel * @listens Component#touchend */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, // so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = void 0; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy pageX/pageY from the object firstTouch = { pageX: event.touches[0].pageX, pageY: event.touches[0].pageY }; // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); /** * Triggered when a `Component` is tapped. * * @event Component#tap * @type {EventTarget~Event} */ this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * This function reports user activity whenever touch events happen. This can get * turned off by any sub-components that wants touch events to act another way. * * Report user touch activity when touch events occur. User activity gets used to * determine when controls should show/hide. It is simple when it comes to mouse * events, because any mouse event should show the controls. So we capture mouse * events that bubble up to the player and report activity when that happens. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player * controls. So touch events can't help us at the player level either. * * User activity gets checked asynchronously. So what could happen is a tap event * on the video turns the controls off. Then the `touchend` event bubbles up to * the player. Which, if it reported user activity, would turn the controls right * back on. We also don't want to completely block touch events from bubbling up. * Furthermore a `touchmove` event and anything other than a tap, should not turn * controls back on. * * @listens Component#touchstart * @listens Component#touchmove * @listens Component#touchend * @listens Component#touchcancel */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = void 0; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * A callback that has no parameters and is bound into `Component`s context. * * @callback Component~GenericCallback * @this Component */ /** * Creates a function that runs after an `x` millisecond timeout. This function is a * wrapper around `window.setTimeout`. There are a few reasons to use this one * instead though: * 1. It gets cleared via {@link Component#clearTimeout} when * {@link Component#dispose} gets called. * 2. The function callback will gets turned into a {@link Component~GenericCallback} * * > Note: You can use `window.clearTimeout` on the id returned by this function. This * will cause its dispose listener not to get cleaned up! Please use * {@link Component#clearTimeout} or {@link Component#dispose}. * * @param {Component~GenericCallback} fn * The function that will be run after `timeout`. * * @param {number} timeout * Timeout in milliseconds to delay before executing the specified function. * * @return {number} * Returns a timeout ID that gets used to identify the timeout. It can also * get used in {@link Component#clearTimeout} to clear the timeout that * was set. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout} */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); var timeoutId = _window2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout that gets created via `window.setTimeout` or * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout} * use this function instead of `window.clearTimout`. If you don't your dispose * listener will not get cleaned up until {@link Component#dispose}! * * @param {number} timeoutId * The id of the timeout to clear. The return value of * {@link Component#setTimeout} or `window.setTimeout`. * * @return {number} * Returns the timeout id that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout} */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _window2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates a function that gets run every `x` milliseconds. This function is a wrapper * around `window.setInterval`. There are a few reasons to use this one instead though. * 1. It gets cleared via {@link Component#clearInterval} when * {@link Component#dispose} gets called. * 2. The function callback will be a {@link Component~GenericCallback} * * @param {Component~GenericCallback} fn * The function to run every `x` seconds. * * @param {number} interval * Execute the specified function every `x` milliseconds. * * @return {number} * Returns an id that can be used to identify the interval. It can also be be used in * {@link Component#clearInterval} to clear the interval. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval} */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _window2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval that gets created via `window.setInterval` or * {@link Component#setInterval}. If you set an inteval via {@link Component#setInterval} * use this function instead of `window.clearInterval`. If you don't your dispose * listener will not get cleaned up until {@link Component#dispose}! * * @param {number} intervalId * The id of the interval to clear. The return value of * {@link Component#setInterval} or `window.setInterval`. * * @return {number} * Returns the interval id that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval} */ Component.prototype.clearInterval = function clearInterval(intervalId) { _window2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Queues up a callback to be passed to requestAnimationFrame (rAF), but * with a few extra bonuses: * * - Supports browsers that do not support rAF by falling back to * {@link Component#setTimeout}. * * - The callback is turned into a {@link Component~GenericCallback} (i.e. * bound to the component). * * - Automatic cancellation of the rAF callback is handled if the component * is disposed before it is called. * * @param {Component~GenericCallback} fn * A function that will be bound to this component and executed just * before the browser's next repaint. * * @return {number} * Returns an rAF ID that gets used to identify the timeout. It can * also be used in {@link Component#cancelAnimationFrame} to cancel * the animation frame callback. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame} */ Component.prototype.requestAnimationFrame = function requestAnimationFrame(fn) { var _this2 = this; if (this.supportsRaf_) { var _ret2 = function () { fn = Fn.bind(_this2, fn); var id = _window2['default'].requestAnimationFrame(fn); var disposeFn = function disposeFn() { return _this2.cancelAnimationFrame(id); }; disposeFn.guid = 'vjs-raf-' + id; _this2.on('dispose', disposeFn); return { v: id }; }(); if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v; } // Fall back to using a timer. return this.setTimeout(fn, 1000 / 60); }; /** * Cancels a queued callback passed to {@link Component#requestAnimationFrame} * (rAF). * * If you queue an rAF callback via {@link Component#requestAnimationFrame}, * use this function instead of `window.cancelAnimationFrame`. If you don't, * your dispose listener will not get cleaned up until {@link Component#dispose}! * * @param {number} id * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}. * * @return {number} * Returns the rAF ID that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame} */ Component.prototype.cancelAnimationFrame = function cancelAnimationFrame(id) { if (this.supportsRaf_) { _window2['default'].cancelAnimationFrame(id); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-raf-' + id; this.off('dispose', disposeFn); return id; } // Fall back to using a timer. return this.clearTimeout(id); }; /** * Register a `Component` with `videojs` given the name and the component. * * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s * should be registered using {@link Tech.registerTech} or * {@link videojs:videojs.registerTech}. * * > NOTE: This function can also be seen on videojs as * {@link videojs:videojs.registerComponent}. * * @param {string} name * The name of the `Component` to register. * * @param {Component} ComponentToRegister * The `Component` class to register. * * @return {Component} * The `Component` that was registered. */ Component.registerComponent = function registerComponent(name, ComponentToRegister) { if (typeof name !== 'string' || !name) { throw new Error('Illegal component name, "' + name + '"; must be a non-empty string.'); } var Tech = Component.getComponent('Tech'); // We need to make sure this check is only done if Tech has been registered. var isTech = Tech && Tech.isTech(ComponentToRegister); var isComp = Component === ComponentToRegister || Component.prototype.isPrototypeOf(ComponentToRegister.prototype); if (isTech || !isComp) { var reason = void 0; if (isTech) { reason = 'techs must be registered using Tech.registerTech()'; } else { reason = 'must be a Component subclass'; } throw new Error('Illegal component, "' + name + '"; ' + reason + '.'); } name = (0, _toTitleCase2['default'])(name); if (!Component.components_) { Component.components_ = {}; } var Player = Component.getComponent('Player'); if (name === 'Player' && Player && Player.players) { (function () { var players = Player.players; var playerNames = Object.keys(players); // If we have players that were disposed, then their name will still be // in Players.players. So, we must loop through and verify that the value // for each item is not null. This allows registration of the Player component // after all players have been disposed or before any were created. if (players && playerNames.length > 0 && playerNames.map(function (pname) { return players[pname]; }).every(Boolean)) { throw new Error('Can not register Player component after player has been created.'); } })(); } Component.components_[name] = ComponentToRegister; return ComponentToRegister; }; /** * Get a `Component` based on the name it was registered with. * * @param {string} name * The Name of the component to get. * * @return {Component} * The `Component` that got registered under the given name. * * @deprecated In `videojs` 6 this will not return `Component`s that were not * registered using {@link Component.registerComponent}. Currently we * check the global `videojs` object for a `Component` name and * return that if it exists. */ Component.getComponent = function getComponent(name) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } }; return Component; }(); /** * Whether or not this component supports `requestAnimationFrame`. * * This is exposed primarily for testing purposes. * * @private * @type {Boolean} */ Component.prototype.supportsRaf_ = typeof _window2['default'].requestAnimationFrame === 'function' && typeof _window2['default'].cancelAnimationFrame === 'function'; Component.registerComponent('Component', Component); exports['default'] = Component; },{"51":51,"52":52,"82":82,"83":83,"86":86,"88":88,"89":89,"90":90,"94":94,"98":98}],6:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackButton = _dereq_(36); var _trackButton2 = _interopRequireDefault(_trackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _audioTrackMenuItem = _dereq_(7); var _audioTrackMenuItem2 = _interopRequireDefault(_audioTrackMenuItem); 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; } /** * @file audio-track-button.js */ /** * The base class for buttons that toggle specific {@link AudioTrack} types. * * @extends TrackButton */ var AudioTrackButton = function (_TrackButton) { _inherits(AudioTrackButton, _TrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function AudioTrackButton(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, AudioTrackButton); options.tracks = player.audioTracks(); var _this = _possibleConstructorReturn(this, _TrackButton.call(this, player, options)); _this.el_.setAttribute('aria-label', 'Audio Menu'); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ AudioTrackButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-audio-button ' + _TrackButton.prototype.buildCSSClass.call(this); }; /** * Create a menu item for each audio track * * @param {AudioTrackMenuItem[]} [items=[]] * An array of existing menu items to use. * * @return {AudioTrackMenuItem[]} * An array of menu items */ AudioTrackButton.prototype.createItems = function createItems() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var tracks = this.player_.audioTracks(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; items.push(new _audioTrackMenuItem2['default'](this.player_, { track: track, // MenuItem is selectable selectable: true })); } return items; }; return AudioTrackButton; }(_trackButton2['default']); /** * The text that should display over the `AudioTrackButton`s controls. Added for localization. * * @type {string} * @private */ AudioTrackButton.prototype.controlText_ = 'Audio Track'; _component2['default'].registerComponent('AudioTrackButton', AudioTrackButton); exports['default'] = AudioTrackButton; },{"36":36,"5":5,"7":7}],7:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuItem = _dereq_(49); var _menuItem2 = _interopRequireDefault(_menuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file audio-track-menu-item.js */ /** * An {@link AudioTrack} {@link MenuItem} * * @extends MenuItem */ var AudioTrackMenuItem = function (_MenuItem) { _inherits(AudioTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function AudioTrackMenuItem(player, options) { _classCallCheck(this, AudioTrackMenuItem); var track = options.track; var tracks = player.audioTracks(); // Modify options for parent MenuItem class's init. options.label = track.label || track.language || 'Unknown'; options.selected = track.enabled; var _this = _possibleConstructorReturn(this, _MenuItem.call(this, player, options)); _this.track = track; var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); return _this; } /** * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent} * for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ AudioTrackMenuItem.prototype.handleClick = function handleClick(event) { var tracks = this.player_.audioTracks(); _MenuItem.prototype.handleClick.call(this, event); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.enabled = track === this.track; } }; /** * Handle any {@link AudioTrack} change. * * @param {EventTarget~Event} [event] * The {@link AudioTrackList#change} event that caused this to run. * * @listens AudioTrackList#change */ AudioTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track.enabled); }; return AudioTrackMenuItem; }(_menuItem2['default']); _component2['default'].registerComponent('AudioTrackMenuItem', AudioTrackMenuItem); exports['default'] = AudioTrackMenuItem; },{"49":49,"5":5,"86":86}],8:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); _dereq_(12); _dereq_(32); _dereq_(33); _dereq_(35); _dereq_(34); _dereq_(10); _dereq_(18); _dereq_(9); _dereq_(41); _dereq_(25); _dereq_(27); _dereq_(29); _dereq_(24); _dereq_(6); _dereq_(13); _dereq_(21); 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; } /** * @file control-bar.js */ // Required children /** * Container of main controls. * * @extends Component */ var ControlBar = function (_Component) { _inherits(ControlBar, _Component); function ControlBar() { _classCallCheck(this, ControlBar); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ ControlBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar', dir: 'ltr' }, { // The control bar is a group, so it can contain menuitems role: 'group' }); }; return ControlBar; }(_component2['default']); /** * Default options for `ControlBar` * * @type {Object} * @private */ ControlBar.prototype.options_ = { children: ['playToggle', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subtitlesButton', 'captionsButton', 'audioTrackButton', 'fullscreenToggle'] }; _component2['default'].registerComponent('ControlBar', ControlBar); exports['default'] = ControlBar; },{"10":10,"12":12,"13":13,"18":18,"21":21,"24":24,"25":25,"27":27,"29":29,"32":32,"33":33,"34":34,"35":35,"41":41,"5":5,"6":6,"9":9}],9:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file fullscreen-toggle.js */ /** * Toggle fullscreen video * * @extends Button */ var FullscreenToggle = function (_Button) { _inherits(FullscreenToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function FullscreenToggle(player, options) { _classCallCheck(this, FullscreenToggle); var _this = _possibleConstructorReturn(this, _Button.call(this, player, options)); _this.on(player, 'fullscreenchange', _this.handleFullscreenChange); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handles fullscreenchange on the player and change control text accordingly. * * @param {EventTarget~Event} [event] * The {@link Player#fullscreenchange} event that caused this function to be * called. * * @listens Player#fullscreenchange */ FullscreenToggle.prototype.handleFullscreenChange = function handleFullscreenChange(event) { if (this.player_.isFullscreen()) { this.controlText('Non-Fullscreen'); } else { this.controlText('Fullscreen'); } }; /** * This gets called when an `FullscreenToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ FullscreenToggle.prototype.handleClick = function handleClick(event) { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); } else { this.player_.exitFullscreen(); } }; return FullscreenToggle; }(_button2['default']); /** * The text that should display over the `FullscreenToggle`s controls. Added for localization. * * @type {string} * @private */ FullscreenToggle.prototype.controlText_ = 'Fullscreen'; _component2['default'].registerComponent('FullscreenToggle', FullscreenToggle); exports['default'] = FullscreenToggle; },{"2":2,"5":5}],10:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file live-display.js */ // TODO - Future make it click to snap to live /** * Displays the live indicator when duration is Infinity. * * @extends Component */ var LiveDisplay = function (_Component) { _inherits(LiveDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function LiveDisplay(player, options) { _classCallCheck(this, LiveDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.updateShowing(); _this.on(_this.player(), 'durationchange', _this.updateShowing); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ LiveDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE') }, { 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide * it accordingly * * @param {EventTarget~Event} [event] * The {@link Player#durationchange} event that caused this function to run. * * @listens Player#durationchange */ LiveDisplay.prototype.updateShowing = function updateShowing(event) { if (this.player().duration() === Infinity) { this.show(); } else { this.hide(); } }; return LiveDisplay; }(_component2['default']); _component2['default'].registerComponent('LiveDisplay', LiveDisplay); exports['default'] = LiveDisplay; },{"5":5,"83":83}],11:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _checkVolumeSupport = _dereq_(37); var _checkVolumeSupport2 = _interopRequireDefault(_checkVolumeSupport); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file mute-toggle.js */ /** * A button component for muting the audio. * * @extends Button */ var MuteToggle = function (_Button) { _inherits(MuteToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function MuteToggle(player, options) { _classCallCheck(this, MuteToggle); // hide this control if volume support is missing var _this = _possibleConstructorReturn(this, _Button.call(this, player, options)); (0, _checkVolumeSupport2['default'])(_this, player); _this.on(player, ['loadstart', 'volumechange'], _this.update); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ MuteToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * This gets called when an `MuteToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ MuteToggle.prototype.handleClick = function handleClick(event) { var vol = this.player_.volume(); var lastVolume = this.player_.lastVolume_(); if (vol === 0) { this.player_.volume(lastVolume); this.player_.muted(false); } else { this.player_.muted(this.player_.muted() ? false : true); } }; /** * Update the state of volume. * * @param {EventTarget~Event} [event] * The {@link Player#loadstart} event if this function was called through an * event. * * @listens Player#loadstart */ MuteToggle.prototype.update = function update(event) { var vol = this.player_.volume(); var level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. var toMute = this.player_.muted() ? 'Unmute' : 'Mute'; if (this.controlText() !== toMute) { this.controlText(toMute); } // TODO improve muted icon classes for (var i = 0; i < 4; i++) { Dom.removeClass(this.el_, 'vjs-vol-' + i); } Dom.addClass(this.el_, 'vjs-vol-' + level); }; return MuteToggle; }(_button2['default']); /** * The text that should display over the `MuteToggle`s controls. Added for localization. * * @type {string} * @private */ MuteToggle.prototype.controlText_ = 'Mute'; _component2['default'].registerComponent('MuteToggle', MuteToggle); exports['default'] = MuteToggle; },{"2":2,"37":37,"5":5,"83":83}],12:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file play-toggle.js */ /** * Button to toggle between play and pause. * * @extends Button */ var PlayToggle = function (_Button) { _inherits(PlayToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlayToggle(player, options) { _classCallCheck(this, PlayToggle); var _this = _possibleConstructorReturn(this, _Button.call(this, player, options)); _this.on(player, 'play', _this.handlePlay); _this.on(player, 'pause', _this.handlePause); _this.on(player, 'ended', _this.handleEnded); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ PlayToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * This gets called when an `PlayToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ PlayToggle.prototype.handleClick = function handleClick(event) { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Add the vjs-playing class to the element so it can change appearance. * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#play */ PlayToggle.prototype.handlePlay = function handlePlay(event) { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // change the button text to "Pause" this.controlText('Pause'); }; /** * Add the vjs-paused class to the element so it can change appearance. * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#pause */ PlayToggle.prototype.handlePause = function handlePause(event) { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); // change the button text to "Play" this.controlText('Play'); }; /** * Add the vjs-ended class to the element so it can change appearance * */ PlayToggle.prototype.handleEnded = function handleEnded(event) { this.removeClass('vjs-playing'); this.addClass('vjs-ended'); // change the button text to "Replay" this.controlText('Replay'); }; return PlayToggle; }(_button2['default']); /** * The text that should display over the `PlayToggle`s controls. Added for localization. * * @type {string} * @private */ PlayToggle.prototype.controlText_ = 'Play'; _component2['default'].registerComponent('PlayToggle', PlayToggle); exports['default'] = PlayToggle; },{"2":2,"5":5}],13:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuButton = _dereq_(48); var _menuButton2 = _interopRequireDefault(_menuButton); var _menu = _dereq_(50); var _menu2 = _interopRequireDefault(_menu); var _playbackRateMenuItem = _dereq_(14); var _playbackRateMenuItem2 = _interopRequireDefault(_playbackRateMenuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file playback-rate-menu-button.js */ /** * The component for controlling the playback rate. * * @extends MenuButton */ var PlaybackRateMenuButton = function (_MenuButton) { _inherits(PlaybackRateMenuButton, _MenuButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlaybackRateMenuButton(player, options) { _classCallCheck(this, PlaybackRateMenuButton); var _this = _possibleConstructorReturn(this, _MenuButton.call(this, player, options)); _this.updateVisibility(); _this.updateLabel(); _this.on(player, 'loadstart', _this.updateVisibility); _this.on(player, 'ratechange', _this.updateLabel); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ PlaybackRateMenuButton.prototype.createEl = function createEl() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = Dom.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this); }; /** * Create the playback rate menu * * @return {Menu} * Menu object populated with {@link PlaybackRateMenuItem}s */ PlaybackRateMenuButton.prototype.createMenu = function createMenu() { var menu = new _menu2['default'](this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new _playbackRateMenuItem2['default'](this.player(), { rate: rates[i] + 'x' })); } } return menu; }; /** * Updates ARIA accessibility attributes */ PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; /** * This gets called when an `PlaybackRateMenuButton` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ PlaybackRateMenuButton.prototype.handleClick = function handleClick(event) { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; /** * Get possible playback rates * * @return {Array} * All possible playback rates */ PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() { return this.options_.playbackRates || this.options_.playerOptions && this.options_.playerOptions.playbackRates; }; /** * Get whether playback rates is supported by the tech * and an array of playback rates exists * * @return {boolean} * Whether changing playback rate is supported */ PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() { return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0; }; /** * Hide playback rate controls when they're no playback rate options to select * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#loadstart */ PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility(event) { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#ratechange */ PlaybackRateMenuButton.prototype.updateLabel = function updateLabel(event) { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; }(_menuButton2['default']); /** * The text that should display over the `FullscreenToggle`s controls. Added for localization. * * @type {string} * @private */ PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; _component2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); exports['default'] = PlaybackRateMenuButton; },{"14":14,"48":48,"5":5,"50":50,"83":83}],14:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuItem = _dereq_(49); var _menuItem2 = _interopRequireDefault(_menuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file playback-rate-menu-item.js */ /** * The specific menu item type for selecting a playback rate. * * @extends MenuItem */ var PlaybackRateMenuItem = function (_MenuItem) { _inherits(PlaybackRateMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlaybackRateMenuItem(player, options) { _classCallCheck(this, PlaybackRateMenuItem); var label = options.rate; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options.label = label; options.selected = rate === 1; var _this = _possibleConstructorReturn(this, _MenuItem.call(this, player, options)); _this.label = label; _this.rate = rate; _this.on(player, 'ratechange', _this.update); return _this; } /** * This gets called when an `PlaybackRateMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ PlaybackRateMenuItem.prototype.handleClick = function handleClick(event) { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); }; /** * Update the PlaybackRateMenuItem when the playbackrate changes. * * @param {EventTarget~Event} [event] * The `ratechange` event that caused this function to run. * * @listens Player#ratechange */ PlaybackRateMenuItem.prototype.update = function update(event) { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; }(_menuItem2['default']); /** * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization. * * @type {string} * @private */ PlaybackRateMenuItem.prototype.contentElType = 'button'; _component2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); exports['default'] = PlaybackRateMenuItem; },{"49":49,"5":5}],15:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file load-progress-bar.js */ /** * Shows loading progress * * @extends Component */ var LoadProgressBar = function (_Component) { _inherits(LoadProgressBar, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function LoadProgressBar(player, options) { _classCallCheck(this, LoadProgressBar); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.partEls_ = []; _this.on(player, 'progress', _this.update); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ LoadProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; /** * Update progress bar * * @param {EventTarget~Event} [event] * The `progress` event that caused this function to run. * * @listens Player#progress */ LoadProgressBar.prototype.update = function update(event) { var buffered = this.player_.buffered(); var duration = this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.partEls_; // get the percent width of a time compared to the total end var percentify = function percentify(time, end) { // no NaN var percent = time / end || 0; return (percent >= 1 ? 1 : percent) * 100 + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(Dom.createEl()); children[i] = part; } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var _i = children.length; _i > buffered.length; _i--) { this.el_.removeChild(children[_i - 1]); } children.length = buffered.length; }; return LoadProgressBar; }(_component2['default']); _component2['default'].registerComponent('LoadProgressBar', LoadProgressBar); exports['default'] = LoadProgressBar; },{"5":5,"83":83}],16:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _formatTime = _dereq_(87); var _formatTime2 = _interopRequireDefault(_formatTime); _dereq_(20); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file mouse-time-display.js */ /** * The {@link MouseTimeDisplay} component tracks mouse movement over the * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip} * indicating the time which is represented by a given point in the * {@link ProgressControl}. * * @extends Component */ var MouseTimeDisplay = function (_Component) { _inherits(MouseTimeDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The {@link Player} that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function MouseTimeDisplay(player, options) { _classCallCheck(this, MouseTimeDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.update = Fn.throttle(Fn.bind(_this, _this.update), 25); return _this; } /** * Create the DOM element for this class. * * @return {Element} * The element that was created. */ MouseTimeDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-mouse-display' }); }; /** * Enqueues updates to its own DOM as well as the DOM of its * {@link TimeTooltip} child. * * @param {Object} seekBarRect * The `ClientRect` for the {@link SeekBar} element. * * @param {number} seekBarPoint * A number from 0 to 1, representing a horizontal reference point * from the left edge of the {@link SeekBar} */ MouseTimeDisplay.prototype.update = function update(seekBarRect, seekBarPoint) { var _this2 = this; // If there is an existing rAF ID, cancel it so we don't over-queue. if (this.rafId_) { this.cancelAnimationFrame(this.rafId_); } this.rafId_ = this.requestAnimationFrame(function () { var duration = _this2.player_.duration(); var content = (0, _formatTime2['default'])(seekBarPoint * duration, duration); _this2.el_.style.left = seekBarRect.width * seekBarPoint + 'px'; _this2.getChild('timeTooltip').update(seekBarRect, seekBarPoint, content); }); }; return MouseTimeDisplay; }(_component2['default']); /** * Default options for `MouseTimeDisplay` * * @type {Object} * @private */ MouseTimeDisplay.prototype.options_ = { children: ['timeTooltip'] }; _component2['default'].registerComponent('MouseTimeDisplay', MouseTimeDisplay); exports['default'] = MouseTimeDisplay; },{"20":20,"5":5,"86":86,"87":87}],17:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _browser = _dereq_(79); var _formatTime = _dereq_(87); var _formatTime2 = _interopRequireDefault(_formatTime); _dereq_(20); 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; } /** * @file play-progress-bar.js */ /** * Used by {@link SeekBar} to display media playback progress as part of the * {@link ProgressControl}. * * @extends Component */ var PlayProgressBar = function (_Component) { _inherits(PlayProgressBar, _Component); function PlayProgressBar() { _classCallCheck(this, PlayProgressBar); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the the DOM element for this class. * * @return {Element} * The element that was created. */ PlayProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress vjs-slider-bar', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; /** * Enqueues updates to its own DOM as well as the DOM of its * {@link TimeTooltip} child. * * @param {Object} seekBarRect * The `ClientRect` for the {@link SeekBar} element. * * @param {number} seekBarPoint * A number from 0 to 1, representing a horizontal reference point * from the left edge of the {@link SeekBar} */ PlayProgressBar.prototype.update = function update(seekBarRect, seekBarPoint) { var _this2 = this; // If there is an existing rAF ID, cancel it so we don't over-queue. if (this.rafId_) { this.cancelAnimationFrame(this.rafId_); } this.rafId_ = this.requestAnimationFrame(function () { var time = _this2.player_.scrubbing() ? _this2.player_.getCache().currentTime : _this2.player_.currentTime(); var content = (0, _formatTime2['default'])(time, _this2.player_.duration()); _this2.getChild('timeTooltip').update(seekBarRect, seekBarPoint, content); }); }; return PlayProgressBar; }(_component2['default']); /** * Default options for {@link PlayProgressBar}. * * @type {Object} * @private */ PlayProgressBar.prototype.options_ = { children: [] }; if (!_browser.IE_VERSION || _browser.IE_VERSION > 8) { PlayProgressBar.prototype.options_.children.push('timeTooltip'); } _component2['default'].registerComponent('PlayProgressBar', PlayProgressBar); exports['default'] = PlayProgressBar; },{"20":20,"5":5,"79":79,"87":87}],18:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(86); _dereq_(19); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file progress-control.js */ /** * The Progress Control component contains the seek bar, load progress, * and play progress. * * @extends Component */ var ProgressControl = function (_Component) { _inherits(ProgressControl, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ProgressControl(player, options) { _classCallCheck(this, ProgressControl); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.handleMouseMove = (0, _fn.throttle)((0, _fn.bind)(_this, _this.handleMouseMove), 25); _this.on(_this.el_, 'mousemove', _this.handleMouseMove); _this.throttledHandleMouseSeek = (0, _fn.throttle)((0, _fn.bind)(_this, _this.handleMouseSeek), 25); _this.on(['mousedown', 'touchstart'], _this.handleMouseDown); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ ProgressControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; /** * When the mouse moves over the `ProgressControl`, the pointer position * gets passed down to the `MouseTimeDisplay` component. * * @param {EventTarget~Event} event * The `mousemove` event that caused this function to run. * * @listen mousemove */ ProgressControl.prototype.handleMouseMove = function handleMouseMove(event) { var seekBar = this.getChild('seekBar'); var mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay'); var seekBarEl = seekBar.el(); var seekBarRect = Dom.getBoundingClientRect(seekBarEl); var seekBarPoint = Dom.getPointerPosition(seekBarEl, event).x; // The default skin has a gap on either side of the `SeekBar`. This means // that it's possible to trigger this behavior outside the boundaries of // the `SeekBar`. This ensures we stay within it at all times. if (seekBarPoint > 1) { seekBarPoint = 1; } else if (seekBarPoint < 0) { seekBarPoint = 0; } if (mouseTimeDisplay) { mouseTimeDisplay.update(seekBarRect, seekBarPoint); } }; /** * A throttled version of the {@link ProgressControl#handleMouseSeek} listener. * * @method ProgressControl#throttledHandleMouseSeek * @param {EventTarget~Event} event * The `mousemove` event that caused this function to run. * * @listen mousemove * @listen touchmove */ /** * Handle `mousemove` or `touchmove` events on the `ProgressControl`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousemove * @listens touchmove */ ProgressControl.prototype.handleMouseSeek = function handleMouseSeek(event) { var seekBar = this.getChild('seekBar'); seekBar.handleMouseMove(event); }; /** * Handle `mousedown` or `touchstart` events on the `ProgressControl`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart */ ProgressControl.prototype.handleMouseDown = function handleMouseDown(event) { var doc = this.el_.ownerDocument; this.on(doc, 'mousemove', this.throttledHandleMouseSeek); this.on(doc, 'touchmove', this.throttledHandleMouseSeek); this.on(doc, 'mouseup', this.handleMouseUp); this.on(doc, 'touchend', this.handleMouseUp); }; /** * Handle `mouseup` or `touchend` events on the `ProgressControl`. * * @param {EventTarget~Event} event * `mouseup` or `touchend` event that triggered this function. * * @listens touchend * @listens mouseup */ ProgressControl.prototype.handleMouseUp = function handleMouseUp(event) { var doc = this.el_.ownerDocument; this.off(doc, 'mousemove', this.throttledHandleMouseSeek); this.off(doc, 'touchmove', this.throttledHandleMouseSeek); this.off(doc, 'mouseup', this.handleMouseUp); this.off(doc, 'touchend', this.handleMouseUp); }; return ProgressControl; }(_component2['default']); /** * Default options for `ProgressControl` * * @type {Object} * @private */ ProgressControl.prototype.options_ = { children: ['seekBar'] }; _component2['default'].registerComponent('ProgressControl', ProgressControl); exports['default'] = ProgressControl; },{"19":19,"5":5,"83":83,"86":86}],19:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _slider = _dereq_(58); var _slider2 = _interopRequireDefault(_slider); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _browser = _dereq_(79); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _formatTime = _dereq_(87); var _formatTime2 = _interopRequireDefault(_formatTime); _dereq_(15); _dereq_(17); _dereq_(16); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file seek-bar.js */ // The number of seconds the `step*` functions move the timeline. var STEP_SECONDS = 5; /** * Seek bar and container for the progress bars. Uses {@link PlayProgressBar} * as its `bar`. * * @extends Slider */ var SeekBar = function (_Slider) { _inherits(SeekBar, _Slider); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function SeekBar(player, options) { _classCallCheck(this, SeekBar); var _this = _possibleConstructorReturn(this, _Slider.call(this, player, options)); _this.update = Fn.throttle(Fn.bind(_this, _this.update), 50); _this.on(player, ['timeupdate', 'ended'], _this.update); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ SeekBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder' }, { 'aria-label': 'progress bar' }); }; /** * Update the seek bar's UI. * * @param {EventTarget~Event} [event] * The `timeupdate` or `ended` event that caused this to run. * * @listens Player#timeupdate * @listens Player#ended */ SeekBar.prototype.update = function update() { var percent = _Slider.prototype.update.call(this); var duration = this.player_.duration(); // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2)); // human readable value of progress bar (time complete) this.el_.setAttribute('aria-valuetext', (0, _formatTime2['default'])(time, duration)); // Update the `PlayProgressBar`. this.bar.update(Dom.getBoundingClientRect(this.el_), percent); return percent; }; /** * Get the percentage of media played so far. * * @return {number} * The percentage of media played so far (0 to 1). */ SeekBar.prototype.getPercent = function getPercent() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); var percent = time / this.player_.duration(); return percent >= 1 ? 1 : percent; }; /** * Handle mouse down on seek bar * * @param {EventTarget~Event} event * The `mousedown` event that caused this to run. * * @listens mousedown */ SeekBar.prototype.handleMouseDown = function handleMouseDown(event) { this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); _Slider.prototype.handleMouseDown.call(this, event); }; /** * Handle mouse move on seek bar * * @param {EventTarget~Event} event * The `mousemove` event that caused this to run. * * @listens mousemove */ SeekBar.prototype.handleMouseMove = function handleMouseMove(event) { var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; /** * Handle mouse up on seek bar * * @param {EventTarget~Event} event * The `mouseup` event that caused this to run. * * @listens mouseup */ SeekBar.prototype.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } }; /** * Move more quickly fast forward for keyboard-only users */ SeekBar.prototype.stepForward = function stepForward() { this.player_.currentTime(this.player_.currentTime() + STEP_SECONDS); }; /** * Move more quickly rewind for keyboard-only users */ SeekBar.prototype.stepBack = function stepBack() { this.player_.currentTime(this.player_.currentTime() - STEP_SECONDS); }; /** * Toggles the playback state of the player * This gets called when enter or space is used on the seekbar * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called * */ SeekBar.prototype.handleAction = function handleAction(event) { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Called when this SeekBar has focus and a key gets pressed down. By * default it will call `this.handleAction` when the key is space or enter. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ SeekBar.prototype.handleKeyPress = function handleKeyPress(event) { // Support Space (32) or Enter (13) key operation to fire a click event if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleAction(event); } else if (_Slider.prototype.handleKeyPress) { // Pass keypress handling up for unsupported keys _Slider.prototype.handleKeyPress.call(this, event); } }; return SeekBar; }(_slider2['default']); /** * Default options for the `SeekBar` * * @type {Object} * @private */ SeekBar.prototype.options_ = { children: ['loadProgressBar', 'playProgressBar'], barName: 'playProgressBar' }; if (!_browser.IE_VERSION || _browser.IE_VERSION > 8) { SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay'); } /** * Call the update event for this Slider when this event happens on the player. * * @type {string} */ SeekBar.prototype.playerEvent = 'timeupdate'; _component2['default'].registerComponent('SeekBar', SeekBar); exports['default'] = SeekBar; },{"15":15,"16":16,"17":17,"5":5,"58":58,"79":79,"83":83,"86":86,"87":87}],20:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file time-tooltip.js */ /** * Time tooltips display a time above the progress bar. * * @extends Component */ var TimeTooltip = function (_Component) { _inherits(TimeTooltip, _Component); function TimeTooltip() { _classCallCheck(this, TimeTooltip); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the time tooltip DOM element * * @return {Element} * The element that was created. */ TimeTooltip.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-tooltip' }); }; /** * Updates the position of the time tooltip relative to the `SeekBar`. * * @param {Object} seekBarRect * The `ClientRect` for the {@link SeekBar} element. * * @param {number} seekBarPoint * A number from 0 to 1, representing a horizontal reference point * from the left edge of the {@link SeekBar} */ TimeTooltip.prototype.update = function update(seekBarRect, seekBarPoint, content) { var tooltipRect = Dom.getBoundingClientRect(this.el_); var playerRect = Dom.getBoundingClientRect(this.player_.el()); var seekBarPointPx = seekBarRect.width * seekBarPoint; // do nothing if either rect isn't available // for example, if the player isn't in the DOM for testing if (!playerRect || !tooltipRect) { return; } // This is the space left of the `seekBarPoint` available within the bounds // of the player. We calculate any gap between the left edge of the player // and the left edge of the `SeekBar` and add the number of pixels in the // `SeekBar` before hitting the `seekBarPoint` var spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx; // This is the space right of the `seekBarPoint` available within the bounds // of the player. We calculate the number of pixels from the `seekBarPoint` // to the right edge of the `SeekBar` and add to that any gap between the // right edge of the `SeekBar` and the player. var spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right); // This is the number of pixels by which the tooltip will need to be pulled // further to the right to center it over the `seekBarPoint`. var pullTooltipBy = tooltipRect.width / 2; // Adjust the `pullTooltipBy` distance to the left or right depending on // the results of the space calculations above. if (spaceLeftOfPoint < pullTooltipBy) { pullTooltipBy += pullTooltipBy - spaceLeftOfPoint; } else if (spaceRightOfPoint < pullTooltipBy) { pullTooltipBy = spaceRightOfPoint; } // Due to the imprecision of decimal/ratio based calculations and varying // rounding behaviors, there are cases where the spacing adjustment is off // by a pixel or two. This adds insurance to these calculations. if (pullTooltipBy < 0) { pullTooltipBy = 0; } else if (pullTooltipBy > tooltipRect.width) { pullTooltipBy = tooltipRect.width; } this.el_.style.right = '-' + pullTooltipBy + 'px'; Dom.textContent(this.el_, content); }; return TimeTooltip; }(_component2['default']); _component2['default'].registerComponent('TimeTooltip', TimeTooltip); exports['default'] = TimeTooltip; },{"5":5,"83":83}],21:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _spacer = _dereq_(22); var _spacer2 = _interopRequireDefault(_spacer); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file custom-control-spacer.js */ /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer */ var CustomControlSpacer = function (_Spacer) { _inherits(CustomControlSpacer, _Spacer); function CustomControlSpacer() { _classCallCheck(this, CustomControlSpacer); return _possibleConstructorReturn(this, _Spacer.apply(this, arguments)); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this); }; /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ CustomControlSpacer.prototype.createEl = function createEl() { var el = _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); // No-flex/table-cell mode requires there be some content // in the cell to fill the remaining space of the table. el.innerHTML = '&nbsp;'; return el; }; return CustomControlSpacer; }(_spacer2['default']); _component2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer); exports['default'] = CustomControlSpacer; },{"22":22,"5":5}],22:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file spacer.js */ /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component */ var Spacer = function (_Component) { _inherits(Spacer, _Component); function Spacer() { _classCallCheck(this, Spacer); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ Spacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this); }; /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ Spacer.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; }(_component2['default']); _component2['default'].registerComponent('Spacer', Spacer); exports['default'] = Spacer; },{"5":5}],23:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackMenuItem = _dereq_(31); var _textTrackMenuItem2 = _interopRequireDefault(_textTrackMenuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file caption-settings-menu-item.js */ /** * The menu item for caption track settings menu * * @extends TextTrackMenuItem */ var CaptionSettingsMenuItem = function (_TextTrackMenuItem) { _inherits(CaptionSettingsMenuItem, _TextTrackMenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CaptionSettingsMenuItem(player, options) { _classCallCheck(this, CaptionSettingsMenuItem); options.track = { player: player, kind: options.kind, label: options.kind + ' settings', selectable: false, 'default': false, mode: 'disabled' }; // CaptionSettingsMenuItem has no concept of 'selected' options.selectable = false; var _this = _possibleConstructorReturn(this, _TextTrackMenuItem.call(this, player, options)); _this.addClass('vjs-texttrack-settings'); _this.controlText(', opens ' + options.kind + ' settings dialog'); return _this; } /** * This gets called when an `CaptionSettingsMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ CaptionSettingsMenuItem.prototype.handleClick = function handleClick(event) { this.player().getChild('textTrackSettings').show(); this.player().getChild('textTrackSettings').el_.focus(); }; return CaptionSettingsMenuItem; }(_textTrackMenuItem2['default']); _component2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); exports['default'] = CaptionSettingsMenuItem; },{"31":31,"5":5}],24:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackButton = _dereq_(30); var _textTrackButton2 = _interopRequireDefault(_textTrackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _captionSettingsMenuItem = _dereq_(23); var _captionSettingsMenuItem2 = _interopRequireDefault(_captionSettingsMenuItem); 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; } /** * @file captions-button.js */ /** * The button component for toggling and selecting captions * * @extends TextTrackButton */ var CaptionsButton = function (_TextTrackButton) { _inherits(CaptionsButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function CaptionsButton(player, options, ready) { _classCallCheck(this, CaptionsButton); var _this = _possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready)); _this.el_.setAttribute('aria-label', 'Captions Menu'); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ CaptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update caption menu items * * @param {EventTarget~Event} [event] * The `addtrack` or `removetrack` event that caused this function to be * called. * * @listens TextTrackList#addtrack * @listens TextTrackList#removetrack */ CaptionsButton.prototype.update = function update(event) { var threshold = 2; _TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech_ && this.player().tech_.featuresNativeTextTracks) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * Create caption menu items * * @return {CaptionSettingsMenuItem[]} * The array of current menu items. */ CaptionsButton.prototype.createItems = function createItems() { var items = []; if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks)) { items.push(new _captionSettingsMenuItem2['default'](this.player_, { kind: this.kind_ })); } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; }(_textTrackButton2['default']); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ CaptionsButton.prototype.kind_ = 'captions'; /** * The text that should display over the `CaptionsButton`s controls. Added for localization. * * @type {string} * @private */ CaptionsButton.prototype.controlText_ = 'Captions'; _component2['default'].registerComponent('CaptionsButton', CaptionsButton); exports['default'] = CaptionsButton; },{"23":23,"30":30,"5":5}],25:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackButton = _dereq_(30); var _textTrackButton2 = _interopRequireDefault(_textTrackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _chaptersTrackMenuItem = _dereq_(26); var _chaptersTrackMenuItem2 = _interopRequireDefault(_chaptersTrackMenuItem); var _toTitleCase = _dereq_(94); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); 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; } /** * @file chapters-button.js */ /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @extends TextTrackButton */ var ChaptersButton = function (_TextTrackButton) { _inherits(ChaptersButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this function is ready. */ function ChaptersButton(player, options, ready) { _classCallCheck(this, ChaptersButton); var _this = _possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready)); _this.el_.setAttribute('aria-label', 'Chapters Menu'); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ChaptersButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update the menu based on the current state of its items. * * @param {EventTarget~Event} [event] * An event that triggered this function to run. * * @listens TextTrackList#addtrack * @listens TextTrackList#removetrack * @listens TextTrackList#change */ ChaptersButton.prototype.update = function update(event) { if (!this.track_ || event && (event.type === 'addtrack' || event.type === 'removetrack')) { this.setTrack(this.findChaptersTrack()); } _TextTrackButton.prototype.update.call(this); }; /** * Set the currently selected track for the chapters button. * * @param {TextTrack} track * The new track to select. Nothing will change if this is the currently selected * track. */ ChaptersButton.prototype.setTrack = function setTrack(track) { if (this.track_ === track) { return; } if (!this.updateHandler_) { this.updateHandler_ = this.update.bind(this); } // here this.track_ refers to the old track instance if (this.track_) { var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_); if (remoteTextTrackEl) { remoteTextTrackEl.removeEventListener('load', this.updateHandler_); } this.track_ = null; } this.track_ = track; // here this.track_ refers to the new track instance if (this.track_) { this.track_.mode = 'hidden'; var _remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_); if (_remoteTextTrackEl) { _remoteTextTrackEl.addEventListener('load', this.updateHandler_); } } }; /** * Find the track object that is currently in use by this ChaptersButton * * @return {TextTrack|undefined} * The current track or undefined if none was found. */ ChaptersButton.prototype.findChaptersTrack = function findChaptersTrack() { var tracks = this.player_.textTracks() || []; for (var i = tracks.length - 1; i >= 0; i--) { // We will always choose the last track as our chaptersTrack var track = tracks[i]; if (track.kind === this.kind_) { return track; } } }; /** * Get the caption for the ChaptersButton based on the track label. This will also * use the current tracks localized kind as a fallback if a label does not exist. * * @return {string} * The tracks current label or the localized track kind. */ ChaptersButton.prototype.getMenuCaption = function getMenuCaption() { if (this.track_ && this.track_.label) { return this.track_.label; } return this.localize((0, _toTitleCase2['default'])(this.kind_)); }; /** * Create menu from chapter track * * @return {Menu} * New menu for the chapter buttons */ ChaptersButton.prototype.createMenu = function createMenu() { this.options_.title = this.getMenuCaption(); return _TextTrackButton.prototype.createMenu.call(this); }; /** * Create a menu item for each text track * * @return {TextTrackMenuItem[]} * Array of menu items */ ChaptersButton.prototype.createItems = function createItems() { var items = []; if (!this.track_) { return items; } var cues = this.track_.cues; if (!cues) { return items; } for (var i = 0, l = cues.length; i < l; i++) { var cue = cues[i]; var mi = new _chaptersTrackMenuItem2['default'](this.player_, { track: this.track_, cue: cue }); items.push(mi); } return items; }; return ChaptersButton; }(_textTrackButton2['default']); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ ChaptersButton.prototype.kind_ = 'chapters'; /** * The text that should display over the `ChaptersButton`s controls. Added for localization. * * @type {string} * @private */ ChaptersButton.prototype.controlText_ = 'Chapters'; _component2['default'].registerComponent('ChaptersButton', ChaptersButton); exports['default'] = ChaptersButton; },{"26":26,"30":30,"5":5,"94":94}],26:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuItem = _dereq_(49); var _menuItem2 = _interopRequireDefault(_menuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file chapters-track-menu-item.js */ /** * The chapter track menu item * * @extends MenuItem */ var ChaptersTrackMenuItem = function (_MenuItem) { _inherits(ChaptersTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ChaptersTrackMenuItem(player, options) { _classCallCheck(this, ChaptersTrackMenuItem); var track = options.track; var cue = options.cue; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options.selectable = true; options.label = cue.text; options.selected = cue.startTime <= currentTime && currentTime < cue.endTime; var _this = _possibleConstructorReturn(this, _MenuItem.call(this, player, options)); _this.track = track; _this.cue = cue; track.addEventListener('cuechange', Fn.bind(_this, _this.update)); return _this; } /** * This gets called when an `ChaptersTrackMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ChaptersTrackMenuItem.prototype.handleClick = function handleClick(event) { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; /** * Update chapter menu item * * @param {EventTarget~Event} [event] * The `cuechange` event that caused this function to run. * * @listens TextTrack#cuechange */ ChaptersTrackMenuItem.prototype.update = function update(event) { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue.startTime <= currentTime && currentTime < cue.endTime); }; return ChaptersTrackMenuItem; }(_menuItem2['default']); _component2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); exports['default'] = ChaptersTrackMenuItem; },{"49":49,"5":5,"86":86}],27:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackButton = _dereq_(30); var _textTrackButton2 = _interopRequireDefault(_textTrackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file descriptions-button.js */ /** * The button component for toggling and selecting descriptions * * @extends TextTrackButton */ var DescriptionsButton = function (_TextTrackButton) { _inherits(DescriptionsButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function DescriptionsButton(player, options, ready) { _classCallCheck(this, DescriptionsButton); var _this = _possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready)); _this.el_.setAttribute('aria-label', 'Descriptions Menu'); var tracks = player.textTracks(); var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); return _this; } /** * Handle text track change * * @param {EventTarget~Event} event * The event that caused this function to run * * @listens TextTrackList#change */ DescriptionsButton.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var disabled = false; // Check whether a track of a different kind is showing for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind !== this.kind_ && track.mode === 'showing') { disabled = true; break; } } // If another track is showing, disable this menu button if (disabled) { this.disable(); } else { this.enable(); } }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ DescriptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-descriptions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return DescriptionsButton; }(_textTrackButton2['default']); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ DescriptionsButton.prototype.kind_ = 'descriptions'; /** * The text that should display over the `DescriptionsButton`s controls. Added for localization. * * @type {string} * @private */ DescriptionsButton.prototype.controlText_ = 'Descriptions'; _component2['default'].registerComponent('DescriptionsButton', DescriptionsButton); exports['default'] = DescriptionsButton; },{"30":30,"5":5,"86":86}],28:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackMenuItem = _dereq_(31); var _textTrackMenuItem2 = _interopRequireDefault(_textTrackMenuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file off-text-track-menu-item.js */ /** * A special menu item for turning of a specific type of text track * * @extends TextTrackMenuItem */ var OffTextTrackMenuItem = function (_TextTrackMenuItem) { _inherits(OffTextTrackMenuItem, _TextTrackMenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function OffTextTrackMenuItem(player, options) { _classCallCheck(this, OffTextTrackMenuItem); // Create pseudo track info // Requires options['kind'] options.track = { player: player, kind: options.kind, label: options.kind + ' off', 'default': false, mode: 'disabled' }; // MenuItem is selectable options.selectable = true; var _this = _possibleConstructorReturn(this, _TextTrackMenuItem.call(this, player, options)); _this.selected(true); return _this; } /** * Handle text track change * * @param {EventTarget~Event} event * The event that caused this function to run */ OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var selected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind === this.track.kind && track.mode === 'showing') { selected = false; break; } } this.selected(selected); }; return OffTextTrackMenuItem; }(_textTrackMenuItem2['default']); _component2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); exports['default'] = OffTextTrackMenuItem; },{"31":31,"5":5}],29:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackButton = _dereq_(30); var _textTrackButton2 = _interopRequireDefault(_textTrackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file subtitles-button.js */ /** * The button component for toggling and selecting subtitles * * @extends TextTrackButton */ var SubtitlesButton = function (_TextTrackButton) { _inherits(SubtitlesButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function SubtitlesButton(player, options, ready) { _classCallCheck(this, SubtitlesButton); var _this = _possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready)); _this.el_.setAttribute('aria-label', 'Subtitles Menu'); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return SubtitlesButton; }(_textTrackButton2['default']); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ SubtitlesButton.prototype.kind_ = 'subtitles'; /** * The text that should display over the `SubtitlesButton`s controls. Added for localization. * * @type {string} * @private */ SubtitlesButton.prototype.controlText_ = 'Subtitles'; _component2['default'].registerComponent('SubtitlesButton', SubtitlesButton); exports['default'] = SubtitlesButton; },{"30":30,"5":5}],30:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackButton = _dereq_(36); var _trackButton2 = _interopRequireDefault(_trackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _textTrackMenuItem = _dereq_(31); var _textTrackMenuItem2 = _interopRequireDefault(_textTrackMenuItem); var _offTextTrackMenuItem = _dereq_(28); var _offTextTrackMenuItem2 = _interopRequireDefault(_offTextTrackMenuItem); 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; } /** * @file text-track-button.js */ /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @extends MenuButton */ var TextTrackButton = function (_TrackButton) { _inherits(TextTrackButton, _TrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function TextTrackButton(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, TextTrackButton); options.tracks = player.textTracks(); return _possibleConstructorReturn(this, _TrackButton.call(this, player, options)); } /** * Create a menu item for each text track * * @param {TextTrackMenuItem[]} [items=[]] * Existing array of items to use during creation * * @return {TextTrackMenuItem[]} * Array of menu items that were created */ TextTrackButton.prototype.createItems = function createItems() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; // Add an OFF menu item to turn all tracks off items.push(new _offTextTrackMenuItem2['default'](this.player_, { kind: this.kind_ })); var tracks = this.player_.textTracks(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track.kind === this.kind_) { items.push(new _textTrackMenuItem2['default'](this.player_, { track: track, // MenuItem is selectable selectable: true })); } } return items; }; return TextTrackButton; }(_trackButton2['default']); _component2['default'].registerComponent('TextTrackButton', TextTrackButton); exports['default'] = TextTrackButton; },{"28":28,"31":31,"36":36,"5":5}],31:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = 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 _menuItem = _dereq_(49); var _menuItem2 = _interopRequireDefault(_menuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file text-track-menu-item.js */ /** * The specific menu item type for selecting a language within a text track kind * * @extends MenuItem */ var TextTrackMenuItem = function (_MenuItem) { _inherits(TextTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TextTrackMenuItem(player, options) { _classCallCheck(this, TextTrackMenuItem); var track = options.track; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options.label = track.label || track.language || 'Unknown'; options.selected = track['default'] || track.mode === 'showing'; var _this = _possibleConstructorReturn(this, _MenuItem.call(this, player, options)); _this.track = track; var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks.onchange === undefined) { (function () { var event = void 0; _this.on(['tap', 'click'], function () { if (_typeof(_window2['default'].Event) !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new _window2['default'].Event('change'); } catch (err) { // continue regardless of error } } if (!event) { event = _document2['default'].createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); })(); } return _this; } /** * This gets called when an `TextTrackMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ TextTrackMenuItem.prototype.handleClick = function handleClick(event) { var kind = this.track.kind; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track.kind !== kind) { continue; } if (track === this.track) { track.mode = 'showing'; } else { track.mode = 'disabled'; } } }; /** * Handle text track list change * * @param {EventTarget~Event} event * The `change` event that caused this function to be called. * * @listens TextTrackList#change */ TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track.mode === 'showing'); }; return TextTrackMenuItem; }(_menuItem2['default']); _component2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem); exports['default'] = TextTrackMenuItem; },{"49":49,"5":5,"86":86,"97":97,"98":98}],32:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _formatTime = _dereq_(87); var _formatTime2 = _interopRequireDefault(_formatTime); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file current-time-display.js */ /** * Displays the current time * * @extends Component */ var CurrentTimeDisplay = function (_Component) { _inherits(CurrentTimeDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CurrentTimeDisplay(player, options) { _classCallCheck(this, CurrentTimeDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.on(player, 'timeupdate', _this.updateContent); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ CurrentTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-current-time-display', // label the current time for screen reader users innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update current time display * * @param {EventTarget~Event} [event] * The `timeupdate` event that caused this function to run. * * @listens Player#timeupdate */ CurrentTimeDisplay.prototype.updateContent = function updateContent(event) { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); var localizedText = this.localize('Current Time'); var formattedTime = (0, _formatTime2['default'])(time, this.player_.duration()); if (formattedTime !== this.formattedTime_) { this.formattedTime_ = formattedTime; this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; } }; return CurrentTimeDisplay; }(_component2['default']); _component2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); exports['default'] = CurrentTimeDisplay; },{"5":5,"83":83,"87":87}],33:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _formatTime = _dereq_(87); var _formatTime2 = _interopRequireDefault(_formatTime); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file duration-display.js */ /** * Displays the duration * * @extends Component */ var DurationDisplay = function (_Component) { _inherits(DurationDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function DurationDisplay(player, options) { _classCallCheck(this, DurationDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.on(player, 'durationchange', _this.updateContent); // Also listen for timeupdate and loadedmetadata because removing those // listeners could have broken dependent applications/libraries. These // can likely be removed for 6.0. _this.on(player, 'timeupdate', _this.updateContent); _this.on(player, 'loadedmetadata', _this.updateContent); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ DurationDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', // label the duration time for screen reader users innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update duration time display. * * @param {EventTarget~Event} [event] * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused * this function to be called. * * @listens Player#durationchange * @listens Player#timeupdate * @listens Player#loadedmetadata */ DurationDisplay.prototype.updateContent = function updateContent(event) { var duration = this.player_.duration(); if (duration && this.duration_ !== duration) { this.duration_ = duration; var localizedText = this.localize('Duration Time'); var formattedTime = (0, _formatTime2['default'])(duration); // label the duration time for screen reader users this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; } }; return DurationDisplay; }(_component2['default']); _component2['default'].registerComponent('DurationDisplay', DurationDisplay); exports['default'] = DurationDisplay; },{"5":5,"83":83,"87":87}],34:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _formatTime = _dereq_(87); var _formatTime2 = _interopRequireDefault(_formatTime); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file remaining-time-display.js */ /** * Displays the time left in the video * * @extends Component */ var RemainingTimeDisplay = function (_Component) { _inherits(RemainingTimeDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function RemainingTimeDisplay(player, options) { _classCallCheck(this, RemainingTimeDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.on(player, 'timeupdate', _this.updateContent); _this.on(player, 'durationchange', _this.updateContent); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ RemainingTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-remaining-time-display', // label the remaining time for screen reader users innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update remaining time display. * * @param {EventTarget~Event} [event] * The `timeupdate` or `durationchange` event that caused this to run. * * @listens Player#timeupdate * @listens Player#durationchange */ RemainingTimeDisplay.prototype.updateContent = function updateContent(event) { if (this.player_.duration()) { var localizedText = this.localize('Remaining Time'); var formattedTime = (0, _formatTime2['default'])(this.player_.remainingTime()); if (formattedTime !== this.formattedTime_) { this.formattedTime_ = formattedTime; this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime; } } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; return RemainingTimeDisplay; }(_component2['default']); _component2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); exports['default'] = RemainingTimeDisplay; },{"5":5,"83":83,"87":87}],35:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file time-divider.js */ /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @extends Component */ var TimeDivider = function (_Component) { _inherits(TimeDivider, _Component); function TimeDivider() { _classCallCheck(this, TimeDivider); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the component's DOM element * * @return {Element} * The element that was created. */ TimeDivider.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; return TimeDivider; }(_component2['default']); _component2['default'].registerComponent('TimeDivider', TimeDivider); exports['default'] = TimeDivider; },{"5":5}],36:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuButton = _dereq_(48); var _menuButton2 = _interopRequireDefault(_menuButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file track-button.js */ /** * The base class for buttons that toggle specific track types (e.g. subtitles). * * @extends MenuButton */ var TrackButton = function (_MenuButton) { _inherits(TrackButton, _MenuButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TrackButton(player, options) { _classCallCheck(this, TrackButton); var tracks = options.tracks; var _this = _possibleConstructorReturn(this, _MenuButton.call(this, player, options)); if (_this.items.length <= 1) { _this.hide(); } if (!tracks) { return _possibleConstructorReturn(_this); } var updateHandler = Fn.bind(_this, _this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); _this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); return _this; } return TrackButton; }(_menuButton2['default']); _component2['default'].registerComponent('TrackButton', TrackButton); exports['default'] = TrackButton; },{"48":48,"5":5,"86":86}],37:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * Check if volume control is supported and if it isn't hide the * `Component` that was passed using the `vjs-hidden` class. * * @param {Component} self * The component that should be hidden if volume is unsupported * * @param {Player} player * A reference to the player * * @private */ var checkVolumeSupport = function checkVolumeSupport(self, player) { // hide volume controls when they're not supported by the current tech if (player.tech_ && !player.tech_.featuresVolumeControl) { self.addClass('vjs-hidden'); } self.on(player, 'loadstart', function () { if (!player.tech_.featuresVolumeControl) { self.addClass('vjs-hidden'); } else { self.removeClass('vjs-hidden'); } }); }; exports['default'] = checkVolumeSupport; },{}],38:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _slider = _dereq_(58); var _slider2 = _interopRequireDefault(_slider); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); _dereq_(40); 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; } /** * @file volume-bar.js */ // Required children /** * The bar that contains the volume level and can be clicked on to adjust the level * * @extends Slider */ var VolumeBar = function (_Slider) { _inherits(VolumeBar, _Slider); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function VolumeBar(player, options) { _classCallCheck(this, VolumeBar); var _this = _possibleConstructorReturn(this, _Slider.call(this, player, options)); _this.on('slideractive', _this.updateLastVolume_); _this.on(player, 'volumechange', _this.updateARIAAttributes); player.ready(function () { return _this.updateARIAAttributes(); }); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ VolumeBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar vjs-slider-bar' }, { 'aria-label': 'volume level', 'aria-live': 'polite' }); }; /** * Handle movement events on the {@link VolumeMenuButton}. * * @param {EventTarget~Event} event * The event that caused this function to run. * * @listens mousemove */ VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) { this.checkMuted(); this.player_.volume(this.calculateDistance(event)); }; /** * If the player is muted unmute it. */ VolumeBar.prototype.checkMuted = function checkMuted() { if (this.player_.muted()) { this.player_.muted(false); } }; /** * Get percent of volume level * * @return {number} * Volume level percent as a decimal number. */ VolumeBar.prototype.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } return this.player_.volume(); }; /** * Increase volume level for keyboard users */ VolumeBar.prototype.stepForward = function stepForward() { this.checkMuted(); this.player_.volume(this.player_.volume() + 0.1); }; /** * Decrease volume level for keyboard users */ VolumeBar.prototype.stepBack = function stepBack() { this.checkMuted(); this.player_.volume(this.player_.volume() - 0.1); }; /** * Update ARIA accessibility attributes * * @param {EventTarget~Event} [event] * The `volumechange` event that caused this function to run. * * @listens Player#volumechange */ VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes(event) { // Current value of volume bar as a percentage var volume = Math.round(this.player_.volume() * 100).toString(); this.el_.setAttribute('aria-valuenow', volume); this.el_.setAttribute('aria-valuetext', volume + '%'); }; /** * When user starts dragging the VolumeBar, store the volume and listen for * the end of the drag. When the drag ends, if the volume was set to zero, * set lastVolume to the stored volume. * * @listens slideractive * @private */ VolumeBar.prototype.updateLastVolume_ = function updateLastVolume_() { var _this2 = this; var volumeBeforeDrag = this.player_.volume(); this.one('sliderinactive', function () { if (_this2.player_.volume() === 0) { _this2.player_.lastVolume_(volumeBeforeDrag); } }); }; return VolumeBar; }(_slider2['default']); /** * Default options for the `VolumeBar` * * @type {Object} * @private */ VolumeBar.prototype.options_ = { children: ['volumeLevel'], barName: 'volumeLevel' }; /** * Call the update event for this Slider when this event happens on the player. * * @type {string} */ VolumeBar.prototype.playerEvent = 'volumechange'; _component2['default'].registerComponent('VolumeBar', VolumeBar); exports['default'] = VolumeBar; },{"40":40,"5":5,"58":58}],39:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _checkVolumeSupport = _dereq_(37); var _checkVolumeSupport2 = _interopRequireDefault(_checkVolumeSupport); var _obj = _dereq_(91); var _fn = _dereq_(86); _dereq_(38); 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; } /** * @file volume-control.js */ // Required children /** * The component for controlling the volume level * * @extends Component */ var VolumeControl = function (_Component) { _inherits(VolumeControl, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function VolumeControl(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, VolumeControl); options.vertical = options.vertical || false; // Pass the vertical option down to the VolumeBar if // the VolumeBar is turned on. if (typeof options.volumeBar === 'undefined' || (0, _obj.isPlain)(options.volumeBar)) { options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = options.vertical; } // hide this control if volume support is missing var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); (0, _checkVolumeSupport2['default'])(_this, player); _this.throttledHandleMouseMove = (0, _fn.throttle)((0, _fn.bind)(_this, _this.handleMouseMove), 25); _this.on('mousedown', _this.handleMouseDown); _this.on('touchstart', _this.handleMouseDown); // while the slider is active (the mouse has been pressed down and // is dragging) or in focus we do not want to hide the VolumeBar _this.on(_this.volumeBar, ['focus', 'slideractive'], function () { _this.volumeBar.addClass('vjs-slider-active'); _this.addClass('vjs-slider-active'); _this.trigger('slideractive'); }); _this.on(_this.volumeBar, ['blur', 'sliderinactive'], function () { _this.volumeBar.removeClass('vjs-slider-active'); _this.removeClass('vjs-slider-active'); _this.trigger('sliderinactive'); }); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ VolumeControl.prototype.createEl = function createEl() { var orientationClass = 'vjs-volume-horizontal'; if (this.options_.vertical) { orientationClass = 'vjs-volume-vertical'; } return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control ' + orientationClass }); }; /** * Handle `mousedown` or `touchstart` events on the `VolumeControl`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart */ VolumeControl.prototype.handleMouseDown = function handleMouseDown(event) { var doc = this.el_.ownerDocument; this.on(doc, 'mousemove', this.throttledHandleMouseMove); this.on(doc, 'touchmove', this.throttledHandleMouseMove); this.on(doc, 'mouseup', this.handleMouseUp); this.on(doc, 'touchend', this.handleMouseUp); }; /** * Handle `mouseup` or `touchend` events on the `VolumeControl`. * * @param {EventTarget~Event} event * `mouseup` or `touchend` event that triggered this function. * * @listens touchend * @listens mouseup */ VolumeControl.prototype.handleMouseUp = function handleMouseUp(event) { var doc = this.el_.ownerDocument; this.off(doc, 'mousemove', this.throttledHandleMouseMove); this.off(doc, 'touchmove', this.throttledHandleMouseMove); this.off(doc, 'mouseup', this.handleMouseUp); this.off(doc, 'touchend', this.handleMouseUp); }; /** * Handle `mousedown` or `touchstart` events on the `VolumeControl`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart */ VolumeControl.prototype.handleMouseMove = function handleMouseMove(event) { this.volumeBar.handleMouseMove(event); }; return VolumeControl; }(_component2['default']); /** * Default options for the `VolumeControl` * * @type {Object} * @private */ VolumeControl.prototype.options_ = { children: ['volumeBar'] }; _component2['default'].registerComponent('VolumeControl', VolumeControl); exports['default'] = VolumeControl; },{"37":37,"38":38,"5":5,"86":86,"91":91}],40:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file volume-level.js */ /** * Shows volume level * * @extends Component */ var VolumeLevel = function (_Component) { _inherits(VolumeLevel, _Component); function VolumeLevel() { _classCallCheck(this, VolumeLevel); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ VolumeLevel.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; }(_component2['default']); _component2['default'].registerComponent('VolumeLevel', VolumeLevel); exports['default'] = VolumeLevel; },{"5":5}],41:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _checkVolumeSupport = _dereq_(37); var _checkVolumeSupport2 = _interopRequireDefault(_checkVolumeSupport); var _obj = _dereq_(91); _dereq_(39); _dereq_(11); 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; } /** * @file volume-control.js */ // Required children /** * A Component to contain the MuteToggle and VolumeControl so that * they can work together. * * @extends Component */ var VolumePanel = function (_Component) { _inherits(VolumePanel, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function VolumePanel(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, VolumePanel); if (typeof options.inline !== 'undefined') { options.inline = options.inline; } else { options.inline = true; } // pass the inline option down to the VolumeControl as vertical if // the VolumeControl is on. if (typeof options.volumeControl === 'undefined' || (0, _obj.isPlain)(options.volumeControl)) { options.volumeControl = options.volumeControl || {}; options.volumeControl.vertical = !options.inline; } // hide this control if volume support is missing var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); (0, _checkVolumeSupport2['default'])(_this, player); // while the slider is active (the mouse has been pressed down and // is dragging) or in focus we do not want to hide the VolumeBar _this.on(_this.volumeControl, ['slideractive'], _this.sliderActive_); _this.on(_this.muteToggle, 'focus', _this.sliderActive_); _this.on(_this.volumeControl, ['sliderinactive'], _this.sliderInactive_); _this.on(_this.muteToggle, 'blur', _this.sliderInactive_); return _this; } /** * Add vjs-slider-active class to the VolumePanel * * @listens VolumeControl#slideractive * @private */ VolumePanel.prototype.sliderActive_ = function sliderActive_() { this.addClass('vjs-slider-active'); }; /** * Removes vjs-slider-active class to the VolumePanel * * @listens VolumeControl#sliderinactive * @private */ VolumePanel.prototype.sliderInactive_ = function sliderInactive_() { this.removeClass('vjs-slider-active'); }; /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ VolumePanel.prototype.createEl = function createEl() { var orientationClass = 'vjs-volume-panel-horizontal'; if (!this.options_.inline) { orientationClass = 'vjs-volume-panel-vertical'; } return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-panel vjs-control ' + orientationClass }); }; return VolumePanel; }(_component2['default']); /** * Default options for the `VolumeControl` * * @type {Object} * @private */ VolumePanel.prototype.options_ = { children: ['muteToggle', 'volumeControl'] }; _component2['default'].registerComponent('VolumePanel', VolumePanel); exports['default'] = VolumePanel; },{"11":11,"37":37,"39":39,"5":5,"91":91}],42:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _modalDialog = _dereq_(53); var _modalDialog2 = _interopRequireDefault(_modalDialog); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); 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; } /** * @file error-display.js */ /** * A display that indicates an error has occurred. This means that the video * is unplayable. * * @extends ModalDialog */ var ErrorDisplay = function (_ModalDialog) { _inherits(ErrorDisplay, _ModalDialog); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ErrorDisplay(player, options) { _classCallCheck(this, ErrorDisplay); var _this = _possibleConstructorReturn(this, _ModalDialog.call(this, player, options)); _this.on(player, 'error', _this.open); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. * * @deprecated Since version 5. */ ErrorDisplay.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-error-display ' + _ModalDialog.prototype.buildCSSClass.call(this); }; /** * Gets the localized error message based on the `Player`s error. * * @return {string} * The `Player`s error message localized or an empty string. */ ErrorDisplay.prototype.content = function content() { var error = this.player().error(); return error ? this.localize(error.message) : ''; }; return ErrorDisplay; }(_modalDialog2['default']); /** * The default options for an `ErrorDisplay`. * * @private */ ErrorDisplay.prototype.options_ = (0, _mergeOptions2['default'])(_modalDialog2['default'].prototype.options_, { fillAlways: true, temporary: false, uncloseable: true }); _component2['default'].registerComponent('ErrorDisplay', ErrorDisplay); exports['default'] = ErrorDisplay; },{"5":5,"53":53,"90":90}],43:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _events = _dereq_(84); var Events = _interopRequireWildcard(_events); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It * adds shorthand functions that wrap around lengthy functions. For example: * the `on` function is a wrapper around `addEventListener`. * * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget} * @class EventTarget */ var EventTarget = function EventTarget() {}; /** * A Custom DOM event. * * @typedef {Object} EventTarget~Event * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent} */ /** * All event listeners should follow the following format. * * @callback EventTarget~EventListener * @this {EventTarget} * * @param {EventTarget~Event} event * the event that triggered this function * * @param {Object} [hash] * hash of data sent during the event */ /** * An object containing event names as keys and booleans as values. * * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger} * will have extra functionality. See that function for more information. * * @property EventTarget.prototype.allowedEvents_ * @private */ /** * @file src/js/event-target.js */ EventTarget.prototype.allowedEvents_ = {}; /** * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a * function that will get called when an event with a certain name gets triggered. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to call with `EventTarget`s */ EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; Events.on(this, type, fn); this.addEventListener = ael; }; /** * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#on} */ EventTarget.prototype.addEventListener = EventTarget.prototype.on; /** * Removes an `event listener` for a specific event from an instance of `EventTarget`. * This makes it so that the `event listener` will no longer get called when the * named event happens. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to remove. */ EventTarget.prototype.off = function (type, fn) { Events.off(this, type, fn); }; /** * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#off} */ EventTarget.prototype.removeEventListener = EventTarget.prototype.off; /** * This function will add an `event listener` that gets triggered only once. After the * first trigger it will get removed. This is like adding an `event listener` * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to be called once for each event name. */ EventTarget.prototype.one = function (type, fn) { // Remove the addEventListener alialing Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; Events.one(this, type, fn); this.addEventListener = ael; }; /** * This function causes an event to happen. This will then cause any `event listeners` * that are waiting for that event, to get called. If there are no `event listeners` * for an event then nothing will happen. * * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`. * Trigger will also call the `on` + `uppercaseEventName` function. * * Example: * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call * `onClick` if it exists. * * @param {string|EventTarget~Event|Object} event * The name of the event, an `Event`, or an object with a key of type set to * an event name. */ EventTarget.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; /** * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#trigger} */ EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; exports['default'] = EventTarget; },{"84":84}],44:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = 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; }; /** * @file extend.js * @module extend */ /** * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. * * @param {Object} subClass * The class to inherit to * * @param {Object} superClass * The class to inherit from * * @private */ var _inherits = 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 === 'undefined' ? 'undefined' : _typeof(superClass))); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) { // node subClass.super_ = superClass; } }; /** * Function for subclassing using the same inheritance that * videojs uses internally * * @static * @const * * @param {Object} superClass * The class to inherit from * * @param {Object} [subClassMethods={}] * The class to inherit to * * @return {Object} * The new object with subClassMethods that inherited superClass. */ var extendFn = function extendFn(superClass) { var subClassMethods = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if ((typeof subClassMethods === 'undefined' ? 'undefined' : _typeof(subClassMethods)) === 'object') { if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; exports['default'] = extendFn; },{}],45:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Store the browser-specific methods for the fullscreen API. * * @type {Object} * @see [Specification]{@link https://fullscreen.spec.whatwg.org} * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js} */ var FullscreenApi = {}; // browser API methods /** * @file fullscreen-api.js * @module fullscreen-api * @private */ var apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = void 0; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _document2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var _i = 0; _i < browserApi.length; _i++) { FullscreenApi[specApi[_i]] = browserApi[_i]; } } exports['default'] = FullscreenApi; },{"97":97}],46:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); 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; } /** * @file loading-spinner.js */ /** * A loading spinner for use during waiting/loading events. * * @extends Component */ var LoadingSpinner = function (_Component) { _inherits(LoadingSpinner, _Component); function LoadingSpinner() { _classCallCheck(this, LoadingSpinner); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the `LoadingSpinner`s DOM element. * * @return {Element} * The dom element that gets created. */ LoadingSpinner.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner', dir: 'ltr' }); }; return LoadingSpinner; }(_component2['default']); _component2['default'].registerComponent('LoadingSpinner', LoadingSpinner); exports['default'] = LoadingSpinner; },{"5":5}],47:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _obj = _dereq_(91); /** * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class. * * @param {number|string|Object|MediaError} value * This can be of multiple types: * - number: should be a standard error code * - string: an error message (the code will be 0) * - Object: arbitrary properties * - `MediaError` (native): used to populate a video.js `MediaError` object * - `MediaError` (video.js): will return itself if it's already a * video.js `MediaError` object. * * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror} * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes} * * @class MediaError */ function MediaError(value) { // Allow redundant calls to this constructor to avoid having `instanceof` // checks peppered around the code. if (value instanceof MediaError) { return value; } if (typeof value === 'number') { this.code = value; } else if (typeof value === 'string') { // default code is zero, so this is a custom error this.message = value; } else if ((0, _obj.isObject)(value)) { // We assign the `code` property manually because native `MediaError` objects // do not expose it as an own/enumerable property of the object. if (typeof value.code === 'number') { this.code = value.code; } (0, _obj.assign)(this, value); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } } /** * The error code that refers two one of the defined `MediaError` types * * @type {Number} */ /** * @file media-error.js */ MediaError.prototype.code = 0; /** * An optional message that to show with the error. Message is not part of the HTML5 * video spec but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /** * An optional status code that can be set by plugins to allow even more detail about * the error. For example a plugin might provide a specific HTTP status code and an * error message for that code. Then when the plugin gets that error this class will * know how to display an error message for it. This allows a custom message to show * up on the `Player` error overlay. * * @type {Array} */ MediaError.prototype.status = null; /** * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the * specification listed under {@link MediaError} for more information. * * @enum {array} * @readonly * @property {string} 0 - MEDIA_ERR_CUSTOM * @property {string} 1 - MEDIA_ERR_CUSTOM * @property {string} 2 - MEDIA_ERR_ABORTED * @property {string} 3 - MEDIA_ERR_NETWORK * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED * @property {string} 5 - MEDIA_ERR_ENCRYPTED */ MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED']; /** * The default `MediaError` messages based on the {@link MediaError.errorTypes}. * * @type {Array} * @constant */ MediaError.defaultMessages = { 1: 'You aborted the media playback', 2: 'A network error caused the media download to fail part-way.', 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.', 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The media is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } // jsdocs for instance/static members added above // instance methods use `#` and static methods use `.` /** * W3C error code for any custom error. * * @member MediaError#MEDIA_ERR_CUSTOM * @constant {number} * @default 0 */ /** * W3C error code for any custom error. * * @member MediaError.MEDIA_ERR_CUSTOM * @constant {number} * @default 0 */ /** * W3C error code for media error aborted. * * @member MediaError#MEDIA_ERR_ABORTED * @constant {number} * @default 1 */ /** * W3C error code for media error aborted. * * @member MediaError.MEDIA_ERR_ABORTED * @constant {number} * @default 1 */ /** * W3C error code for any network error. * * @member MediaError#MEDIA_ERR_NETWORK * @constant {number} * @default 2 */ /** * W3C error code for any network error. * * @member MediaError.MEDIA_ERR_NETWORK * @constant {number} * @default 2 */ /** * W3C error code for any decoding error. * * @member MediaError#MEDIA_ERR_DECODE * @constant {number} * @default 3 */ /** * W3C error code for any decoding error. * * @member MediaError.MEDIA_ERR_DECODE * @constant {number} * @default 3 */ /** * W3C error code for any time that a source is not supported. * * @member MediaError#MEDIA_ERR_SRC_NOT_SUPPORTED * @constant {number} * @default 4 */ /** * W3C error code for any time that a source is not supported. * * @member MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED * @constant {number} * @default 4 */ /** * W3C error code for any time that a source is encrypted. * * @member MediaError#MEDIA_ERR_ENCRYPTED * @constant {number} * @default 5 */ /** * W3C error code for any time that a source is encrypted. * * @member MediaError.MEDIA_ERR_ENCRYPTED * @constant {number} * @default 5 */ exports['default'] = MediaError; },{"91":91}],48:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _menu = _dereq_(50); var _menu2 = _interopRequireDefault(_menu); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _toTitleCase = _dereq_(94); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file menu-button.js */ /** * A `MenuButton` class for any popup {@link Menu}. * * @extends ClickableComponent */ var MenuButton = function (_ClickableComponent) { _inherits(MenuButton, _ClickableComponent); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function MenuButton(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, MenuButton); var _this = _possibleConstructorReturn(this, _ClickableComponent.call(this, player, options)); _this.update(); _this.enabled_ = true; _this.el_.setAttribute('aria-haspopup', 'true'); _this.el_.setAttribute('role', 'menuitem'); _this.on('keydown', _this.handleSubmenuKeyPress); return _this; } /** * Update the menu based on the current state of its items. */ MenuButton.prototype.update = function update() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; this.el_.setAttribute('aria-expanded', 'false'); if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create the menu and add all items to it. * * @return {Menu} * The constructed menu */ MenuButton.prototype.createMenu = function createMenu() { var menu = new _menu2['default'](this.player_); // Add a title list item to the top if (this.options_.title) { var title = Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: (0, _toTitleCase2['default'])(this.options_.title), tabIndex: -1 }); menu.children_.unshift(title); Dom.prependTo(title, menu.contentEl()); } this.items = this.createItems(); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. * * @abstract */ MenuButton.prototype.createItems = function createItems() {}; /** * Create the `MenuButtons`s DOM element. * * @return {Element} * The element that gets created. */ MenuButton.prototype.createEl = function createEl() { return _ClickableComponent.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ MenuButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _ClickableComponent.prototype.buildCSSClass.call(this); }; /** * Handle a click on a `MenuButton`. * See {@link ClickableComponent#handleClick} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ MenuButton.prototype.handleClick = function handleClick(event) { // When you click the button it adds focus, which will show the menu. // So we'll remove focus when the mouse leaves the button. Focus is needed // for tab navigation. this.one(this.menu.contentEl(), 'mouseleave', Fn.bind(this, function (e) { this.unpressButton(); this.el_.blur(); })); if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } }; /** * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See * {@link ClickableComponent#handleKeyPress} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ MenuButton.prototype.handleKeyPress = function handleKeyPress(event) { // Escape (27) key or Tab (9) key unpress the 'button' if (event.which === 27 || event.which === 9) { if (this.buttonPressed_) { this.unpressButton(); } // Don't preventDefault for Tab key - we still want to lose focus if (event.which !== 9) { event.preventDefault(); } // Up (38) key or Down (40) key press the 'button' } else if (event.which === 38 || event.which === 40) { if (!this.buttonPressed_) { this.pressButton(); event.preventDefault(); } } else { _ClickableComponent.prototype.handleKeyPress.call(this, event); } }; /** * Handle a `keydown` event on a sub-menu. The listener for this is added in * the constructor. * * @param {EventTarget~Event} event * Key press event * * @listens keydown */ MenuButton.prototype.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) { // Escape (27) key or Tab (9) key unpress the 'button' if (event.which === 27 || event.which === 9) { if (this.buttonPressed_) { this.unpressButton(); } // Don't preventDefault for Tab key - we still want to lose focus if (event.which !== 9) { event.preventDefault(); } } }; /** * Put the current `MenuButton` into a pressed state. */ MenuButton.prototype.pressButton = function pressButton() { if (this.enabled_) { this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-expanded', 'true'); // set the focus into the submenu this.menu.focus(); } }; /** * Take the current `MenuButton` out of a pressed state. */ MenuButton.prototype.unpressButton = function unpressButton() { if (this.enabled_) { this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-expanded', 'false'); // Set focus back to this menu button this.el_.focus(); } }; /** * Disable the `MenuButton`. Don't allow it to be clicked. */ MenuButton.prototype.disable = function disable() { // Unpress, but don't force focus on this button this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-expanded', 'false'); this.enabled_ = false; _ClickableComponent.prototype.disable.call(this); }; /** * Enable the `MenuButton`. Allow it to be clicked. */ MenuButton.prototype.enable = function enable() { this.enabled_ = true; _ClickableComponent.prototype.enable.call(this); }; return MenuButton; }(_clickableComponent2['default']); _component2['default'].registerComponent('MenuButton', MenuButton); exports['default'] = MenuButton; },{"3":3,"5":5,"50":50,"83":83,"86":86,"94":94}],49:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _obj = _dereq_(91); 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; } /** * @file menu-item.js */ /** * The component for a menu item. `<li>` * * @extends ClickableComponent */ var MenuItem = function (_ClickableComponent) { _inherits(MenuItem, _ClickableComponent); /** * Creates an instance of the this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. * */ function MenuItem(player, options) { _classCallCheck(this, MenuItem); var _this = _possibleConstructorReturn(this, _ClickableComponent.call(this, player, options)); _this.selectable = options.selectable; _this.selected(options.selected); if (_this.selectable) { // TODO: May need to be either menuitemcheckbox or menuitemradio, // and may need logical grouping of menu items. _this.el_.setAttribute('role', 'menuitemcheckbox'); } else { _this.el_.setAttribute('role', 'menuitem'); } return _this; } /** * Create the `MenuItem's DOM element * * @param {string} [type=li] * Element's node type, not actually used, always set to `li`. * * @param {Object} [props={}] * An object of properties that should be set on the element * * @param {Object} [attrs={}] * An object of attributes that should be set on the element * * @return {Element} * The element that gets created. */ MenuItem.prototype.createEl = function createEl(type, props, attrs) { // The control is textual, not just an icon this.nonIconControl = true; return _ClickableComponent.prototype.createEl.call(this, 'li', (0, _obj.assign)({ className: 'vjs-menu-item', innerHTML: '<span class="vjs-menu-item-text">' + this.localize(this.options_.label) + '</span>', tabIndex: -1 }, props), attrs); }; /** * Any click on a `MenuItem` puts int into the selected state. * See {@link ClickableComponent#handleClick} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ MenuItem.prototype.handleClick = function handleClick(event) { this.selected(true); }; /** * Set the state for this menu item as selected or not. * * @param {boolean} selected * if the menu item is selected or not */ MenuItem.prototype.selected = function selected(_selected) { if (this.selectable) { if (_selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-checked', 'true'); // aria-checked isn't fully supported by browsers/screen readers, // so indicate selected state to screen reader in the control text. this.controlText(', selected'); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-checked', 'false'); // Indicate un-selected state to screen reader // Note that a space clears out the selected state text this.controlText(' '); } } }; return MenuItem; }(_clickableComponent2['default']); _component2['default'].registerComponent('MenuItem', MenuItem); exports['default'] = MenuItem; },{"3":3,"5":5,"91":91}],50:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _events = _dereq_(84); var Events = _interopRequireWildcard(_events); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file menu.js */ /** * The Menu component is used to build popup menus, including subtitle and * captions selection menus. * * @extends Component */ var Menu = function (_Component) { _inherits(Menu, _Component); /** * Create an instance of this class. * * @param {Player} player * the player that this component should attach to * * @param {Object} [options] * Object of option names and values * */ function Menu(player, options) { _classCallCheck(this, Menu); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.focusedChild_ = -1; _this.on('keydown', _this.handleKeyPress); return _this; } /** * Add a {@link MenuItem} to the menu. * * @param {Object|string} component * The name or instance of the `MenuItem` to add. * */ Menu.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function (event) { this.unlockShowing(); // TODO: Need to set keyboard focus back to the menuButton })); }; /** * Create the `Menu`s DOM element. * * @return {Element} * the element that was created */ Menu.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); this.contentEl_.setAttribute('role', 'menu'); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.setAttribute('role', 'presentation'); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; /** * Handle a `keydown` event on this menu. This listener is added in the constructor. * * @param {EventTarget~Event} event * A `keydown` event that happened on the menu. * * @listens keydown */ Menu.prototype.handleKeyPress = function handleKeyPress(event) { // Left and Down Arrows if (event.which === 37 || event.which === 40) { event.preventDefault(); this.stepForward(); // Up and Right Arrows } else if (event.which === 38 || event.which === 39) { event.preventDefault(); this.stepBack(); } }; /** * Move to next (lower) menu item for keyboard users. */ Menu.prototype.stepForward = function stepForward() { var stepChild = 0; if (this.focusedChild_ !== undefined) { stepChild = this.focusedChild_ + 1; } this.focus(stepChild); }; /** * Move to previous (higher) menu item for keyboard users. */ Menu.prototype.stepBack = function stepBack() { var stepChild = 0; if (this.focusedChild_ !== undefined) { stepChild = this.focusedChild_ - 1; } this.focus(stepChild); }; /** * Set focus on a {@link MenuItem} in the `Menu`. * * @param {Object|string} [item=0] * Index of child item set focus on. */ Menu.prototype.focus = function focus() { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var children = this.children().slice(); var haveTitle = children.length && children[0].className && /vjs-menu-title/.test(children[0].className); if (haveTitle) { children.shift(); } if (children.length > 0) { if (item < 0) { item = 0; } else if (item >= children.length) { item = children.length - 1; } this.focusedChild_ = item; children[item].el_.focus(); } }; return Menu; }(_component2['default']); _component2['default'].registerComponent('Menu', Menu); exports['default'] = Menu; },{"5":5,"83":83,"84":84,"86":86}],51:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.isEvented = undefined; var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _events = _dereq_(84); var Events = _interopRequireWildcard(_events); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _obj = _dereq_(91); var Obj = _interopRequireWildcard(_obj); var _eventTarget = _dereq_(43); var _eventTarget2 = _interopRequireDefault(_eventTarget); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * Returns whether or not an object has had the evented mixin applied. * * @param {Object} object * An object to test. * * @return {boolean} * Whether or not the object appears to be evented. */ var isEvented = function isEvented(object) { return object instanceof _eventTarget2['default'] || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(function (k) { return typeof object[k] === 'function'; }); }; /** * Whether a value is a valid event type - non-empty string or array. * * @private * @param {string|Array} type * The type value to test. * * @return {boolean} * Whether or not the type is a valid event type. */ /** * @file mixins/evented.js * @module evented */ var isValidEventType = function isValidEventType(type) { return ( // The regex here verifies that the `type` contains at least one non- // whitespace character. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length ); }; /** * Validates a value to determine if it is a valid event target. Throws if not. * * @private * @throws {Error} * If the target does not appear to be a valid event target. * * @param {Object} target * The object to test. */ var validateTarget = function validateTarget(target) { if (!target.nodeName && !isEvented(target)) { throw new Error('Invalid target; must be a DOM node or evented object.'); } }; /** * Validates a value to determine if it is a valid event target. Throws if not. * * @private * @throws {Error} * If the type does not appear to be a valid event type. * * @param {string|Array} type * The type to test. */ var validateEventType = function validateEventType(type) { if (!isValidEventType(type)) { throw new Error('Invalid event type; must be a non-empty string or array.'); } }; /** * Validates a value to determine if it is a valid listener. Throws if not. * * @private * @throws {Error} * If the listener is not a function. * * @param {Function} listener * The listener to test. */ var validateListener = function validateListener(listener) { if (typeof listener !== 'function') { throw new Error('Invalid listener; must be a function.'); } }; /** * Takes an array of arguments given to `on()` or `one()`, validates them, and * normalizes them into an object. * * @private * @param {Object} self * The evented object on which `on()` or `one()` was called. This * object will be bound as the `this` value for the listener. * * @param {Array} args * An array of arguments passed to `on()` or `one()`. * * @return {Object} * An object containing useful values for `on()` or `one()` calls. */ var normalizeListenArgs = function normalizeListenArgs(self, args) { // If the number of arguments is less than 3, the target is always the // evented object itself. var isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_; var target = void 0; var type = void 0; var listener = void 0; if (isTargetingSelf) { target = self.eventBusEl_; // Deal with cases where we got 3 arguments, but we are still listening to // the evented object itself. if (args.length >= 3) { args.shift(); } type = args[0]; listener = args[1]; } else { target = args[0]; type = args[1]; listener = args[2]; } validateTarget(target); validateEventType(type); validateListener(listener); listener = Fn.bind(self, listener); return { isTargetingSelf: isTargetingSelf, target: target, type: type, listener: listener }; }; /** * Adds the listener to the event type(s) on the target, normalizing for * the type of target. * * @private * @param {Element|Object} target * A DOM node or evented object. * * @param {string} method * The event binding method to use ("on" or "one"). * * @param {string|Array} type * One or more event type(s). * * @param {Function} listener * A listener function. */ var listen = function listen(target, method, type, listener) { validateTarget(target); if (target.nodeName) { Events[method](target, type, listener); } else { target[method](type, listener); } }; /** * Contains methods that provide event capabilites to an object which is passed * to {@link module:evented|evented}. * * @mixin EventedMixin */ var EventedMixin = { /** * Add a listener to an event (or events) on this object or another evented * object. * * @param {string|Array|Element|Object} targetOrType * If this is a string or array, it represents the event type(s) * that will trigger the listener. * * Another evented object can be passed here instead, which will * cause the listener to listen for events on _that_ object. * * In either case, the listener's `this` value will be bound to * this object. * * @param {string|Array|Function} typeOrListener * If the first argument was a string or array, this should be the * listener function. Otherwise, this is a string or array of event * type(s). * * @param {Function} [listener] * If the first argument was another evented object, this will be * the listener function. */ on: function on() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var _normalizeListenArgs = normalizeListenArgs(this, args), isTargetingSelf = _normalizeListenArgs.isTargetingSelf, target = _normalizeListenArgs.target, type = _normalizeListenArgs.type, listener = _normalizeListenArgs.listener; listen(target, 'on', type, listener); // If this object is listening to another evented object. if (!isTargetingSelf) { (function () { // If this object is disposed, remove the listener. var removeListenerOnDispose = function removeListenerOnDispose() { return _this.off(target, type, listener); }; // Use the same function ID as the listener so we can remove it later it // using the ID of the original listener. removeListenerOnDispose.guid = listener.guid; // Add a listener to the target's dispose event as well. This ensures // that if the target is disposed BEFORE this object, we remove the // removal listener that was just added. Otherwise, we create a memory leak. var removeRemoverOnTargetDispose = function removeRemoverOnTargetDispose() { return _this.off('dispose', removeListenerOnDispose); }; // Use the same function ID as the listener so we can remove it later // it using the ID of the original listener. removeRemoverOnTargetDispose.guid = listener.guid; listen(_this, 'on', 'dispose', removeListenerOnDispose); listen(target, 'on', 'dispose', removeRemoverOnTargetDispose); })(); } }, /** * Add a listener to an event (or events) on this object or another evented * object. The listener will only be called once and then removed. * * @param {string|Array|Element|Object} targetOrType * If this is a string or array, it represents the event type(s) * that will trigger the listener. * * Another evented object can be passed here instead, which will * cause the listener to listen for events on _that_ object. * * In either case, the listener's `this` value will be bound to * this object. * * @param {string|Array|Function} typeOrListener * If the first argument was a string or array, this should be the * listener function. Otherwise, this is a string or array of event * type(s). * * @param {Function} [listener] * If the first argument was another evented object, this will be * the listener function. */ one: function one() { var _this2 = this; for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var _normalizeListenArgs2 = normalizeListenArgs(this, args), isTargetingSelf = _normalizeListenArgs2.isTargetingSelf, target = _normalizeListenArgs2.target, type = _normalizeListenArgs2.type, listener = _normalizeListenArgs2.listener; // Targeting this evented object. if (isTargetingSelf) { listen(target, 'one', type, listener); // Targeting another evented object. } else { (function () { var wrapper = function wrapper() { for (var _len3 = arguments.length, largs = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { largs[_key3] = arguments[_key3]; } _this2.off(target, type, wrapper); listener.apply(null, largs); }; // Use the same function ID as the listener so we can remove it later // it using the ID of the original listener. wrapper.guid = listener.guid; listen(target, 'one', type, wrapper); })(); } }, /** * Removes listener(s) from event(s) on an evented object. * * @param {string|Array|Element|Object} [targetOrType] * If this is a string or array, it represents the event type(s). * * Another evented object can be passed here instead, in which case * ALL 3 arguments are _required_. * * @param {string|Array|Function} [typeOrListener] * If the first argument was a string or array, this may be the * listener function. Otherwise, this is a string or array of event * type(s). * * @param {Function} [listener] * If the first argument was another evented object, this will be * the listener function; otherwise, _all_ listeners bound to the * event type(s) will be removed. */ off: function off(targetOrType, typeOrListener, listener) { // Targeting this evented object. if (!targetOrType || isValidEventType(targetOrType)) { Events.off(this.eventBusEl_, targetOrType, typeOrListener); // Targeting another evented object. } else { var target = targetOrType; var type = typeOrListener; // Fail fast and in a meaningful way! validateTarget(target); validateEventType(type); validateListener(listener); // Ensure there's at least a guid, even if the function hasn't been used listener = Fn.bind(this, listener); // Remove the dispose listener on this evented object, which was given // the same guid as the event listener in on(). this.off('dispose', listener); if (target.nodeName) { Events.off(target, type, listener); Events.off(target, 'dispose', listener); } else if (isEvented(target)) { target.off(type, listener); target.off('dispose', listener); } } }, /** * Fire an event on this evented object, causing its listeners to be called. * * @param {string|Object} event * An event type or an object with a type property. * * @param {Object} [hash] * An additional object to pass along to listeners. * * @returns {boolean} * Whether or not the default behavior was prevented. */ trigger: function trigger(event, hash) { return Events.trigger(this.eventBusEl_, event, hash); } }; /** * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object. * * @param {Object} target * The object to which to add event methods. * * @param {Object} [options={}] * Options for customizing the mixin behavior. * * @param {String} [options.eventBusKey] * By default, adds a `eventBusEl_` DOM element to the target object, * which is used as an event bus. If the target object already has a * DOM element that should be used, pass its key here. * * @return {Object} * The target object. */ function evented(target) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var eventBusKey = options.eventBusKey; // Set or create the eventBusEl_. if (eventBusKey) { if (!target[eventBusKey].nodeName) { throw new Error('The eventBusKey "' + eventBusKey + '" does not refer to an element.'); } target.eventBusEl_ = target[eventBusKey]; } else { target.eventBusEl_ = Dom.createEl('span', { className: 'vjs-event-bus' }); } Obj.assign(target, EventedMixin); // When any evented object is disposed, it removes all its listeners. target.on('dispose', function () { return target.off(); }); return target; } exports['default'] = evented; exports.isEvented = isEvented; },{"43":43,"83":83,"84":84,"86":86,"91":91}],52:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _evented = _dereq_(51); var _obj = _dereq_(91); var Obj = _interopRequireWildcard(_obj); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * Contains methods that provide statefulness to an object which is passed * to {@link module:stateful}. * * @mixin StatefulMixin */ /** * @file mixins/stateful.js * @module stateful */ var StatefulMixin = { /** * A hash containing arbitrary keys and values representing the state of * the object. * * @type {Object} */ state: {}, /** * Set the state of an object by mutating its * {@link module:stateful~StatefulMixin.state|state} object in place. * * @fires module:stateful~StatefulMixin#statechanged * @param {Object|Function} stateUpdates * A new set of properties to shallow-merge into the plugin state. * Can be a plain object or a function returning a plain object. * * @returns {Object|undefined} * An object containing changes that occurred. If no changes * occurred, returns `undefined`. */ setState: function setState(stateUpdates) { var _this = this; // Support providing the `stateUpdates` state as a function. if (typeof stateUpdates === 'function') { stateUpdates = stateUpdates(); } var changes = void 0; Obj.each(stateUpdates, function (value, key) { // Record the change if the value is different from what's in the // current state. if (_this.state[key] !== value) { changes = changes || {}; changes[key] = { from: _this.state[key], to: value }; } _this.state[key] = value; }); // Only trigger "statechange" if there were changes AND we have a trigger // function. This allows us to not require that the target object be an // evented object. if (changes && (0, _evented.isEvented)(this)) { /** * An event triggered on an object that is both * {@link module:stateful|stateful} and {@link module:evented|evented} * indicating that its state has changed. * * @event module:stateful~StatefulMixin#statechanged * @type {Object} * @property {Object} changes * A hash containing the properties that were changed and * the values they were changed `from` and `to`. */ this.trigger({ changes: changes, type: 'statechanged' }); } return changes; } }; /** * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target * object. * * If the target object is {@link module:evented|evented} and has a * `handleStateChanged` method, that method will be automatically bound to the * `statechanged` event on itself. * * @param {Object} target * The object to be made stateful. * * @param {Object} [defaultState] * A default set of properties to populate the newly-stateful object's * `state` property. * * @returns {Object} * Returns the `target`. */ function stateful(target, defaultState) { Obj.assign(target, StatefulMixin); // This happens after the mixing-in because we need to replace the `state` // added in that step. target.state = Obj.assign({}, target.state, defaultState); // Auto-bind the `handleStateChanged` method of the target object if it exists. if (typeof target.handleStateChanged === 'function' && (0, _evented.isEvented)(target)) { target.on('statechanged', target.handleStateChanged); } return target; } exports['default'] = stateful; },{"51":51,"91":91}],53:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file modal-dialog.js */ var MODAL_CLASS_NAME = 'vjs-modal-dialog'; var ESC = 27; /** * The `ModalDialog` displays over the video and its controls, which blocks * interaction with the player until it is closed. * * Modal dialogs include a "Close" button and will close when that button * is activated - or when ESC is pressed anywhere. * * @extends Component */ var ModalDialog = function (_Component) { _inherits(ModalDialog, _Component); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Mixed} [options.content=undefined] * Provide customized content for this modal. * * @param {string} [options.description] * A text description for the modal, primarily for accessibility. * * @param {boolean} [options.fillAlways=false] * Normally, modals are automatically filled only the first time * they open. This tells the modal to refresh its content * every time it opens. * * @param {string} [options.label] * A text label for the modal, primarily for accessibility. * * @param {boolean} [options.temporary=true] * If `true`, the modal can only be opened once; it will be * disposed as soon as it's closed. * * @param {boolean} [options.uncloseable=false] * If `true`, the user will not be able to close the modal * through the UI in the normal ways. Programmatic closing is * still possible. */ function ModalDialog(player, options) { _classCallCheck(this, ModalDialog); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false; _this.closeable(!_this.options_.uncloseable); _this.content(_this.options_.content); // Make sure the contentEl is defined AFTER any children are initialized // because we only want the contents of the modal in the contentEl // (not the UI elements like the close button). _this.contentEl_ = Dom.createEl('div', { className: MODAL_CLASS_NAME + '-content' }, { role: 'document' }); _this.descEl_ = Dom.createEl('p', { className: MODAL_CLASS_NAME + '-description vjs-offscreen', id: _this.el().getAttribute('aria-describedby') }); Dom.textContent(_this.descEl_, _this.description()); _this.el_.appendChild(_this.descEl_); _this.el_.appendChild(_this.contentEl_); return _this; } /** * Create the `ModalDialog`'s DOM element * * @return {Element} * The DOM element that gets created. */ ModalDialog.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass(), tabIndex: -1 }, { 'aria-describedby': this.id() + '_description', 'aria-hidden': 'true', 'aria-label': this.label(), 'role': 'dialog' }); }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ModalDialog.prototype.buildCSSClass = function buildCSSClass() { return MODAL_CLASS_NAME + ' vjs-hidden ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handles `keydown` events on the document, looking for ESC, which closes * the modal. * * @param {EventTarget~Event} e * The keypress that triggered this event. * * @listens keydown */ ModalDialog.prototype.handleKeyPress = function handleKeyPress(e) { if (e.which === ESC && this.closeable()) { this.close(); } }; /** * Returns the label string for this modal. Primarily used for accessibility. * * @return {string} * the localized or raw label of this modal. */ ModalDialog.prototype.label = function label() { return this.options_.label || this.localize('Modal Window'); }; /** * Returns the description string for this modal. Primarily used for * accessibility. * * @return {string} * The localized or raw description of this modal. */ ModalDialog.prototype.description = function description() { var desc = this.options_.description || this.localize('This is a modal window.'); // Append a universal closeability message if the modal is closeable. if (this.closeable()) { desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.'); } return desc; }; /** * Opens the modal. * * @fires ModalDialog#beforemodalopen * @fires ModalDialog#modalopen */ ModalDialog.prototype.open = function open() { if (!this.opened_) { var player = this.player(); /** * Fired just before a `ModalDialog` is opened. * * @event ModalDialog#beforemodalopen * @type {EventTarget~Event} */ this.trigger('beforemodalopen'); this.opened_ = true; // Fill content if the modal has never opened before and // never been filled. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) { this.fill(); } // If the player was playing, pause it and take note of its previously // playing state. this.wasPlaying_ = !player.paused(); if (this.wasPlaying_) { player.pause(); } if (this.closeable()) { this.on(this.el_.ownerDocument, 'keydown', Fn.bind(this, this.handleKeyPress)); } player.controls(false); this.show(); this.el().setAttribute('aria-hidden', 'false'); /** * Fired just after a `ModalDialog` is opened. * * @event ModalDialog#modalopen * @type {EventTarget~Event} */ this.trigger('modalopen'); this.hasBeenOpened_ = true; } }; /** * If the `ModalDialog` is currently open or closed. * * @param {boolean} [value] * If given, it will open (`true`) or close (`false`) the modal. * * @return {boolean} * the current open state of the modaldialog */ ModalDialog.prototype.opened = function opened(value) { if (typeof value === 'boolean') { this[value ? 'open' : 'close'](); } return this.opened_; }; /** * Closes the modal, does nothing if the `ModalDialog` is * not open. * * @fires ModalDialog#beforemodalclose * @fires ModalDialog#modalclose */ ModalDialog.prototype.close = function close() { if (!this.opened_) { return; } var player = this.player(); /** * Fired just before a `ModalDialog` is closed. * * @event ModalDialog#beforemodalclose * @type {EventTarget~Event} */ this.trigger('beforemodalclose'); this.opened_ = false; if (this.wasPlaying_) { player.play(); } if (this.closeable()) { this.off(this.el_.ownerDocument, 'keydown', Fn.bind(this, this.handleKeyPress)); } player.controls(true); this.hide(); this.el().setAttribute('aria-hidden', 'true'); /** * Fired just after a `ModalDialog` is closed. * * @event ModalDialog#modalclose * @type {EventTarget~Event} */ this.trigger('modalclose'); if (this.options_.temporary) { this.dispose(); } }; /** * Check to see if the `ModalDialog` is closeable via the UI. * * @param {boolean} [value] * If given as a boolean, it will set the `closeable` option. * * @return {boolean} * Returns the final value of the closable option. */ ModalDialog.prototype.closeable = function closeable(value) { if (typeof value === 'boolean') { var closeable = this.closeable_ = !!value; var close = this.getChild('closeButton'); // If this is being made closeable and has no close button, add one. if (closeable && !close) { // The close button should be a child of the modal - not its // content element, so temporarily change the content element. var temp = this.contentEl_; this.contentEl_ = this.el_; close = this.addChild('closeButton', { controlText: 'Close Modal Dialog' }); this.contentEl_ = temp; this.on(close, 'close', this.close); } // If this is being made uncloseable and has a close button, remove it. if (!closeable && close) { this.off(close, 'close', this.close); this.removeChild(close); close.dispose(); } } return this.closeable_; }; /** * Fill the modal's content element with the modal's "content" option. * The content element will be emptied before this change takes place. */ ModalDialog.prototype.fill = function fill() { this.fillWith(this.content()); }; /** * Fill the modal's content element with arbitrary content. * The content element will be emptied before this change takes place. * * @fires ModalDialog#beforemodalfill * @fires ModalDialog#modalfill * * @param {Mixed} [content] * The same rules apply to this as apply to the `content` option. */ ModalDialog.prototype.fillWith = function fillWith(content) { var contentEl = this.contentEl(); var parentEl = contentEl.parentNode; var nextSiblingEl = contentEl.nextSibling; /** * Fired just before a `ModalDialog` is filled with content. * * @event ModalDialog#beforemodalfill * @type {EventTarget~Event} */ this.trigger('beforemodalfill'); this.hasBeenFilled_ = true; // Detach the content element from the DOM before performing // manipulation to avoid modifying the live DOM multiple times. parentEl.removeChild(contentEl); this.empty(); Dom.insertContent(contentEl, content); /** * Fired just after a `ModalDialog` is filled with content. * * @event ModalDialog#modalfill * @type {EventTarget~Event} */ this.trigger('modalfill'); // Re-inject the re-filled content element. if (nextSiblingEl) { parentEl.insertBefore(contentEl, nextSiblingEl); } else { parentEl.appendChild(contentEl); } }; /** * Empties the content element. This happens anytime the modal is filled. * * @fires ModalDialog#beforemodalempty * @fires ModalDialog#modalempty */ ModalDialog.prototype.empty = function empty() { /** * Fired just before a `ModalDialog` is emptied. * * @event ModalDialog#beforemodalempty * @type {EventTarget~Event} */ this.trigger('beforemodalempty'); Dom.emptyEl(this.contentEl()); /** * Fired just after a `ModalDialog` is emptied. * * @event ModalDialog#modalempty * @type {EventTarget~Event} */ this.trigger('modalempty'); }; /** * Gets or sets the modal content, which gets normalized before being * rendered into the DOM. * * This does not update the DOM or fill the modal, but it is called during * that process. * * @param {Mixed} [value] * If defined, sets the internal content value to be used on the * next call(s) to `fill`. This value is normalized before being * inserted. To "clear" the internal content value, pass `null`. * * @return {Mixed} * The current content of the modal dialog */ ModalDialog.prototype.content = function content(value) { if (typeof value !== 'undefined') { this.content_ = value; } return this.content_; }; return ModalDialog; }(_component2['default']); /** * Default options for `ModalDialog` default options. * * @type {Object} * @private */ ModalDialog.prototype.options_ = { temporary: true }; _component2['default'].registerComponent('ModalDialog', ModalDialog); exports['default'] = ModalDialog; },{"5":5,"83":83,"86":86}],54:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _templateObject = _taggedTemplateLiteralLoose(['\n Using the tech directly can be dangerous. I hope you know what you\'re doing.\n See https://github.com/videojs/video.js/issues/2617 for more info.\n '], ['\n Using the tech directly can be dangerous. I hope you know what you\'re doing.\n See https://github.com/videojs/video.js/issues/2617 for more info.\n ']); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _tsml = _dereq_(101); var _tsml2 = _interopRequireDefault(_tsml); var _evented = _dereq_(51); var _evented2 = _interopRequireDefault(_evented); var _events = _dereq_(84); var Events = _interopRequireWildcard(_events); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _guid = _dereq_(88); var Guid = _interopRequireWildcard(_guid); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _toTitleCase = _dereq_(94); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); var _timeRanges = _dereq_(93); var _buffer = _dereq_(80); var _stylesheet = _dereq_(92); var stylesheet = _interopRequireWildcard(_stylesheet); var _fullscreenApi = _dereq_(45); var _fullscreenApi2 = _interopRequireDefault(_fullscreenApi); var _mediaError = _dereq_(47); var _mediaError2 = _interopRequireDefault(_mediaError); var _tuple = _dereq_(100); var _tuple2 = _interopRequireDefault(_tuple); var _obj = _dereq_(91); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _textTrackListConverter = _dereq_(69); var _textTrackListConverter2 = _interopRequireDefault(_textTrackListConverter); var _modalDialog = _dereq_(53); var _modalDialog2 = _interopRequireDefault(_modalDialog); var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); var _middleware = _dereq_(61); var middleware = _interopRequireWildcard(_middleware); var _trackTypes = _dereq_(75); var _filterSource = _dereq_(85); var _filterSource2 = _interopRequireDefault(_filterSource); _dereq_(60); _dereq_(56); _dereq_(68); _dereq_(46); _dereq_(1); _dereq_(4); _dereq_(8); _dereq_(42); _dereq_(71); _dereq_(59); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } 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; } /** * @file player.js */ // Subclasses Component // The following imports are used only to ensure that the corresponding modules // are always included in the video.js package. Importing the modules will // execute them and they will register themselves with video.js. // Import Html5 tech, at least for disposing the original video tag. // The following tech events are simply re-triggered // on the player when they happen var TECH_EVENTS_RETRIGGER = [ /** * Fired while the user agent is downloading media data. * * @event Player#progress * @type {EventTarget~Event} */ /** * Retrigger the `progress` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechProgress_ * @fires Player#progress * @listens Tech#progress */ 'progress', /** * Fires when the loading of an audio/video is aborted. * * @event Player#abort * @type {EventTarget~Event} */ /** * Retrigger the `abort` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechAbort_ * @fires Player#abort * @listens Tech#abort */ 'abort', /** * Fires when the browser is intentionally not getting media data. * * @event Player#suspend * @type {EventTarget~Event} */ /** * Retrigger the `suspend` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechSuspend_ * @fires Player#suspend * @listens Tech#suspend */ 'suspend', /** * Fires when the current playlist is empty. * * @event Player#emptied * @type {EventTarget~Event} */ /** * Retrigger the `emptied` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechEmptied_ * @fires Player#emptied * @listens Tech#emptied */ 'emptied', /** * Fires when the browser is trying to get media data, but data is not available. * * @event Player#stalled * @type {EventTarget~Event} */ /** * Retrigger the `stalled` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechStalled_ * @fires Player#stalled * @listens Tech#stalled */ 'stalled', /** * Fires when the browser has loaded meta data for the audio/video. * * @event Player#loadedmetadata * @type {EventTarget~Event} */ /** * Retrigger the `stalled` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechLoadedmetadata_ * @fires Player#loadedmetadata * @listens Tech#loadedmetadata */ 'loadedmetadata', /** * Fires when the browser has loaded the current frame of the audio/video. * * @event player#loadeddata * @type {event} */ /** * Retrigger the `loadeddata` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechLoaddeddata_ * @fires Player#loadeddata * @listens Tech#loadeddata */ 'loadeddata', /** * Fires when the current playback position has changed. * * @event player#timeupdate * @type {event} */ /** * Retrigger the `timeupdate` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechTimeUpdate_ * @fires Player#timeupdate * @listens Tech#timeupdate */ 'timeupdate', /** * Fires when the playing speed of the audio/video is changed * * @event player#ratechange * @type {event} */ /** * Retrigger the `ratechange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechRatechange_ * @fires Player#ratechange * @listens Tech#ratechange */ 'ratechange', /** * Fires when the video's intrinsic dimensions change * * @event Player#resize * @type {event} */ /** * Retrigger the `resize` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechResize_ * @fires Player#resize * @listens Tech#resize */ 'resize', /** * Fires when the volume has been changed * * @event player#volumechange * @type {event} */ /** * Retrigger the `volumechange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechVolumechange_ * @fires Player#volumechange * @listens Tech#volumechange */ 'volumechange', /** * Fires when the text track has been changed * * @event player#texttrackchange * @type {event} */ /** * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechTexttrackchange_ * @fires Player#texttrackchange * @listens Tech#texttrackchange */ 'texttrackchange']; /** * An instance of the `Player` class is created when any of the Video.js setup methods * are used to initialize a video. * * After an instance has been created it can be accessed globally in two ways: * 1. By calling `videojs('example_video_1');` * 2. By using it directly via `videojs.players.example_video_1;` * * @extends Component */ var Player = function (_Component) { _inherits(Player, _Component); /** * Create an instance of this class. * * @param {Element} tag * The original video DOM element used for configuring options. * * @param {Object} [options] * Object of option names and values. * * @param {Component~ReadyCallback} [ready] * Ready callback function. */ function Player(tag, options, ready) { _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + Guid.newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = (0, _obj.assign)(Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // If language is not set, get the closest lang attribute if (!options.language) { if (typeof tag.closest === 'function') { var closest = tag.closest('[lang]'); if (closest) { options.language = closest.getAttribute('lang'); } } else { var element = tag; while (element && element.nodeType === 1) { if (Dom.getAttributes(element).hasOwnProperty('lang')) { options.language = element.getAttribute('lang'); break; } element = element.parentNode; } } } // Run base component initializing with new options // if the global option object was accidentally blown away by // someone, bail early with an informative error var _this = _possibleConstructorReturn(this, _Component.call(this, null, options, ready)); if (!_this.options_ || !_this.options_.techOrder || !_this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } // Store the original tag used to set options _this.tag = tag; // Store the tag attributes used to restore html5 element _this.tagAttributes = tag && Dom.getAttributes(tag); // Update current language _this.language(_this.options_.language); // Update Supported Languages if (options.languages) { (function () { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; })(); } else { _this.languages_ = Player.prototype.options_.languages; } // Cache for video property values. _this.cache_ = {}; // Set poster _this.poster_ = options.poster || ''; // Set controls _this.controls_ = !!options.controls; // Set default values for lastVolume _this.cache_.lastVolume = 1; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ _this.scrubbing_ = false; _this.el_ = _this.createEl(); // Make this an evented object and use `el_` as its event bus. (0, _evented2['default'])(_this, { eventBusKey: 'el_' }); // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = (0, _mergeOptions2['default'])(_this.options_); // Load plugins if (options.plugins) { (function () { var plugins = options.plugins; Object.keys(plugins).forEach(function (name) { if (typeof this[name] === 'function') { this[name](plugins[name]); } else { throw new Error('plugin "' + name + '" does not exist'); } }, _this); })(); } _this.options_.playerOptions = playerOptionsCopy; _this.middleware_ = []; _this.initChildren(); // Set isAudio based on whether or not an audio tag was used _this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (_this.controls()) { _this.addClass('vjs-controls-enabled'); } else { _this.addClass('vjs-controls-disabled'); } // Set ARIA label and region role depending on player type _this.el_.setAttribute('role', 'region'); if (_this.isAudio()) { _this.el_.setAttribute('aria-label', 'audio player'); } else { _this.el_.setAttribute('aria-label', 'video player'); } if (_this.isAudio()) { _this.addClass('vjs-audio'); } if (_this.flexNotSupported_()) { _this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // iOS Safari has broken hover handling if (!browser.IS_IOS) { _this.addClass('vjs-workinghover'); } // Make player easily findable by ID Player.players[_this.id_] = _this; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed _this.userActive(true); _this.reportUserActivity(); _this.listenForUserActivity_(); _this.on('fullscreenchange', _this.handleFullscreenChange_); _this.on('stageclick', _this.handleStageClick_); _this.changingSrc_ = false; return _this; } /** * Destroys the video player and does any necessary cleanup. * * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @fires Player#dispose */ Player.prototype.dispose = function dispose() { /** * Called when the player is being disposed of. * * @event Player#dispose * @type {EventTarget~Event} */ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); if (this.styleEl_ && this.styleEl_.parentNode) { this.styleEl_.parentNode.removeChild(this.styleEl_); } // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech_) { this.tech_.dispose(); } _Component.prototype.dispose.call(this); }; /** * Create the `Player`'s DOM element. * * @return {Element} * The DOM element that gets created. */ Player.prototype.createEl = function createEl() { var tag = this.tag; var el = void 0; var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player'); if (playerElIngest) { el = this.el_ = tag.parentNode; } else { el = this.el_ = _Component.prototype.createEl.call(this, 'div'); } // set tabindex to -1 so we could focus on the player element tag.setAttribute('tabindex', '-1'); // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className += ' ' + attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.playerId = tag.id; tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element if (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE !== true) { this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions'); var defaultsStyleEl = Dom.$('.vjs-styles-defaults'); var head = Dom.$('head'); head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild); } // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // Hide any links within the video/audio tag, because IE doesn't hide them completely. var links = tag.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { var linkEl = links.item(i); Dom.addClass(linkEl, 'vjs-hidden'); linkEl.setAttribute('hidden', 'hidden'); } // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode && !playerElIngest) { tag.parentNode.insertBefore(el, tag); } // insert the tag as the first child of the player element // then manually add it to the children array so that this.addChild // will work properly for other components // // Breaks iPhone, fixed in HTML5 setup. Dom.prependTo(tag, el); this.children_.unshift(tag); this.el_ = el; return el; }; /** * A getter/setter for the `Player`'s width. * * @param {number} [value] * The value to set the `Player's width to. * * @return {number} * The current width of the `Player` when getting. */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * A getter/setter for the `Player`'s height. * * @param {number} [value] * The value to set the `Player's heigth to. * * @return {number} * The current height of the `Player` when getting. */ Player.prototype.height = function height(value) { return this.dimension('height', value); }; /** * A getter/setter for the `Player`'s width & height. * * @param {string} dimension * This string can be: * - 'width' * - 'height' * * @param {number} [value] * Value for dimension specified in the first argument. * * @return {number} * The dimension arguments value when getting (width/height). */ Player.prototype.dimension = function dimension(_dimension, value) { var privDimension = _dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _log2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension); return; } this[privDimension] = parsedVal; } this.updateStyleEl_(); }; /** * A getter/setter/toggler for the vjs-fluid `className` on the `Player`. * * @param {boolean} [bool] * - A value of true adds the class. * - A value of false removes the class. * - No value will toggle the fluid class. * * @return {boolean|undefined} * - The value of fluid when getting. * - `undefined` when setting. */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } this.updateStyleEl_(); }; /** * Get/Set the aspect ratio * * @param {string} [ratio] * Aspect ratio for player * * @return {string|undefined} * returns the current aspect ratio when getting */ /** * A getter/setter for the `Player`'s aspect ratio. * * @param {string} [ratio] * The value to set the `Player's aspect ratio to. * * @return {string|undefined} * - The current aspect ratio of the `Player` when getting. * - undefined when setting */ Player.prototype.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); }; /** * Update styles of the `Player` element (height, width and aspect ratio). * * @private * @listens Tech#loadedmetadata */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { if (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE === true) { var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width; var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height; var techEl = this.tech_ && this.tech_.el(); if (techEl) { if (_width >= 0) { techEl.width = _width; } if (_height >= 0) { techEl.height = _height; } } return; } var width = void 0; var height = void 0; var aspectRatio = void 0; var idClass = void 0; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth() > 0) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } // Ensure the CSS class is valid by starting with an alpha character if (/^[^a-zA-Z]/.test(this.id())) { idClass = 'dimensions-' + this.id(); } else { idClass = this.id() + '-dimensions'; } // Ensure the right class is still on the player for the style element this.addClass(idClass); stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n '); }; /** * Load/Create an instance of playback {@link Tech} including element * and API methods. Then append the `Tech` element in `Player` as a child. * * @param {string} techName * name of the playback technology * * @param {string} source * video source * * @private */ Player.prototype.loadTech_ = function loadTech_(techName, source) { var _this2 = this; // Pause and remove current playback technology if (this.tech_) { this.unloadTech_(); } var titleTechName = (0, _toTitleCase2['default'])(techName); var camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1); // get rid of the HTML5 video tag as soon as we are using another tech if (titleTechName !== 'Html5' && this.tag) { _tech2['default'].getTech('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName_ = titleTechName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = { source: source, 'nativeControlsForTouch': this.options_.nativeControlsForTouch, 'playerId': this.id(), 'techId': this.id() + '_' + titleTechName + '_api', 'autoplay': this.options_.autoplay, 'preload': this.options_.preload, 'loop': this.options_.loop, 'muted': this.options_.muted, 'poster': this.poster(), 'language': this.language(), 'playerElIngest': this.playerElIngest_ || false, 'vtt.js': this.options_['vtt.js'] }; _trackTypes.ALL.names.forEach(function (name) { var props = _trackTypes.ALL[name]; techOptions[props.getterName] = _this2[props.privateName]; }); (0, _obj.assign)(techOptions, this.options_[titleTechName]); (0, _obj.assign)(techOptions, this.options_[camelTechName]); (0, _obj.assign)(techOptions, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } // Initialize tech instance var TechClass = _tech2['default'].getTech(techName); if (!TechClass) { throw new Error('No Tech named \'' + titleTechName + '\' exists! \'' + titleTechName + '\' should be registered using videojs.registerTech()\''); } this.tech_ = new TechClass(techOptions); // player.triggerReady is always async, so don't need this to be async this.tech_.ready(Fn.bind(this, this.handleTechReady_), true); _textTrackListConverter2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player TECH_EVENTS_RETRIGGER.forEach(function (event) { _this2.on(_this2.tech_, event, _this2['handleTech' + (0, _toTitleCase2['default'])(event) + '_']); }); this.on(this.tech_, 'loadstart', this.handleTechLoadStart_); this.on(this.tech_, 'waiting', this.handleTechWaiting_); this.on(this.tech_, 'canplay', this.handleTechCanPlay_); this.on(this.tech_, 'canplaythrough', this.handleTechCanPlayThrough_); this.on(this.tech_, 'playing', this.handleTechPlaying_); this.on(this.tech_, 'ended', this.handleTechEnded_); this.on(this.tech_, 'seeking', this.handleTechSeeking_); this.on(this.tech_, 'seeked', this.handleTechSeeked_); this.on(this.tech_, 'play', this.handleTechPlay_); this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_); this.on(this.tech_, 'pause', this.handleTechPause_); this.on(this.tech_, 'durationchange', this.handleTechDurationChange_); this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_); this.on(this.tech_, 'error', this.handleTechError_); this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_); this.on(this.tech_, 'posterchange', this.handleTechPosterChange_); this.on(this.tech_, 'textdata', this.handleTechTextData_); this.usingNativeControls(this.techGet_('controls')); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners_(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) { Dom.prependTo(this.tech_.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } }; /** * Unload and dispose of the current playback {@link Tech}. * * @private */ Player.prototype.unloadTech_ = function unloadTech_() { var _this3 = this; // Save the current text tracks so that we can reuse the same text tracks with the next tech _trackTypes.ALL.names.forEach(function (name) { var props = _trackTypes.ALL[name]; _this3[props.privateName] = _this3[props.getterName](); }); this.textTracksJson_ = _textTrackListConverter2['default'].textTracksToJson(this.tech_); this.isReady_ = false; this.tech_.dispose(); this.tech_ = false; }; /** * Return a reference to the current {@link Tech}. * It will print a warning by default about the danger of using the tech directly * but any argument that is passed in will silence the warning. * * @param {*} [safety] * Anything passed in to silence the warning * * @return {Tech} * The Tech */ Player.prototype.tech = function tech(safety) { if (safety === undefined) { _log2['default'].warn((0, _tsml2['default'])(_templateObject)); } return this.tech_; }; /** * Set up click and touch listeners for the playback element * * - On desktops: a click on the video itself will toggle playback * - On mobile devices: a click on the video toggles controls * which is done by toggling the user state between active and * inactive * - A tap can signal that a user has become active or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * - In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * * > Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold * on any controls will still keep the user active * * @private */ Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() { // Make sure to remove all the previous listeners in case we are called multiple times. this.removeTechControlsListeners_(); // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech_, 'mousedown', this.handleTechClick_); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech_, 'touchstart', this.handleTechTouchStart_); this.on(this.tech_, 'touchmove', this.handleTechTouchMove_); this.on(this.tech_, 'touchend', this.handleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech_, 'tap', this.handleTechTap_); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @private */ Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech_, 'tap', this.handleTechTap_); this.off(this.tech_, 'touchstart', this.handleTechTouchStart_); this.off(this.tech_, 'touchmove', this.handleTechTouchMove_); this.off(this.tech_, 'touchend', this.handleTechTouchEnd_); this.off(this.tech_, 'mousedown', this.handleTechClick_); }; /** * Player waits for the tech to be ready * * @private */ Player.prototype.handleTechReady_ = function handleTechReady_() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall_('setVolume', this.cache_.volume); } // Look if the tech found a higher resolution poster while loading this.handleTechPosterChange_(); // Update the duration if available this.handleTechDurationChange_(); // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if ((this.src() || this.currentSrc()) && this.tag && this.options_.autoplay && this.paused()) { try { // Chrome Fix. Fixed in Chrome v16. delete this.tag.poster; } catch (e) { (0, _log2['default'])('deleting tag.poster throws in some browsers', e); } this.play(); } }; /** * Retrigger the `loadstart` event that was triggered by the {@link Tech}. This * function will also trigger {@link Player#firstplay} if it is the first loadstart * for a video. * * @fires Player#loadstart * @fires Player#firstplay * @listens Tech#loadstart * @private */ Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); this.removeClass('vjs-seeking'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { /** * Fired when the user agent begins looking for media data * * @event Player#loadstart * @type {EventTarget~Event} */ this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @fires Player#firstplay * * @param {boolean} hasStarted * - true: adds the class * - false: remove the class * * @return {boolean} * the boolean value of hasStarted */ Player.prototype.hasStarted = function hasStarted(_hasStarted) { if (_hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== _hasStarted) { this.hasStarted_ = _hasStarted; if (_hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return; } return !!this.hasStarted_; }; /** * Fired whenever the media begins or resumes playback * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play} * @fires Player#play * @listens Tech#play * @private */ Player.prototype.handleTechPlay_ = function handleTechPlay_() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play this.hasStarted(true); /** * Triggered whenever an {@link Tech#play} event happens. Indicates that * playback has started or resumed. * * @event Player#play * @type {EventTarget~Event} */ this.trigger('play'); }; /** * Retrigger the `waiting` event that was triggered by the {@link Tech}. * * @fires Player#waiting * @listens Tech#waiting * @private */ Player.prototype.handleTechWaiting_ = function handleTechWaiting_() { var _this4 = this; this.addClass('vjs-waiting'); /** * A readyState change on the DOM element has caused playback to stop. * * @event Player#waiting * @type {EventTarget~Event} */ this.trigger('waiting'); this.one('timeupdate', function () { return _this4.removeClass('vjs-waiting'); }); }; /** * Retrigger the `canplay` event that was triggered by the {@link Tech}. * > Note: This is not consistent between browsers. See #1351 * * @fires Player#canplay * @listens Tech#canplay * @private */ Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() { this.removeClass('vjs-waiting'); /** * The media has a readyState of HAVE_FUTURE_DATA or greater. * * @event Player#canplay * @type {EventTarget~Event} */ this.trigger('canplay'); }; /** * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}. * * @fires Player#canplaythrough * @listens Tech#canplaythrough * @private */ Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() { this.removeClass('vjs-waiting'); /** * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the * entire media file can be played without buffering. * * @event Player#canplaythrough * @type {EventTarget~Event} */ this.trigger('canplaythrough'); }; /** * Retrigger the `playing` event that was triggered by the {@link Tech}. * * @fires Player#playing * @listens Tech#playing * @private */ Player.prototype.handleTechPlaying_ = function handleTechPlaying_() { this.removeClass('vjs-waiting'); /** * The media is no longer blocked from playback, and has started playing. * * @event Player#playing * @type {EventTarget~Event} */ this.trigger('playing'); }; /** * Retrigger the `seeking` event that was triggered by the {@link Tech}. * * @fires Player#seeking * @listens Tech#seeking * @private */ Player.prototype.handleTechSeeking_ = function handleTechSeeking_() { this.addClass('vjs-seeking'); /** * Fired whenever the player is jumping to a new time * * @event Player#seeking * @type {EventTarget~Event} */ this.trigger('seeking'); }; /** * Retrigger the `seeked` event that was triggered by the {@link Tech}. * * @fires Player#seeked * @listens Tech#seeked * @private */ Player.prototype.handleTechSeeked_ = function handleTechSeeked_() { this.removeClass('vjs-seeking'); /** * Fired when the player has finished jumping to a new time * * @event Player#seeked * @type {EventTarget~Event} */ this.trigger('seeked'); }; /** * Retrigger the `firstplay` event that was triggered by the {@link Tech}. * * @fires Player#firstplay * @listens Tech#firstplay * @deprecated As of 6.0 passing the `starttime` option to the player will be deprecated * @private */ Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() { // If the first starttime attribute is specified // then we will start at the given offset in seconds if (this.options_.starttime) { _log2['default'].warn('Passing the `starttime` option to the player will be deprecated in 6.0'); this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); /** * Fired the first time a video is played. Not part of the HLS spec, and this is * probably not the best implementation yet, so use sparingly. If you don't have a * reason to prevent playback, use `myPlayer.one('play');` instead. * * @event Player#firstplay * @type {EventTarget~Event} */ this.trigger('firstplay'); }; /** * Retrigger the `pause` event that was triggered by the {@link Tech}. * * @fires Player#pause * @listens Tech#pause * @private */ Player.prototype.handleTechPause_ = function handleTechPause_() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); /** * Fired whenever the media has been paused * * @event Player#pause * @type {EventTarget~Event} */ this.trigger('pause'); }; /** * Retrigger the `ended` event that was triggered by the {@link Tech}. * * @fires Player#ended * @listens Tech#ended * @private */ Player.prototype.handleTechEnded_ = function handleTechEnded_() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } /** * Fired when the end of the media resource is reached (currentTime == duration) * * @event Player#ended * @type {EventTarget~Event} */ this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @listens Tech#durationchange * @private */ Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() { this.duration(this.techGet_('duration')); }; /** * Handle a click on the media element to play/pause * * @param {EventTarget~Event} event * the event that caused this function to trigger * * @listens Tech#mousedown * @private */ Player.prototype.handleTechClick_ = function handleTechClick_(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) { return; } // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @listens Tech#tap * @private */ Player.prototype.handleTechTap_ = function handleTechTap_() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @listens Tech#touchstart * @private */ Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @listens Tech#touchmove * @private */ Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @param {EventTarget~Event} event * the touchend event that triggered * this function * * @listens Tech#touchend * @private */ Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Fired when the player switches in or out of fullscreen mode * * @private * @listens Player#fullscreenchange */ Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @listens stageclick */ Player.prototype.handleStageClick_ = function handleStageClick_() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @param {EventTarget~Event} event * the fullscreenchange event that triggered this function * * @param {Object} data * the data that was sent with the event * * @private * @listens Tech#fullscreenchange * @fires Player#fullscreenchange */ Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } /** * Fired when going in and out of fullscreen. * * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video. * * @private * @listens Tech#error */ Player.prototype.handleTechError_ = function handleTechError_() { var error = this.tech_.error(); this.error(error); }; /** * Retrigger the `textdata` event that was triggered by the {@link Tech}. * * @fires Player#textdata * @listens Tech#textdata * @private */ Player.prototype.handleTechTextData_ = function handleTechTextData_() { var data = null; if (arguments.length > 1) { data = arguments[1]; } /** * Fires when we get a textdata event from tech * * @event Player#textdata * @type {EventTarget~Event} */ this.trigger('textdata', data); }; /** * Get object for cached values. * * @return {Object} * get the current object cache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {string} [method] * the method to call * * @param {Object} arg * the argument to pass * * @private */ Player.prototype.techCall_ = function techCall_(method, arg) { // If it's not ready yet, call method when it is this.ready(function () { if (method in middleware.allowedSetters) { return middleware.set(this.middleware_, this.tech_, method, arg); } try { if (this.tech_) { this.tech_[method](arg); } } catch (e) { (0, _log2['default'])(e); throw e; } }, true); }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {string} method * Tech method * * @return {Function|undefined} * the method or undefined * * @private */ Player.prototype.techGet_ = function techGet_(method) { if (this.tech_ && this.tech_.isReady_) { if (method in middleware.allowedGetters) { return middleware.get(this.middleware_, this.tech_, method); } // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech_[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech_[method] === undefined) { (0, _log2['default'])('Video.js: ' + method + ' method not defined for ' + this.techName_ + ' playback technology.', e); // When a method isn't available on the object it throws a TypeError } else if (e.name === 'TypeError') { (0, _log2['default'])('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e); this.tech_.isReady_ = false; } else { (0, _log2['default'])(e); } throw e; } } return; }; /** * start media playback * * @return {Promise|undefined} * Returns a `Promise` if the browser returns one, for most browsers this will * return undefined. */ Player.prototype.play = function play() { if (this.changingSrc_) { this.ready(function () { this.techCall_('play'); }); // Only calls the tech's play if we already have a src loaded } else if (this.src() || this.currentSrc()) { return this.techGet_('play'); } else { this.ready(function () { this.tech_.one('loadstart', function () { var retval = this.play(); // silence errors (unhandled promise from play) if (retval !== undefined && typeof retval.then === 'function') { retval.then(null, function (e) {}); } }); }); } }; /** * Pause the video playback * * @return {Player} * A reference to the player object this function was called on */ Player.prototype.pause = function pause() { this.techCall_('pause'); }; /** * Check if the player is paused or has yet to play * * @return {boolean} * - false: if the media is currently playing * - true: if media is not currently playing */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet_('paused') === false ? false : true; }; /** * Get a TimeRange object representing the current ranges of time that the user * has played. * * @return {TimeRange} * A time range object that represents all the increments of time that have * been played. */ Player.prototype.played = function played() { return this.techGet_('played') || (0, _timeRanges.createTimeRange)(0, 0); }; /** * Returns whether or not the user is "scrubbing". Scrubbing is * when the user has clicked the progress bar handle and is * dragging it along the progress bar. * * @param {boolean} [isScrubbing] * wether the user is or is not scrubbing * * @return {boolean} * The value of scrubbing when getting */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (typeof isScrubbing === 'undefined') { return this.scrubbing_; } this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } }; /** * Get or set the current time (in seconds) * * @param {number|string} [seconds] * The time to seek to in seconds * * @return {number} * - the current time in seconds when getting */ Player.prototype.currentTime = function currentTime(seconds) { if (typeof seconds !== 'undefined') { this.techCall_('setCurrentTime', seconds); return; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. this.cache_.currentTime = this.techGet_('currentTime') || 0; return this.cache_.currentTime; }; /** * Normally gets the length in time of the video in seconds; * in all but the rarest use cases an argument will NOT be passed to the method * * > **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @fires Player#durationchange * * @param {number} [seconds] * The duration of the video to set in seconds * * @return {number} * - The duration of the video in seconds when getting */ Player.prototype.duration = function duration(seconds) { if (seconds === undefined) { return this.cache_.duration || 0; } seconds = parseFloat(seconds) || 0; // Standardize on Inifity for signaling video is live if (seconds < 0) { seconds = Infinity; } if (seconds !== this.cache_.duration) { // Cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = seconds; if (seconds === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } /** * @event Player#durationchange * @type {EventTarget~Event} */ this.trigger('durationchange'); } }; /** * Calculates how much time is left in the video. Not part * of the native video API. * * @return {number} * The time remaining in seconds */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with an array of the times of the video * that have been downloaded. If you just want the percent of the * video that's been downloaded, use bufferedPercent. * * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered} * * @return {TimeRange} * A mock TimeRange object (following HTML spec) */ Player.prototype.buffered = function buffered() { var buffered = this.techGet_('buffered'); if (!buffered || !buffered.length) { buffered = (0, _timeRanges.createTimeRange)(0, 0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded. * This method is not a part of the native HTML video API. * * @return {number} * A decimal between 0 and 1 representing the percent * that is bufferred 0 being 0% and 1 being 100% */ Player.prototype.bufferedPercent = function bufferedPercent() { return (0, _buffer.bufferedPercent)(this.buffered(), this.duration()); }; /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {number} * The end of the last buffered time range */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(); var duration = this.duration(); var end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * * @param {number} [percentAsDecimal] * The new volume as a decimal percent: * - 0 is muted/0%/off * - 1.0 is 100%/full * - 0.5 is half volume or 50% * * @return {number} * The current volume as a percent when getting */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = void 0; if (percentAsDecimal !== undefined) { // Force value to between 0 and 1 vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); this.cache_.volume = vol; this.techCall_('setVolume', vol); if (vol > 0) { this.lastVolume_(vol); } return; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet_('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * * @param {boolean} [muted] * - true to mute * - false to unmute * * @return {boolean} * - true if mute is on and getting * - false if mute is off and getting */ Player.prototype.muted = function muted(_muted) { if (_muted !== undefined) { this.techCall_('setMuted', _muted); return; } return this.techGet_('muted') || false; }; /** * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted * indicates the state of muted on intial playback. * * ```js * var myPlayer = videojs('some-player-id'); * * myPlayer.src("http://www.example.com/path/to/video.mp4"); * * // get, should be false * console.log(myPlayer.defaultMuted()); * // set to true * myPlayer.defaultMuted(true); * // get should be true * console.log(myPlayer.defaultMuted()); * ``` * * @param {boolean} [defaultMuted] * - true to mute * - false to unmute * * @return {boolean|Player} * - true if defaultMuted is on and getting * - false if defaultMuted is off and getting * - A reference to the current player when setting */ Player.prototype.defaultMuted = function defaultMuted(_defaultMuted) { if (_defaultMuted !== undefined) { return this.techCall_('setDefaultMuted', _defaultMuted); } return this.techGet_('defaultMuted') || false; }; /** * Get the last volume, or set it * * @param {number} [percentAsDecimal] * The new last volume as a decimal percent: * - 0 is muted/0%/off * - 1.0 is 100%/full * - 0.5 is half volume or 50% * * @return {number} * the current value of lastVolume as a percent when getting * * @private */ Player.prototype.lastVolume_ = function lastVolume_(percentAsDecimal) { if (percentAsDecimal !== undefined && percentAsDecimal !== 0) { this.cache_.lastVolume = percentAsDecimal; return; } return this.cache_.lastVolume; }; /** * Check if current tech can support native fullscreen * (e.g. with built in controls like iOS, so not our flash swf) * * @return {boolean} * if native fullscreen is supported */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet_('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode or tell the player that it * is or is not in fullscreen mode. * * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {boolean} [isFS] * Set the players current fullscreen state * * @return {boolean} * - true if fullscreen is on and getting * - false if fullscreen is off and getting */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return; } return !!this.isFullscreen_; }; /** * Increase the size of the video to full screen * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @fires Player#fullscreenchange */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _fullscreenApi2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_document2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_document2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_document2['default'], fsApi.fullscreenchange, documentFullscreenChange); } /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech_.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall_('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } }; /** * Return the video to its normal size after having been in full screen mode * * @fires Player#fullscreenchange */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _fullscreenApi2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _document2['default'][fsApi.exitFullscreen](); } else if (this.tech_.supportsFullScreen()) { this.techCall_('exitFullScreen'); } else { this.exitFullWindow(); /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } }; /** * When fullscreen isn't supported we can stretch the * video container to as wide as the browser will let us. * * @fires Player#enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _document2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_document2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _document2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addClass(_document2['default'].body, 'vjs-full-window'); /** * @event Player#enterFullWindow * @type {EventTarget~Event} */ this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or * full screen on ESC key * * @param {string} event * Event to check for key press */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @fires Player#exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_document2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _document2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeClass(_document2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); /** * @event Player#exitFullWindow * @type {EventTarget~Event} */ this.trigger('exitFullWindow'); }; /** * Check whether the player can play a given mimetype * * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype * * @param {string} type * The mimetype to check * * @return {string} * 'probably', 'maybe', or '' (empty string) */ Player.prototype.canPlayType = function canPlayType(type) { var can = void 0; // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = j[i]; var tech = _tech2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!tech) { tech = _component2['default'].getComponent(techName); } // Check if the current tech is defined before continuing if (!tech) { _log2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { can = tech.canPlayType(type); if (can) { return can; } } } return ''; }; /** * Select source based on tech-order or source-order * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, * defaults to tech-order selection * * @param {Array} sources * The sources for a media asset * * @return {Object|boolean} * Object of source and tech order or false */ Player.prototype.selectSource = function selectSource(sources) { var _this5 = this; // Get only the techs specified in `techOrder` that exist and are supported by the // current platform var techs = this.options_.techOrder.map(function (techName) { return [techName, _tech2['default'].getTech(techName)]; }).filter(function (_ref) { var techName = _ref[0], tech = _ref[1]; // Check if the current tech is defined before continuing if (tech) { // Check if the browser supports this technology return tech.isSupported(); } _log2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); return false; }); // Iterate over each `innerArray` element once per `outerArray` element and execute // `tester` with both. If `tester` returns a non-falsy value, exit early and return // that value. var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) { var found = void 0; outerArray.some(function (outerChoice) { return innerArray.some(function (innerChoice) { found = tester(outerChoice, innerChoice); if (found) { return true; } }); }); return found; }; var foundSourceAndTech = void 0; var flip = function flip(fn) { return function (a, b) { return fn(b, a); }; }; var finder = function finder(_ref2, source) { var techName = _ref2[0], tech = _ref2[1]; if (tech.canPlaySource(source, _this5.options_[techName.toLowerCase()])) { return { source: source, tech: techName }; } }; // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources // to select from them based on their priority. if (this.options_.sourceOrder) { // Source-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder)); } else { // Tech-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder); } return foundSourceAndTech || false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL string**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * * @param {Tech~SourceObject|Tech~SourceObject[]} [source] * One SourceObject or an array of SourceObjects * * @return {string} * The current video source when getting */ Player.prototype.src = function src(source) { var _this6 = this; // getter usage if (typeof source === 'undefined') { return this.cache_.src; } // filter out invalid sources and turn our source into // an array of source objects var sources = (0, _filterSource2['default'])(source); // if a source was passed in then it is invalid because // it was filtered to a zero length Array. So we have to // show an error if (!sources.length) { this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); return; } // intial sources this.cache_.sources = sources; this.changingSrc_ = true; // intial source this.cache_.source = sources[0]; // middlewareSource is the source after it has been changed by middleware middleware.setSource(this, sources[0], function (middlewareSource, mws) { _this6.middleware_ = mws; var err = _this6.src_(middlewareSource); if (err) { if (sources.length > 1) { return _this6.src(sources.slice(1)); } // We need to wrap this in a timeout to give folks a chance to add error event handlers _this6.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed _this6.triggerReady(); return; } _this6.changingSrc_ = false; // video element listed source _this6.cache_.src = middlewareSource.src; middleware.setTech(mws, _this6.tech_); }); }; /** * Set the source object on the tech, returns a boolean that indicates wether * there is a tech that can play the source or not * * @param {Tech~SourceObject} source * The source object to set on the Tech * * @return {Boolean} * - True if there is no Tech to playback this source * - False otherwise * * @private */ Player.prototype.src_ = function src_(source) { var sourceTech = this.selectSource([source]); if (!sourceTech) { return true; } if (sourceTech.tech !== this.techName_) { this.changingSrc_ = true; // load this technology with the chosen source this.loadTech_(sourceTech.tech, sourceTech.source); return false; } // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) { this.techCall_('setSource', source); } else { this.techCall_('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } // Set the source synchronously if possible (#2326) }, true); return false; }; /** * Begin loading the src data. */ Player.prototype.load = function load() { this.techCall_('load'); }; /** * Reset the player. Loads the first tech in the techOrder, * and calls `reset` on the tech`. */ Player.prototype.reset = function reset() { this.loadTech_(this.options_.techOrder[0], null); this.techCall_('reset'); }; /** * Returns all of the current source objects. * * @return {Tech~SourceObject[]} * The current source objects */ Player.prototype.currentSources = function currentSources() { var source = this.currentSource(); var sources = []; // assume `{}` or `{ src }` if (Object.keys(source).length !== 0) { sources.push(source); } return this.cache_.sources || sources; }; /** * Returns the current source object. * * @return {Tech~SourceObject} * The current source object */ Player.prototype.currentSource = function currentSource() { return this.cache_.source || {}; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {string} * The current source */ Player.prototype.currentSrc = function currentSrc() { return this.currentSource() && this.currentSource().src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {string} * The source MIME type */ Player.prototype.currentType = function currentType() { return this.currentSource() && this.currentSource().type || ''; }; /** * Get or set the preload attribute * * @param {boolean} [value] * - true means that we should preload * - false maens that we should not preload * * @return {string} * The preload attribute value when getting */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall_('setPreload', value); this.options_.preload = value; return; } return this.techGet_('preload'); }; /** * Get or set the autoplay attribute. * * @param {boolean} [value] * - true means that we should autoplay * - false means that we should not autoplay * * @return {string} * The current value of autoplay when getting */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall_('setAutoplay', value); this.options_.autoplay = value; return; } return this.techGet_('autoplay', value); }; /** * Get or set the loop attribute on the video element. * * @param {boolean} [value] * - true means that we should loop the video * - false means that we should not loop the video * * @return {string} * The current value of loop when getting */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall_('setLoop', value); this.options_.loop = value; return; } return this.techGet_('loop'); }; /** * Get or set the poster image source url * * @fires Player#posterchange * * @param {string} [src] * Poster image source URL * * @return {string} * The current value of poster when getting */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall_('setPoster', src); // alert components that the poster has been set /** * This event fires when the poster image is changed on the player. * * @event Player#posterchange * @type {EventTarget~Event} */ this.trigger('posterchange'); }; /** * Some techs (e.g. YouTube) can provide a poster source in an * asynchronous way. We want the poster component to use this * poster source so that it covers up the tech's controls. * (YouTube's play button). However we only want to use this * soruce if the player user hasn't set a poster through * the normal APIs. * * @fires Player#posterchange * @listens Tech#posterchange * @private */ Player.prototype.handleTechPosterChange_ = function handleTechPosterChange_() { if (!this.poster_ && this.tech_ && this.tech_.poster) { this.poster_ = this.tech_.poster() || ''; // Let components know the poster has changed this.trigger('posterchange'); } }; /** * Get or set whether or not the controls are showing. * * @fires Player#controlsenabled * * @param {boolean} [bool] * - true to turn controls on * - false to turn controls off * * @return {boolean} * The current value of controls when getting */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall_('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); /** * @event Player#controlsenabled * @type {EventTarget~Event} */ this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners_(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); /** * @event Player#controlsdisabled * @type {EventTarget~Event} */ this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners_(); } } } return; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @fires Player#usingnativecontrols * @fires Player#usingcustomcontrols * * @param {boolean} [bool] * - true to turn native controls on * - false to turn native controls off * * @return {boolean} * The current value of native controls when getting */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event Player#usingnativecontrols * @type {EventTarget~Event} */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event Player#usingcustomcontrols * @type {EventTarget~Event} */ this.trigger('usingcustomcontrols'); } } return; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @fires Player#error * * @param {MediaError|string|number} [err] * A MediaError or a string/number to be turned * into a MediaError * * @return {MediaError|null} * The current MediaError when getting (or null) */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); if (this.errorDisplay) { this.errorDisplay.close(); } return; } this.error_ = new _mediaError2['default'](err); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _log2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaError2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); /** * @event Player#error * @type {EventTarget~Event} */ this.trigger('error'); return; }; /** * Report user activity * * @param {Object} event * Event object */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @fires Player#useractive * @fires Player#userinactive * * @param {boolean} [bool] * - true if the user is active * - false if the user is inactive * * @return {boolean} * The current value of userActive when getting */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); /** * @event Player#useractive * @type {EventTarget~Event} */ this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech_) { this.tech_.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); /** * @event Player#userinactive * @type {EventTarget~Event} */ this.trigger('userinactive'); } } return; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @private */ Player.prototype.listenForUserActivity_ = function listenForUserActivity_() { var mouseInProgress = void 0; var lastMoveX = void 0; var lastMoveY = void 0; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = void 0; this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_.inactivityTimeout; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activity check loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {number} [rate] * New playback rate to set. * * @return {number} * The current playback rate when getting or 1.0 */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall_('setPlaybackRate', rate); return; } if (this.tech_ && this.tech_.featuresPlaybackRate) { return this.techGet_('playbackRate'); } return 1.0; }; /** * Gets or sets the current default playback rate. A default playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance. * defaultPlaybackRate will only represent what the intial playbackRate of a video was, not * not the current playbackRate. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate * * @param {number} [rate] * New default playback rate to set. * * @return {number|Player} * - The default playback rate when getting or 1.0 * - the player when setting */ Player.prototype.defaultPlaybackRate = function defaultPlaybackRate(rate) { if (rate !== undefined) { return this.techCall_('setDefaultPlaybackRate', rate); } if (this.tech_ && this.tech_.featuresPlaybackRate) { return this.techGet_('defaultPlaybackRate'); } return 1.0; }; /** * Gets or sets the audio flag * * @param {boolean} bool * - true signals that this is an audio player * - false signals that this is not an audio player * * @return {boolean} * The current value of isAudio when getting */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return; } return !!this.isAudio_; }; /** * A helper method for adding a {@link TextTrack} to our * {@link TextTrackList}. * * In addition to the W3C settings we allow adding additional info through options. * * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {string} [kind] * the kind of TextTrack you are adding * * @param {string} [label] * the label to give the TextTrack label * * @param {string} [language] * the language to set on the TextTrack * * @return {TextTrack|undefined} * the TextTrack that was added or undefined * if there is no tech */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (this.tech_) { return this.tech_.addTextTrack(kind, label, language); } }; /** * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will * automatically removed from the video element whenever the source changes, unless * manualCleanup is set to false. * * @param {Object} options * Options to pass to {@link HTMLTrackElement} during creation. See * {@link HTMLTrackElement} for object properties that you should use. * * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be * * @return {HTMLTrackElement} * the HTMLTrackElement that was created and added * to the HTMLTrackElementList and the remote * TextTrackList * * @deprecated The default value of the "manualCleanup" parameter will default * to "false" in upcoming versions of Video.js */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) { if (this.tech_) { return this.tech_.addRemoteTextTrack(options, manualCleanup); } }; /** * Remove a remote {@link TextTrack} from the respective * {@link TextTrackList} and {@link HTMLTrackElementList}. * * @param {Object} track * Remote {@link TextTrack} to remove * * @return {undefined} * does not return anything */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack() { var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref3$track = _ref3.track, track = _ref3$track === undefined ? arguments[0] : _ref3$track; // destructure the input into an object with a track argument, defaulting to arguments[0] // default the whole argument to an empty object if nothing was passed in if (this.tech_) { return this.tech_.removeRemoteTextTrack(track); } }; /** * Get video width * * @return {number} * current video width */ Player.prototype.videoWidth = function videoWidth() { return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0; }; /** * Get video height * * @return {number} * current video height */ Player.prototype.videoHeight = function videoHeight() { return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0; }; /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {string} [code] * the language code to set the player to * * @return {string} * The current language code when getting */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = String(code).toLowerCase(); }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} * An array of of supported languages */ Player.prototype.languages = function languages() { return (0, _mergeOptions2['default'])(Player.prototype.options_.languages, this.languages_); }; /** * returns a JavaScript object reperesenting the current track * information. **DOES not return it as JSON** * * @return {Object} * Object representing the current of track info */ Player.prototype.toJSON = function toJSON() { var options = (0, _mergeOptions2['default'])(this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = (0, _mergeOptions2['default'])(track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Creates a simple modal dialog (an instance of the {@link ModalDialog} * component) that immediately overlays the player with arbitrary * content and removes itself when closed. * * @param {string|Function|Element|Array|null} content * Same as {@link ModalDialog#content}'s param of the same name. * The most straight-forward usage is to provide a string or DOM * element. * * @param {Object} [options] * Extra options which will be passed on to the {@link ModalDialog}. * * @return {ModalDialog} * the {@link ModalDialog} that was created */ Player.prototype.createModal = function createModal(content, options) { var _this7 = this; options = options || {}; options.content = content || ''; var modal = new _modalDialog2['default'](this, options); this.addChild(modal); modal.on('dispose', function () { _this7.removeChild(modal); }); modal.open(); return modal; }; /** * Gets tag settings * * @param {Element} tag * The player tag * * @return {Object} * An object containing all of the settings * for a player tag */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { sources: [], tracks: [] }; var tagOptions = Dom.getAttributes(tag); var dataSetup = tagOptions['data-setup']; if (Dom.hasClass(tag, 'vjs-fluid')) { tagOptions.fluid = true; } // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON // If empty string, make it a parsable json object. var _safeParseTuple = (0, _tuple2['default'])(dataSetup || '{}'), err = _safeParseTuple[0], data = _safeParseTuple[1]; if (err) { _log2['default'].error(err); } (0, _obj.assign)(tagOptions, data); } (0, _obj.assign)(baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getAttributes(child)); } } } return baseOptions; }; /** * Determine wether or not flexbox is supported * * @return {boolean} * - true if flexbox is supported * - false if flexbox is not supported */ Player.prototype.flexNotSupported_ = function flexNotSupported_() { var elem = _document2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || // IE10-specific (2012 flex spec) 'msFlexOrder' in elem.style); }; return Player; }(_component2['default']); /** * Get the {@link VideoTrackList} * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist * * @return {VideoTrackList} * the current video track list * * @method Player.prototype.videoTracks */ /** * Get the {@link AudioTrackList} * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist * * @return {AudioTrackList} * the current audio track list * * @method Player.prototype.audioTracks */ /** * Get the {@link TextTrackList} * * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {TextTrackList} * the current text track list * * @method Player.prototype.textTracks */ /** * Get the remote {@link TextTrackList} * * @return {TextTrackList} * The current remote text track list * * @method Player.prototype.textTracks */ /** * Get the remote {@link HTMLTrackElementList} tracks. * * @return {HTMLTrackElementList} * The current remote text track element list * * @method Player.prototype.remoteTextTrackEls */ _trackTypes.ALL.names.forEach(function (name) { var props = _trackTypes.ALL[name]; Player.prototype[props.getterName] = function () { if (this.tech_) { return this.tech_[props.getterName](); } // if we have not yet loadTech_, we create {video,audio,text}Tracks_ // these will be passed to the tech during loading this[props.privateName] = this[props.privateName] || new props.ListClass(); return this[props.privateName]; }; }); /** * Global player list * * @type {Object} */ Player.players = {}; var navigator = _window2['default'].navigator; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * * @type {Object} * @private */ Player.prototype.options_ = { // Default order of fallback technology techOrder: _tech2['default'].defaultTechOrder_, html5: {}, flash: {}, // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'controlBar', 'errorDisplay', 'textTrackSettings'], language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this media.' }; [ /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method Player#ended */ 'ended', /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method Player#seeking */ 'seeking', /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method Player#seekable */ 'seekable', /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {number} the current network activity state * @method Player#networkState */ 'networkState', /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {number} the current playback rendering state * @method Player#readyState */ 'readyState'].forEach(function (fn) { Player.prototype[fn] = function () { return this.techGet_(fn); }; }); TECH_EVENTS_RETRIGGER.forEach(function (event) { Player.prototype['handleTech' + (0, _toTitleCase2['default'])(event) + '_'] = function () { return this.trigger(event); }; }); /** * Fired when the player has initial duration and dimension information * * @event Player#loadedmetadata * @type {EventTarget~Event} */ /** * Fired when the player has downloaded data at the current playback position * * @event Player#loadeddata * @type {EventTarget~Event} */ /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event Player#timeupdate * @type {EventTarget~Event} */ /** * Fired when the volume changes * * @event Player#volumechange * @type {EventTarget~Event} */ /** * Reports whether or not a player has a plugin available. * * This does not report whether or not the plugin has ever been initialized * on this player. For that, [usingPlugin]{@link Player#usingPlugin}. * * @method Player#hasPlugin * @param {string} name * The name of a plugin. * * @return {boolean} * Whether or not this player has the requested plugin available. */ /** * Reports whether or not a player is using a plugin by name. * * For basic plugins, this only reports whether the plugin has _ever_ been * initialized on this player. * * @method Player#usingPlugin * @param {string} name * The name of a plugin. * * @return {boolean} * Whether or not this player is using the requested plugin. */ _component2['default'].registerComponent('Player', Player); exports['default'] = Player; },{"1":1,"100":100,"101":101,"4":4,"42":42,"45":45,"46":46,"47":47,"5":5,"51":51,"53":53,"56":56,"59":59,"60":60,"61":61,"62":62,"68":68,"69":69,"71":71,"75":75,"79":79,"8":8,"80":80,"83":83,"84":84,"85":85,"86":86,"88":88,"89":89,"90":90,"91":91,"92":92,"93":93,"94":94,"97":97,"98":98}],55:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = 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 _evented = _dereq_(51); var _evented2 = _interopRequireDefault(_evented); var _stateful = _dereq_(52); var _stateful2 = _interopRequireDefault(_stateful); var _events = _dereq_(84); var Events = _interopRequireWildcard(_events); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _player = _dereq_(54); var _player2 = _interopRequireDefault(_player); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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"); } } /** * @file plugin.js */ /** * The base plugin name. * * @private * @constant * @type {string} */ var BASE_PLUGIN_NAME = 'plugin'; /** * The key on which a player's active plugins cache is stored. * * @private * @constant * @type {string} */ var PLUGIN_CACHE_KEY = 'activePlugins_'; /** * Stores registered plugins in a private space. * * @private * @type {Object} */ var pluginStorage = {}; /** * Reports whether or not a plugin has been registered. * * @private * @param {string} name * The name of a plugin. * * @returns {boolean} * Whether or not the plugin has been registered. */ var pluginExists = function pluginExists(name) { return pluginStorage.hasOwnProperty(name); }; /** * Get a single registered plugin by name. * * @private * @param {string} name * The name of a plugin. * * @returns {Function|undefined} * The plugin (or undefined). */ var getPlugin = function getPlugin(name) { return pluginExists(name) ? pluginStorage[name] : undefined; }; /** * Marks a plugin as "active" on a player. * * Also, ensures that the player has an object for tracking active plugins. * * @private * @param {Player} player * A Video.js player instance. * * @param {string} name * The name of a plugin. */ var markPluginAsActive = function markPluginAsActive(player, name) { player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {}; player[PLUGIN_CACHE_KEY][name] = true; }; /** * Takes a basic plugin function and returns a wrapper function which marks * on the player that the plugin has been activated. * * @private * @param {string} name * The name of the plugin. * * @param {Function} plugin * The basic plugin. * * @returns {Function} * A wrapper function for the given plugin. */ var createBasicPlugin = function createBasicPlugin(name, plugin) { return function () { var instance = plugin.apply(this, arguments); markPluginAsActive(this, name); // We trigger the "pluginsetup" event on the player regardless, but we want // the hash to be consistent with the hash provided for advanced plugins. // The only potentially counter-intuitive thing here is the `instance` is the // value returned by the `plugin` function. this.trigger('pluginsetup', { name: name, plugin: plugin, instance: instance }); return instance; }; }; /** * Takes a plugin sub-class and returns a factory function for generating * instances of it. * * This factory function will replace itself with an instance of the requested * sub-class of Plugin. * * @private * @param {string} name * The name of the plugin. * * @param {Plugin} PluginSubClass * The advanced plugin. * * @returns {Function} */ var createPluginFactory = function createPluginFactory(name, PluginSubClass) { // Add a `name` property to the plugin prototype so that each plugin can // refer to itself by name. PluginSubClass.prototype.name = name; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var instance = new (Function.prototype.bind.apply(PluginSubClass, [null].concat([this].concat(args))))(); // The plugin is replaced by a function that returns the current instance. this[name] = function () { return instance; }; return instance; }; }; /** * Parent class for all advanced plugins. * * @mixes module:evented~EventedMixin * @mixes module:stateful~StatefulMixin * @fires Player#pluginsetup * @listens Player#dispose * @throws {Error} * If attempting to instantiate the base {@link Plugin} class * directly instead of via a sub-class. */ var Plugin = function () { /** * Creates an instance of this class. * * Sub-classes should call `super` to ensure plugins are properly initialized. * * @param {Player} player * A Video.js player instance. */ function Plugin(player) { _classCallCheck(this, Plugin); this.player = player; if (this.constructor === Plugin) { throw new Error('Plugin must be sub-classed; not directly instantiated.'); } // Make this object evented, but remove the added `trigger` method so we // use the prototype version instead. (0, _evented2['default'])(this); delete this.trigger; (0, _stateful2['default'])(this, this.constructor.defaultState); markPluginAsActive(player, this.name); // Auto-bind the dispose method so we can use it as a listener and unbind // it later easily. this.dispose = Fn.bind(this, this.dispose); // If the player is disposed, dispose the plugin. player.on('dispose', this.dispose); player.trigger('pluginsetup', this.getEventHash()); } /** * Each event triggered by plugins includes a hash of additional data with * conventional properties. * * This returns that object or mutates an existing hash. * * @param {Object} [hash={}] * An object to be used as event an event hash. * * @returns {Plugin~PluginEventHash} * An event hash object with provided properties mixed-in. */ Plugin.prototype.getEventHash = function getEventHash() { var hash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; hash.name = this.name; hash.plugin = this.constructor; hash.instance = this; return hash; }; /** * Triggers an event on the plugin object and overrides * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}. * * @param {string|Object} event * An event type or an object with a type property. * * @param {Object} [hash={}] * Additional data hash to merge with a * {@link Plugin~PluginEventHash|PluginEventHash}. * * @returns {boolean} * Whether or not default was prevented. */ Plugin.prototype.trigger = function trigger(event) { var hash = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return Events.trigger(this.eventBusEl_, event, this.getEventHash(hash)); }; /** * Handles "statechanged" events on the plugin. No-op by default, override by * subclassing. * * @abstract * @param {Event} e * An event object provided by a "statechanged" event. * * @param {Object} e.changes * An object describing changes that occurred with the "statechanged" * event. */ Plugin.prototype.handleStateChanged = function handleStateChanged(e) {}; /** * Disposes a plugin. * * Subclasses can override this if they want, but for the sake of safety, * it's probably best to subscribe the "dispose" event. * * @fires Plugin#dispose */ Plugin.prototype.dispose = function dispose() { var name = this.name, player = this.player; /** * Signals that a advanced plugin is about to be disposed. * * @event Plugin#dispose * @type {EventTarget~Event} */ this.trigger('dispose'); this.off(); player.off('dispose', this.dispose); // Eliminate any possible sources of leaking memory by clearing up // references between the player and the plugin instance and nulling out // the plugin's state and replacing methods with a function that throws. player[PLUGIN_CACHE_KEY][name] = false; this.player = this.state = null; // Finally, replace the plugin name on the player with a new factory // function, so that the plugin is ready to be set up again. player[name] = createPluginFactory(name, pluginStorage[name]); }; /** * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`). * * @param {string|Function} plugin * If a string, matches the name of a plugin. If a function, will be * tested directly. * * @returns {boolean} * Whether or not a plugin is a basic plugin. */ Plugin.isBasic = function isBasic(plugin) { var p = typeof plugin === 'string' ? getPlugin(plugin) : plugin; return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype); }; /** * Register a Video.js plugin. * * @param {string} name * The name of the plugin to be registered. Must be a string and * must not match an existing plugin or a method on the `Player` * prototype. * * @param {Function} plugin * A sub-class of `Plugin` or a function for basic plugins. * * @returns {Function} * For advanced plugins, a factory function for that plugin. For * basic plugins, a wrapper function that initializes the plugin. */ Plugin.registerPlugin = function registerPlugin(name, plugin) { if (typeof name !== 'string') { throw new Error('Illegal plugin name, "' + name + '", must be a string, was ' + (typeof name === 'undefined' ? 'undefined' : _typeof(name)) + '.'); } if (pluginExists(name) || _player2['default'].prototype.hasOwnProperty(name)) { throw new Error('Illegal plugin name, "' + name + '", already exists.'); } if (typeof plugin !== 'function') { throw new Error('Illegal plugin for "' + name + '", must be a function, was ' + (typeof plugin === 'undefined' ? 'undefined' : _typeof(plugin)) + '.'); } pluginStorage[name] = plugin; // Add a player prototype method for all sub-classed plugins (but not for // the base Plugin class). if (name !== BASE_PLUGIN_NAME) { if (Plugin.isBasic(plugin)) { _player2['default'].prototype[name] = createBasicPlugin(name, plugin); } else { _player2['default'].prototype[name] = createPluginFactory(name, plugin); } } return plugin; }; /** * De-register a Video.js plugin. * * @param {string} name * The name of the plugin to be deregistered. */ Plugin.deregisterPlugin = function deregisterPlugin(name) { if (name === BASE_PLUGIN_NAME) { throw new Error('Cannot de-register base plugin.'); } if (pluginExists(name)) { delete pluginStorage[name]; delete _player2['default'].prototype[name]; } }; /** * Gets an object containing multiple Video.js plugins. * * @param {Array} [names] * If provided, should be an array of plugin names. Defaults to _all_ * plugin names. * * @returns {Object|undefined} * An object containing plugin(s) associated with their name(s) or * `undefined` if no matching plugins exist). */ Plugin.getPlugins = function getPlugins() { var names = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Object.keys(pluginStorage); var result = void 0; names.forEach(function (name) { var plugin = getPlugin(name); if (plugin) { result = result || {}; result[name] = plugin; } }); return result; }; /** * Gets a plugin's version, if available * * @param {string} name * The name of a plugin. * * @returns {string} * The plugin's version or an empty string. */ Plugin.getPluginVersion = function getPluginVersion(name) { var plugin = getPlugin(name); return plugin && plugin.VERSION || ''; }; return Plugin; }(); /** * Gets a plugin by name if it exists. * * @static * @method getPlugin * @memberOf Plugin * @param {string} name * The name of a plugin. * * @returns {Function|undefined} * The plugin (or `undefined`). */ Plugin.getPlugin = getPlugin; /** * The name of the base plugin class as it is registered. * * @type {string} */ Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME; Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin); /** * Documented in player.js * * @ignore */ _player2['default'].prototype.usingPlugin = function (name) { return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true; }; /** * Documented in player.js * * @ignore */ _player2['default'].prototype.hasPlugin = function (name) { return !!pluginExists(name); }; exports['default'] = Plugin; /** * Signals that a plugin has just been set up on a player. * * @event Player#pluginsetup * @type {Plugin~PluginEventHash} */ /** * @typedef {Object} Plugin~PluginEventHash * * @property {string} instance * For basic plugins, the return value of the plugin function. For * advanced plugins, the plugin instance on which the event is fired. * * @property {string} name * The name of the plugin. * * @property {string} plugin * For basic plugins, the plugin function. For advanced plugins, the * plugin class/constructor. */ },{"51":51,"52":52,"54":54,"84":84,"86":86}],56:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file poster-image.js */ /** * A `ClickableComponent` that handles showing the poster image for the player. * * @extends ClickableComponent */ var PosterImage = function (_ClickableComponent) { _inherits(PosterImage, _ClickableComponent); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should attach to. * * @param {Object} [options] * The key/value store of player options. */ function PosterImage(player, options) { _classCallCheck(this, PosterImage); var _this = _possibleConstructorReturn(this, _ClickableComponent.call(this, player, options)); _this.update(); player.on('posterchange', Fn.bind(_this, _this.update)); return _this; } /** * Clean up and dispose of the `PosterImage`. */ PosterImage.prototype.dispose = function dispose() { this.player().off('posterchange', this.update); _ClickableComponent.prototype.dispose.call(this); }; /** * Create the `PosterImage`s DOM element. * * @return {Element} * The element that gets created. */ PosterImage.prototype.createEl = function createEl() { var el = Dom.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!browser.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = Dom.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * An {@link EventTarget~EventListener} for {@link Player#posterchange} events. * * @listens Player#posterchange * * @param {EventTarget~Event} [event] * The `Player#posterchange` event that triggered this function. */ PosterImage.prototype.update = function update(event) { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the source of the `PosterImage` depending on the display method. * * @param {string} url * The URL to the source for the `PosterImage`. */ PosterImage.prototype.setSrc = function setSrc(url) { if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { var backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See * {@link ClickableComponent#handleClick} for instances where this will be triggered. * * @listens tap * @listens click * @listens keydown * * @param {EventTarget~Event} event + The `click`, `tap` or `keydown` event that caused this function to be called. */ PosterImage.prototype.handleClick = function handleClick(event) { // We don't want a click to trigger playback when controls are disabled if (!this.player_.controls()) { return; } if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; return PosterImage; }(_clickableComponent2['default']); _component2['default'].registerComponent('PosterImage', PosterImage); exports['default'] = PosterImage; },{"3":3,"5":5,"79":79,"83":83,"86":86}],57:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.hasLoaded = exports.autoSetupTimeout = exports.autoSetup = undefined; var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _events = _dereq_(84); var Events = _interopRequireWildcard(_events); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * @file setup.js - Functions for setting up a player without * user interaction based on the data-setup `attribute` of the video tag. * * @module setup */ var _windowLoaded = false; var videojs = void 0; /** * Set up any tags that have a data-setup `attribute` when the player is started. */ var autoSetup = function autoSetup() { // Protect against breakage in non-browser environments. if (!Dom.isReal()) { return; } // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop // through each list of elements to build up a new, combined list of elements. var vids = _document2['default'].getElementsByTagName('video'); var audios = _document2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var _i = 0, _e = audios.length; _i < _e; _i++) { mediaEls.push(audios[_i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var _i2 = 0, _e2 = mediaEls.length; _i2 < _e2; _i2++) { var mediaEl = mediaEls[_i2]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of // 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl.player === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; /** * Wait until the page is loaded before running autoSetup. This will be called in * autoSetup if `hasLoaded` returns false. * * @param {number} wait * How long to wait in ms * * @param {videojs} [vjs] * The videojs library function */ function autoSetupTimeout(wait, vjs) { if (vjs) { videojs = vjs; } _window2['default'].setTimeout(autoSetup, wait); } if (Dom.isReal() && _document2['default'].readyState === 'complete') { _windowLoaded = true; } else { /** * Listen for the load event on window, and set _windowLoaded to true. * * @listens load */ Events.one(_window2['default'], 'load', function () { _windowLoaded = true; }); } /** * check if the document has been loaded */ var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; },{"83":83,"84":84,"97":97,"98":98}],58:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _obj = _dereq_(91); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file slider.js */ /** * The base functionality for a slider. Can be vertical or horizontal. * For instance the volume bar or the seek bar on a video is a slider. * * @extends Component */ var Slider = function (_Component) { _inherits(Slider, _Component); /** * Create an instance of this class * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function Slider(player, options) { _classCallCheck(this, Slider); // Set property names to bar to match with the child Slider class is looking for var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.bar = _this.getChild(_this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type _this.vertical(!!_this.options_.vertical); _this.on('mousedown', _this.handleMouseDown); _this.on('touchstart', _this.handleMouseDown); _this.on('focus', _this.handleFocus); _this.on('blur', _this.handleBlur); _this.on('click', _this.handleClick); _this.on(player, 'controlsvisible', _this.update); if (_this.playerEvent) { _this.on(player, _this.playerEvent, _this.update); } return _this; } /** * Create the `Button`s DOM element. * * @param {string} type * Type of element to create. * * @param {Object} [props={}] * List of properties in Object form. * * @param {Object} [attributes={}] * list of attributes in Object form. * * @return {Element} * The element that gets created. */ Slider.prototype.createEl = function createEl(type) { var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = (0, _obj.assign)({ tabIndex: 0 }, props); attributes = (0, _obj.assign)({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, 'tabIndex': 0 }, attributes); return _Component.prototype.createEl.call(this, type, props, attributes); }; /** * Handle `mousedown` or `touchstart` events on the `Slider`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart * @fires Slider#slideractive */ Slider.prototype.handleMouseDown = function handleMouseDown(event) { var doc = this.bar.el_.ownerDocument; event.preventDefault(); Dom.blockTextSelection(); this.addClass('vjs-sliding'); /** * Triggered when the slider is in an active state * * @event Slider#slideractive * @type {EventTarget~Event} */ this.trigger('slideractive'); this.on(doc, 'mousemove', this.handleMouseMove); this.on(doc, 'mouseup', this.handleMouseUp); this.on(doc, 'touchmove', this.handleMouseMove); this.on(doc, 'touchend', this.handleMouseUp); this.handleMouseMove(event); }; /** * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`. * The `mousemove` and `touchmove` events will only only trigger this function during * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and * {@link Slider#handleMouseUp}. * * @param {EventTarget~Event} event * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered * this function * * @listens mousemove * @listens touchmove */ Slider.prototype.handleMouseMove = function handleMouseMove(event) {}; /** * Handle `mouseup` or `touchend` events on the `Slider`. * * @param {EventTarget~Event} event * `mouseup` or `touchend` event that triggered this function. * * @listens touchend * @listens mouseup * @fires Slider#sliderinactive */ Slider.prototype.handleMouseUp = function handleMouseUp() { var doc = this.bar.el_.ownerDocument; Dom.unblockTextSelection(); this.removeClass('vjs-sliding'); /** * Triggered when the slider is no longer in an active state. * * @event Slider#sliderinactive * @type {EventTarget~Event} */ this.trigger('sliderinactive'); this.off(doc, 'mousemove', this.handleMouseMove); this.off(doc, 'mouseup', this.handleMouseUp); this.off(doc, 'touchmove', this.handleMouseMove); this.off(doc, 'touchend', this.handleMouseUp); this.update(); }; /** * Update the progress bar of the `Slider`. * * @returns {number} * The percentage of progress the progress bar represents as a * number from 0 to 1. */ Slider.prototype.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update // to the end of the execution stack. The player is destroyed before then // update will cause an error if (!this.el_) { return; } // If scrubbing, we could use a cached value to make the handle keep up // with the user's mouse. On HTML5 browsers scrubbing is really smooth, but // some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) { return; } // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = (progress * 100).toFixed(2) + '%'; var style = bar.el().style; // Set the new bar width or height if (this.vertical()) { style.height = percentage; } else { style.width = percentage; } return progress; }; /** * Calculate distance for slider * * @param {EventTarget~Event} event * The event that caused this function to run. * * @return {number} * The current position of the Slider. * - postition.x for vertical `Slider`s * - postition.y for horizontal `Slider`s */ Slider.prototype.calculateDistance = function calculateDistance(event) { var position = Dom.getPointerPosition(this.el_, event); if (this.vertical()) { return position.y; } return position.x; }; /** * Handle a `focus` event on this `Slider`. * * @param {EventTarget~Event} event * The `focus` event that caused this function to run. * * @listens focus */ Slider.prototype.handleFocus = function handleFocus() { this.on(this.bar.el_.ownerDocument, 'keydown', this.handleKeyPress); }; /** * Handle a `keydown` event on the `Slider`. Watches for left, rigth, up, and down * arrow keys. This function will only be called when the slider has focus. See * {@link Slider#handleFocus} and {@link Slider#handleBlur}. * * @param {EventTarget~Event} event * the `keydown` event that caused this function to run. * * @listens keydown */ Slider.prototype.handleKeyPress = function handleKeyPress(event) { // Left and Down Arrows if (event.which === 37 || event.which === 40) { event.preventDefault(); this.stepBack(); // Up and Right Arrows } else if (event.which === 38 || event.which === 39) { event.preventDefault(); this.stepForward(); } }; /** * Handle a `blur` event on this `Slider`. * * @param {EventTarget~Event} event * The `blur` event that caused this function to run. * * @listens blur */ Slider.prototype.handleBlur = function handleBlur() { this.off(this.bar.el_.ownerDocument, 'keydown', this.handleKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event * Event that caused this object to run */ Slider.prototype.handleClick = function handleClick(event) { event.stopImmediatePropagation(); event.preventDefault(); }; /** * Get/set if slider is horizontal for vertical * * @param {boolean} [bool] * - true if slider is vertical, * - false is horizontal * * @return {boolean} * - true if slider is vertical, and getting * - false if the slider is horizontal, and getting */ Slider.prototype.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } }; return Slider; }(_component2['default']); _component2['default'].registerComponent('Slider', Slider); exports['default'] = Slider; },{"5":5,"83":83,"91":91}],59:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = 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 _templateObject = _taggedTemplateLiteralLoose(['Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n This may prevent text tracks from loading.'], ['Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n This may prevent text tracks from loading.']); var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _url = _dereq_(95); var Url = _interopRequireWildcard(_url); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _tsml = _dereq_(101); var _tsml2 = _interopRequireDefault(_tsml); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _obj = _dereq_(91); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _toTitleCase = _dereq_(94); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); var _trackTypes = _dereq_(75); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } 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; } /** * @file html5.js */ /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @mixes Tech~SouceHandlerAdditions * @extends Tech */ var Html5 = function (_Tech) { _inherits(Html5, _Tech); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `HTML5` Tech is ready. */ function Html5(options, ready) { _classCallCheck(this, Html5); var _this = _possibleConstructorReturn(this, _Tech.call(this, options, ready)); var source = options.source; var crossoriginTracks = false; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (_this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { _this.setSource(source); } else { _this.handleLateInit_(_this.el_); } if (_this.el_.hasChildNodes()) { var nodes = _this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!_this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { // store HTMLTrackElement and TextTrack to remote list _this.remoteTextTrackEls().addTrackElement_(node); _this.remoteTextTracks().addTrack(node.track); if (!crossoriginTracks && !_this.el_.hasAttribute('crossorigin') && Url.isCrossOrigin(node.src)) { crossoriginTracks = true; } } } } for (var i = 0; i < removeNodes.length; i++) { _this.el_.removeChild(removeNodes[i]); } } _this.proxyNativeTracks_(); if (_this.featuresNativeTextTracks && crossoriginTracks) { _log2['default'].warn((0, _tsml2['default'])(_templateObject)); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if ((browser.TOUCH_ENABLED || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) { _this.setControls(true); } // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen` // into a `fullscreenchange` event _this.proxyWebkitFullscreen_(); _this.triggerReady(); return _this; } /** * Dispose of `HTML5` media element and remove all tracks. */ Html5.prototype.dispose = function dispose() { Html5.disposeMediaElement(this.el_); // tech will handle clearing of the emulated track list _Tech.prototype.dispose.call(this); }; /** * Proxy all native track list events to our track lists if the browser we are playing * in supports that type of track list. * * @private */ Html5.prototype.proxyNativeTracks_ = function proxyNativeTracks_() { var _this2 = this; _trackTypes.NORMAL.names.forEach(function (name) { var props = _trackTypes.NORMAL[name]; var elTracks = _this2.el()[props.getterName]; var techTracks = _this2[props.getterName](); if (!_this2['featuresNative' + props.capitalName + 'Tracks'] || !elTracks || !elTracks.addEventListener) { return; } var listeners = { change: function change(e) { techTracks.trigger({ type: 'change', target: techTracks, currentTarget: techTracks, srcElement: techTracks }); }, addtrack: function addtrack(e) { techTracks.addTrack(e.track); }, removetrack: function removetrack(e) { techTracks.removeTrack(e.track); } }; var removeOldTracks = function removeOldTracks() { var removeTracks = []; for (var i = 0; i < techTracks.length; i++) { var found = false; for (var j = 0; j < elTracks.length; j++) { if (elTracks[j] === techTracks[i]) { found = true; break; } } if (!found) { removeTracks.push(techTracks[i]); } } while (removeTracks.length) { techTracks.removeTrack(removeTracks.shift()); } }; Object.keys(listeners).forEach(function (eventName) { var listener = listeners[eventName]; elTracks.addEventListener(eventName, listener); _this2.on('dispose', function (e) { return elTracks.removeEventListener(eventName, listener); }); }); // Remove (native) tracks that are not used anymore _this2.on('loadstart', removeOldTracks); _this2.on('dispose', function (e) { return _this2.off('loadstart', removeOldTracks); }); }); }; /** * Create the `Html5` Tech's DOM element. * * @return {Element} * The element that gets created. */ Html5.prototype.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. // If we ingested the player div, we do not need to move the media element. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(true); if (el.parentNode) { el.parentNode.insertBefore(clone, el); } Html5.disposeMediaElement(el); el = clone; } else { el = _document2['default'].createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && Dom.getAttributes(this.options_.tag); var attributes = (0, _mergeOptions2['default'])({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setAttributes(el, (0, _obj.assign)(attributes, { id: this.options_.techId, 'class': 'vjs-tech' })); } el.playerId = this.options_.playerId; } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setAttributes(el, overwriteAttrs); } return el; }; /** * This will be triggered if the loadstart event has already fired, before videojs was * ready. Two known examples of when this can happen are: * 1. If we're loading the playback object after it has started loading * 2. The media is already playing the (often with autoplay on) then * * This function will fire another loadstart so that videojs can catchup. * * @fires Tech#loadstart * * @return {undefined} * returns nothing. */ Html5.prototype.handleLateInit_ = function handleLateInit_(el) { var _this3 = this; if (el.networkState === 0 || el.networkState === 3) { // The video element hasn't started loading the source yet // or didn't find a source return; } if (el.readyState === 0) { var _ret = function () { // NetworkState is set synchronously BUT loadstart is fired at the // end of the current stack, usually before setInterval(fn, 0). // So at this point we know loadstart may have already fired or is // about to fire, and either way the player hasn't seen it yet. // We don't want to fire loadstart prematurely here and cause a // double loadstart so we'll wait and see if it happens between now // and the next loop, and fire it if not. // HOWEVER, we also want to make sure it fires before loadedmetadata // which could also happen between now and the next loop, so we'll // watch for that also. var loadstartFired = false; var setLoadstartFired = function setLoadstartFired() { loadstartFired = true; }; _this3.on('loadstart', setLoadstartFired); var triggerLoadstart = function triggerLoadstart() { // We did miss the original loadstart. Make sure the player // sees loadstart before loadedmetadata if (!loadstartFired) { this.trigger('loadstart'); } }; _this3.on('loadedmetadata', triggerLoadstart); _this3.ready(function () { this.off('loadstart', setLoadstartFired); this.off('loadedmetadata', triggerLoadstart); if (!loadstartFired) { // We did miss the original native loadstart. Fire it now. this.trigger('loadstart'); } }); return { v: void 0 }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } // From here on we know that loadstart already fired and we missed it. // The other readyState events aren't as much of a problem if we double // them, so not going to go to as much trouble as loadstart to prevent // that unless we find reason to. var eventsToTrigger = ['loadstart']; // loadedmetadata: newly equal to HAVE_METADATA (1) or greater eventsToTrigger.push('loadedmetadata'); // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater if (el.readyState >= 2) { eventsToTrigger.push('loadeddata'); } // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater if (el.readyState >= 3) { eventsToTrigger.push('canplay'); } // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4) if (el.readyState >= 4) { eventsToTrigger.push('canplaythrough'); } // We still need to give the player time to add event listeners this.ready(function () { eventsToTrigger.forEach(function (type) { this.trigger(type); }, this); }); }; /** * Called by {@link Player#play} to play using the `Html5` `Tech`. */ Html5.prototype.play = function play() { var playPromise = this.el_.play(); // Catch/silence error when a pause interrupts a play request // on browsers which return a promise if (playPromise !== undefined && typeof playPromise.then === 'function') { playPromise.then(null, function (e) {}); } }; /** * Set current time for the `HTML5` tech. * * @param {number} seconds * Set the current time of the media to this. */ Html5.prototype.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { (0, _log2['default'])(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; /** * Get the current duration of the HTML5 media element. * * @return {number} * The duration of the media or 0 if there is no duration. */ Html5.prototype.duration = function duration() { var _this4 = this; // Android Chrome will report duration as Infinity for VOD HLS until after // playback has started, which triggers the live display erroneously. // Return NaN if playback has not started and trigger a durationupdate once // the duration can be reliably known. if (this.el_.duration === Infinity && browser.IS_ANDROID && browser.IS_CHROME) { if (this.el_.currentTime === 0) { var _ret2 = function () { // Wait for the first `timeupdate` with currentTime > 0 - there may be // several with 0 var checkProgress = function checkProgress() { if (_this4.el_.currentTime > 0) { // Trigger durationchange for genuinely live video if (_this4.el_.duration === Infinity) { _this4.trigger('durationchange'); } _this4.off('timeupdate', checkProgress); } }; _this4.on('timeupdate', checkProgress); return { v: NaN }; }(); if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v; } } return this.el_.duration || NaN; }; /** * Get the current width of the HTML5 media element. * * @return {number} * The width of the HTML5 media element. */ Html5.prototype.width = function width() { return this.el_.offsetWidth; }; /** * Get the current height of the HTML5 media element. * * @return {number} * The heigth of the HTML5 media element. */ Html5.prototype.height = function height() { return this.el_.offsetHeight; }; /** * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into * `fullscreenchange` event. * * @private * @fires fullscreenchange * @listens webkitendfullscreen * @listens webkitbeginfullscreen * @listens webkitbeginfullscreen */ Html5.prototype.proxyWebkitFullscreen_ = function proxyWebkitFullscreen_() { var _this5 = this; if (!('webkitDisplayingFullscreen' in this.el_)) { return; } var endFn = function endFn() { this.trigger('fullscreenchange', { isFullscreen: false }); }; var beginFn = function beginFn() { this.one('webkitendfullscreen', endFn); this.trigger('fullscreenchange', { isFullscreen: true }); }; this.on('webkitbeginfullscreen', beginFn); this.on('dispose', function () { _this5.off('webkitbeginfullscreen', beginFn); _this5.off('webkitendfullscreen', endFn); }); }; /** * Check if fullscreen is supported on the current playback device. * * @return {boolean} * - True if fullscreen is supported. * - False if fullscreen is not supported. */ Html5.prototype.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = _window2['default'].navigator && _window2['default'].navigator.userAgent || ''; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; }; /** * Request that the `HTML5` Tech enter fullscreen. */ Html5.prototype.enterFullScreen = function enterFullScreen() { var video = this.el_; if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; /** * Request that the `HTML5` Tech exit fullscreen. */ Html5.prototype.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); }; /** * A getter/setter for the `Html5` Tech's source object. * > Note: Please use {@link Html5#setSource} * * @param {Tech~SourceObject} [src] * The source object you want to set on the `HTML5` techs element. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting * * @deprecated Since version 5. */ Html5.prototype.src = function src(_src) { if (_src === undefined) { return this.el_.src; } // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(_src); }; /** * Reset the tech by removing all sources and then calling * {@link Html5.resetMediaElement}. */ Html5.prototype.reset = function reset() { Html5.resetMediaElement(this.el_); }; /** * Get the current source on the `HTML5` Tech. Falls back to returning the source from * the HTML5 media element. * * @return {Tech~SourceObject} * The current source object from the HTML5 tech. With a fallback to the * elements source. */ Html5.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } return this.el_.currentSrc; }; /** * Set controls attribute for the HTML5 media Element. * * @param {string} val * Value to set the controls attribute to */ Html5.prototype.setControls = function setControls(val) { this.el_.controls = !!val; }; /** * Create and returns a remote {@link TextTrack} object. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @return {TextTrack} * The TextTrack that gets created. */ Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; /** * Creates either native TextTrack or an emulated TextTrack depending * on the value of `featuresNativeTextTracks` * * @param {Object} options * The object should contain the options to intialize the TextTrack with. * * @param {string} [options.kind] * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). * * @param {string} [options.label]. * Label to identify the text track * * @param {string} [options.language] * Two letter language abbreviation. * * @param {boolean} [options.default] * Default this track to on. * * @param {string} [options.id] * The internal id to assign this track. * * @param {string} [options.src] * A source url for the track. * * @return {HTMLTrackElement} * The track element that gets created. */ Html5.prototype.createRemoteTextTrack = function createRemoteTextTrack(options) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.createRemoteTextTrack.call(this, options); } var htmlTrackElement = _document2['default'].createElement('track'); if (options.kind) { htmlTrackElement.kind = options.kind; } if (options.label) { htmlTrackElement.label = options.label; } if (options.language || options.srclang) { htmlTrackElement.srclang = options.language || options.srclang; } if (options['default']) { htmlTrackElement['default'] = options['default']; } if (options.id) { htmlTrackElement.id = options.id; } if (options.src) { htmlTrackElement.src = options.src; } return htmlTrackElement; }; /** * Creates a remote text track object and returns an html track element. * * @param {Object} options The object should contain values for * kind, language, label, and src (location of the WebVTT file) * @param {Boolean} [manualCleanup=true] if set to false, the TextTrack will be * automatically removed from the video element whenever the source changes * @return {HTMLTrackElement} An Html Track Element. * This can be an emulated {@link HTMLTrackElement} or a native one. * @deprecated The default value of the "manualCleanup" parameter will default * to "false" in upcoming versions of Video.js */ Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) { var htmlTrackElement = _Tech.prototype.addRemoteTextTrack.call(this, options, manualCleanup); if (this.featuresNativeTextTracks) { this.el().appendChild(htmlTrackElement); } return htmlTrackElement; }; /** * Remove remote `TextTrack` from `TextTrackList` object * * @param {TextTrack} track * `TextTrack` object to remove */ Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { _Tech.prototype.removeRemoteTextTrack.call(this, track); if (this.featuresNativeTextTracks) { var tracks = this.$$('track'); var i = tracks.length; while (i--) { if (track === tracks[i] || track === tracks[i].track) { this.el().removeChild(tracks[i]); } } } }; return Html5; }(_tech2['default']); /* HTML5 Support Testing ---------------------------------------------------- */ if (Dom.isReal()) { /** * Element for testing browser HTML5 media capabilities * * @type {Element} * @constant * @private */ Html5.TEST_VID = _document2['default'].createElement('video'); var track = _document2['default'].createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); } /** * Check if HTML5 media is supported by this browser/device. * * @return {boolean} * - True if HTML5 media is supported. * - False if HTML5 media is not supported. */ Html5.isSupported = function () { // IE9 with no Media Player is a LIAR! (#984) try { Html5.TEST_VID.volume = 0.5; } catch (e) { return false; } return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType); }; /** * Check if the tech can support the given type * * @param {string} type * The mimetype to check * @return {string} 'probably', 'maybe', or '' (empty string) */ Html5.canPlayType = function (type) { return Html5.TEST_VID.canPlayType(type); }; /** * Check if the tech can support the given source * @param {Object} srcObj * The source object * @param {Object} options * The options passed to the tech * @return {string} 'probably', 'maybe', or '' (empty string) */ Html5.canPlaySource = function (srcObj, options) { return Html5.canPlayType(srcObj.type); }; /** * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {boolean} * - True if volume can be controlled * - False otherwise */ Html5.canControlVolume = function () { // IE will error if Windows Media Player not installed #3315 try { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; } catch (e) { return false; } }; /** * Check if the playback rate can be changed in this browser/device. * * @return {boolean} * - True if playback rate can be controlled * - False otherwise */ Html5.canControlPlaybackRate = function () { // Playback rate API is implemented in Android Chrome, but doesn't do anything // https://github.com/videojs/video.js/issues/3180 if (browser.IS_ANDROID && browser.IS_CHROME) { return false; } // IE will error if Windows Media Player not installed #3315 try { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; } catch (e) { return false; } }; /** * Check to see if native `TextTrack`s are supported by this browser/device. * * @return {boolean} * - True if native `TextTrack`s are supported. * - False otherwise */ Html5.supportsNativeTextTracks = function () { return browser.IS_ANY_SAFARI; }; /** * Check to see if native `VideoTrack`s are supported by this browser/device * * @return {boolean} * - True if native `VideoTrack`s are supported. * - False otherwise */ Html5.supportsNativeVideoTracks = function () { return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks); }; /** * Check to see if native `AudioTrack`s are supported by this browser/device * * @return {boolean} * - True if native `AudioTrack`s are supported. * - False otherwise */ Html5.supportsNativeAudioTracks = function () { return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks); }; /** * An array of events available on the Html5 tech. * * @private * @type {Array} */ Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange']; /** * Boolean indicating whether the `Tech` supports volume control. * * @type {boolean} * @default {@link Html5.canControlVolume} */ Html5.prototype.featuresVolumeControl = Html5.canControlVolume(); /** * Boolean indicating whether the `Tech` supports changing the speed at which the media * plays. Examples: * - Set player to play 2x (twice) as fast * - Set player to play 0.5x (half) as fast * * @type {boolean} * @default {@link Html5.canControlPlaybackRate} */ Html5.prototype.featuresPlaybackRate = Html5.canControlPlaybackRate(); /** * Boolean indicating whether the `HTML5` tech currently supports the media element * moving in the DOM. iOS breaks if you move the media element, so this is set this to * false there. Everywhere else this should be true. * * @type {boolean} * @default */ Html5.prototype.movingMediaElementInDOM = !browser.IS_IOS; // TODO: Previous comment: No longer appears to be used. Can probably be removed. // Is this true? /** * Boolean indicating whether the `HTML5` tech currently supports automatic media resize * when going into fullscreen. * * @type {boolean} * @default */ Html5.prototype.featuresFullscreenResize = true; /** * Boolean indicating whether the `HTML5` tech currently supports the progress event. * If this is false, manual `progress` events will be triggred instead. * * @type {boolean} * @default */ Html5.prototype.featuresProgressEvents = true; /** * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event. * If this is false, manual `timeupdate` events will be triggred instead. * * @default */ Html5.prototype.featuresTimeupdateEvents = true; /** * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeTextTracks} */ Html5.prototype.featuresNativeTextTracks = Html5.supportsNativeTextTracks(); /** * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeVideoTracks} */ Html5.prototype.featuresNativeVideoTracks = Html5.supportsNativeVideoTracks(); /** * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeAudioTracks} */ Html5.prototype.featuresNativeAudioTracks = Html5.supportsNativeAudioTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; var mp4RE = /^video\/mp4/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (browser.ANDROID_VERSION >= 4.0 && !browser.IS_FIREFOX) { Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; // Override Android 2.2 and less canPlayType method which is broken } else if (browser.IS_OLD_ANDROID) { Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; return r; }; // by default, patch the media element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) { // not supported } })(); } }; Html5.resetMediaElement = function (el) { if (!el) { return; } var sources = el.querySelectorAll('source'); var i = sources.length; while (i--) { el.removeChild(sources[i]); } // remove any src reference. // not setting `src=''` because that throws an error el.removeAttribute('src'); if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) { // satisfy linter } })(); } }; /* Native HTML5 element property wrapping ----------------------------------- */ // Wrap native properties with a getter [ /** * Get the value of `paused` from the media element. `paused` indicates whether the media element * is currently paused or not. * * @method Html5#paused * @return {boolean} * The value of `paused` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused} */ 'paused', /** * Get the value of `currentTime` from the media element. `currentTime` indicates * the current second that the media is at in playback. * * @method Html5#currentTime * @return {number} * The value of `currentTime` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime} */ 'currentTime', /** * Get the value of `buffered` from the media element. `buffered` is a `TimeRange` * object that represents the parts of the media that are already downloaded and * available for playback. * * @method Html5#buffered * @return {TimeRange} * The value of `buffered` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered} */ 'buffered', /** * Get the value of `volume` from the media element. `volume` indicates * the current playback volume of audio for a media. `volume` will be a value from 0 * (silent) to 1 (loudest and default). * * @method Html5#volume * @return {number} * The value of `volume` from the media element. Value will be between 0-1. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume} */ 'volume', /** * Get the value of `muted` from the media element. `muted` indicates * that the volume for the media should be set to silent. This does not actually change * the `volume` attribute. * * @method Html5#muted * @return {boolean} * - True if the value of `volume` should be ignored and the audio set to silent. * - False if the value of `volume` should be used. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted} */ 'muted', /** * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates * that the volume for the media should be set to silent when the video first starts. * This does not actually change the `volume` attribute. After playback has started `muted` * will indicate the current status of the volume and `defaultMuted` will not. * * @method Html5.prototype.defaultMuted * @return {boolean} * - True if the value of `volume` should be ignored and the audio set to silent. * - False if the value of `volume` should be used. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted} */ 'defaultMuted', /** * Get the value of `poster` from the media element. `poster` indicates * that the url of an image file that can/will be shown when no media data is available. * * @method Html5#poster * @return {string} * The value of `poster` from the media element. Value will be a url to an * image. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster} */ 'poster', /** * Get the value of `preload` from the media element. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Html5#preload * @return {string} * The value of `preload` from the media element. Will be 'none', 'metadata', * or 'auto'. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload} */ 'preload', /** * Get the value of `autoplay` from the media element. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Html5#autoplay * @return {boolean} * - The value of `autoplay` from the media element. * - True indicates that the media should start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay} */ 'autoplay', /** * Get the value of `controls` from the media element. `controls` indicates * whether the native media controls should be shown or hidden. * * @method Html5#controls * @return {boolean} * - The value of `controls` from the media element. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls} */ 'controls', /** * Get the value of `loop` from the media element. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Html5#loop * @return {boolean} * - The value of `loop` from the media element. * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop} */ 'loop', /** * Get the value of the `error` from the media element. `error` indicates any * MediaError that may have occured during playback. If error returns null there is no * current error. * * @method Html5#error * @return {MediaError|null} * The value of `error` from the media element. Will be `MediaError` if there * is a current error and null otherwise. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error} */ 'error', /** * Get the value of `seeking` from the media element. `seeking` indicates whether the * media is currently seeking to a new position or not. * * @method Html5#seeking * @return {boolean} * - The value of `seeking` from the media element. * - True indicates that the media is currently seeking to a new position. * - Flase indicates that the media is not seeking to a new position at this time. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking} */ 'seeking', /** * Get the value of `seekable` from the media element. `seekable` returns a * `TimeRange` object indicating ranges of time that can currently be `seeked` to. * * @method Html5#seekable * @return {TimeRange} * The value of `seekable` from the media element. A `TimeRange` object * indicating the current ranges of time that can be seeked to. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable} */ 'seekable', /** * Get the value of `ended` from the media element. `ended` indicates whether * the media has reached the end or not. * * @method Html5#ended * @return {boolean} * - The value of `ended` from the media element. * - True indicates that the media has ended. * - False indicates that the media has not ended. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended} */ 'ended', /** * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the * current state. * * @method Html5#defaultMuted * @return {boolean} * - The value of `defaultMuted` from the media element. * - True indicates that the media should start muted. * - False indicates that the media should not start muted * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted} */ 'defaultMuted', /** * Get the value of `playbackRate` from the media element. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Html5#playbackRate * @return {number} * The value of `playbackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate} */ 'playbackRate', /** * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates * the rate at which the media is currently playing back. This value will not indicate the current * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that. * * Examples: * - if defaultPlaybackRate is set to 2, media will play twice as fast. * - if defaultPlaybackRate is set to 0.5, media will play half as fast. * * @method Html5.prototype.defaultPlaybackRate * @return {number} * The value of `defaultPlaybackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate} */ 'defaultPlaybackRate', /** * Get the value of `played` from the media element. `played` returns a `TimeRange` * object representing points in the media timeline that have been played. * * @method Html5#played * @return {TimeRange} * The value of `played` from the media element. A `TimeRange` object indicating * the ranges of time that have been played. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played} */ 'played', /** * Get the value of `networkState` from the media element. `networkState` indicates * the current network state. It returns an enumeration from the following list: * - 0: NETWORK_EMPTY * - 1: NEWORK_IDLE * - 2: NETWORK_LOADING * - 3: NETWORK_NO_SOURCE * * @method Html5#networkState * @return {number} * The value of `networkState` from the media element. This will be a number * from the list in the description. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate} */ 'networkState', /** * Get the value of `readyState` from the media element. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Html5#readyState * @return {number} * The value of `readyState` from the media element. This will be a number * from the list in the description. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states} */ 'readyState', /** * Get the value of `videoWidth` from the video element. `videoWidth` indicates * the current width of the video in css pixels. * * @method Html5#videoWidth * @return {number} * The value of `videoWidth` from the video element. This will be a number * in css pixels. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth} */ 'videoWidth', /** * Get the value of `videoHeight` from the video element. `videoHeigth` indicates * the current height of the video in css pixels. * * @method Html5#videoHeight * @return {number} * The value of `videoHeight` from the video element. This will be a number * in css pixels. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth} */ 'videoHeight'].forEach(function (prop) { Html5.prototype[prop] = function () { return this.el_[prop]; }; }); // Wrap native properties with a setter in this format: // set + toTitleCase(name) [ /** * Set the value of `volume` on the media element. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Html5#setVolume * @param {number} percentAsDecimal * The volume percent as a decimal. Valid range is from 0-1. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume} */ 'volume', /** * Set the value of `muted` on the media element. `muted` indicates that the current * audio level should be silent. * * @method Html5#setMuted * @param {boolean} muted * - True if the audio should be set to silent * - False otherwise * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted} */ 'muted', /** * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current * audio level should be silent, but will only effect the muted level on intial playback.. * * @method Html5.prototype.setDefaultMuted * @param {boolean} defaultMuted * - True if the audio should be set to silent * - False otherwise * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted} */ 'defaultMuted', /** * Set the value of `src` on the media element. `src` indicates the current * {@link Tech~SourceObject} for the media. * * @method Html5#setSrc * @param {Tech~SourceObject} src * The source object to set as the current source. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src} */ 'src', /** * Set the value of `poster` on the media element. `poster` is the url to * an image file that can/will be shown when no media data is available. * * @method Html5#setPoster * @param {string} poster * The url to an image that should be used as the `poster` for the media * element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster} */ 'poster', /** * Set the value of `preload` on the media element. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Html5#setPreload * @param {string} preload * The value of `preload` to set on the media element. Must be 'none', 'metadata', * or 'auto'. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload} */ 'preload', /** * Set the value of `autoplay` on the media element. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Html5#setAutoplay * @param {boolean} autoplay * - True indicates that the media should start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay} */ 'autoplay', /** * Set the value of `loop` on the media element. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Html5#setLoop * @param {boolean} loop * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop} */ 'loop', /** * Set the value of `playbackRate` on the media element. `playbackRate` indicates * the rate at which the media should play back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Html5#setPlaybackRate * @return {number} * The value of `playbackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate} */ 'playbackRate', /** * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates * the rate at which the media should play back upon initial startup. Changing this value * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}. * * Example Values: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Html5.prototype.setDefaultPlaybackRate * @return {number} * The value of `defaultPlaybackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate} */ 'defaultPlaybackRate'].forEach(function (prop) { Html5.prototype['set' + (0, _toTitleCase2['default'])(prop)] = function (v) { this.el_[prop] = v; }; }); // wrap native functions with a function [ /** * A wrapper around the media elements `pause` function. This will call the `HTML5` * media elements `pause` function. * * @method Html5#pause * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause} */ 'pause', /** * A wrapper around the media elements `load` function. This will call the `HTML5`s * media element `load` function. * * @method Html5#load * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load} */ 'load', /** * A wrapper around the media elements `play` function. This will call the `HTML5`s * media element `play` function. * * @method Html5#play * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play} */ 'play'].forEach(function (prop) { Html5.prototype[prop] = function () { return this.el_[prop](); }; }); _tech2['default'].withSourceHandlers(Html5); /** * Native source handler for Html5, simply passes the source to the media element. * * @proprety {Tech~SourceObject} source * The source object * * @proprety {Html5} tech * The instance of the HTML5 tech. */ Html5.nativeSourceHandler = {}; /** * Check if the media element can play the given mime type. * * @param {string} type * The mimetype to check * * @return {string} * 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canPlayType = function (type) { // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } }; /** * Check if the media element can handle a source natively. * * @param {Tech~SourceObject} source * The source object * * @param {Object} [options] * Options to be passed to the tech. * * @return {string} * 'probably', 'maybe', or '' (empty string). */ Html5.nativeSourceHandler.canHandleSource = function (source, options) { // If a type was provided we should rely on that if (source.type) { return Html5.nativeSourceHandler.canPlayType(source.type); // If no type, fall back to checking 'video/[EXTENSION]' } else if (source.src) { var ext = Url.getFileExtension(source.src); return Html5.nativeSourceHandler.canPlayType('video/' + ext); } return ''; }; /** * Pass the source to the native media element. * * @param {Tech~SourceObject} source * The source object * * @param {Html5} tech * The instance of the Html5 tech * * @param {Object} [options] * The options to pass to the source */ Html5.nativeSourceHandler.handleSource = function (source, tech, options) { tech.setSrc(source.src); }; /** * A noop for the native dispose function, as cleanup is not needed. */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); _tech2['default'].registerTech('Html5', Html5); exports['default'] = Html5; },{"101":101,"62":62,"75":75,"79":79,"83":83,"89":89,"90":90,"91":91,"94":94,"95":95,"97":97,"98":98}],60:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); var _toTitleCase = _dereq_(94); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); 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; } /** * @file loader.js */ /** * The `MediaLoader` is the `Component` that decides which playback technology to load * when a player is initialized. * * @extends Component */ var MediaLoader = function (_Component) { _inherits(MediaLoader, _Component); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should attach to. * * @param {Object} [options] * The key/value stroe of player options. * * @param {Component~ReadyCallback} [ready] * The function that is run when this component is ready. */ function MediaLoader(player, options, ready) { _classCallCheck(this, MediaLoader); // If there are no sources when the player is initialized, // load the first supported playback technology. var _this = _possibleConstructorReturn(this, _Component.call(this, player, options, ready)); if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) { for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) { var techName = (0, _toTitleCase2['default'])(j[i]); var tech = _tech2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!techName) { tech = _component2['default'].getComponent(techName); } // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech_(techName); break; } } } else { // Loop through playback technologies (HTML5, Flash) and check for support. // Then load the best source. // A few assumptions here: // All playback technologies respect preload false. player.src(options.playerOptions.sources); } return _this; } return MediaLoader; }(_component2['default']); _component2['default'].registerComponent('MediaLoader', MediaLoader); exports['default'] = MediaLoader; },{"5":5,"62":62,"94":94}],61:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.allowedSetters = exports.allowedGetters = undefined; exports.use = use; exports.getMiddleware = getMiddleware; exports.setSource = setSource; exports.setTech = setTech; exports.get = get; exports.set = set; var _obj = _dereq_(91); var middlewares = {}; function use(type, middleware) { middlewares[type] = middlewares[type] || []; middlewares[type].push(middleware); } function getMiddleware(type) { if (type) { return middlewares[type]; } return middlewares; } function setSource(player, src, next) { player.setTimeout(function () { return setSourceHelper(src, middlewares[src.type], next, player); }, 1); } function setTech(middleware, tech) { middleware.forEach(function (mw) { return mw.setTech && mw.setTech(tech); }); } function get(middleware, tech, method) { return middleware.reduceRight(middlewareIterator(method), tech[method]()); } function set(middleware, tech, method, arg) { return tech[method](middleware.reduce(middlewareIterator(method), arg)); } var allowedGetters = exports.allowedGetters = { buffered: 1, currentTime: 1, duration: 1, seekable: 1, played: 1 }; var allowedSetters = exports.allowedSetters = { setCurrentTime: 1 }; function middlewareIterator(method) { return function (value, mw) { if (mw[method]) { return mw[method](value); } return value; }; } function setSourceHelper() { var src = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var middleware = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var next = arguments[2]; var player = arguments[3]; var acc = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; var lastRun = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; var mwFactory = middleware[0], mwrest = middleware.slice(1); // if mwFactory is a string, then we're at a fork in the road if (typeof mwFactory === 'string') { setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun); // if we have an mwFactory, call it with the player to get the mw, // then call the mw's setSource method } else if (mwFactory) { (function () { var mw = mwFactory(player); mw.setSource((0, _obj.assign)({}, src), function (err, _src) { // something happened, try the next middleware on the current level // make sure to use the old src if (err) { return setSourceHelper(src, mwrest, next, player, acc, lastRun); } // we've succeeded, now we need to go deeper acc.push(mw); // if it's the same time, continue does the current chain // otherwise, we want to go down the new chain setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun); }); })(); } else if (mwrest.length) { setSourceHelper(src, mwrest, next, player, acc, lastRun); } else if (lastRun) { next(src, acc); } else { setSourceHelper(src, middlewares['*'], next, player, acc, true); } } },{"91":91}],62:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = 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 _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _timeRanges = _dereq_(93); var _buffer = _dereq_(80); var _mediaError = _dereq_(47); var _mediaError2 = _interopRequireDefault(_mediaError); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _obj = _dereq_(91); var _trackTypes = _dereq_(75); var TRACK_TYPES = _interopRequireWildcard(_trackTypes); var _toTitleCase = _dereq_(94); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file tech.js */ /** * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string * that just contains the src url alone. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};` * `var SourceString = 'http://example.com/some-video.mp4';` * * @typedef {Object|string} Tech~SourceObject * * @property {string} src * The url to the source * * @property {string} type * The mime type of the source */ /** * A function used by {@link Tech} to create a new {@link TextTrack}. * * @private * * @param {Tech} self * An instance of the Tech class. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @param {Object} [options={}] * An object with additional text track options * * @return {TextTrack} * The text track that was created. */ function createTrackHelper(self, kind, label, language) { var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new TRACK_TYPES.ALL.text.TrackClass(options); tracks.addTrack(track); return track; } /** * This is the base class for media playback technology controllers, such as * {@link Flash} and {@link HTML5} * * @extends Component */ var Tech = function (_Component) { _inherits(Tech, _Component); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `HTML5` Tech is ready. */ function Tech() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var ready = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; // keep track of whether the current source has played at all to // implement a very limited played() var _this = _possibleConstructorReturn(this, _Component.call(this, null, options, ready)); _this.hasStarted_ = false; _this.on('playing', function () { this.hasStarted_ = true; }); _this.on('loadstart', function () { this.hasStarted_ = false; }); TRACK_TYPES.ALL.names.forEach(function (name) { var props = TRACK_TYPES.ALL[name]; if (options && options[props.getterName]) { _this[props.privateName] = options[props.getterName]; } }); // Manually track progress in cases where the browser/flash player doesn't report it. if (!_this.featuresProgressEvents) { _this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!_this.featuresTimeupdateEvents) { _this.manualTimeUpdatesOn(); } ['Text', 'Audio', 'Video'].forEach(function (track) { if (options['native' + track + 'Tracks'] === false) { _this['featuresNative' + track + 'Tracks'] = false; } }); if (options.nativeCaptions === false) { _this.featuresNativeTextTracks = false; } if (!_this.featuresNativeTextTracks) { _this.emulateTextTracks(); } _this.autoRemoteTextTracks_ = new TRACK_TYPES.ALL.text.ListClass(); _this.initTrackListeners(); // Turn on component tap events only if not using native controls if (!options.nativeControlsForTouch) { _this.emitTapEvents(); } if (_this.constructor) { _this.name_ = _this.constructor.name || 'Unknown Tech'; } return _this; } /* Fallbacks for unsupported event types ================================================================================ */ /** * Polyfill the `progress` event for browsers that don't support it natively. * * @see {@link Tech#trackProgress} */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off the polyfill for `progress` events that was created in * {@link Tech#manualProgressOn} */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * This is used to trigger a `progress` event when the buffered percent changes. It * sets an interval function that will be called every 500 milliseconds to check if the * buffer end percent has changed. * * > This function is called by {@link Tech#manualProgressOn} * * @param {EventTarget~Event} event * The `ready` event that caused this to run. * * @listens Tech#ready * @fires Tech#progress */ Tech.prototype.trackProgress = function trackProgress(event) { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { /** * See {@link Player#progress} * * @event Tech#progress * @type {EventTarget~Event} */ this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update our internal duration on a `durationchange` event by calling * {@link Tech#duration}. * * @param {EventTarget~Event} event * The `durationchange` event that caused this to run. * * @listens Tech#durationchange */ Tech.prototype.onDurationChange = function onDurationChange(event) { this.duration_ = this.duration(); }; /** * Get and create a `TimeRange` object for buffering. * * @return {TimeRange} * The time range object that was created. */ Tech.prototype.buffered = function buffered() { return (0, _timeRanges.createTimeRange)(0, 0); }; /** * Get the percentage of the current video that is currently buffered. * * @return {number} * A number from 0 to 1 that represents the decimal percentage of the * video that is buffered. * */ Tech.prototype.bufferedPercent = function bufferedPercent() { return (0, _buffer.bufferedPercent)(this.buffered(), this.duration_); }; /** * Turn off the polyfill for `progress` events that was created in * {@link Tech#manualProgressOn} * Stop manually tracking progress events by clearing the interval that was set in * {@link Tech#trackProgress}. */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /** * Polyfill the `timeupdate` event for browsers that don't support it. * * @see {@link Tech#trackCurrentTime} */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Turn off the polyfill for `timeupdate` events that was created in * {@link Tech#manualTimeUpdatesOn} */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Sets up an interval function to track current time and trigger `timeupdate` every * 250 milliseconds. * * @listens Tech#play * @triggers Tech#timeupdate */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { /** * Triggered at an interval of 250ms to indicated that time is passing in the video. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }, 250); }; /** * Stop the interval function created in {@link Tech#trackCurrentTime} so that the * `timeupdate` event is no longer triggered. * * @listens {Tech#pause} */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList}, * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech. * * @fires Component#dispose */ Tech.prototype.dispose = function dispose() { // clear out all tracks because we can't reuse them between techs this.clearTracks(TRACK_TYPES.NORMAL.names); // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * Clear out a single `TrackList` or an array of `TrackLists` given their names. * * > Note: Techs without source handlers should call this between sources for `video` * & `audio` tracks. You don't want to use them between tracks! * * @param {string[]|string} types * TrackList names to clear, valid names are `video`, `audio`, and * `text`. */ Tech.prototype.clearTracks = function clearTracks(types) { var _this2 = this; types = [].concat(types); // clear out all tracks because we can't reuse them between techs types.forEach(function (type) { var list = _this2[type + 'Tracks']() || []; var i = list.length; while (i--) { var track = list[i]; if (type === 'text') { _this2.removeRemoteTextTrack(track); } list.removeTrack(track); } }); }; /** * Remove any TextTracks added via addRemoteTextTrack that are * flagged for automatic garbage collection */ Tech.prototype.cleanupAutoTextTracks = function cleanupAutoTextTracks() { var list = this.autoRemoteTextTracks_ || []; var i = list.length; while (i--) { var track = list[i]; this.removeRemoteTextTrack(track); } }; /** * Reset the tech, which will removes all sources and reset the internal readyState. * * @abstract */ Tech.prototype.reset = function reset() {}; /** * Get or set an error on the Tech. * * @param {MediaError} [err] * Error to set on the Tech * * @return {MediaError|null} * The current error object on the tech, or null if there isn't one. */ Tech.prototype.error = function error(err) { if (err !== undefined) { this.error_ = new _mediaError2['default'](err); this.trigger('error'); } return this.error_; }; /** * Returns the `TimeRange`s that have been played through for the current source. * * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`. * It only checks wether the source has played at all or not. * * @return {TimeRange} * - A single time range if this video has played * - An empty set of ranges if not. */ Tech.prototype.played = function played() { if (this.hasStarted_) { return (0, _timeRanges.createTimeRange)(0, 0); } return (0, _timeRanges.createTimeRange)(); }; /** * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was * previously called. * * @fires Tech#timeupdate */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { /** * A manual `timeupdate` event. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and * {@link TextTrackList} events. * * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`. * * @fires Tech#audiotrackchange * @fires Tech#videotrackchange * @fires Tech#texttrackchange */ Tech.prototype.initTrackListeners = function initTrackListeners() { var _this3 = this; /** * Triggered when tracks are added or removed on the Tech {@link AudioTrackList} * * @event Tech#audiotrackchange * @type {EventTarget~Event} */ /** * Triggered when tracks are added or removed on the Tech {@link VideoTrackList} * * @event Tech#videotrackchange * @type {EventTarget~Event} */ /** * Triggered when tracks are added or removed on the Tech {@link TextTrackList} * * @event Tech#texttrackchange * @type {EventTarget~Event} */ TRACK_TYPES.NORMAL.names.forEach(function (name) { var props = TRACK_TYPES.NORMAL[name]; var trackListChanges = function trackListChanges() { _this3.trigger(name + 'trackchange'); }; var tracks = _this3[props.getterName](); tracks.addEventListener('removetrack', trackListChanges); tracks.addEventListener('addtrack', trackListChanges); _this3.on('dispose', function () { tracks.removeEventListener('removetrack', trackListChanges); tracks.removeEventListener('addtrack', trackListChanges); }); }); }; /** * Emulate TextTracks using vtt.js if necessary * * @fires Tech#vttjsloaded * @fires Tech#vttjserror */ Tech.prototype.addWebVttScript_ = function addWebVttScript_() { var _this4 = this; if (!_window2['default'].WebVTT && this.el().parentNode !== null && this.el().parentNode !== undefined) { var _ret = function () { var vtt = _dereq_(102); // load via require if available and vtt.js script location was not passed in // as an option. novtt builds will turn the above require call into an empty object // which will cause this if check to always fail. if (!_this4.options_['vtt.js'] && (0, _obj.isPlain)(vtt) && Object.keys(vtt).length > 0) { Object.keys(vtt).forEach(function (k) { _window2['default'][k] = vtt[k]; }); _this4.trigger('vttjsloaded'); return { v: void 0 }; } // load vtt.js via the script location option or the cdn of no location was // passed in var script = _document2['default'].createElement('script'); script.src = _this4.options_['vtt.js'] || 'https://cdn.rawgit.com/gkatsev/vtt.js/vjs-v0.12.1/dist/vtt.min.js'; script.onload = function () { /** * Fired when vtt.js is loaded. * * @event Tech#vttjsloaded * @type {EventTarget~Event} */ _this4.trigger('vttjsloaded'); }; script.onerror = function () { /** * Fired when vtt.js was not loaded due to an error * * @event Tech#vttjsloaded * @type {EventTarget~Event} */ _this4.trigger('vttjserror'); }; _this4.on('dispose', function () { script.onload = null; script.onerror = null; }); // but have not loaded yet and we set it to true before the inject so that // we don't overwrite the injected window.WebVTT if it loads right away _window2['default'].WebVTT = true; _this4.el().parentNode.appendChild(script); }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } }; /** * Emulate texttracks * */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { var _this5 = this; var tracks = this.textTracks(); var remoteTracks = this.remoteTextTracks(); var handleAddTrack = function handleAddTrack(e) { return tracks.addTrack(e.track); }; var handleRemoveTrack = function handleRemoveTrack(e) { return tracks.removeTrack(e.track); }; remoteTracks.on('addtrack', handleAddTrack); remoteTracks.on('removetrack', handleRemoveTrack); // Initially, Tech.el_ is a child of a dummy-div wait until the Component system // signals that the Tech is ready at which point Tech.el_ is part of the DOM // before inserting the WebVTT script this.on('ready', this.addWebVttScript_); var updateDisplay = function updateDisplay() { return _this5.trigger('texttrackchange'); }; var textTracksChanges = function textTracksChanges() { updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }; textTracksChanges(); tracks.addEventListener('change', textTracksChanges); this.on('dispose', function () { remoteTracks.off('addtrack', handleAddTrack); remoteTracks.off('removetrack', handleRemoveTrack); tracks.removeEventListener('change', textTracksChanges); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); } }); }; /** * Create and returns a remote {@link TextTrack} object. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @return {TextTrack} * The TextTrack that gets created. */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Create an emulated TextTrack for use by addRemoteTextTrack * * This is intended to be overridden by classes that inherit from * Tech in order to create native or custom TextTracks. * * @param {Object} options * The object should contain the options to initialize the TextTrack with. * * @param {string} [options.kind] * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). * * @param {string} [options.label]. * Label to identify the text track * * @param {string} [options.language] * Two letter language abbreviation. * * @return {HTMLTrackElement} * The track element that gets created. */ Tech.prototype.createRemoteTextTrack = function createRemoteTextTrack(options) { var track = (0, _mergeOptions2['default'])(options, { tech: this }); return new TRACK_TYPES.REMOTE.remoteTextEl.TrackClass(track); }; /** * Creates a remote text track object and returns an html track element. * * > Note: This can be an emulated {@link HTMLTrackElement} or a native one. * * @param {Object} options * See {@link Tech#createRemoteTextTrack} for more detailed properties. * * @param {boolean} [manualCleanup=true] * - When false: the TextTrack will be automatically removed from the video * element whenever the source changes * - When True: The TextTrack will have to be cleaned up manually * * @return {HTMLTrackElement} * An Html Track Element. * * @deprecated The default functionality for this function will be equivalent * to "manualCleanup=false" in the future. The manualCleanup parameter will * also be removed. */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var manualCleanup = arguments[1]; var htmlTrackElement = this.createRemoteTextTrack(options); if (manualCleanup !== true && manualCleanup !== false) { // deprecation warning _log2['default'].warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js'); manualCleanup = true; } // store HTMLTrackElement and TextTrack to remote list this.remoteTextTrackEls().addTrackElement_(htmlTrackElement); this.remoteTextTracks().addTrack(htmlTrackElement.track); if (manualCleanup !== true) { // create the TextTrackList if it doesn't exist this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track); } return htmlTrackElement; }; /** * Remove a remote text track from the remote `TextTrackList`. * * @param {TextTrack} track * `TextTrack` to remove from the `TextTrackList` */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list this.remoteTextTrackEls().removeTrackElement_(trackElement); this.remoteTextTracks().removeTrack(track); this.autoRemoteTextTracks_.removeTrack(track); }; /** * A method to set a poster from a `Tech`. * * @abstract */ Tech.prototype.setPoster = function setPoster() {}; /* * Check if the tech can support the given mime-type. * * The base tech does not support any type, but source handlers might * overwrite this. * * @param {string} type * The mimetype to check for support * * @return {string} * 'probably', 'maybe', or empty string * * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType} * * @abstract */ Tech.prototype.canPlayType = function canPlayType() { return ''; }; /** * Check if the type is supported by this tech. * * The base tech does not support any type, but source handlers might * overwrite this. * * @param {string} type * The media type to check * @return {string} Returns the native video element's response */ Tech.canPlayType = function canPlayType() { return ''; }; /** * Check if the tech can support the given source * @param {Object} srcObj * The source object * @param {Object} options * The options passed to the tech * @return {string} 'probably', 'maybe', or '' (empty string) */ Tech.canPlaySource = function canPlaySource(srcObj, options) { return Tech.canPlayType(srcObj.type); }; /* * Return whether the argument is a Tech or not. * Can be passed either a Class like `Html5` or a instance like `player.tech_` * * @param {Object} component * The item to check * * @return {boolean} * Whether it is a tech or not * - True if it is a tech * - False if it is not */ Tech.isTech = function isTech(component) { return component.prototype instanceof Tech || component instanceof Tech || component === Tech; }; /** * Registers a `Tech` into a shared list for videojs. * * @param {string} name * Name of the `Tech` to register. * * @param {Object} tech * The `Tech` class to register. */ Tech.registerTech = function registerTech(name, tech) { if (!Tech.techs_) { Tech.techs_ = {}; } if (!Tech.isTech(tech)) { throw new Error('Tech ' + name + ' must be a Tech'); } if (!Tech.canPlayType) { throw new Error('Techs must have a static canPlayType method on them'); } if (!Tech.canPlaySource) { throw new Error('Techs must have a static canPlaySource method on them'); } name = (0, _toTitleCase2['default'])(name); Tech.techs_[name] = tech; if (name !== 'Tech') { // camel case the techName for use in techOrder Tech.defaultTechOrder_.push(name); } return tech; }; /** * Get a `Tech` from the shared list by name. * * @param {string} name * `camelCase` or `TitleCase` name of the Tech to get * * @return {Tech|undefined} * The `Tech` or undefined if there was no tech with the name requsted. */ Tech.getTech = function getTech(name) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); if (Tech.techs_ && Tech.techs_[name]) { return Tech.techs_[name]; } if (_window2['default'] && _window2['default'].videojs && _window2['default'].videojs[name]) { _log2['default'].warn('The ' + name + ' tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)'); return _window2['default'].videojs[name]; } }; return Tech; }(_component2['default']); /** * Get the {@link VideoTrackList} * * @returns {VideoTrackList} * @method Tech.prototype.videoTracks */ /** * Get the {@link AudioTrackList} * * @returns {AudioTrackList} * @method Tech.prototype.audioTracks */ /** * Get the {@link TextTrackList} * * @returns {TextTrackList} * @method Tech.prototype.textTracks */ /** * Get the remote element {@link TextTrackList} * * @returns {TextTrackList} * @method Tech.prototype.remoteTextTracks */ /** * Get the remote element {@link HTMLTrackElementList} * * @returns {HTMLTrackElementList} * @method Tech.prototype.remoteTextTrackEls */ TRACK_TYPES.ALL.names.forEach(function (name) { var props = TRACK_TYPES.ALL[name]; Tech.prototype[props.getterName] = function () { this[props.privateName] = this[props.privateName] || new props.ListClass(); return this[props.privateName]; }; }); /** * List of associated text tracks * * @type {TextTrackList} * @private * @property Tech#textTracks_ */ /** * List of associated audio tracks. * * @type {AudioTrackList} * @private * @property Tech#audioTracks_ */ /** * List of associated video tracks. * * @type {VideoTrackList} * @private * @property Tech#videoTracks_ */ /** * Boolean indicating wether the `Tech` supports volume control. * * @type {boolean} * @default */ Tech.prototype.featuresVolumeControl = true; /** * Boolean indicating wether the `Tech` support fullscreen resize control. * Resizing plugins using request fullscreen reloads the plugin * * @type {boolean} * @default */ Tech.prototype.featuresFullscreenResize = false; /** * Boolean indicating wether the `Tech` supports changing the speed at which the video * plays. Examples: * - Set player to play 2x (twice) as fast * - Set player to play 0.5x (half) as fast * * @type {boolean} * @default */ Tech.prototype.featuresPlaybackRate = false; /** * Boolean indicating wether the `Tech` supports the `progress` event. This is currently * not triggered by video-js-swf. This will be used to determine if * {@link Tech#manualProgressOn} should be called. * * @type {boolean} * @default */ Tech.prototype.featuresProgressEvents = false; /** * Boolean indicating wether the `Tech` supports the `timeupdate` event. This is currently * not triggered by video-js-swf. This will be used to determine if * {@link Tech#manualTimeUpdates} should be called. * * @type {boolean} * @default */ Tech.prototype.featuresTimeupdateEvents = false; /** * Boolean indicating wether the `Tech` supports the native `TextTrack`s. * This will help us integrate with native `TextTrack`s if the browser supports them. * * @type {boolean} * @default */ Tech.prototype.featuresNativeTextTracks = false; /** * A functional mixin for techs that want to use the Source Handler pattern. * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * Example: `Tech.withSourceHandlers.call(MyTech);` * * @param {Tech} _Tech * The tech to add source handler functions to. * * @mixes Tech~SourceHandlerAdditions */ Tech.withSourceHandlers = function (_Tech) { /** * Register a source handler * * @param {Function} handler * The source handler class * * @param {number} [index] * Register it at the following index */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /** * Check if the tech can support the given type. Also checks the * Techs sourceHandlers. * * @param {string} type * The mimetype to check. * * @return {string} * 'probably', 'maybe', or '' (empty string) */ _Tech.canPlayType = function (type) { var handlers = _Tech.sourceHandlers || []; var can = void 0; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canPlayType(type); if (can) { return can; } } return ''; }; /** * Returns the first source handler that supports the source. * * TODO: Answer question: should 'probably' be prioritized over 'maybe' * * @param {Tech~SourceObject} source * The source object * * @param {Object} options * The options passed to the tech * * @return {SourceHandler|null} * The first source handler that supports the source or null if * no SourceHandler supports the source */ _Tech.selectSourceHandler = function (source, options) { var handlers = _Tech.sourceHandlers || []; var can = void 0; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source, options); if (can) { return handlers[i]; } } return null; }; /** * Check if the tech can support the given source. * * @param {Tech~SourceObject} srcObj * The source object * * @param {Object} options * The options passed to the tech * * @return {string} * 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj, options) { var sh = _Tech.selectSourceHandler(srcObj, options); if (sh) { return sh.canHandleSource(srcObj, options); } return ''; }; /** * When using a source handler, prefer its implementation of * any function normally provided by the tech. */ var deferrable = ['seekable', 'duration']; /** * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable * function if it exists, with a fallback to the Techs seekable function. * * @method _Tech.seekable */ /** * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration * function if it exists, otherwise it will fallback to the techs duration function. * * @method _Tech.duration */ deferrable.forEach(function (fnName) { var originalFn = this[fnName]; if (typeof originalFn !== 'function') { return; } this[fnName] = function () { if (this.sourceHandler_ && this.sourceHandler_[fnName]) { return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments); } return originalFn.apply(this, arguments); }; }, _Tech.prototype); /** * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * * @param {Tech~SourceObject} source * A source object with src and type keys */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source, this.options_); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { _log2['default'].error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); if (sh !== _Tech.nativeSourceHandler) { this.currentSource_ = source; } this.sourceHandler_ = sh.handleSource(source, this, this.options_); this.on('dispose', this.disposeSourceHandler); }; /** * Clean up any existing SourceHandlers and listeners when the Tech is disposed. * * @listens Tech#dispose */ _Tech.prototype.disposeSourceHandler = function () { // if we have a source and get another one // then we are loading something new // than clear all of our current tracks if (this.currentSource_) { this.clearTracks(['audio', 'video']); this.currentSource_ = null; } // always clean up auto-text tracks this.cleanupAutoTextTracks(); if (this.sourceHandler_) { if (this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } this.sourceHandler_ = null; } }; }; // The base Tech class needs to be registered as a Component. It is the only // Tech that can be registered as a Component. _component2['default'].registerComponent('Tech', Tech); Tech.registerTech('Tech', Tech); /** * A list of techs that should be added to techOrder on Players * * @private */ Tech.defaultTechOrder_ = []; exports['default'] = Tech; },{"102":102,"47":47,"5":5,"75":75,"80":80,"86":86,"89":89,"90":90,"91":91,"93":93,"94":94,"97":97,"98":98}],63:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackList = _dereq_(74); var _trackList2 = _interopRequireDefault(_trackList); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file audio-track-list.js */ /** * Anywhere we call this function we diverge from the spec * as we only support one enabled audiotrack at a time * * @param {AudioTrackList} list * list to work on * * @param {AudioTrack} track * The track to skip * * @private */ var disableOthers = function disableOthers(list, track) { for (var i = 0; i < list.length; i++) { if (track.id === list[i].id) { continue; } // another audio track is enabled, disable it list[i].enabled = false; } }; /** * The current list of {@link AudioTrack} for a media file. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist} * @extends TrackList */ var AudioTrackList = function (_TrackList) { _inherits(AudioTrackList, _TrackList); /** * Create an instance of this class. * * @param {AudioTrack[]} [tracks=[]] * A list of `AudioTrack` to instantiate the list with. */ function AudioTrackList() { var _this, _ret; var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, AudioTrackList); var list = void 0; // make sure only 1 track is enabled // sorted from last index to first index for (var i = tracks.length - 1; i >= 0; i--) { if (tracks[i].enabled) { disableOthers(tracks, tracks[i]); break; } } // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in _trackList2['default'].prototype) { if (prop !== 'constructor') { list[prop] = _trackList2['default'].prototype[prop]; } } for (var _prop in AudioTrackList.prototype) { if (_prop !== 'constructor') { list[_prop] = AudioTrackList.prototype[_prop]; } } } list = (_this = _possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this); list.changing_ = false; return _ret = list, _possibleConstructorReturn(_this, _ret); } /** * Add an {@link AudioTrack} to the `AudioTrackList`. * * @param {AudioTrack} track * The AudioTrack to add to the list * * @fires TrackList#addtrack */ AudioTrackList.prototype.addTrack = function addTrack(track) { var _this2 = this; if (track.enabled) { disableOthers(this, track); } _TrackList.prototype.addTrack.call(this, track); // native tracks don't have this if (!track.addEventListener) { return; } /** * @listens AudioTrack#enabledchange * @fires TrackList#change */ track.addEventListener('enabledchange', function () { // when we are disabling other tracks (since we don't support // more than one track at a time) we will set changing_ // to true so that we don't trigger additional change events if (_this2.changing_) { return; } _this2.changing_ = true; disableOthers(_this2, track); _this2.changing_ = false; _this2.trigger('change'); }); }; return AudioTrackList; }(_trackList2['default']); exports['default'] = AudioTrackList; },{"74":74,"79":79,"97":97}],64:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackEnums = _dereq_(73); var _track = _dereq_(76); var _track2 = _interopRequireDefault(_track); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList} * only one `AudioTrack` in the list will be enabled at a time. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack} * @extends Track */ var AudioTrack = function (_Track) { _inherits(AudioTrack, _Track); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {AudioTrack~Kind} [options.kind=''] * A valid audio track kind * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {boolean} [options.enabled] * If this track is the one that is currently playing. If this track is part of * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled. */ function AudioTrack() { var _this, _ret; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, AudioTrack); var settings = (0, _mergeOptions2['default'])(options, { kind: _trackEnums.AudioTrackKind[options.kind] || '' }); // on IE8 this will be a document element // for every other browser this will be a normal object var track = (_this = _possibleConstructorReturn(this, _Track.call(this, settings)), _this); var enabled = false; if (browser.IS_IE8) { for (var prop in AudioTrack.prototype) { if (prop !== 'constructor') { track[prop] = AudioTrack.prototype[prop]; } } } /** * @memberof AudioTrack * @member {boolean} enabled * If this `AudioTrack` is enabled or not. When setting this will * fire {@link AudioTrack#enabledchange} if the state of enabled is changed. * @instance * * @fires VideoTrack#selectedchange */ Object.defineProperty(track, 'enabled', { get: function get() { return enabled; }, set: function set(newEnabled) { // an invalid or unchanged value if (typeof newEnabled !== 'boolean' || newEnabled === enabled) { return; } enabled = newEnabled; /** * An event that fires when enabled changes on this track. This allows * the AudioTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! Native tracks will do * this internally without an event. * * @event AudioTrack#enabledchange * @type {EventTarget~Event} */ this.trigger('enabledchange'); } }); // if the user sets this track to selected then // set selected to that true value otherwise // we keep it false if (settings.enabled) { track.enabled = settings.enabled; } track.loaded_ = true; return _ret = track, _possibleConstructorReturn(_this, _ret); } return AudioTrack; }(_track2['default']); exports['default'] = AudioTrack; },{"73":73,"76":76,"79":79,"90":90}],65:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @file html-track-element-list.js */ /** * The current list of {@link HtmlTrackElement}s. */ var HtmlTrackElementList = function () { /** * Create an instance of this class. * * @param {HtmlTrackElement[]} [tracks=[]] * A list of `HtmlTrackElement` to instantiate the list with. */ function HtmlTrackElementList() { var trackElements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, HtmlTrackElementList); var list = this; // eslint-disable-line if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in HtmlTrackElementList.prototype) { if (prop !== 'constructor') { list[prop] = HtmlTrackElementList.prototype[prop]; } } } list.trackElements_ = []; /** * @memberof HTMLTrackElementList * @member {number} length * The current number of `Track`s in the this Trackist. * @instance */ Object.defineProperty(list, 'length', { get: function get() { return this.trackElements_.length; } }); for (var i = 0, length = trackElements.length; i < length; i++) { list.addTrackElement_(trackElements[i]); } if (browser.IS_IE8) { return list; } } /** * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList` * * @param {HtmlTrackElement} trackElement * The track element to add to the list. * * @private */ HtmlTrackElementList.prototype.addTrackElement_ = function addTrackElement_(trackElement) { var index = this.trackElements_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.trackElements_[index]; } }); } // Do not add duplicate elements if (this.trackElements_.indexOf(trackElement) === -1) { this.trackElements_.push(trackElement); } }; /** * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an * {@link TextTrack}. * * @param {TextTrack} track * The track associated with a track element. * * @return {HtmlTrackElement|undefined} * The track element that was found or undefined. * * @private */ HtmlTrackElementList.prototype.getTrackElementByTrack_ = function getTrackElementByTrack_(track) { var trackElement_ = void 0; for (var i = 0, length = this.trackElements_.length; i < length; i++) { if (track === this.trackElements_[i].track) { trackElement_ = this.trackElements_[i]; break; } } return trackElement_; }; /** * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList` * * @param {HtmlTrackElement} trackElement * The track element to remove from the list. * * @private */ HtmlTrackElementList.prototype.removeTrackElement_ = function removeTrackElement_(trackElement) { for (var i = 0, length = this.trackElements_.length; i < length; i++) { if (trackElement === this.trackElements_[i]) { this.trackElements_.splice(i, 1); break; } } }; return HtmlTrackElementList; }(); exports['default'] = HtmlTrackElementList; },{"79":79,"97":97}],66:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _eventTarget = _dereq_(43); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _textTrack = _dereq_(72); var _textTrack2 = _interopRequireDefault(_textTrack); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file html-track-element.js */ /** * @memberof HTMLTrackElement * @typedef {HTMLTrackElement~ReadyState} * @enum {number} */ var NONE = 0; var LOADING = 1; var LOADED = 2; var ERROR = 3; /** * A single track represented in the DOM. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement} * @extends EventTarget */ var HTMLTrackElement = function (_EventTarget) { _inherits(HTMLTrackElement, _EventTarget); /** * Create an instance of this class. * * @param {Object} options={} * Object of option names and values * * @param {Tech} options.tech * A reference to the tech that owns this HTMLTrackElement. * * @param {TextTrack~Kind} [options.kind='subtitles'] * A valid text track kind. * * @param {TextTrack~Mode} [options.mode='disabled'] * A valid text track mode. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this TextTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {string} [options.srclang=''] * A valid two character language code. An alternative, but deprioritized * vesion of `options.language` * * @param {string} [options.src] * A url to TextTrack cues. * * @param {boolean} [options.default] * If this track should default to on or off. */ function HTMLTrackElement() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, HTMLTrackElement); var _this = _possibleConstructorReturn(this, _EventTarget.call(this)); var readyState = void 0; var trackElement = _this; // eslint-disable-line if (browser.IS_IE8) { trackElement = _document2['default'].createElement('custom'); for (var prop in HTMLTrackElement.prototype) { if (prop !== 'constructor') { trackElement[prop] = HTMLTrackElement.prototype[prop]; } } } var track = new _textTrack2['default'](options); trackElement.kind = track.kind; trackElement.src = track.src; trackElement.srclang = track.language; trackElement.label = track.label; trackElement['default'] = track['default']; /** * @memberof HTMLTrackElement * @member {HTMLTrackElement~ReadyState} readyState * The current ready state of the track element. * @instance */ Object.defineProperty(trackElement, 'readyState', { get: function get() { return readyState; } }); /** * @memberof HTMLTrackElement * @member {TextTrack} track * The underlying TextTrack object. * @instance * */ Object.defineProperty(trackElement, 'track', { get: function get() { return track; } }); readyState = NONE; /** * @listens TextTrack#loadeddata * @fires HTMLTrackElement#load */ track.addEventListener('loadeddata', function () { readyState = LOADED; trackElement.trigger({ type: 'load', target: trackElement }); }); if (browser.IS_IE8) { var _ret; return _ret = trackElement, _possibleConstructorReturn(_this, _ret); } return _this; } return HTMLTrackElement; }(_eventTarget2['default']); HTMLTrackElement.prototype.allowedEvents_ = { load: 'load' }; HTMLTrackElement.NONE = NONE; HTMLTrackElement.LOADING = LOADING; HTMLTrackElement.LOADED = LOADED; HTMLTrackElement.ERROR = ERROR; exports['default'] = HTMLTrackElement; },{"43":43,"72":72,"79":79,"97":97}],67:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @file text-track-cue-list.js */ /** * @typedef {Object} TextTrackCueList~TextTrackCue * * @property {string} id * The unique id for this text track cue * * @property {number} startTime * The start time for this text track cue * * @property {number} endTime * The end time for this text track cue * * @property {boolean} pauseOnExit * Pause when the end time is reached if true. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue} */ /** * A List of TextTrackCues. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist} */ var TextTrackCueList = function () { /** * Create an instance of this class.. * * @param {Array} cues * A list of cues to be initialized with */ function TextTrackCueList(cues) { _classCallCheck(this, TextTrackCueList); var list = this; // eslint-disable-line if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in TextTrackCueList.prototype) { if (prop !== 'constructor') { list[prop] = TextTrackCueList.prototype[prop]; } } } TextTrackCueList.prototype.setCues_.call(list, cues); /** * @memberof TextTrackCueList * @member {number} length * The current number of `TextTrackCue`s in the TextTrackCueList. * @instance */ Object.defineProperty(list, 'length', { get: function get() { return this.length_; } }); if (browser.IS_IE8) { return list; } } /** * A setter for cues in this list. Creates getters * an an index for the cues. * * @param {Array} cues * An array of cues to set * * @private */ TextTrackCueList.prototype.setCues_ = function setCues_(cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(index) { if (!('' + index in this)) { Object.defineProperty(this, '' + index, { get: function get() { return this.cues_[index]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } }; /** * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id. * * @param {string} id * The id of the cue that should be searched for. * * @return {TextTrackCueList~TextTrackCue|null} * A single cue or null if none was found. */ TextTrackCueList.prototype.getCueById = function getCueById(id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; return TextTrackCueList; }(); exports['default'] = TextTrackCueList; },{"79":79,"97":97}],68:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file text-track-display.js */ var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * Construct an rgba color from a given hex color code. * * @param {number} color * Hex number for color, like #f0e. * * @param {number} opacity * Value for opacity, 0.0 - 1.0. * * @return {string} * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'. * * @private */ function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; } /** * Try to update the style of a DOM element. Some style changes will throw an error, * particularly in IE8. Those should be noops. * * @param {Element} el * The DOM element to be styled. * * @param {string} style * The CSS property on the element that should be styled. * * @param {string} rule * The style rule that should be applied to the property. * * @private */ function tryUpdateStyle(el, style, rule) { try { el.style[style] = rule; } catch (e) { // Satisfies linter. return; } } /** * The component for displaying text track cues. * * @extends Component */ var TextTrackDisplay = function (_Component) { _inherits(TextTrackDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when `TextTrackDisplay` is ready. */ function TextTrackDisplay(player, options, ready) { _classCallCheck(this, TextTrackDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options, ready)); player.on('loadstart', Fn.bind(_this, _this.toggleDisplay)); player.on('texttrackchange', Fn.bind(_this, _this.updateDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(Fn.bind(_this, function () { if (player.tech_ && player.tech_.featuresNativeTextTracks) { this.hide(); return; } player.on('fullscreenchange', Fn.bind(this, this.updateDisplay)); var tracks = this.options_.playerOptions.tracks || []; for (var i = 0; i < tracks.length; i++) { this.player_.addRemoteTextTrack(tracks[i], true); } var modes = { captions: 1, subtitles: 1 }; var trackList = this.player_.textTracks(); var firstDesc = void 0; var firstCaptions = void 0; for (var _i = 0; _i < trackList.length; _i++) { var track = trackList[_i]; if (track['default']) { if (track.kind === 'descriptions' && !firstDesc) { firstDesc = track; } else if (track.kind in modes && !firstCaptions) { firstCaptions = track; } } } // We want to show the first default track but captions and subtitles // take precedence over descriptions. // So, display the first default captions or subtitles track // and otherwise the first default descriptions track. if (firstCaptions) { firstCaptions.mode = 'showing'; } else if (firstDesc) { firstDesc.mode = 'showing'; } })); return _this; } /** * Turn display of {@link TextTrack}'s from the current state into the other state. * There are only two states: * - 'shown' * - 'hidden' * * @listens Player#loadstart */ TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() { if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) { this.hide(); } else { this.show(); } }; /** * Create the {@link Component}'s DOM element. * * @return {Element} * The element that was created. */ TextTrackDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }, { 'aria-live': 'off', 'aria-atomic': 'true' }); }; /** * Clear all displayed {@link TextTrack}s. */ TextTrackDisplay.prototype.clearDisplay = function clearDisplay() { if (typeof _window2['default'].WebVTT === 'function') { _window2['default'].WebVTT.processCues(_window2['default'], [], this.el_); } }; /** * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or * a {@link Player#fullscreenchange} is fired. * * @listens Player#texttrackchange * @listens Player#fullscreenchange */ TextTrackDisplay.prototype.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); this.clearDisplay(); // Track display prioritization model: if multiple tracks are 'showing', // display the first 'subtitles' or 'captions' track which is 'showing', // otherwise display the first 'descriptions' track which is 'showing' var descriptionsTrack = null; var captionsSubtitlesTrack = null; var i = tracks.length; while (i--) { var track = tracks[i]; if (track.mode === 'showing') { if (track.kind === 'descriptions') { descriptionsTrack = track; } else { captionsSubtitlesTrack = track; } } } if (captionsSubtitlesTrack) { if (this.getAttribute('aria-live') !== 'off') { this.setAttribute('aria-live', 'off'); } this.updateForTrack(captionsSubtitlesTrack); } else if (descriptionsTrack) { if (this.getAttribute('aria-live') !== 'assertive') { this.setAttribute('aria-live', 'assertive'); } this.updateForTrack(descriptionsTrack); } }; /** * Add an {@link Texttrack} to to the {@link Tech}s {@link TextTrackList}. * * @param {TextTrack} track * Text track object to be added to the list. */ TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) { if (typeof _window2['default'].WebVTT !== 'function' || !track.activeCues) { return; } var overrides = this.player_.textTrackSettings.getValues(); var cues = []; for (var _i2 = 0; _i2 < track.activeCues.length; _i2++) { cues.push(track.activeCues[_i2]); } _window2['default'].WebVTT.processCues(_window2['default'], cues, this.el_); var i = cues.length; while (i--) { var cue = cues[i]; if (!cue) { continue; } var cueDiv = cue.displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = _window2['default'].parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; return TextTrackDisplay; }(_component2['default']); _component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay); exports['default'] = TextTrackDisplay; },{"5":5,"86":86,"98":98}],69:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file text-track-list-converter.js Utilities for capturing text track state and * re-creating tracks based on a capture. * * @module text-track-list-converter */ /** * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that * represents the {@link TextTrack}'s state. * * @param {TextTrack} track * The text track to query. * * @return {Object} * A serializable javascript representation of the TextTrack. * @private */ var trackToJson_ = function trackToJson_(track) { var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) { if (track[prop]) { acc[prop] = track[prop]; } return acc; }, { cues: track.cues && Array.prototype.map.call(track.cues, function (cue) { return { startTime: cue.startTime, endTime: cue.endTime, text: cue.text, id: cue.id }; }) }); return ret; }; /** * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the * state of all {@link TextTrack}s currently configured. The return array is compatible with * {@link text-track-list-converter:jsonToTextTracks}. * * @param {Tech} tech * The tech object to query * * @return {Array} * A serializable javascript representation of the {@link Tech}s * {@link TextTrackList}. */ var textTracksToJson = function textTracksToJson(tech) { var trackEls = tech.$$('track'); var trackObjs = Array.prototype.map.call(trackEls, function (t) { return t.track; }); var tracks = Array.prototype.map.call(trackEls, function (trackEl) { var json = trackToJson_(trackEl.track); if (trackEl.src) { json.src = trackEl.src; } return json; }); return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) { return trackObjs.indexOf(track) === -1; }).map(trackToJson_)); }; /** * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript * object {@link TextTrack} representations. * * @param {Array} json * An array of `TextTrack` representation objects, like those that would be * produced by `textTracksToJson`. * * @param {Tech} tech * The `Tech` to create the `TextTrack`s on. */ var jsonToTextTracks = function jsonToTextTracks(json, tech) { json.forEach(function (track) { var addedTrack = tech.addRemoteTextTrack(track).track; if (!track.src && track.cues) { track.cues.forEach(function (cue) { return addedTrack.addCue(cue); }); } }); return tech.textTracks(); }; exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ }; },{}],70:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackList = _dereq_(74); var _trackList2 = _interopRequireDefault(_trackList); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file text-track-list.js */ /** * The current list of {@link TextTrack} for a media file. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist} * @extends TrackList */ var TextTrackList = function (_TrackList) { _inherits(TextTrackList, _TrackList); /** * Create an instance of this class. * * @param {TextTrack[]} [tracks=[]] * A list of `TextTrack` to instantiate the list with. */ function TextTrackList() { var _this, _ret; var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, TextTrackList); var list = void 0; // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in _trackList2['default'].prototype) { if (prop !== 'constructor') { list[prop] = _trackList2['default'].prototype[prop]; } } for (var _prop in TextTrackList.prototype) { if (_prop !== 'constructor') { list[_prop] = TextTrackList.prototype[_prop]; } } } list = (_this = _possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this); return _ret = list, _possibleConstructorReturn(_this, _ret); } /** * Add a {@link TextTrack} to the `TextTrackList` * * @param {TextTrack} track * The text track to add to the list. * * @fires TrackList#addtrack */ TextTrackList.prototype.addTrack = function addTrack(track) { _TrackList.prototype.addTrack.call(this, track); /** * @listens TextTrack#modechange * @fires TrackList#change */ track.addEventListener('modechange', Fn.bind(this, function () { this.trigger('change'); })); }; return TextTrackList; }(_trackList2['default']); exports['default'] = TextTrackList; },{"74":74,"79":79,"86":86,"97":97}],71:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(83); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _obj = _dereq_(91); var Obj = _interopRequireWildcard(_obj); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file text-track-settings.js */ var LOCAL_STORAGE_KEY = 'vjs-text-track-settings'; var COLOR_BLACK = ['#000', 'Black']; var COLOR_BLUE = ['#00F', 'Blue']; var COLOR_CYAN = ['#0FF', 'Cyan']; var COLOR_GREEN = ['#0F0', 'Green']; var COLOR_MAGENTA = ['#F0F', 'Magenta']; var COLOR_RED = ['#F00', 'Red']; var COLOR_WHITE = ['#FFF', 'White']; var COLOR_YELLOW = ['#FF0', 'Yellow']; var OPACITY_OPAQUE = ['1', 'Opaque']; var OPACITY_SEMI = ['0.5', 'Semi-Transparent']; var OPACITY_TRANS = ['0', 'Transparent']; // Configuration for the various <select> elements in the DOM of this component. // // Possible keys include: // // `default`: // The default option index. Only needs to be provided if not zero. // `parser`: // A function which is used to parse the value from the selected option in // a customized way. // `selector`: // The selector used to find the associated <select> element. var selectConfigs = { backgroundColor: { selector: '.vjs-bg-color > select', id: 'captions-background-color-%s', label: 'Color', options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN] }, backgroundOpacity: { selector: '.vjs-bg-opacity > select', id: 'captions-background-opacity-%s', label: 'Transparency', options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS] }, color: { selector: '.vjs-fg-color > select', id: 'captions-foreground-color-%s', label: 'Color', options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN] }, edgeStyle: { selector: '.vjs-edge-style > select', id: '%s', label: 'Text Edge Style', options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']] }, fontFamily: { selector: '.vjs-font-family > select', id: 'captions-font-family-%s', label: 'Font Family', options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']] }, fontPercent: { selector: '.vjs-font-percent > select', id: 'captions-font-size-%s', label: 'Font Size', options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']], 'default': 2, parser: function parser(v) { return v === '1.00' ? null : Number(v); } }, textOpacity: { selector: '.vjs-text-opacity > select', id: 'captions-foreground-opacity-%s', label: 'Transparency', options: [OPACITY_OPAQUE, OPACITY_SEMI] }, // Options for this object are defined below. windowColor: { selector: '.vjs-window-color > select', id: 'captions-window-color-%s', label: 'Color' }, // Options for this object are defined below. windowOpacity: { selector: '.vjs-window-opacity > select', id: 'captions-window-opacity-%s', label: 'Transparency', options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE] } }; selectConfigs.windowColor.options = selectConfigs.backgroundColor.options; /** * Get the actual value of an option. * * @param {string} value * The value to get * * @param {Function} [parser] * Optional function to adjust the value. * * @return {Mixed} * - Will be `undefined` if no value exists * - Will be `undefined` if the given value is "none". * - Will be the actual value otherwise. * * @private */ function parseOptionValue(value, parser) { if (parser) { value = parser(value); } if (value && value !== 'none') { return value; } } /** * Gets the value of the selected <option> element within a <select> element. * * @param {Element} el * the element to look in * * @param {Function} [parser] * Optional function to adjust the value. * * @return {Mixed} * - Will be `undefined` if no value exists * - Will be `undefined` if the given value is "none". * - Will be the actual value otherwise. * * @private */ function getSelectedOptionValue(el, parser) { var value = el.options[el.options.selectedIndex].value; return parseOptionValue(value, parser); } /** * Sets the selected <option> element within a <select> element based on a * given value. * * @param {Element} el * The element to look in. * * @param {string} value * the property to look on. * * @param {Function} [parser] * Optional function to adjust the value before comparing. * * @private */ function setSelectedOption(el, value, parser) { if (!value) { return; } for (var i = 0; i < el.options.length; i++) { if (parseOptionValue(el.options[i].value, parser) === value) { el.selectedIndex = i; break; } } } /** * Manipulate Text Tracks settings. * * @extends Component */ var TextTrackSettings = function (_Component) { _inherits(TextTrackSettings, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TextTrackSettings(player, options) { _classCallCheck(this, TextTrackSettings); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.setDefaults(); _this.hide(); _this.updateDisplay = Fn.bind(_this, _this.updateDisplay); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { _this.options_.persistTextTrackSettings = _this.options_.playerOptions.persistTextTrackSettings; } _this.on(_this.$('.vjs-done-button'), 'click', function () { _this.saveSettings(); _this.hide(); }); _this.on(_this.$('.vjs-default-button'), 'click', function () { _this.setDefaults(); _this.updateDisplay(); }); Obj.each(selectConfigs, function (config) { _this.on(_this.$(config.selector), 'change', _this.updateDisplay); }); if (_this.options_.persistTextTrackSettings) { _this.restoreSettings(); } return _this; } /** * Create a <select> element with configured options. * * @param {string} key * Configuration key to use during creation. * * @return {Element} * The DOM element that gets created. * @private */ TextTrackSettings.prototype.createElSelect_ = function createElSelect_(key) { var _this2 = this; var config = selectConfigs[key]; var id = config.id.replace('%s', this.id_); return [(0, _dom.createEl)('label', { className: 'vjs-label', textContent: this.localize(config.label) }, { 'for': id }), (0, _dom.createEl)('select', { id: id }, undefined, config.options.map(function (o) { return (0, _dom.createEl)('option', { textContent: _this2.localize(o[1]), value: o[0] }); }))]; }; /** * Create foreground color element for the component * * @return {Element} * The element that was created. * * @private */ TextTrackSettings.prototype.createElFgColor_ = function createElFgColor_() { var legend = (0, _dom.createEl)('legend', { textContent: this.localize('Text') }); var select = this.createElSelect_('color'); var opacity = (0, _dom.createEl)('span', { className: 'vjs-text-opacity vjs-opacity' }, undefined, this.createElSelect_('textOpacity')); return (0, _dom.createEl)('fieldset', { className: 'vjs-fg-color vjs-tracksetting' }, undefined, [legend].concat(select, opacity)); }; /** * Create background color element for the component * * @return {Element} * The element that was created * * @private */ TextTrackSettings.prototype.createElBgColor_ = function createElBgColor_() { var legend = (0, _dom.createEl)('legend', { textContent: this.localize('Background') }); var select = this.createElSelect_('backgroundColor'); var opacity = (0, _dom.createEl)('span', { className: 'vjs-bg-opacity vjs-opacity' }, undefined, this.createElSelect_('backgroundOpacity')); return (0, _dom.createEl)('fieldset', { className: 'vjs-bg-color vjs-tracksetting' }, undefined, [legend].concat(select, opacity)); }; /** * Create window color element for the component * * @return {Element} * The element that was created * * @private */ TextTrackSettings.prototype.createElWinColor_ = function createElWinColor_() { var legend = (0, _dom.createEl)('legend', { textContent: this.localize('Window') }); var select = this.createElSelect_('windowColor'); var opacity = (0, _dom.createEl)('span', { className: 'vjs-window-opacity vjs-opacity' }, undefined, this.createElSelect_('windowOpacity')); return (0, _dom.createEl)('fieldset', { className: 'vjs-window-color vjs-tracksetting' }, undefined, [legend].concat(select, opacity)); }; /** * Create color elements for the component * * @return {Element} * The element that was created * * @private */ TextTrackSettings.prototype.createElColors_ = function createElColors_() { return (0, _dom.createEl)('div', { className: 'vjs-tracksettings-colors' }, undefined, [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()]); }; /** * Create font elements for the component * * @return {Element} * The element that was created. * * @private */ TextTrackSettings.prototype.createElFont_ = function createElFont_() { var fontPercent = (0, _dom.createEl)('div', { className: 'vjs-font-percent vjs-tracksetting' }, undefined, this.createElSelect_('fontPercent')); var edgeStyle = (0, _dom.createEl)('div', { className: 'vjs-edge-style vjs-tracksetting' }, undefined, this.createElSelect_('edgeStyle')); var fontFamily = (0, _dom.createEl)('div', { className: 'vjs-font-family vjs-tracksetting' }, undefined, this.createElSelect_('fontFamily')); return (0, _dom.createEl)('div', { className: 'vjs-tracksettings-font' }, undefined, [fontPercent, edgeStyle, fontFamily]); }; /** * Create controls for the component * * @return {Element} * The element that was created. * * @private */ TextTrackSettings.prototype.createElControls_ = function createElControls_() { var defaultsButton = (0, _dom.createEl)('button', { className: 'vjs-default-button', textContent: this.localize('Defaults') }); var doneButton = (0, _dom.createEl)('button', { className: 'vjs-done-button', textContent: this.localize('Done') }); return (0, _dom.createEl)('div', { className: 'vjs-tracksettings-controls' }, undefined, [defaultsButton, doneButton]); }; /** * Create the component's DOM element * * @return {Element} * The element that was created. */ TextTrackSettings.prototype.createEl = function createEl() { var settings = (0, _dom.createEl)('div', { className: 'vjs-tracksettings' }, undefined, [this.createElColors_(), this.createElFont_(), this.createElControls_()]); var heading = (0, _dom.createEl)('div', { className: 'vjs-control-text', id: 'TTsettingsDialogLabel-' + this.id_, textContent: this.localize('Caption Settings Dialog') }, { 'aria-level': '1', 'role': 'heading' }); var description = (0, _dom.createEl)('div', { className: 'vjs-control-text', id: 'TTsettingsDialogDescription-' + this.id_, textContent: this.localize('Beginning of dialog window. Escape will cancel and close the window.') }); var doc = (0, _dom.createEl)('div', undefined, { role: 'document' }, [heading, description, settings]); return (0, _dom.createEl)('div', { className: 'vjs-caption-settings vjs-modal-overlay', tabIndex: -1 }, { 'role': 'dialog', 'aria-labelledby': heading.id, 'aria-describedby': description.id }, doc); }; /** * Gets an object of text track settings (or null). * * @return {Object} * An object with config values parsed from the DOM or localStorage. */ TextTrackSettings.prototype.getValues = function getValues() { var _this3 = this; return Obj.reduce(selectConfigs, function (accum, config, key) { var value = getSelectedOptionValue(_this3.$(config.selector), config.parser); if (value !== undefined) { accum[key] = value; } return accum; }, {}); }; /** * Sets text track settings from an object of values. * * @param {Object} values * An object with config values parsed from the DOM or localStorage. */ TextTrackSettings.prototype.setValues = function setValues(values) { var _this4 = this; Obj.each(selectConfigs, function (config, key) { setSelectedOption(_this4.$(config.selector), values[key], config.parser); }); }; /** * Sets all <select> elements to their default values. */ TextTrackSettings.prototype.setDefaults = function setDefaults() { var _this5 = this; Obj.each(selectConfigs, function (config) { var index = config.hasOwnProperty('default') ? config['default'] : 0; _this5.$(config.selector).selectedIndex = index; }); }; /** * Restore texttrack settings from localStorage */ TextTrackSettings.prototype.restoreSettings = function restoreSettings() { var values = void 0; try { values = JSON.parse(_window2['default'].localStorage.getItem(LOCAL_STORAGE_KEY)); } catch (err) { _log2['default'].warn(err); } if (values) { this.setValues(values); } }; /** * Save text track settings to localStorage */ TextTrackSettings.prototype.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.keys(values).length) { _window2['default'].localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(values)); } else { _window2['default'].localStorage.removeItem(LOCAL_STORAGE_KEY); } } catch (err) { _log2['default'].warn(err); } }; /** * Update display of text track settings */ TextTrackSettings.prototype.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; return TextTrackSettings; }(_component2['default']); _component2['default'].registerComponent('TextTrackSettings', TextTrackSettings); exports['default'] = TextTrackSettings; },{"5":5,"83":83,"86":86,"89":89,"91":91,"98":98}],72:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackCueList = _dereq_(67); var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _trackEnums = _dereq_(73); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _track = _dereq_(76); var _track2 = _interopRequireDefault(_track); var _url = _dereq_(95); var _xhr = _dereq_(108); var _xhr2 = _interopRequireDefault(_xhr); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file text-track.js */ /** * Takes a webvtt file contents and parses it into cues * * @param {string} srcContent * webVTT file contents * * @param {TextTrack} track * TextTrack to add cues to. Cues come from the srcContent. * * @private */ var parseCues = function parseCues(srcContent, track) { var parser = new _window2['default'].WebVTT.Parser(_window2['default'], _window2['default'].vttjs, _window2['default'].WebVTT.StringDecoder()); var errors = []; parser.oncue = function (cue) { track.addCue(cue); }; parser.onparsingerror = function (error) { errors.push(error); }; parser.onflush = function () { track.trigger({ type: 'loadeddata', target: track }); }; parser.parse(srcContent); if (errors.length > 0) { if (_window2['default'].console && _window2['default'].console.groupCollapsed) { _window2['default'].console.groupCollapsed('Text Track parsing errors for ' + track.src); } errors.forEach(function (error) { return _log2['default'].error(error); }); if (_window2['default'].console && _window2['default'].console.groupEnd) { _window2['default'].console.groupEnd(); } } parser.flush(); }; /** * Load a `TextTrack` from a specifed url. * * @param {string} src * Url to load track from. * * @param {TextTrack} track * Track to add cues to. Comes from the content at the end of `url`. * * @private */ var loadTrack = function loadTrack(src, track) { var opts = { uri: src }; var crossOrigin = (0, _url.isCrossOrigin)(src); if (crossOrigin) { opts.cors = crossOrigin; } (0, _xhr2['default'])(opts, Fn.bind(this, function (err, response, responseBody) { if (err) { return _log2['default'].error(err, response); } track.loaded_ = true; // Make sure that vttjs has loaded, otherwise, wait till it finished loading // NOTE: this is only used for the alt/video.novtt.js build if (typeof _window2['default'].WebVTT !== 'function') { if (track.tech_) { (function () { var loadHandler = function loadHandler() { return parseCues(responseBody, track); }; track.tech_.on('vttjsloaded', loadHandler); track.tech_.on('vttjserror', function () { _log2['default'].error('vttjs failed to load, stopping trying to process ' + track.src); track.tech_.off('vttjsloaded', loadHandler); }); })(); } } else { parseCues(responseBody, track); } })); }; /** * A representation of a single `TextTrack`. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack} * @extends Track */ var TextTrack = function (_Track) { _inherits(TextTrack, _Track); /** * Create an instance of this class. * * @param {Object} options={} * Object of option names and values * * @param {Tech} options.tech * A reference to the tech that owns this TextTrack. * * @param {TextTrack~Kind} [options.kind='subtitles'] * A valid text track kind. * * @param {TextTrack~Mode} [options.mode='disabled'] * A valid text track mode. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this TextTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {string} [options.srclang=''] * A valid two character language code. An alternative, but deprioritized * vesion of `options.language` * * @param {string} [options.src] * A url to TextTrack cues. * * @param {boolean} [options.default] * If this track should default to on or off. */ function TextTrack() { var _this, _ret2; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, TextTrack); if (!options.tech) { throw new Error('A tech was not provided.'); } var settings = (0, _mergeOptions2['default'])(options, { kind: _trackEnums.TextTrackKind[options.kind] || 'subtitles', language: options.language || options.srclang || '' }); var mode = _trackEnums.TextTrackMode[settings.mode] || 'disabled'; var default_ = settings['default']; if (settings.kind === 'metadata' || settings.kind === 'chapters') { mode = 'hidden'; } // on IE8 this will be a document element // for every other browser this will be a normal object var tt = (_this = _possibleConstructorReturn(this, _Track.call(this, settings)), _this); tt.tech_ = settings.tech; if (browser.IS_IE8) { for (var prop in TextTrack.prototype) { if (prop !== 'constructor') { tt[prop] = TextTrack.prototype[prop]; } } } tt.cues_ = []; tt.activeCues_ = []; var cues = new _textTrackCueList2['default'](tt.cues_); var activeCues = new _textTrackCueList2['default'](tt.activeCues_); var changed = false; var timeupdateHandler = Fn.bind(tt, function () { // Accessing this.activeCues for the side-effects of updating itself // due to it's nature as a getter function. Do not remove or cues will // stop updating! /* eslint-disable no-unused-expressions */ this.activeCues; /* eslint-enable no-unused-expressions */ if (changed) { this.trigger('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.tech_.on('timeupdate', timeupdateHandler); } /** * @memberof TextTrack * @member {boolean} default * If this track was set to be on or off by default. Cannot be changed after * creation. * @instance * * @readonly */ Object.defineProperty(tt, 'default', { get: function get() { return default_; }, set: function set() {} }); /** * @memberof TextTrack * @member {string} mode * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will * not be set if setting to an invalid mode. * @instance * * @fires TextTrack#modechange */ Object.defineProperty(tt, 'mode', { get: function get() { return mode; }, set: function set(newMode) { if (!_trackEnums.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.tech_.on('timeupdate', timeupdateHandler); } /** * An event that fires when mode changes on this track. This allows * the TextTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! * * @event TextTrack#modechange * @type {EventTarget~Event} */ this.trigger('modechange'); } }); /** * @memberof TextTrack * @member {TextTrackCueList} cues * The text track cue list for this TextTrack. * @instance */ Object.defineProperty(tt, 'cues', { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: function set() {} }); /** * @memberof TextTrack * @member {TextTrackCueList} activeCues * The list text track cues that are currently active for this TextTrack. * @instance */ Object.defineProperty(tt, 'activeCues', { get: function get() { if (!this.loaded_) { return null; } // nothing to do if (this.cues.length === 0) { return activeCues; } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this.cues.length; i < l; i++) { var cue = this.cues[i]; if (cue.startTime <= ct && cue.endTime >= ct) { active.push(cue); } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var _i = 0; _i < active.length; _i++) { if (this.activeCues_.indexOf(active[_i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: function set() {} }); if (settings.src) { tt.src = settings.src; loadTrack(settings.src, tt); } else { tt.loaded_ = true; } return _ret2 = tt, _possibleConstructorReturn(_this, _ret2); } /** * Add a cue to the internal list of cues. * * @param {TextTrack~Cue} cue * The cue to add to our internal list */ TextTrack.prototype.addCue = function addCue(cue) { var tracks = this.tech_.textTracks(); for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } this.cues_.push(cue); this.cues.setCues_(this.cues_); }; /** * Remove a cue from our internal list * * @param {TextTrack~Cue} removeCue * The cue to remove from our internal list */ TextTrack.prototype.removeCue = function removeCue(_removeCue) { var removed = false; for (var i = 0, l = this.cues_.length; i < l; i++) { var cue = this.cues_[i]; if (cue === _removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; return TextTrack; }(_track2['default']); /** * cuechange - One or more cues in the track have become active or stopped being active. */ TextTrack.prototype.allowedEvents_ = { cuechange: 'cuechange' }; exports['default'] = TextTrack; },{"108":108,"67":67,"73":73,"76":76,"79":79,"86":86,"89":89,"90":90,"95":95,"98":98}],73:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file track-kinds.js */ /** * All possible `VideoTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind * @typedef VideoTrack~Kind * @enum */ var VideoTrackKind = exports.VideoTrackKind = { alternative: 'alternative', captions: 'captions', main: 'main', sign: 'sign', subtitles: 'subtitles', commentary: 'commentary' }; /** * All possible `AudioTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind * @typedef AudioTrack~Kind * @enum */ var AudioTrackKind = exports.AudioTrackKind = { 'alternative': 'alternative', 'descriptions': 'descriptions', 'main': 'main', 'main-desc': 'main-desc', 'translation': 'translation', 'commentary': 'commentary' }; /** * All possible `TextTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind * @typedef TextTrack~Kind * @enum */ var TextTrackKind = exports.TextTrackKind = { subtitles: 'subtitles', captions: 'captions', descriptions: 'descriptions', chapters: 'chapters', metadata: 'metadata' }; /** * All possible `TextTrackMode`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * @typedef TextTrack~Mode * @enum */ var TextTrackMode = exports.TextTrackMode = { disabled: 'disabled', hidden: 'hidden', showing: 'showing' }; },{}],74:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _eventTarget = _dereq_(43); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file track-list.js */ /** * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and * {@link VideoTrackList} * * @extends EventTarget */ var TrackList = function (_EventTarget) { _inherits(TrackList, _EventTarget); /** * Create an instance of this class * * @param {Track[]} tracks * A list of tracks to initialize the list with. * * @param {Object} [list] * The child object with inheritance done manually for ie8. * * @abstract */ function TrackList() { var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var _ret; var list = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; _classCallCheck(this, TrackList); var _this = _possibleConstructorReturn(this, _EventTarget.call(this)); if (!list) { list = _this; // eslint-disable-line if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in TrackList.prototype) { if (prop !== 'constructor') { list[prop] = TrackList.prototype[prop]; } } } } list.tracks_ = []; /** * @memberof TrackList * @member {number} length * The current number of `Track`s in the this Trackist. * @instance */ Object.defineProperty(list, 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { list.addTrack(tracks[i]); } // must return the object, as for ie8 it will not be this // but a reference to a document object return _ret = list, _possibleConstructorReturn(_this, _ret); } /** * Add a {@link Track} to the `TrackList` * * @param {Track} track * The audio, video, or text track to add to the list. * * @fires TrackList#addtrack */ TrackList.prototype.addTrack = function addTrack(track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } // Do not add duplicate tracks if (this.tracks_.indexOf(track) === -1) { this.tracks_.push(track); /** * Triggered when a track is added to a track list. * * @event TrackList#addtrack * @type {EventTarget~Event} * @property {Track} track * A reference to track that was added. */ this.trigger({ track: track, type: 'addtrack' }); } }; /** * Remove a {@link Track} from the `TrackList` * * @param {Track} rtrack * The audio, video, or text track to remove from the list. * * @fires TrackList#removetrack */ TrackList.prototype.removeTrack = function removeTrack(rtrack) { var track = void 0; for (var i = 0, l = this.length; i < l; i++) { if (this[i] === rtrack) { track = this[i]; if (track.off) { track.off(); } this.tracks_.splice(i, 1); break; } } if (!track) { return; } /** * Triggered when a track is removed from track list. * * @event TrackList#removetrack * @type {EventTarget~Event} * @property {Track} track * A reference to track that was removed. */ this.trigger({ track: track, type: 'removetrack' }); }; /** * Get a Track from the TrackList by a tracks id * * @param {String} id - the id of the track to get * @method getTrackById * @return {Track} * @private */ TrackList.prototype.getTrackById = function getTrackById(id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; return TrackList; }(_eventTarget2['default']); /** * Triggered when a different track is selected/enabled. * * @event TrackList#change * @type {EventTarget~Event} */ /** * Events that can be called with on + eventName. See {@link EventHandler}. * * @property {Object} TrackList#allowedEvents_ * @private */ TrackList.prototype.allowedEvents_ = { change: 'change', addtrack: 'addtrack', removetrack: 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var event in TrackList.prototype.allowedEvents_) { TrackList.prototype['on' + event] = null; } exports['default'] = TrackList; },{"43":43,"79":79,"97":97}],75:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.ALL = exports.REMOTE = exports.NORMAL = undefined; var _audioTrackList = _dereq_(63); var _audioTrackList2 = _interopRequireDefault(_audioTrackList); var _videoTrackList = _dereq_(77); var _videoTrackList2 = _interopRequireDefault(_videoTrackList); var _textTrackList = _dereq_(70); var _textTrackList2 = _interopRequireDefault(_textTrackList); var _htmlTrackElementList = _dereq_(65); var _htmlTrackElementList2 = _interopRequireDefault(_htmlTrackElementList); var _textTrack = _dereq_(72); var _textTrack2 = _interopRequireDefault(_textTrack); var _audioTrack = _dereq_(64); var _audioTrack2 = _interopRequireDefault(_audioTrack); var _videoTrack = _dereq_(78); var _videoTrack2 = _interopRequireDefault(_videoTrack); var _htmlTrackElement = _dereq_(66); var _htmlTrackElement2 = _interopRequireDefault(_htmlTrackElement); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This file contains all track properties that are used in * player.js, tech.js, html5.js and possibly other techs in the future. */ var NORMAL = { audio: { ListClass: _audioTrackList2['default'], TrackClass: _audioTrack2['default'], capitalName: 'Audio' }, video: { ListClass: _videoTrackList2['default'], TrackClass: _videoTrack2['default'], capitalName: 'Video' }, text: { ListClass: _textTrackList2['default'], TrackClass: _textTrack2['default'], capitalName: 'Text' } }; Object.keys(NORMAL).forEach(function (type) { NORMAL[type].getterName = type + 'Tracks'; NORMAL[type].privateName = type + 'Tracks_'; }); var REMOTE = { remoteText: { ListClass: _textTrackList2['default'], TrackClass: _textTrack2['default'], capitalName: 'RemoteText', getterName: 'remoteTextTracks', privateName: 'remoteTextTracks_' }, remoteTextEl: { ListClass: _htmlTrackElementList2['default'], TrackClass: _htmlTrackElement2['default'], capitalName: 'RemoteTextTrackEls', getterName: 'remoteTextTrackEls', privateName: 'remoteTextTrackEls_' } }; var ALL = (0, _mergeOptions2['default'])(NORMAL, REMOTE); REMOTE.names = Object.keys(REMOTE); NORMAL.names = Object.keys(NORMAL); ALL.names = [].concat(REMOTE.names).concat(NORMAL.names); exports.NORMAL = NORMAL; exports.REMOTE = REMOTE; exports.ALL = ALL; },{"63":63,"64":64,"65":65,"66":66,"70":70,"72":72,"77":77,"78":78,"90":90}],76:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _guid = _dereq_(88); var Guid = _interopRequireWildcard(_guid); var _eventTarget = _dereq_(43); var _eventTarget2 = _interopRequireDefault(_eventTarget); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file track.js */ /** * A Track class that contains all of the common functionality for {@link AudioTrack}, * {@link VideoTrack}, and {@link TextTrack}. * * > Note: This class should not be used directly * * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html} * @extends EventTarget * @abstract */ var Track = function (_EventTarget) { _inherits(Track, _EventTarget); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {string} [options.kind=''] * A valid kind for the track type you are creating. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @abstract */ function Track() { var _ret; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Track); var _this = _possibleConstructorReturn(this, _EventTarget.call(this)); var track = _this; // eslint-disable-line if (browser.IS_IE8) { track = _document2['default'].createElement('custom'); for (var prop in Track.prototype) { if (prop !== 'constructor') { track[prop] = Track.prototype[prop]; } } } var trackProps = { id: options.id || 'vjs_track_' + Guid.newGUID(), kind: options.kind || '', label: options.label || '', language: options.language || '' }; /** * @memberof Track * @member {string} id * The id of this track. Cannot be changed after creation. * @instance * * @readonly */ /** * @memberof Track * @member {string} kind * The kind of track that this is. Cannot be changed after creation. * @instance * * @readonly */ /** * @memberof Track * @member {string} label * The label of this track. Cannot be changed after creation. * @instance * * @readonly */ /** * @memberof Track * @member {string} language * The two letter language code for this track. Cannot be changed after * creation. * @instance * * @readonly */ var _loop = function _loop(key) { Object.defineProperty(track, key, { get: function get() { return trackProps[key]; }, set: function set() {} }); }; for (var key in trackProps) { _loop(key); } return _ret = track, _possibleConstructorReturn(_this, _ret); } return Track; }(_eventTarget2['default']); exports['default'] = Track; },{"43":43,"79":79,"88":88,"97":97}],77:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackList = _dereq_(74); var _trackList2 = _interopRequireDefault(_trackList); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * @file video-track-list.js */ /** * Un-select all other {@link VideoTrack}s that are selected. * * @param {VideoTrackList} list * list to work on * * @param {VideoTrack} track * The track to skip * * @private */ var disableOthers = function disableOthers(list, track) { for (var i = 0; i < list.length; i++) { if (track.id === list[i].id) { continue; } // another video track is enabled, disable it list[i].selected = false; } }; /** * The current list of {@link VideoTrack} for a video. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist} * @extends TrackList */ var VideoTrackList = function (_TrackList) { _inherits(VideoTrackList, _TrackList); /** * Create an instance of this class. * * @param {VideoTrack[]} [tracks=[]] * A list of `VideoTrack` to instantiate the list with. */ function VideoTrackList() { var _this, _ret; var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, VideoTrackList); var list = void 0; // make sure only 1 track is enabled // sorted from last index to first index for (var i = tracks.length - 1; i >= 0; i--) { if (tracks[i].selected) { disableOthers(tracks, tracks[i]); break; } } // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in _trackList2['default'].prototype) { if (prop !== 'constructor') { list[prop] = _trackList2['default'].prototype[prop]; } } for (var _prop in VideoTrackList.prototype) { if (_prop !== 'constructor') { list[_prop] = VideoTrackList.prototype[_prop]; } } } list = (_this = _possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this); list.changing_ = false; /** * @member {number} VideoTrackList#selectedIndex * The current index of the selected {@link VideoTrack`}. */ Object.defineProperty(list, 'selectedIndex', { get: function get() { for (var _i = 0; _i < this.length; _i++) { if (this[_i].selected) { return _i; } } return -1; }, set: function set() {} }); return _ret = list, _possibleConstructorReturn(_this, _ret); } /** * Add a {@link VideoTrack} to the `VideoTrackList`. * * @param {VideoTrack} track * The VideoTrack to add to the list * * @fires TrackList#addtrack */ VideoTrackList.prototype.addTrack = function addTrack(track) { var _this2 = this; if (track.selected) { disableOthers(this, track); } _TrackList.prototype.addTrack.call(this, track); // native tracks don't have this if (!track.addEventListener) { return; } /** * @listens VideoTrack#selectedchange * @fires TrackList#change */ track.addEventListener('selectedchange', function () { if (_this2.changing_) { return; } _this2.changing_ = true; disableOthers(_this2, track); _this2.changing_ = false; _this2.trigger('change'); }); }; return VideoTrackList; }(_trackList2['default']); exports['default'] = VideoTrackList; },{"74":74,"79":79,"97":97}],78:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackEnums = _dereq_(73); var _track = _dereq_(76); var _track2 = _interopRequireDefault(_track); var _mergeOptions = _dereq_(90); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } 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; } /** * A representation of a single `VideoTrack`. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack} * @extends Track */ var VideoTrack = function (_Track) { _inherits(VideoTrack, _Track); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {string} [options.kind=''] * A valid {@link VideoTrack~Kind} * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {boolean} [options.selected] * If this track is the one that is currently playing. */ function VideoTrack() { var _this, _ret; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, VideoTrack); var settings = (0, _mergeOptions2['default'])(options, { kind: _trackEnums.VideoTrackKind[options.kind] || '' }); // on IE8 this will be a document element // for every other browser this will be a normal object var track = (_this = _possibleConstructorReturn(this, _Track.call(this, settings)), _this); var selected = false; if (browser.IS_IE8) { for (var prop in VideoTrack.prototype) { if (prop !== 'constructor') { track[prop] = VideoTrack.prototype[prop]; } } } /** * @memberof VideoTrack * @member {boolean} selected * If this `VideoTrack` is selected or not. When setting this will * fire {@link VideoTrack#selectedchange} if the state of selected changed. * @instance * * @fires VideoTrack#selectedchange */ Object.defineProperty(track, 'selected', { get: function get() { return selected; }, set: function set(newSelected) { // an invalid or unchanged value if (typeof newSelected !== 'boolean' || newSelected === selected) { return; } selected = newSelected; /** * An event that fires when selected changes on this track. This allows * the VideoTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! Native tracks will do * this internally without an event. * * @event VideoTrack#selectedchange * @type {EventTarget~Event} */ this.trigger('selectedchange'); } }); // if the user sets this track to selected then // set selected to that true value otherwise // we keep it false if (settings.selected) { track.selected = settings.selected; } return _ret = track, _possibleConstructorReturn(_this, _ret); } return VideoTrack; }(_track2['default']); exports['default'] = VideoTrack; },{"73":73,"76":76,"79":79,"90":90}],79:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.BACKGROUND_SIZE_SUPPORTED = exports.TOUCH_ENABLED = exports.IS_ANY_SAFARI = exports.IS_SAFARI = exports.IE_VERSION = exports.IS_IE8 = exports.IS_CHROME = exports.IS_EDGE = exports.IS_FIREFOX = exports.IS_NATIVE_ANDROID = exports.IS_OLD_ANDROID = exports.ANDROID_VERSION = exports.IS_ANDROID = exports.IOS_VERSION = exports.IS_IOS = exports.IS_IPOD = exports.IS_IPHONE = exports.IS_IPAD = undefined; var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * @file browser.js * @module browser */ var USER_AGENT = _window2['default'].navigator && _window2['default'].navigator.userAgent || ''; var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT); var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPAD = exports.IS_IPAD = /iPad/i.test(USER_AGENT); // The Facebook app's UIWebView identifies as both an iPhone and iPad, so // to identify iPhones, we need to exclude iPads. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/ var IS_IPHONE = exports.IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD; var IS_IPOD = exports.IS_IPOD = /iPod/i.test(USER_AGENT); var IS_IOS = exports.IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; var IOS_VERSION = exports.IOS_VERSION = function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } return null; }(); var IS_ANDROID = exports.IS_ANDROID = /Android/i.test(USER_AGENT); var ANDROID_VERSION = exports.ANDROID_VERSION = function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i); if (!match) { return null; } var major = match[1] && parseFloat(match[1]); var minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } return null; }(); // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = exports.IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; var IS_NATIVE_ANDROID = exports.IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537; var IS_FIREFOX = exports.IS_FIREFOX = /Firefox/i.test(USER_AGENT); var IS_EDGE = exports.IS_EDGE = /Edge/i.test(USER_AGENT); var IS_CHROME = exports.IS_CHROME = !IS_EDGE && /Chrome/i.test(USER_AGENT); var IS_IE8 = exports.IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); var IE_VERSION = exports.IE_VERSION = function (result) { return result && parseFloat(result[1]); }(/MSIE\s(\d+)\.\d/.exec(USER_AGENT)); var IS_SAFARI = exports.IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE; var IS_ANY_SAFARI = exports.IS_ANY_SAFARI = IS_SAFARI || IS_IOS; var TOUCH_ENABLED = exports.TOUCH_ENABLED = Dom.isReal() && ('ontouchstart' in _window2['default'] || _window2['default'].DocumentTouch && _window2['default'].document instanceof _window2['default'].DocumentTouch); var BACKGROUND_SIZE_SUPPORTED = exports.BACKGROUND_SIZE_SUPPORTED = Dom.isReal() && 'backgroundSize' in _window2['default'].document.createElement('video').style; },{"83":83,"98":98}],80:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.bufferedPercent = bufferedPercent; var _timeRanges = _dereq_(93); /** * Compute the percentage of the media that has been buffered. * * @param {TimeRange} buffered * The current `TimeRange` object representing buffered time ranges * * @param {number} duration * Total duration of the media * * @return {number} * Percent buffered of the total duration in decimal form. */ function bufferedPercent(buffered, duration) { var bufferedDuration = 0; var start = void 0; var end = void 0; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = (0, _timeRanges.createTimeRange)(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } /** * @file buffer.js * @module buffer */ },{"93":93}],81:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports['default'] = computedStyle; var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * A safe getComputedStyle with an IE8 fallback. * * This is needed because in Firefox, if the player is loaded in an iframe with * `display:none`, then `getComputedStyle` returns `null`, so, we do a null-check to * make sure that the player doesn't break in these cases. * * @param {Element} el * The element you want the computed style of * * @param {string} prop * The property name you want * * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397 * * @static * @const */ function computedStyle(el, prop) { if (!el || !prop) { return ''; } if (typeof _window2['default'].getComputedStyle === 'function') { var cs = _window2['default'].getComputedStyle(el); return cs ? cs[prop] : ''; } return el.currentStyle[prop] || ''; } /** * @file computed-style.js * @module computed-style */ },{"98":98}],82:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.getData = getData; exports.hasData = hasData; exports.removeData = removeData; var _guid = _dereq_(88); var Guid = _interopRequireWildcard(_guid); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * Element Data Store. * * Allows for binding data to an element without putting it directly on the * element. Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {String} * @constant * @private */ /** * @file dom-data.js * @module dom-data */ var elIdAttr = 'vdata' + new Date().getTime(); /** * Returns the cache object where data for an element is stored * * @param {Element} el * Element to store data for. * * @return {Object} * The cache object for that el that was passed in. */ function getData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } /** * Returns whether or not an element has cached data * * @param {Element} el * Check if this element has cached data. * * @return {boolean} * - True if the DOM element has cached data. * - False otherwise. */ function hasData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el * Remove cached data for this element. */ function removeData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } },{"88":88}],83:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.$$ = exports.$ = 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 _templateObject = _taggedTemplateLiteralLoose(['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.'], ['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.']); exports.isReal = isReal; exports.isEl = isEl; exports.createEl = createEl; exports.textContent = textContent; exports.prependTo = prependTo; exports.hasClass = hasClass; exports.addClass = addClass; exports.removeClass = removeClass; exports.toggleClass = toggleClass; exports.setAttributes = setAttributes; exports.getAttributes = getAttributes; exports.getAttribute = getAttribute; exports.setAttribute = setAttribute; exports.removeAttribute = removeAttribute; exports.blockTextSelection = blockTextSelection; exports.unblockTextSelection = unblockTextSelection; exports.getBoundingClientRect = getBoundingClientRect; exports.findPosition = findPosition; exports.getPointerPosition = getPointerPosition; exports.isTextNode = isTextNode; exports.emptyEl = emptyEl; exports.normalizeContent = normalizeContent; exports.appendContent = appendContent; exports.insertContent = insertContent; var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _tsml = _dereq_(101); var _tsml2 = _interopRequireDefault(_tsml); var _obj = _dereq_(91); var _computedStyle = _dereq_(81); var _computedStyle2 = _interopRequireDefault(_computedStyle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } /** * @file dom.js * @module dom */ /** * Detect if a value is a string with any non-whitespace characters. * * @param {string} str * The string to check * * @return {boolean} * - True if the string is non-blank * - False otherwise * */ function isNonBlankString(str) { return typeof str === 'string' && /\S/.test(str); } /** * Throws an error if the passed string has whitespace. This is used by * class methods to be relatively consistent with the classList API. * * @param {string} str * The string to check for whitespace. * * @throws {Error} * Throws an error if there is whitespace in the string. * */ function throwIfWhitespace(str) { if (/\s/.test(str)) { throw new Error('class has illegal whitespace characters'); } } /** * Produce a regular expression for matching a className within an elements className. * * @param {string} className * The className to generate the RegExp for. * * @return {RegExp} * The RegExp that will check for a specific `className` in an elements * className. */ function classRegExp(className) { return new RegExp('(^|\\s)' + className + '($|\\s)'); } /** * Whether the current DOM interface appears to be real. * * @return {Boolean} */ function isReal() { return ( // Both document and window will never be undefined thanks to `global`. _document2['default'] === _window2['default'].document && // In IE < 9, DOM methods return "object" as their type, so all we can // confidently check is that it exists. typeof _document2['default'].createElement !== 'undefined' ); } /** * Determines, via duck typing, whether or not a value is a DOM element. * * @param {Mixed} value * The thing to check * * @return {boolean} * - True if it is a DOM element * - False otherwise */ function isEl(value) { return (0, _obj.isObject)(value) && value.nodeType === 1; } /** * Creates functions to query the DOM using a given method. * * @param {string} method * The method to create the query with. * * @return {Function} * The query method */ function createQuerier(method) { return function (selector, context) { if (!isNonBlankString(selector)) { return _document2['default'][method](null); } if (isNonBlankString(context)) { context = _document2['default'].querySelector(context); } var ctx = isEl(context) ? context : _document2['default']; return ctx[method] && ctx[method](selector); }; } /** * Creates an element and applies properties. * * @param {string} [tagName='div'] * Name of tag to be created. * * @param {Object} [properties={}] * Element properties to be applied. * * @param {Object} [attributes={}] * Element attributes to be applied. * * @param {String|Element|TextNode|Array|Function} [content] * Contents for the element (see: {@link dom:normalizeContent}) * * @return {Element} * The element that was created. */ function createEl() { var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div'; var properties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var content = arguments[3]; var el = _document2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // See #2176 // We originally were accepting both properties and attributes in the // same object, but that doesn't work so well. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { _log2['default'].warn((0, _tsml2['default'])(_templateObject, propName, val)); el.setAttribute(propName, val); // Handle textContent since it's not supported everywhere and we have a // method for it. } else if (propName === 'textContent') { textContent(el, val); } else { el[propName] = val; } }); Object.getOwnPropertyNames(attributes).forEach(function (attrName) { el.setAttribute(attrName, attributes[attrName]); }); if (content) { appendContent(el, content); } return el; } /** * Injects text into an element, replacing any existing contents entirely. * * @param {Element} el * The element to add text content into * * @param {string} text * The text content to add. * * @return {Element} * The element with added text content. */ function textContent(el, text) { if (typeof el.textContent === 'undefined') { el.innerText = text; } else { el.textContent = text; } return el; } /** * Insert an element as the first child node of another * * @param {Element} child * Element to insert * * @param {Element} parent * Element to insert child into */ function prependTo(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Check if an element has a CSS class * * @param {Element} element * Element to check * * @param {string} classToCheck * Class name to check for * * @return {boolean} * - True if the element had the class * - False otherwise. * * @throws {Error} * Throws an error if `classToCheck` has white space. */ function hasClass(element, classToCheck) { throwIfWhitespace(classToCheck); if (element.classList) { return element.classList.contains(classToCheck); } return classRegExp(classToCheck).test(element.className); } /** * Add a CSS class name to an element * * @param {Element} element * Element to add class name to. * * @param {string} classToAdd * Class name to add. * * @return {Element} * The dom element with the added class name. */ function addClass(element, classToAdd) { if (element.classList) { element.classList.add(classToAdd); // Don't need to `throwIfWhitespace` here because `hasElClass` will do it // in the case of classList not being supported. } else if (!hasClass(element, classToAdd)) { element.className = (element.className + ' ' + classToAdd).trim(); } return element; } /** * Remove a CSS class name from an element * * @param {Element} element * Element to remove a class name from. * * @param {string} classToRemove * Class name to remove * * @return {Element} * The dom element with class name removed. */ function removeClass(element, classToRemove) { if (element.classList) { element.classList.remove(classToRemove); } else { throwIfWhitespace(classToRemove); element.className = element.className.split(/\s+/).filter(function (c) { return c !== classToRemove; }).join(' '); } return element; } /** * The callback definition for toggleElClass. * * @callback Dom~PredicateCallback * @param {Element} element * The DOM element of the Component. * * @param {string} classToToggle * The `className` that wants to be toggled * * @return {boolean|undefined} * - If true the `classToToggle` will get added to `element`. * - If false the `classToToggle` will get removed from `element`. * - If undefined this callback will be ignored */ /** * Adds or removes a CSS class name on an element depending on an optional * condition or the presence/absence of the class name. * * @param {Element} element * The element to toggle a class name on. * * @param {string} classToToggle * The class that should be toggled * * @param {boolean|PredicateCallback} [predicate] * See the return value for {@link Dom~PredicateCallback} * * @return {Element} * The element with a class that has been toggled. */ function toggleClass(element, classToToggle, predicate) { // This CANNOT use `classList` internally because IE does not support the // second parameter to the `classList.toggle()` method! Which is fine because // `classList` will be used by the add/remove functions. var has = hasClass(element, classToToggle); if (typeof predicate === 'function') { predicate = predicate(element, classToToggle); } if (typeof predicate !== 'boolean') { predicate = !has; } // If the necessary class operation matches the current state of the // element, no action is required. if (predicate === has) { return; } if (predicate) { addClass(element, classToToggle); } else { removeClass(element, classToToggle); } return element; } /** * Apply attributes to an HTML element. * * @param {Element} el * Element to add attributes to. * * @param {Object} [attributes] * Attributes to be applied. */ function setAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag * Element from which to get tag attributes. * * @return {Object} * All attributes of the element. */ function getAttributes(tag) { var obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from var knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { var attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { var attrName = attrs[i].name; var attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } /** * Get the value of an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to get the value of * * @return {string} * value of the attribute */ function getAttribute(el, attribute) { return el.getAttribute(attribute); } /** * Set the value of an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to set * * @param {string} value * Value to set the attribute to */ function setAttribute(el, attribute, value) { el.setAttribute(attribute, value); } /** * Remove an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to remove */ function removeAttribute(el, attribute) { el.removeAttribute(attribute); } /** * Attempt to block the ability to select text while dragging controls */ function blockTextSelection() { _document2['default'].body.focus(); _document2['default'].onselectstart = function () { return false; }; } /** * Turn off text selection blocking */ function unblockTextSelection() { _document2['default'].onselectstart = function () { return true; }; } /** * Identical to the native `getBoundingClientRect` function, but ensures that * the method is supported at all (it is in all browsers we claim to support) * and that the element is in the DOM before continuing. * * This wrapper function also shims properties which are not provided by some * older browsers (namely, IE8). * * Additionally, some browsers do not support adding properties to a * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard * properties (except `x` and `y` which are not widely supported). This helps * avoid implementations where keys are non-enumerable. * * @param {Element} el * Element whose `ClientRect` we want to calculate. * * @return {Object|undefined} * Always returns a plain */ function getBoundingClientRect(el) { if (el.getBoundingClientRect && el.parentNode) { var _ret = function () { var rect = el.getBoundingClientRect(); var result = {}; ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(function (k) { if (rect[k] !== undefined) { result[k] = rect[k]; } }); if (!result.height) { result.height = parseFloat((0, _computedStyle2['default'])(el, 'height')); } if (!result.width) { result.width = parseFloat((0, _computedStyle2['default'])(el, 'width')); } return { v: result }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } } /** * The postion of a DOM element on the page. * * @typedef {Object} Dom~Position * * @property {number} left * Pixels to the left * * @property {number} top * Pixels on top */ /** * Offset Left. * getBoundingClientRect technique from * John Resig * * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el * Element from which to get offset * * @return {Dom~Position} * The position of the element that was passed in. */ function findPosition(el) { var box = void 0; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _document2['default'].documentElement; var body = _document2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _window2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _window2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } /** * x and y coordinates for a dom element or mouse pointer * * @typedef {Object} Dom~Coordinates * * @property {number} x * x coordinate in pixels * * @property {number} y * y coordinate in pixels */ /** * Get pointer position in element * Returns an object with x and y coordinates. * The base on the coordinates are the bottom left of the element. * * @param {Element} el * Element on which to get the pointer position on * * @param {EventTarget~Event} event * Event object * * @return {Dom~Coordinates} * A Coordinates object corresponding to the mouse position. * */ function getPointerPosition(el, event) { var position = {}; var box = findPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var boxY = box.top; var boxX = box.left; var pageY = event.pageY; var pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; } /** * Determines, via duck typing, whether or not a value is a text node. * * @param {Mixed} value * Check if this value is a text node. * * @return {boolean} * - True if it is a text node * - False otherwise */ function isTextNode(value) { return (0, _obj.isObject)(value) && value.nodeType === 3; } /** * Empties the contents of an element. * * @param {Element} el * The element to empty children from * * @return {Element} * The element with no children */ function emptyEl(el) { while (el.firstChild) { el.removeChild(el.firstChild); } return el; } /** * Normalizes content for eventual insertion into the DOM. * * This allows a wide range of content definition methods, but protects * from falling into the trap of simply writing to `innerHTML`, which is * an XSS concern. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * @param {String|Element|TextNode|Array|Function} content * - String: Normalized into a text node. * - Element/TextNode: Passed through. * - Array: A one-dimensional array of strings, elements, nodes, or functions * (which return single strings, elements, or nodes). * - Function: If the sole argument, is expected to produce a string, element, * node, or array as defined above. * * @return {Array} * All of the content that was passed in normalized. */ function normalizeContent(content) { // First, invoke content if it is a function. If it produces an array, // that needs to happen before normalization. if (typeof content === 'function') { content = content(); } // Next up, normalize to an array, so one or many items can be normalized, // filtered, and returned. return (Array.isArray(content) ? content : [content]).map(function (value) { // First, invoke value if it is a function to produce a new value, // which will be subsequently normalized to a Node of some kind. if (typeof value === 'function') { value = value(); } if (isEl(value) || isTextNode(value)) { return value; } if (typeof value === 'string' && /\S/.test(value)) { return _document2['default'].createTextNode(value); } }).filter(function (value) { return value; }); } /** * Normalizes and appends content to an element. * * @param {Element} el * Element to append normalized content to. * * * @param {String|Element|TextNode|Array|Function} content * See the `content` argument of {@link dom:normalizeContent} * * @return {Element} * The element with appended normalized content. */ function appendContent(el, content) { normalizeContent(content).forEach(function (node) { return el.appendChild(node); }); return el; } /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * @param {Element} el * Element to insert normalized content into. * * @param {String|Element|TextNode|Array|Function} content * See the `content` argument of {@link dom:normalizeContent} * * @return {Element} * The element with inserted normalized content. * */ function insertContent(el, content) { return appendContent(emptyEl(el), content); } /** * Finds a single DOM element matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @param {string} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {Element|null} * The element that was found or null. */ var $ = exports.$ = createQuerier('querySelector'); /** * Finds a all DOM elements matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @param {string} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {NodeList} * A element list of elements that were found. Will be empty if none were found. * */ var $$ = exports.$$ = createQuerier('querySelectorAll'); },{"101":101,"81":81,"89":89,"91":91,"97":97,"98":98}],84:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.fixEvent = fixEvent; exports.on = on; exports.off = off; exports.trigger = trigger; exports.one = one; var _domData = _dereq_(82); var DomData = _interopRequireWildcard(_domData); var _guid = _dereq_(88); var Guid = _interopRequireWildcard(_guid); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem * Element to clean up * * @param {string} type * Type of event to clean up */ function _cleanUpEvents(elem, type) { var data = DomData.getData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { DomData.removeData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn * The event method we want to use. * * @param {Element|Object} elem * Element or object to bind listeners to * * @param {string} type * Type of event to bind to. * * @param {EventTarget~EventListener} callback * Event listener. */ /** * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. * * @module events */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { // Call the event method for each one of the types fn(elem, type, callback); }); } /** * Fix a native event to have standard property values * * @param {Object} event * Event object to fix. * * @return {Object} * Fixed event object. */ function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { (function () { var old = event || _window2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation // and webkitMovementX/Y if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _document2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; old.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; old.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX !== null && event.clientX !== undefined) { var doc = _document2['default'].documentElement; var body = _document2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button !== null && event.button !== undefined) { // The following is disabled because it does not pass videojs-standard // and... yikes. /* eslint-disable */ event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; /* eslint-enable */ } })(); } // Returns fixed-up instance return event; } /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem * Element or object to bind listeners to * * @param {string|string[]} type * Type of event to bind to. * * @param {EventTarget~EventListener} fn * Event listener. */ function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = DomData.getData(elem); // We need a place to store all our handler data if (!data.handlers) { data.handlers = {}; } if (!data.handlers[type]) { data.handlers[type] = []; } if (!fn.guid) { fn.guid = Guid.newGUID(); } data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) { return; } event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { try { handlersCopy[m].call(elem, event, hash); } catch (e) { _log2['default'].error(e); } } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } /** * Removes event listeners from an element * * @param {Element|Object} elem * Object to remove listeners from. * * @param {string|string[]} [type] * Type of listener to remove. Don't include to remove all events from element. * * @param {EventTarget~EventListener} [fn] * Specific listener to remove. Don't include to remove listeners for an event * type. */ function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!DomData.hasData(elem)) { return; } var data = DomData.getData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); } return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) { return; } // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } /** * Trigger an event for an element * * @param {Element|Object} elem * Element to trigger an event on * * @param {EventTarget~Event|string} event * A string (the type) or an event object with a type attribute * * @param {Object} [hash] * data hash to pass along with the event * * @return {boolean|undefined} * - Returns the opposite of `defaultPrevented` if default was prevented * - Otherwise returns undefined */ function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = DomData.hasData(elem) ? DomData.getData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = DomData.getData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } /** * Trigger a listener only once for an event * * @param {Element|Object} elem * Element or object to bind to. * * @param {string|string[]} type * Name/type of event * * @param {Event~EventListener} fn * Event Listener function */ function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } },{"82":82,"88":88,"89":89,"97":97,"98":98}],85:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _obj = _dereq_(91); /** * Filter out single bad source objects or multiple source objects in an * array. Also flattens nested source object arrays into a 1 dimensional * array of source objects. * * @param {Tech~SourceObject|Tech~SourceObject[]} src * The src object to filter * * @return {Tech~SourceObject[]} * An array of sourceobjects containing only valid sources * * @private */ var filterSource = function filterSource(src) { // traverse array if (Array.isArray(src)) { (function () { var newsrc = []; src.forEach(function (srcobj) { srcobj = filterSource(srcobj); if (Array.isArray(srcobj)) { newsrc = newsrc.concat(srcobj); } else if ((0, _obj.isObject)(srcobj)) { newsrc.push(srcobj); } }); src = newsrc; })(); } else if (typeof src === 'string' && src.trim()) { // convert string into object src = [{ src: src }]; } else if ((0, _obj.isObject)(src) && typeof src.src === 'string' && src.src && src.src.trim()) { // src is already valid src = [src]; } else { // invalid source, turn it into an empty array src = []; } return src; }; /** * @module filter-source */ exports['default'] = filterSource; },{"91":91}],86:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.throttle = exports.bind = undefined; var _guid = _dereq_(88); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events. * * @param {Mixed} context * The object to bind as scope. * * @param {Function} fn * The function to be bound to a scope. * * @param {number} [uid] * An optional unique ID for the function to be set * * @return {Function} * The new function that will be bound into the context given */ var bind = exports.bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = (0, _guid.newGUID)(); } // Create the new function that changes the context var bound = function bound() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks bound.guid = uid ? uid + '_' + fn.guid : fn.guid; return bound; }; /** * Wraps the given function, `fn`, with a new function that only invokes `fn` * at most once per every `wait` milliseconds. * * @param {Function} fn * The function to be throttled. * * @param {Number} wait * The number of milliseconds by which to throttle. * * @return {Function} */ /** * @file fn.js * @module fn */ var throttle = exports.throttle = function throttle(fn, wait) { var last = Date.now(); var throttled = function throttled() { var now = Date.now(); if (now - last >= wait) { fn.apply(undefined, arguments); last = now; } }; return throttled; }; },{"88":88}],87:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file format-time.js * @module Format-time */ /** * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds) * will force a number of leading zeros to cover the length of the guide. * * @param {number} seconds * Number of seconds to be turned into a string * * @param {number} guide * Number (in seconds) to model the string after * * @return {string} * Time formatted as H:MM:SS or M:SS */ function formatTime(seconds) { var guide = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : seconds; seconds = seconds < 0 ? 0 : seconds; var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; } exports['default'] = formatTime; },{}],88:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; exports.newGUID = newGUID; /** * @file guid.js * @module guid */ /** * Unique ID for an element or function * @type {Number} */ var _guid = 1; /** * Get a unique auto-incrementing ID by number that has not been returned before. * * @return {number} * A new unique ID. */ function newGUID() { return _guid++; } },{}],89:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.logByType = undefined; var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _browser = _dereq_(79); var _obj = _dereq_(91); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var log = void 0; // This is the private tracking variable for logging level. /** * @file log.js * @module log */ var level = 'all'; // This is the private tracking variable for the logging history. var history = []; /** * Log messages to the console and history based on the type of message * * @private * @param {string} type * The name of the console method to use. * * @param {Array} args * The arguments to be passed to the matching console method. * * @param {boolean} [stringify] * By default, only old IEs should get console argument stringification, * but this is exposed as a parameter to facilitate testing. */ var logByType = exports.logByType = function logByType(type, args) { var stringify = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : !!_browser.IE_VERSION && _browser.IE_VERSION < 11; var lvl = log.levels[level]; var lvlRegExp = new RegExp('^(' + lvl + ')$'); if (type !== 'log') { // Add the type to the front of the message when it's not "log". args.unshift(type.toUpperCase() + ':'); } // Add a clone of the args at this point to history. if (history) { history.push([].concat(args)); } // Add console prefix after adding to history. args.unshift('VIDEOJS:'); // If there's no console then don't try to output messages, but they will // still be stored in history. // // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist // when the module is executed. var fn = _window2['default'].console && _window2['default'].console[type]; // Bail out if there's no console or if this type is not allowed by the // current logging level. if (!fn || !lvl || !lvlRegExp.test(type)) { return; } // IEs previous to 11 log objects uselessly as "[object Object]"; so, JSONify // objects and arrays for those less-capable browsers. if (stringify) { args = args.map(function (a) { if ((0, _obj.isObject)(a) || Array.isArray(a)) { try { return JSON.stringify(a); } catch (x) { return String(a); } } // Cast to string before joining, so we get null and undefined explicitly // included in output (as we would in a modern console). return String(a); }).join(' '); } // Old IE versions do not allow .apply() for console methods (they are // reported as objects rather than functions). if (!fn.apply) { fn(args); } else { fn[Array.isArray(args) ? 'apply' : 'call'](_window2['default'].console, args); } }; /** * Logs plain debug messages. Similar to `console.log`. * * @class * @param {Mixed[]} args * One or more messages or objects that should be logged. */ log = function log() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } logByType('log', args); }; /** * Enumeration of available logging levels, where the keys are the level names * and the values are `|`-separated strings containing logging methods allowed * in that logging level. These strings are used to create a regular expression * matching the function name being called. * * Levels provided by video.js are: * * - `off`: Matches no calls. Any value that can be cast to `false` will have * this effect. The most restrictive. * - `all` (default): Matches only Video.js-provided functions (`log`, * `log.warn`, and `log.error`). * - `warn`: Matches `log.warn` and `log.error` calls. * - `error`: Matches only `log.error` calls. * * @type {Object} */ log.levels = { all: 'log|warn|error', error: 'error', off: '', warn: 'warn|error', DEFAULT: level }; /** * Get or set the current logging level. If a string matching a key from * {@link log.levels} is provided, acts as a setter. Regardless of argument, * returns the current logging level. * * @param {string} [lvl] * Pass to set a new logging level. * * @return {string} * The current logging level. */ log.level = function (lvl) { if (typeof lvl === 'string') { if (!log.levels.hasOwnProperty(lvl)) { throw new Error('"' + lvl + '" in not a valid log level'); } level = lvl; } return level; }; /** * Returns an array containing everything that has been logged to the history. * * This array is a shallow clone of the internal history record. However, its * contents are _not_ cloned; so, mutating objects inside this array will * mutate them in history. * * @return {Array} */ log.history = function () { return history ? [].concat(history) : []; }; /** * Clears the internal history tracking, but does not prevent further history * tracking. */ log.history.clear = function () { if (history) { history.length = 0; } }; /** * Disable history tracking if it is currently enabled. */ log.history.disable = function () { if (history !== null) { history.length = 0; history = null; } }; /** * Enable history tracking if it is currently disabled. */ log.history.enable = function () { if (history === null) { history = []; } }; /** * Logs error messages. Similar to `console.error`. * * @param {Mixed[]} args * One or more messages or objects that should be logged as an error */ log.error = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return logByType('error', args); }; /** * Logs warning messages. Similar to `console.warn`. * * @param {Mixed[]} args * One or more messages or objects that should be logged as a warning. */ log.warn = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return logByType('warn', args); }; exports['default'] = log; },{"79":79,"91":91,"98":98}],90:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports['default'] = mergeOptions; var _obj = _dereq_(91); /** * Deep-merge one or more options objects, recursively merging **only** plain * object properties. * * @param {Object[]} sources * One or more objects to merge into a new object. * * @returns {Object} * A new object that is the merged result of all sources. */ function mergeOptions() { var result = {}; for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) { sources[_key] = arguments[_key]; } sources.forEach(function (source) { if (!source) { return; } (0, _obj.each)(source, function (value, key) { if (!(0, _obj.isPlain)(value)) { result[key] = value; return; } if (!(0, _obj.isPlain)(result[key])) { result[key] = {}; } result[key] = mergeOptions(result[key], value); }); }); return result; } /** * @file merge-options.js * @module merge-options */ },{"91":91}],91:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = 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; }; exports.each = each; exports.reduce = reduce; exports.assign = assign; exports.isObject = isObject; exports.isPlain = isPlain; /** * @file obj.js * @module obj */ /** * @callback obj:EachCallback * * @param {Mixed} value * The current key for the object that is being iterated over. * * @param {string} key * The current key-value for object that is being iterated over */ /** * @callback obj:ReduceCallback * * @param {Mixed} accum * The value that is accumulating over the reduce loop. * * @param {Mixed} value * The current key for the object that is being iterated over. * * @param {string} key * The current key-value for object that is being iterated over * * @return {Mixed} * The new accumulated value. */ var toString = Object.prototype.toString; /** * Array-like iteration for objects. * * @param {Object} object * The object to iterate over * * @param {obj:EachCallback} fn * The callback function which is called for each key in the object. */ function each(object, fn) { Object.keys(object).forEach(function (key) { return fn(object[key], key); }); } /** * Array-like reduce for objects. * * @param {Object} object * The Object that you want to reduce. * * @param {Function} fn * A callback function which is called for each key in the object. It * receives the accumulated value and the per-iteration value and key * as arguments. * * @param {Mixed} [initial = 0] * Starting value * * @return {Mixed} * The final accumulated value. */ function reduce(object, fn) { var initial = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; return Object.keys(object).reduce(function (accum, key) { return fn(accum, object[key], key); }, initial); } /** * Object.assign-style object shallow merge/extend. * * @param {Object} target * @param {Object} ...sources * @return {Object} */ function assign(target) { for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } if (Object.assign) { return Object.assign.apply(Object, [target].concat(sources)); } sources.forEach(function (source) { if (!source) { return; } each(source, function (value, key) { target[key] = value; }); }); return target; } /** * Returns whether a value is an object of any kind - including DOM nodes, * arrays, regular expressions, etc. Not functions, though. * * This avoids the gotcha where using `typeof` on a `null` value * results in `'object'`. * * @param {Object} value * @return {Boolean} */ function isObject(value) { return !!value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object'; } /** * Returns whether an object appears to be a "plain" object - that is, a * direct instance of `Object`. * * @param {Object} value * @return {Boolean} */ function isPlain(value) { return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object; } },{}],92:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.setTextContent = exports.createStyleElement = undefined; var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Create a DOM syle element given a className for it. * * @param {string} className * The className to add to the created style element. * * @return {Element} * The element that was created. */ var createStyleElement = exports.createStyleElement = function createStyleElement(className) { var style = _document2['default'].createElement('style'); style.className = className; return style; }; /** * Add text to a DOM element. * * @param {Element} el * The Element to add text content to. * * @param {string} content * The text to add to the element. */ /** * @file stylesheet.js * @module stylesheet */ var setTextContent = exports.setTextContent = function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }; },{"97":97}],93:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.createTimeRanges = createTimeRanges; /** * @file time-ranges.js * @module time-ranges */ /** * Returns the time for the specified index at the start or end * of a TimeRange object. * * @function time-ranges:indexFunction * * @param {number} [index=0] * The range number to return the time for. * * @return {number} * The time that offset at the specified index. * * @depricated index must be set to a value, in the future this will throw an error. */ /** * An object that contains ranges of time for various reasons. * * @typedef {Object} TimeRange * * @property {number} length * The number of time ranges represented by this Object * * @property {time-ranges:indexFunction} start * Returns the time offset at which a specified time range begins. * * @property {time-ranges:indexFunction} end * Returns the time offset at which a specified time range begins. * * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges */ /** * Check if any of the time ranges are over the maximum index. * * @param {string} fnName * The function name to use for logging * * @param {number} index * The index to check * * @param {number} maxIndex * The maximum possible index * * @throws {Error} if the timeRanges provided are over the maxIndex */ function rangeCheck(fnName, index, maxIndex) { if (typeof index !== 'number' || index < 0 || index > maxIndex) { throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is non-numeric or out of bounds (0-' + maxIndex + ').'); } } /** * Check if any of the time ranges are over the maximum index. * * @param {string} fnName * The function name to use for logging * * @param {string} valueIndex * The proprety that should be used to get the time. should be 'start' or 'end' * * @param {Array} ranges * An array of time ranges * * @param {Array} [rangeIndex=0] * The index to start the search at * * @return {number} * The time that offset at the specified index. * * * @depricated rangeIndex must be set to a value, in the future this will throw an error. * @throws {Error} if rangeIndex is more than the length of ranges */ function getRange(fnName, valueIndex, ranges, rangeIndex) { rangeCheck(fnName, rangeIndex, ranges.length - 1); return ranges[rangeIndex][valueIndex]; } /** * Create a time range object givent ranges of time. * * @param {Array} [ranges] * An array of time ranges. */ function createTimeRangesObj(ranges) { if (ranges === undefined || ranges.length === 0) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: ranges.length, start: getRange.bind(null, 'start', 0, ranges), end: getRange.bind(null, 'end', 1, ranges) }; } /** * Should create a fake `TimeRange` object which mimics an HTML5 time range instance. * * @param {number|Array} start * The start of a single range or an array of ranges * * @param {number} end * The end of a single range. * * @private */ function createTimeRanges(start, end) { if (Array.isArray(start)) { return createTimeRangesObj(start); } else if (start === undefined || end === undefined) { return createTimeRangesObj(); } return createTimeRangesObj([[start, end]]); } exports.createTimeRange = createTimeRanges; },{}],94:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file to-title-case.js * @module to-title-case */ /** * Uppercase the first letter of a string. * * @param {string} string * String to be uppercased * * @return {string} * The string with an uppercased first letter */ function toTitleCase(string) { if (typeof string !== 'string') { return string; } return string.charAt(0).toUpperCase() + string.slice(1); } exports['default'] = toTitleCase; },{}],95:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.isCrossOrigin = exports.getFileExtension = exports.getAbsoluteURL = exports.parseUrl = undefined; var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * @typedef {Object} url:URLObject * * @property {string} protocol * The protocol of the url that was parsed. * * @property {string} hostname * The hostname of the url that was parsed. * * @property {string} port * The port of the url that was parsed. * * @property {string} pathname * The pathname of the url that was parsed. * * @property {string} search * The search query of the url that was parsed. * * @property {string} hash * The hash of the url that was parsed. * * @property {string} host * The host of the url that was parsed. */ /** * Resolve and parse the elements of a URL. * * @param {String} url * The url to parse * * @return {url:URLObject} * An object of url details */ /** * @file url.js * @module url */ var parseUrl = exports.parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = _document2['default'].createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div = void 0; if (addToBody) { div = _document2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); _document2['default'].body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { _document2['default'].body.removeChild(div); } return details; }; /** * Get absolute version of relative URL. Used to tell flash correct URL. * * * @param {string} url * URL to make absolute * * @return {string} * Absolute URL * * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue */ var getAbsoluteURL = exports.getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = _document2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } return url; }; /** * Returns the extension of the passed file name. It will return an empty string * if passed an invalid path. * * @param {string} path * The fileName path like '/path/to/file.mp4' * * @returns {string} * The extension in lower case or an empty string if no * extension could be found. */ var getFileExtension = exports.getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; /** * Returns whether the url passed is a cross domain request or not. * * @param {string} url * The url to check. * * @return {boolean} * Whether it is a cross domain request or not. */ var isCrossOrigin = exports.isCrossOrigin = function isCrossOrigin(url) { var winLoc = _window2['default'].location; var urlInfo = parseUrl(url); // IE8 protocol relative urls will return ':' for protocol var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host; return crossOrigin; }; },{"97":97,"98":98}],96:[function(_dereq_,module,exports){ 'use strict'; var _window = _dereq_(98); var _window2 = _interopRequireDefault(_window); var _document = _dereq_(97); var _document2 = _interopRequireDefault(_document); var _setup = _dereq_(57); var setup = _interopRequireWildcard(_setup); var _stylesheet = _dereq_(92); var stylesheet = _interopRequireWildcard(_stylesheet); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _eventTarget = _dereq_(43); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _events = _dereq_(84); var Events = _interopRequireWildcard(_events); var _player = _dereq_(54); var _player2 = _interopRequireDefault(_player); var _plugin = _dereq_(55); var _plugin2 = _interopRequireDefault(_plugin); var _mergeOptions2 = _dereq_(90); var _mergeOptions3 = _interopRequireDefault(_mergeOptions2); var _fn = _dereq_(86); var Fn = _interopRequireWildcard(_fn); var _textTrack = _dereq_(72); var _textTrack2 = _interopRequireDefault(_textTrack); var _audioTrack = _dereq_(64); var _audioTrack2 = _interopRequireDefault(_audioTrack); var _videoTrack = _dereq_(78); var _videoTrack2 = _interopRequireDefault(_videoTrack); var _timeRanges = _dereq_(93); var _formatTime = _dereq_(87); var _formatTime2 = _interopRequireDefault(_formatTime); var _log = _dereq_(89); var _log2 = _interopRequireDefault(_log); var _dom = _dereq_(83); var Dom = _interopRequireWildcard(_dom); var _browser = _dereq_(79); var browser = _interopRequireWildcard(_browser); var _url = _dereq_(95); var Url = _interopRequireWildcard(_url); var _obj = _dereq_(91); var _computedStyle = _dereq_(81); var _computedStyle2 = _interopRequireDefault(_computedStyle); var _extend = _dereq_(44); var _extend2 = _interopRequireDefault(_extend); var _xhr = _dereq_(108); var _xhr2 = _interopRequireDefault(_xhr); var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); var _middleware = _dereq_(61); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // HTML5 Element Shim for IE8 // Include the built-in techs /** * @file video.js * @module videojs */ if (typeof HTMLVideoElement === 'undefined' && Dom.isReal()) { _document2['default'].createElement('video'); _document2['default'].createElement('audio'); _document2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * * @param {string|Element} id * Video element or video element ID * * @param {Object} [options] * Optional options object for config/settings * * @param {Component~ReadyCallback} [ready] * Optional ready callback * * @return {Player} * A player instance * * @mixes videojs */ function videojs(id, options, ready) { var tag = void 0; // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { var players = videojs.getPlayers(); // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (players[id]) { // If options or ready function are passed, warn if (options) { _log2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { players[id].ready(ready); } return players[id]; } // Otherwise get element for ID tag = Dom.$('#' + id); // ID is a media element } else { tag = id; } // Check for a useable element // re: nodeName, could be a box div also if (!tag || !tag.nodeName) { throw new TypeError('The element or ID supplied is not valid. (videojs)'); } // Element may have a player attr referring to an already created player instance. // If so return that otherwise set up a new player below if (tag.player || _player2['default'].players[tag.playerId]) { return tag.player || _player2['default'].players[tag.playerId]; } options = options || {}; videojs.hooks('beforesetup').forEach(function (hookFunction) { var opts = hookFunction(tag, (0, _mergeOptions3['default'])(options)); if (!(0, _obj.isObject)(opts) || Array.isArray(opts)) { _log2['default'].error('please return an object in beforesetup hooks'); return; } options = (0, _mergeOptions3['default'])(options, opts); }); var PlayerComponent = _component2['default'].getComponent('Player'); // If not, set up a new player var player = new PlayerComponent(tag, options, ready); videojs.hooks('setup').forEach(function (hookFunction) { return hookFunction(player); }); return player; } /** * An Object that contains lifecycle hooks as keys which point to an array * of functions that are run when a lifecycle is triggered */ videojs.hooks_ = {}; /** * Get a list of hooks for a specific lifecycle * * @param {string} type * the lifecyle to get hooks from * * @param {Function} [fn] * Optionally add a hook to the lifecycle that your are getting. * * @return {Array} * an array of hooks, or an empty array if there are none. */ videojs.hooks = function (type, fn) { videojs.hooks_[type] = videojs.hooks_[type] || []; if (fn) { videojs.hooks_[type] = videojs.hooks_[type].concat(fn); } return videojs.hooks_[type]; }; /** * Add a function hook to a specific videojs lifecycle. * * @param {string} type * the lifecycle to hook the function to. * * @param {Function|Function[]} * The function or array of functions to attach. */ videojs.hook = function (type, fn) { videojs.hooks(type, fn); }; /** * Remove a hook from a specific videojs lifecycle. * * @param {string} type * the lifecycle that the function hooked to * * @param {Function} fn * The hooked function to remove * * @return {boolean} * The function that was removed or undef */ videojs.removeHook = function (type, fn) { var index = videojs.hooks(type).indexOf(fn); if (index <= -1) { return false; } videojs.hooks_[type] = videojs.hooks_[type].slice(); videojs.hooks_[type].splice(index, 1); return true; }; // Add default styles if (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE !== true && Dom.isReal()) { var style = Dom.$('.vjs-styles-defaults'); if (!style) { style = stylesheet.createStyleElement('vjs-styles-defaults'); var head = Dom.$('head'); if (head) { head.insertBefore(style, head.firstChild); } stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid {\n padding-top: 56.25%\n }\n '); } } // Run Auto-load players // You have to wait at least once in case this script is loaded after your // video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /** * Current software version. Follows semver. * * @type {string} */ videojs.VERSION = '6.0.0-RC.2'; /** * The global options object. These are the settings that take effect * if no overrides are specified when the player is created. * * @type {Object} */ videojs.options = _player2['default'].prototype.options_; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} * The created players */ videojs.getPlayers = function () { return _player2['default'].players; }; /** * Expose players object. * * @memberOf videojs * @property {Object} players */ videojs.players = _player2['default'].players; /** * Get a component class object by name * * @borrows Component.getComponent as videojs.getComponent */ videojs.getComponent = _component2['default'].getComponent; /** * Register a component so it can referred to by name. Used when adding to other * components, either through addChild `component.addChild('myComponent')` or through * default children options `{ children: ['myComponent'] }`. * * > NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {string} name * The class name of the component * * @param {Component} comp * The component class * * @return {Component} * The newly registered component */ videojs.registerComponent = function (name, comp) { if (_tech2['default'].isTech(comp)) { _log2['default'].warn('The ' + name + ' tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)'); } _component2['default'].registerComponent.call(_component2['default'], name, comp); }; /** * Get a Tech class object by name * * @borrows Tech.getTech as videojs.getTech */ videojs.getTech = _tech2['default'].getTech; /** * Register a Tech so it can referred to by name. * This is used in the tech order for the player. * * @borrows Tech.registerTech as videojs.registerTech */ videojs.registerTech = _tech2['default'].registerTech; videojs.use = _middleware.use; /** * A suite of browser and device tests from {@link browser}. * * @type {Object} * @private */ videojs.browser = browser; /** * Whether or not the browser supports touch events. Included for backward * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED` * instead going forward. * * @deprecated since version 5.0 * @type {boolean} */ videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED; /** * Subclass an existing class * Mimics ES6 subclassing with the `extend` keyword * * @borrows extend:extendFn as videojs.extend */ videojs.extend = _extend2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * * @borrows merge-options:mergeOptions as videojs.mergeOptions */ videojs.mergeOptions = _mergeOptions3['default']; /** * Change the context (this) of a function * * > NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function() {}.bind(newContext);` instead of this. * * @borrows fn:bind as videojs.bind */ videojs.bind = Fn.bind; /** * Register a Video.js plugin. * * @borrows plugin:registerPlugin as videojs.registerPlugin * @mixes videojs * @method registerPlugin * * @param {string} name * The name of the plugin to be registered. Must be a string and * must not match an existing plugin or a method on the `Player` * prototype. * * @param {Function} plugin * A sub-class of `Plugin` or a function for basic plugins. * * @return {Function} * For advanced plugins, a factory function for that plugin. For * basic plugins, a wrapper function that initializes the plugin. */ videojs.registerPlugin = _plugin2['default'].registerPlugin; /** * Deprecated method to register a plugin with Video.js * * @deprecated * videojs.plugin() is deprecated; use videojs.registerPlugin() instead * * @param {string} name * The plugin name * * @param {Plugin|Function} plugin * The plugin sub-class or function */ videojs.plugin = function (name, plugin) { _log2['default'].warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead'); return _plugin2['default'].registerPlugin(name, plugin); }; /** * Gets an object containing multiple Video.js plugins. * * @param {Array} [names] * If provided, should be an array of plugin names. Defaults to _all_ * plugin names. * * @return {Object|undefined} * An object containing plugin(s) associated with their name(s) or * `undefined` if no matching plugins exist). */ videojs.getPlugins = _plugin2['default'].getPlugins; /** * Gets a plugin by name if it exists. * * @param {string} name * The name of a plugin. * * @return {Function|undefined} * The plugin (or `undefined`). */ videojs.getPlugin = _plugin2['default'].getPlugin; /** * Gets a plugin's version, if available * * @param {string} name * The name of a plugin. * * @return {string} * The plugin's version or an empty string. */ videojs.getPluginVersion = _plugin2['default'].getPluginVersion; /** * Adding languages so that they're available to all players. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });` * * @param {string} code * The language code or dictionary property * * @param {Object} data * The data values to be translated * * @return {Object} * The resulting language dictionary object */ videojs.addLanguage = function (code, data) { var _mergeOptions; code = ('' + code).toLowerCase(); videojs.options.languages = (0, _mergeOptions3['default'])(videojs.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions)); return videojs.options.languages[code]; }; /** * Log messages * * @borrows log:log as videojs.log */ videojs.log = _log2['default']; /** * Creates an emulated TimeRange object. * * @borrows time-ranges:createTimeRanges as videojs.createTimeRange */ /** * @borrows time-ranges:createTimeRanges as videojs.createTimeRanges */ videojs.createTimeRange = videojs.createTimeRanges = _timeRanges.createTimeRanges; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @borrows format-time:formatTime as videojs.formatTime */ videojs.formatTime = _formatTime2['default']; /** * Resolve and parse the elements of a URL * * @borrows url:parseUrl as videojs.parseUrl */ videojs.parseUrl = Url.parseUrl; /** * Returns whether the url passed is a cross domain request or not. * * @borrows url:isCrossOrigin as videojs.isCrossOrigin */ videojs.isCrossOrigin = Url.isCrossOrigin; /** * Event target class. * * @borrows EventTarget as videojs.EventTarget */ videojs.EventTarget = _eventTarget2['default']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @borrows events:on as videojs.on */ videojs.on = Events.on; /** * Trigger a listener only once for an event * * @borrows events:one as videojs.one */ videojs.one = Events.one; /** * Removes event listeners from an element * * @borrows events:off as videojs.off */ videojs.off = Events.off; /** * Trigger an event for an element * * @borrows events:trigger as videojs.trigger */ videojs.trigger = Events.trigger; /** * A cross-browser XMLHttpRequest wrapper. Here's a simple example: * * @param {Object} options * settings for the request. * * @return {XMLHttpRequest|XDomainRequest} * The request object. * * @see https://github.com/Raynos/xhr */ videojs.xhr = _xhr2['default']; /** * TextTrack class * * @borrows TextTrack as videojs.TextTrack */ videojs.TextTrack = _textTrack2['default']; /** * export the AudioTrack class so that source handlers can create * AudioTracks and then add them to the players AudioTrackList * * @borrows AudioTrack as videojs.AudioTrack */ videojs.AudioTrack = _audioTrack2['default']; /** * export the VideoTrack class so that source handlers can create * VideoTracks and then add them to the players VideoTrackList * * @borrows VideoTrack as videojs.VideoTrack */ videojs.VideoTrack = _videoTrack2['default']; /** * Determines, via duck typing, whether or not a value is a DOM element. * * @borrows dom:isEl as videojs.isEl * @deprecated Use videojs.dom.isEl() instead */ /** * Determines, via duck typing, whether or not a value is a text node. * * @borrows dom:isTextNode as videojs.isTextNode * @deprecated Use videojs.dom.isTextNode() instead */ /** * Creates an element and applies properties. * * @borrows dom:createEl as videojs.createEl * @deprecated Use videojs.dom.createEl() instead */ /** * Check if an element has a CSS class * * @borrows dom:hasElClass as videojs.hasClass * @deprecated Use videojs.dom.hasClass() instead */ /** * Add a CSS class name to an element * * @borrows dom:addElClass as videojs.addClass * @deprecated Use videojs.dom.addClass() instead */ /** * Remove a CSS class name from an element * * @borrows dom:removeElClass as videojs.removeClass * @deprecated Use videojs.dom.removeClass() instead */ /** * Adds or removes a CSS class name on an element depending on an optional * condition or the presence/absence of the class name. * * @borrows dom:toggleElClass as videojs.toggleClass * @deprecated Use videojs.dom.toggleClass() instead */ /** * Apply attributes to an HTML element. * * @borrows dom:setElAttributes as videojs.setAttribute * @deprecated Use videojs.dom.setAttributes() instead */ /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @borrows dom:getElAttributes as videojs.getAttributes * @deprecated Use videojs.dom.getAttributes() instead */ /** * Empties the contents of an element. * * @borrows dom:emptyEl as videojs.emptyEl * @deprecated Use videojs.dom.emptyEl() instead */ /** * Normalizes and appends content to an element. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @borrows dom:appendContents as videojs.appendContet * @deprecated Use videojs.dom.appendContent() instead */ /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @borrows dom:insertContent as videojs.insertContent * @deprecated Use videojs.dom.insertContent() instead */ ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(function (k) { videojs[k] = function () { _log2['default'].warn('videojs.' + k + '() is deprecated; use videojs.dom.' + k + '() instead'); return Dom[k].apply(null, arguments); }; }); /** * A safe getComputedStyle with an IE8 fallback. * * This is because in Firefox, if the player is loaded in an iframe with `display:none`, * then `getComputedStyle` returns `null`, so, we do a null-check to make sure * that the player doesn't break in these cases. * See https://bugzilla.mozilla.org/show_bug.cgi?id=548397 for more details. * * @borrows computed-style:computedStyle as videojs.computedStyle */ videojs.computedStyle = _computedStyle2['default']; /** * Export the Dom utilities for use in external plugins * and Tech's */ videojs.dom = Dom; /** * Export the Url utilities for use in external plugins * and Tech's */ videojs.url = Url; // We use Node-style module.exports here instead of ES6 because it is more // compatible with different module systems. module.exports = videojs; },{"108":108,"43":43,"44":44,"5":5,"54":54,"55":55,"57":57,"61":61,"62":62,"64":64,"72":72,"78":78,"79":79,"81":81,"83":83,"84":84,"86":86,"87":87,"89":89,"90":90,"91":91,"92":92,"93":93,"95":95,"97":97,"98":98}],97:[function(_dereq_,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = _dereq_(99); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"99":99}],98:[function(_dereq_,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],99:[function(_dereq_,module,exports){ },{}],100:[function(_dereq_,module,exports){ module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } },{}],101:[function(_dereq_,module,exports){ function clean (s) { return s.replace(/\n\r?\s*/g, '') } module.exports = function tsml (sa) { var s = '' , i = 0 for (; i < arguments.length; i++) s += clean(sa[i]) + (arguments[i + 1] || '') return s } },{}],102:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * 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. */ // Default exports for Node. Export the extended versions of VTTCue and // VTTRegion in Node since we likely want the capability to convert back and // forth between JSON. If we don't then it's not that big of a deal since we're // off browser. module.exports = { WebVTT: _dereq_(103).WebVTT, VTTCue: _dereq_(104).VTTCue, VTTRegion: _dereq_(106).VTTRegion }; },{"103":103,"104":104,"106":106}],103:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * 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. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F, 0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E, 0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678, 0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A, 0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C, 0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5, 0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE, 0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7, 0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0, 0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9, 0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2, 0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB, 0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D, 0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718, 0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721, 0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A, 0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750, 0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759, 0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762, 0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B, 0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774, 0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D, 0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786, 0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F, 0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798, 0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1, 0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3, 0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC, 0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5, 0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE, 0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7, 0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802, 0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B, 0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814, 0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834, 0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D, 0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847, 0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850, 0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E, 0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9, 0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22, 0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55, 0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67, 0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82, 0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B, 0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94, 0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D, 0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF, 0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8, 0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB, 0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED, 0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6, 0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF, 0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08, 0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11, 0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A, 0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23, 0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C, 0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35, 0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E, 0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47, 0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50, 0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59, 0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62, 0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B, 0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74, 0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D, 0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86, 0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F, 0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98, 0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1, 0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA, 0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3, 0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC, 0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5, 0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE, 0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7, 0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0, 0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9, 0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2, 0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB, 0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04, 0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D, 0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16, 0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F, 0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28, 0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31, 0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A, 0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55, 0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E, 0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67, 0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70, 0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79, 0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82, 0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B, 0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96, 0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F, 0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8, 0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1, 0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA, 0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3, 0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4, 0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C, 0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95, 0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB, 0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4, 0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF, 0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8, 0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803, 0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E, 0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816, 0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E, 0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826, 0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E, 0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837, 0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844, 0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C, 0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854, 0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905, 0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D, 0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921, 0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929, 0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931, 0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939, 0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986, 0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E, 0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996, 0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E, 0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13, 0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D, 0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25, 0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D, 0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51, 0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60, 0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68, 0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70, 0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78, 0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00, 0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08, 0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10, 0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18, 0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20, 0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28, 0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30, 0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42, 0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A, 0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52, 0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64, 0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C, 0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01, 0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09, 0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11, 0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19, 0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21, 0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29, 0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31, 0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39, 0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41, 0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00, 0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09, 0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11, 0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19, 0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E, 0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E, 0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A, 0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74, 0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E, 0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87, 0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90, 0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98, 0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6, 0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF, 0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7, 0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD]; function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); for (var j = 0; j < strongRTLChars.length; j++) { if (strongRTLChars[j] === charCode) { return "rtl"; } } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%") }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px") }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, vttjs, decoder) { if (!decoder) { decoder = vttjs; vttjs = {}; } if (!vttjs) { vttjs = {}; } this.window = window; this.vttjs = vttjs; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this, (this.vttjs || {}))); },{}],104:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * 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. */ // If we're in Node.js then require VTTCue so we can extend it, otherwise assume // VTTCue is on the global. if (typeof module !== "undefined" && module.exports) { this.VTTCue = this.VTTCue || _dereq_(105).VTTCue; } // Extend VTTCue with methods to convert to JSON, from JSON, and construct a // VTTCue from an options object. The primary purpose of this is for use in the // vtt.js test suite (for testing only properties that we care about). It's also // useful if you need to work with VTTCues in JSON format. (function(root) { root.VTTCue.prototype.toJSON = function() { var cue = {}, self = this; // Filter out getCueAsHTML as it's a function and hasBeenReset and displayState as // they're only used when running the processing model algorithm. Object.keys(this).forEach(function(key) { if (key !== "getCueAsHTML" && key !== "hasBeenReset" && key !== "displayState") { cue[key] = self[key]; } }); return cue; }; root.VTTCue.create = function(options) { if (!options.hasOwnProperty("startTime") || !options.hasOwnProperty("endTime") || !options.hasOwnProperty("text")) { throw new Error("You must at least have start time, end time, and text."); } var cue = new root.VTTCue(options.startTime, options.endTime, options.text); for (var key in options) { if (cue.hasOwnProperty(key)) { cue[key] = options[key]; } } return cue; }; root.VTTCue.fromJSON = function(json) { return this.create(JSON.parse(json)); }; }(this)); },{"105":105}],105:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * 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. */ (function(root, vttjs) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = root.VTTCue || VTTCue; vttjs.VTTCue = VTTCue; }(this, (this.vttjs || {}))); },{}],106:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * 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. */ // If we're in Node.js then require VTTRegion so we can extend it, otherwise assume // VTTRegion is on the global. if (typeof module !== "undefined" && module.exports) { this.VTTRegion = _dereq_(107).VTTRegion; } // Extend VTTRegion with methods to convert to JSON, from JSON, and construct a // VTTRegion from an options object. The primary purpose of this is for use in the // vtt.js test suite. It's also useful if you need to work with VTTRegions in // JSON format. (function(root) { root.VTTRegion.create = function(options) { var region = new root.VTTRegion(); for (var key in options) { if (region.hasOwnProperty(key)) { region[key] = options[key]; } } return region; }; root.VTTRegion.fromJSON = function(json) { return this.create(JSON.parse(json)); }; }(this)); },{"107":107}],107:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * 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. */ (function(root, vttjs) { var scrollSetting = { "": true, "up": true }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; vttjs.VTTRegion = VTTRegion; }(this, (this.vttjs || {}))); },{}],108:[function(_dereq_,module,exports){ "use strict"; var window = _dereq_(98) var isFunction = _dereq_(109) var parseHeaders = _dereq_(112) var xtend = _dereq_(113) module.exports = createXHR createXHR.XMLHttpRequest = window.XMLHttpRequest || noop createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) { createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) { options = initParams(uri, options, callback) options.method = method.toUpperCase() return _createXHR(options) } }) function forEachArray(array, iterator) { for (var i = 0; i < array.length; i++) { iterator(array[i]) } } function isEmpty(obj){ for(var i in obj){ if(obj.hasOwnProperty(i)) return false } return true } function initParams(uri, options, callback) { var params = uri if (isFunction(options)) { callback = options if (typeof uri === "string") { params = {uri:uri} } } else { params = xtend(options, {uri: uri}) } params.callback = callback return params } function createXHR(uri, options, callback) { options = initParams(uri, options, callback) return _createXHR(options) } function _createXHR(options) { if(typeof options.callback === "undefined"){ throw new Error("callback argument missing") } var called = false var callback = function cbOnce(err, response, body){ if(!called){ called = true options.callback(err, response, body) } } function readystatechange() { if (xhr.readyState === 4) { loadFunc() } } function getBody() { // Chrome with requestType=blob throws errors arround when even testing access to responseText var body = undefined if (xhr.response) { body = xhr.response } else { body = xhr.responseText || getXml(xhr) } if (isJson) { try { body = JSON.parse(body) } catch (e) {} } return body } function errorFunc(evt) { clearTimeout(timeoutTimer) if(!(evt instanceof Error)){ evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) } evt.statusCode = 0 return callback(evt, failureResponse) } // will load the data & process the response in a special response object function loadFunc() { if (aborted) return var status clearTimeout(timeoutTimer) if(options.useXDR && xhr.status===undefined) { //IE8 CORS GET successful response doesn't have a status field, but body is fine status = 200 } else { status = (xhr.status === 1223 ? 204 : xhr.status) } var response = failureResponse var err = null if (status !== 0){ response = { body: getBody(), statusCode: status, method: method, headers: {}, url: uri, rawRequest: xhr } if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE response.headers = parseHeaders(xhr.getAllResponseHeaders()) } } else { err = new Error("Internal XMLHttpRequest Error") } return callback(err, response, response.body) } var xhr = options.xhr || null if (!xhr) { if (options.cors || options.useXDR) { xhr = new createXHR.XDomainRequest() }else{ xhr = new createXHR.XMLHttpRequest() } } var key var aborted var uri = xhr.url = options.uri || options.url var method = xhr.method = options.method || "GET" var body = options.body || options.data var headers = xhr.headers = options.headers || {} var sync = !!options.sync var isJson = false var timeoutTimer var failureResponse = { body: undefined, headers: {}, statusCode: 0, method: method, url: uri, rawRequest: xhr } if ("json" in options && options.json !== false) { isJson = true headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user if (method !== "GET" && method !== "HEAD") { headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user body = JSON.stringify(options.json === true ? body : options.json) } } xhr.onreadystatechange = readystatechange xhr.onload = loadFunc xhr.onerror = errorFunc // IE9 must have onprogress be set to a unique function. xhr.onprogress = function () { // IE must die } xhr.onabort = function(){ aborted = true; } xhr.ontimeout = errorFunc xhr.open(method, uri, !sync, options.username, options.password) //has to be after open if(!sync) { xhr.withCredentials = !!options.withCredentials } // Cannot set timeout with sync request // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent if (!sync && options.timeout > 0 ) { timeoutTimer = setTimeout(function(){ if (aborted) return aborted = true//IE9 may still call readystatechange xhr.abort("timeout") var e = new Error("XMLHttpRequest timeout") e.code = "ETIMEDOUT" errorFunc(e) }, options.timeout ) } if (xhr.setRequestHeader) { for(key in headers){ if(headers.hasOwnProperty(key)){ xhr.setRequestHeader(key, headers[key]) } } } else if (options.headers && !isEmpty(options.headers)) { throw new Error("Headers cannot be set on an XDomainRequest object") } if ("responseType" in options) { xhr.responseType = options.responseType } if ("beforeSend" in options && typeof options.beforeSend === "function" ) { options.beforeSend(xhr) } // Microsoft Edge browser sends "undefined" when send is called with undefined value. // XMLHttpRequest spec says to pass null as body to indicate no body // See https://github.com/naugtur/xhr/issues/100. xhr.send(body || null) return xhr } function getXml(xhr) { if (xhr.responseType === "document") { return xhr.responseXML } var firefoxBugTakenEffect = xhr.status === 204 && xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror" if (xhr.responseType === "" && !firefoxBugTakenEffect) { return xhr.responseXML } return null } function noop() {} },{"109":109,"112":112,"113":113,"98":98}],109:[function(_dereq_,module,exports){ module.exports = isFunction var toString = Object.prototype.toString function isFunction (fn) { var string = toString.call(fn) return string === '[object Function]' || (typeof fn === 'function' && string !== '[object RegExp]') || (typeof window !== 'undefined' && // IE8 and below (fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt)) }; },{}],110:[function(_dereq_,module,exports){ var isFunction = _dereq_(109) module.exports = forEach var toString = Object.prototype.toString var hasOwnProperty = Object.prototype.hasOwnProperty function forEach(list, iterator, context) { if (!isFunction(iterator)) { throw new TypeError('iterator must be a function') } if (arguments.length < 3) { context = this } if (toString.call(list) === '[object Array]') forEachArray(list, iterator, context) else if (typeof list === 'string') forEachString(list, iterator, context) else forEachObject(list, iterator, context) } function forEachArray(array, iterator, context) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { iterator.call(context, array[i], i, array) } } } function forEachString(string, iterator, context) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. iterator.call(context, string.charAt(i), i, string) } } function forEachObject(object, iterator, context) { for (var k in object) { if (hasOwnProperty.call(object, k)) { iterator.call(context, object[k], k, object) } } } },{"109":109}],111:[function(_dereq_,module,exports){ exports = module.exports = trim; function trim(str){ return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ return str.replace(/^\s*/, ''); }; exports.right = function(str){ return str.replace(/\s*$/, ''); }; },{}],112:[function(_dereq_,module,exports){ var trim = _dereq_(111) , forEach = _dereq_(110) , isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } module.exports = function (headers) { if (!headers) return {} var result = {} forEach( trim(headers).split('\n') , function (row) { var index = row.indexOf(':') , key = trim(row.slice(0, index)).toLowerCase() , value = trim(row.slice(index + 1)) if (typeof(result[key]) === 'undefined') { result[key] = value } else if (isArray(result[key])) { result[key].push(value) } else { result[key] = [ result[key], value ] } } ) return result } },{"110":110,"111":111}],113:[function(_dereq_,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } },{}]},{},[96])(96) });
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'quicktable', 'bg', { more: 'Още...' } );
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * 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 NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK 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. * * @providesModule Game2048 * @flow */ 'use strict'; var React = require('react-native'); var { AppRegistry, StyleSheet, Text, View, } = React; var Animated = require('Animated'); var GameBoard = require('GameBoard'); var TouchableBounce = require('TouchableBounce'); var BOARD_PADDING = 3; var CELL_MARGIN = 4; var CELL_SIZE = 60; class Cell extends React.Component { render() { return <View style={styles.cell} />; } } class Board extends React.Component { render() { return ( <View style={styles.board}> <View style={styles.row}><Cell/><Cell/><Cell/><Cell/></View> <View style={styles.row}><Cell/><Cell/><Cell/><Cell/></View> <View style={styles.row}><Cell/><Cell/><Cell/><Cell/></View> <View style={styles.row}><Cell/><Cell/><Cell/><Cell/></View> {this.props.children} </View> ); } } class Tile extends React.Component { static _getPosition(index): number { return BOARD_PADDING + (index * (CELL_SIZE + CELL_MARGIN * 2) + CELL_MARGIN); } constructor(props: {}) { super(props); var tile = this.props.tile; this.state = { opacity: new Animated.Value(0), top: new Animated.Value(Tile._getPosition(tile.toRow())), left: new Animated.Value(Tile._getPosition(tile.toColumn())), }; } calculateOffset(): {top: number; left: number; opacity: number} { var tile = this.props.tile; var offset = { top: this.state.top, left: this.state.left, opacity: this.state.opacity, }; if (tile.isNew()) { Animated.timing(this.state.opacity, { duration: 100, toValue: 1, }).start(); } else { Animated.parallel([ Animated.timing(offset.top, { duration: 100, toValue: Tile._getPosition(tile.toRow()), }), Animated.timing(offset.left, { duration: 100, toValue: Tile._getPosition(tile.toColumn()), }), ]).start(); } return offset; } render() { var tile = this.props.tile; var tileStyles = [ styles.tile, styles['tile' + tile.value], this.calculateOffset(), ]; var textStyles = [ styles.value, tile.value > 4 && styles.whiteText, tile.value > 100 && styles.threeDigits, tile.value > 1000 && styles.fourDigits, ]; return ( <Animated.View style={tileStyles}> <Text style={textStyles}>{tile.value}</Text> </Animated.View> ); } } class GameEndOverlay extends React.Component { render() { var board = this.props.board; if (!board.hasWon() && !board.hasLost()) { return <View/>; } var message = board.hasWon() ? 'Good Job!' : 'Game Over'; return ( <View style={styles.overlay}> <Text style={styles.overlayMessage}>{message}</Text> <TouchableBounce onPress={this.props.onRestart} style={styles.tryAgain}> <Text style={styles.tryAgainText}>Try Again?</Text> </TouchableBounce> </View> ); } } class Game2048 extends React.Component { startX: number; startY: number; constructor(props: {}) { super(props); this.state = { board: new GameBoard(), }; this.startX = 0; this.startY = 0; } restartGame() { this.setState({board: new GameBoard()}); } handleTouchStart(event: Object) { if (this.state.board.hasWon()) { return; } this.startX = event.nativeEvent.pageX; this.startY = event.nativeEvent.pageY; } handleTouchEnd(event: Object) { if (this.state.board.hasWon()) { return; } var deltaX = event.nativeEvent.pageX - this.startX; var deltaY = event.nativeEvent.pageY - this.startY; var direction = -1; if (Math.abs(deltaX) > 3 * Math.abs(deltaY) && Math.abs(deltaX) > 30) { direction = deltaX > 0 ? 2 : 0; } else if (Math.abs(deltaY) > 3 * Math.abs(deltaX) && Math.abs(deltaY) > 30) { direction = deltaY > 0 ? 3 : 1; } if (direction !== -1) { this.setState({board: this.state.board.move(direction)}); } } render() { var tiles = this.state.board.tiles .filter((tile) => tile.value) .map((tile) => <Tile ref={tile.id} key={tile.id} tile={tile} />); return ( <View style={styles.container} onTouchStart={(event) => this.handleTouchStart(event)} onTouchEnd={(event) => this.handleTouchEnd(event)}> <Board> {tiles} </Board> <GameEndOverlay board={this.state.board} onRestart={() => this.restartGame()} /> </View> ); } } var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, board: { padding: BOARD_PADDING, backgroundColor: '#bbaaaa', borderRadius: 5, }, overlay: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, backgroundColor: 'rgba(221, 221, 221, 0.5)', flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }, overlayMessage: { fontSize: 40, marginBottom: 20, }, tryAgain: { backgroundColor: '#887761', padding: 20, borderRadius: 5, }, tryAgainText: { color: '#ffffff', fontSize: 20, fontWeight: '500', }, cell: { width: CELL_SIZE, height: CELL_SIZE, borderRadius: 5, backgroundColor: '#ddccbb', margin: CELL_MARGIN, }, row: { flexDirection: 'row', }, tile: { position: 'absolute', width: CELL_SIZE, height: CELL_SIZE, backgroundColor: '#ddccbb', borderRadius: 5, flex: 1, justifyContent: 'center', alignItems: 'center', }, value: { fontSize: 24, color: '#776666', fontFamily: 'Verdana', fontWeight: '500', }, tile2: { backgroundColor: '#eeeeee', }, tile4: { backgroundColor: '#eeeecc', }, tile8: { backgroundColor: '#ffbb87', }, tile16: { backgroundColor: '#ff9966', }, tile32: { backgroundColor: '#ff7755', }, tile64: { backgroundColor: '#ff5533', }, tile128: { backgroundColor: '#eecc77', }, tile256: { backgroundColor: '#eecc66', }, tile512: { backgroundColor: '#eecc55', }, tile1024: { backgroundColor: '#eecc33', }, tile2048: { backgroundColor: '#eecc22', }, whiteText: { color: '#ffffff', }, threeDigits: { fontSize: 20, }, fourDigits: { fontSize: 18, }, }); AppRegistry.registerComponent('Game2048', () => Game2048); module.exports = Game2048;
/*! Raven.js 3.9.2 (5286373) | github.com/getsentry/raven-js */ !function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b=b.Raven||(b.Raven={}),b=b.Plugins||(b.Plugins={}),b.Require=a()}}(function(){var a;return function b(a,c,d){function e(g,h){if(!c[g]){if(!a[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};a[g][0].call(k.exports,function(b){var c=a[g][1][b];return e(c?c:b)},k,k.exports,b,a,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(b,c,d){"use strict";function e(c){"function"==typeof a&&a.amd&&(window.define=c.wrap({deep:!1},a),window.require=c.wrap({deep:!1},b))}c.exports=e},{}]},{},[1])(1)}); //# sourceMappingURL=require.min.js.map
/** * @license Angulartics v0.17.2 * (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics * License: MIT */ (function(angular) { 'use strict'; /** * @ngdoc overview * @name angulartics.google.analytics * Enables analytics support for Google Analytics (http://google.com/analytics) * for Cordova with google-analytics-plugin (https://github.com/danwilson/google-analytics-plugin) */ angular.module('angulartics.google.analytics.cordova', ['angulartics']) .provider('googleAnalyticsCordova', function () { var GoogleAnalyticsCordova = [ '$q', '$log', 'ready', 'debug', 'trackingId', 'period', function ($q, $log, ready, debug, trackingId, period) { var deferred = $q.defer(); var deviceReady = false; window.addEventListener('deviceReady', function () { deviceReady = true; deferred.resolve(); }); setTimeout(function () { if (!deviceReady) { deferred.resolve(); } }, 3000); function success() { if (debug) { $log.info(arguments); } } function failure(err) { if (debug) { $log.error(err); } } this.init = function () { return deferred.promise.then(function () { if (typeof analytics != 'undefined') { ready(analytics, success, failure); analytics.startTrackerWithId(trackingId); } else if (debug) { $log.error('Google Analytics Plugin for Cordova is not available'); } }); }; }]; return { $get: ['$injector', function ($injector) { return $injector.instantiate(GoogleAnalyticsCordova, { ready: this._ready || angular.noop, debug: this.debug, trackingId: this.trackingId, period: this.period }); }], ready: function (fn) { this._ready = fn; } }; }) .config(['$analyticsProvider', 'googleAnalyticsCordovaProvider', function ($analyticsProvider, googleAnalyticsCordovaProvider) { googleAnalyticsCordovaProvider.ready(function (analytics, success, failure) { $analyticsProvider.registerPageTrack(function (path) { analytics.trackView(path); }); $analyticsProvider.registerEventTrack(function (action, properties) { analytics.trackEvent(properties.category, action, properties.label, properties.value); }); }); }]) .run(['googleAnalyticsCordova', function (googleAnalyticsCordova) { googleAnalyticsCordova.init(); }]); })(angular);
/** * Sinon.JS 1.17.3, 2016/02/10 * * @author Christian Johansen (christian@cjohansen.no) * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS * * (The BSD License) * * Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Christian Johansen nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Helps IE run the fake timers. By defining global functions, IE allows * them to be overwritten at a later point. If these are not defined like * this, overwriting them will result in anything from an exception to browser * crash. * * If you don't require fake timers to work in IE, don't include this file. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ /*eslint-disable strict, no-inner-declarations, no-unused-vars*/ if (typeof window !== "undefined") { function setTimeout() {} function clearTimeout() {} function setImmediate() {} function clearImmediate() {} function setInterval() {} function clearInterval() {} function Date() {} // Reassign the original functions. Now their writable attribute // should be true. Hackish, I know, but it works. /*global sinon*/ setTimeout = sinon.timers.setTimeout; clearTimeout = sinon.timers.clearTimeout; setImmediate = sinon.timers.setImmediate; clearImmediate = sinon.timers.clearImmediate; setInterval = sinon.timers.setInterval; clearInterval = sinon.timers.clearInterval; Date = sinon.timers.Date; // eslint-disable-line no-native-reassign } /*eslint-enable no-inner-declarations*/ /** * Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows * them to be overwritten at a later point. If these are not defined like * this, overwriting them will result in anything from an exception to browser * crash. * * If you don't require fake XHR to work in IE, don't include this file. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ /*eslint-disable strict*/ if (typeof window !== "undefined") { function XMLHttpRequest() {} // eslint-disable-line no-unused-vars, no-inner-declarations // Reassign the original function. Now its writable attribute // should be true. Hackish, I know, but it works. /*global sinon*/ XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined; } /*eslint-enable strict*/ /** * Helps IE run the fake XDomainRequest. By defining global functions, IE allows * them to be overwritten at a later point. If these are not defined like * this, overwriting them will result in anything from an exception to browser * crash. * * If you don't require fake XDR to work in IE, don't include this file. */ /*eslint-disable strict*/ if (typeof window !== "undefined") { function XDomainRequest() {} // eslint-disable-line no-unused-vars, no-inner-declarations // Reassign the original function. Now its writable attribute // should be true. Hackish, I know, but it works. /*global sinon*/ XDomainRequest = sinon.xdr.XDomainRequest || undefined; } /*eslint-enable strict*/
var dom = require("../../../../lib/jsdom/living"); exports.hc_staff = function() { var doc = new dom.Document("html"); var implementation = new dom.DOMImplementation(doc, { "XML" : ["1.0", "2.0"], "core": ["1.0", "2.0", "3.0"] }); var notations = new dom.NotationNodeMap( doc, doc.createNotationNode("notation1","notation1File", null), doc.createNotationNode("notation2",null, "notation2File") ); // TODO: consider importing the master list of entities // http://www.w3schools.com/tags/ref_symbols.asp var entities = new dom.EntityNodeMap( doc, doc.createEntityNode("alpha", doc.createTextNode("α")), doc.createEntityNode("beta", doc.createTextNode("&#946;")), doc.createEntityNode("gamma", doc.createTextNode("&#947;")), doc.createEntityNode("delta", doc.createTextNode("&#948;")), doc.createEntityNode("epsilon", doc.createTextNode("&#949;")) ); // <!ATTLIST acronym dir CDATA "ltr"> var defaultAttributes = new dom.NamedNodeMap(doc); var acronym = doc.createElementNS("http://www.w3.org/2000/xmlns/","acronym"); acronym.setAttribute("dir", "ltr"); defaultAttributes.setNamedItem(acronym); var doctype = new dom.DocumentType(doc, "xml", entities, notations, defaultAttributes); doc.doctype = doctype; doc.implementation = implementation; doc.appendChild(doc.createComment(" This is comment number 1.")); var html = doc.createElementNS("http://www.w3.org/2000/xmlns/","html"); var html = doc.appendChild(html); var head = doc.createElementNS("http://www.w3.org/2000/xmlns/","head"); var head = html.appendChild(head); var meta = doc.createElementNS("http://www.w3.org/2000/xmlns/","meta"); meta.setAttribute("http-equiv", "Content-Type"); meta.setAttribute("content", "text/html; charset=UTF-8"); head.appendChild(meta); var title = doc.createElementNS("http://www.w3.org/2000/xmlns/","title") title.appendChild(doc.createTextNode("hc_staff")); var title = head.appendChild(title); // make the tests work.... head.appendChild(doc.createElementNS("http://www.w3.org/2000/xmlns/","script")); head.appendChild(doc.createElementNS("http://www.w3.org/2000/xmlns/","script")); head.appendChild(doc.createElementNS("http://www.w3.org/2000/xmlns/","script")); var body = doc.createElementNS("http://www.w3.org/2000/xmlns/","body"); var staff = html.appendChild(body); var employees = []; var addresses = []; var names = []; var positions = []; var genders = []; var ids = []; var salaries = []; // create 5 employees for (var i=0; i<5; i++) { var employee = doc.createElementNS("http://www.w3.org/2000/xmlns/","p"); var address = doc.createElementNS("http://www.w3.org/2000/xmlns/","acronym"); var name = doc.createElementNS("http://www.w3.org/2000/xmlns/","strong"); var position = doc.createElementNS("http://www.w3.org/2000/xmlns/","code"); var gender = doc.createElementNS("http://www.w3.org/2000/xmlns/","var"); var id = doc.createElementNS("http://www.w3.org/2000/xmlns/","em"); var salary = doc.createElementNS("http://www.w3.org/2000/xmlns/","sup"); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(id); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(name); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(position); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(salary); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(gender); employee.appendChild(doc.createTextNode("\n")); employee.appendChild(address); employee.appendChild(doc.createTextNode("\n")); staff.appendChild(employee); names.push(name); employees.push(employee); addresses.push(address); genders.push(gender); positions.push(position); ids.push(id); salaries.push(salary); } ids[0].appendChild(doc.createTextNode("EMP0001")); salaries[0].appendChild(doc.createTextNode("56,000")); addresses[0].setAttribute("title", "Yes"); addresses[0].appendChild(doc.createTextNode('1230 North Ave. Dallas, Texas 98551')); names[0].appendChild(doc.createTextNode("Margaret Martin")); genders[0].appendChild(doc.createTextNode("Female")); positions[0].appendChild(doc.createTextNode("Accountant")); ids[1].appendChild(doc.createTextNode("EMP0002")); salaries[1].appendChild(doc.createTextNode("35,000")); addresses[1].setAttribute("title", "Yes"); addresses[1].setAttribute("class", "Yes"); addresses[1].appendChild(doc.createTextNode("β Dallas, γ\n 98554")); names[1].appendChild(doc.createTextNode("Martha Raynolds")); names[1].appendChild(doc.createCDATASection("This is a CDATASection with EntityReference number 2 &amp;ent2;")); names[1].appendChild(doc.createCDATASection("This is an adjacent CDATASection with a reference to a tab &amp;tab;")); genders[1].appendChild(doc.createTextNode("Female")); positions[1].appendChild(doc.createTextNode("Secretary")); ids[2].appendChild(doc.createTextNode("EMP0003")); salaries[2].appendChild(doc.createTextNode("100,000")); addresses[2].setAttribute("title", "Yes"); addresses[2].setAttribute("class", "No"); addresses[2].appendChild(doc.createTextNode("PO Box 27 Irving, texas 98553")); names[2].appendChild(doc.createTextNode("Roger\n Jones")) ; genders[2].appendChild(doc.createEntityReference("&delta;"));//Text("&delta;")); positions[2].appendChild(doc.createTextNode("Department Manager")); ids[3].appendChild(doc.createTextNode("EMP0004")); salaries[3].appendChild(doc.createTextNode("95,000")); addresses[3].setAttribute("title", "Yes"); addresses[3].setAttribute("class", "Yα"); addresses[3].appendChild(doc.createTextNode("27 South Road. Dallas, Texas 98556")); names[3].appendChild(doc.createTextNode("Jeny Oconnor")); genders[3].appendChild(doc.createTextNode("Female")); positions[3].appendChild(doc.createTextNode("Personal Director")); ids[4].appendChild(doc.createTextNode("EMP0005")); salaries[4].appendChild(doc.createTextNode("90,000")); addresses[4].setAttribute("title", "Yes"); addresses[4].appendChild(doc.createTextNode("1821 Nordic. Road, Irving Texas 98558")); names[4].appendChild(doc.createTextNode("Robert Myers")); genders[4].appendChild(doc.createTextNode("male")); positions[4].appendChild(doc.createTextNode("Computer Specialist")); doc.appendChild(doc.createProcessingInstruction("TEST-STYLE", "PIDATA")); doc.normalize(); return doc; };
"use strict" /** * @class elFinder command "archive" * Archive selected files * * @author Dmitry (dio) Levashov **/ elFinder.prototype.commands.archive = function() { var self = this, fm = self.fm, mimes = []; this.variants = []; this.disableOnSearch = true; /** * Update mimes on open/reload * * @return void **/ fm.bind('open reload', function() { self.variants = []; $.each((mimes = fm.option('archivers')['create'] || []), function(i, mime) { self.variants.push([mime, fm.mime2kind(mime)]) }); self.change(); }); this.getstate = function() { return !this._disabled && mimes.length && fm.selected().length && fm.cwd().write ? 0 : -1; } this.exec = function(hashes, type) { var files = this.files(hashes), cnt = files.length, mime = type || mimes[0], cwd = fm.cwd(), error = ['errArchive', 'errPerm', 'errCreatingTempDir', 'errFtpDownloadFile', 'errFtpUploadFile', 'errFtpMkdir', 'errArchiveExec', 'errExtractExec', 'errRm'], dfrd = $.Deferred().fail(function(error) { error && fm.error(error); }), i; if (!(this.enabled() && cnt && mimes.length && $.inArray(mime, mimes) !== -1)) { return dfrd.reject(); } if (!cwd.write) { return dfrd.reject(error); } for (i = 0; i < cnt; i++) { if (!files[i].read) { return dfrd.reject(error); } } return fm.request({ data : {cmd : 'archive', targets : this.hashes(hashes), type : mime}, notify : {type : 'archive', cnt : 1}, syncOnFail : true }); } }
export class DynamicDialogConfig{};
// fixture/logo.png var assert = require('assert') , Stream = require('stream') , fs = require('fs') , mongo = require('mongodb') , Grid = require('../') , crypto = require('crypto') , checksum = require('checksum') , tmpDir = __dirname + '/tmp/' , fixturesDir = __dirname + '/fixtures/' , imgReadPath = fixturesDir + 'mongo.png' , txtReadPath =fixturesDir + 'text.txt' , emptyReadPath = fixturesDir + 'emptydoc.txt' , largeBlobPath = tmpDir + '1mbBlob' , server , db describe('test', function(){ var id; before(function (done) { server = new mongo.Server('localhost', 27017); db = new mongo.Db('gridstream_test', server, {w:1}); if (!fs.existsSync(tmpDir)) { fs.mkdirSync(tmpDir); } fs.writeFile(largeBlobPath, crypto.randomBytes(1024*1024), function (err) { if (err) { done(err); } db.open(done) }); }); describe('Grid', function () { it('should be a function', function () { assert('function' == typeof Grid); }); it('should create instances without the new keyword', function () { var x = Grid(2,3); assert(x instanceof Grid); }); it('should store the arguments', function () { var x = new Grid(4, 5); assert.equal(x.db, 4); assert.equal(x.mongo, 5); }); it('should require mongo argument', function(){ assert.throws(function () { new Grid(3) }, /missing mongo argument/); }) it('should require db argument', function(){ assert.throws(function () { new Grid(null, 3) }, /missing db argument/); }) describe('files', function(){ it('returns a collection', function(){ var g = new Grid(db, mongo); assert(g.files instanceof mongo.Collection); }) }) describe('collection()', function(){ it('changes the files collection', function(){ var g = new Grid(db, mongo); assert.equal('function', typeof g.collection); assert(g.collection() instanceof mongo.Collection); assert.equal(g.collection(), g.files); var old = g.collection(); g.collection('changed'); assert(g.collection() instanceof mongo.Collection); assert.ok(g.collection() == g.files); assert.ok(g.collection() != old); assert.equal(g.collection(), g.files); assert.equal(g.collection().collectionName, 'changed.files'); }) }); }); describe('createWriteStream', function(){ it('should be a function', function () { var x = Grid(1, mongo); assert('function' == typeof x.createWriteStream); }); }) describe('GridWriteStream', function(){ var g , ws before(function(){ Grid.mongo = mongo; g = Grid(db); ws = g.createWriteStream({ filename: 'logo.png' }); }); it('should be an instance of Stream', function(){ assert(ws instanceof Stream); }) it('should be an instance of Stream.Writable', function(){ assert(ws instanceof Stream.Writable); }) it('should should be writable', function(){ assert(ws.writable); }); it('should store the grid', function(){ assert(ws._grid == g) }); it('should have an id', function(){ assert(ws.id) }) it('id should be an ObjectId', function(){ assert(ws.id instanceof mongo.ObjectID); }); it('should have a name', function(){ assert(ws.name == 'logo.png') }) describe('options', function(){ it('should have one key', function(){ assert(Object.keys(ws.options).length === 1); }); it('should have filename option', function(){ assert(ws.options.filename === 'logo.png'); }); }) it('mode should default to w', function(){ assert(ws.mode == 'w'); }) describe('store', function(){ it('should be an instance of mongo.GridStore', function(){ assert(ws._store instanceof mongo.GridStore) }) }) describe('#methods', function(){ describe('write', function(){ it('should be a function', function(){ assert('function' == typeof ws.write) }) }) describe('end', function(){ it('should be a function', function(){ assert('function' == typeof ws.end) }) }) describe('destroy', function(){ it('should be a function', function(){ assert('function' == typeof ws.destroy) }) }) }); it('should provide piping from a readableStream into GridFS', function(done){ var readStream = fs.createReadStream(imgReadPath, { bufferSize: 1024 }); var ws = g.createWriteStream({ filename: 'logo.png'}); // used in readable stream test id = ws.id; var progress = 0; var finished = false; var opened = false; var closed = false; var file; ws.on('progress', function (size) { progress = size; }); ws.on('open', function () { opened = true; }); ws.on('close', function (file_) { closed = true; file = file_; }); ws.on('finish', function () { assert(opened); assert(progress > 0); assert(closed); assert(file.filename === 'logo.png'); assert(file._id === id); assert(file.length === fs.readFileSync(imgReadPath).length); done(); }); var pipe = readStream.pipe(ws); }); it('should provide Error and File object on WriteStream close event', function(done){ var readStream = fs.createReadStream(imgReadPath, { bufferSize: 1024 }); var ws = g.createWriteStream({ mode: 'w', filename: 'closeEvent.png', content_type: "image/png" }); // used in readable stream test id = ws.id; var progress = 0; ws.on('progress', function (size) { progress = size; }); ws.on('close', function (file) { assert(file.filename === 'closeEvent.png') assert(file.contentType === 'image/png') assert(progress > 0); done(); }); var pipe = readStream.pipe(ws); }); //W+ not supported in new mongodb v2 gridstore driver it.skip('should pipe more data to an existing GridFS file', function(done){ function pipe (id, cb) { if (!cb) cb = id, id = null; var readStream = fs.createReadStream(txtReadPath); var ws = g.createWriteStream({ _id: id, mode: 'w+' }); ws.on('close', function () { cb(ws.id); }); readStream.pipe(ws); } pipe(function (id) { pipe(id, function (id) { // read the file out. it should consist of two copies of original mongo.GridStore.read(db, id, function (err, txt) { if (err) return done(err); assert.equal(txt.length, fs.readFileSync(txtReadPath).length*2); done(); }); }); }) }); it('should be able to store a 12-letter file name', function() { var ws = g.createWriteStream({ filename: '12345678.png' }); assert.equal(ws.name,'12345678.png'); }); it("shouldn't clobber filename when rewriting to an existing file by id", function(done){ var ws = g.createWriteStream({ mode: 'w', filename: 'filename.txt', content_type: 'text/plain' }); var rewrite_id = ws.id; ws.write("Some text\n"); ws.end(); ws.on('close', function () { // Rewrite the same file by _id var ws2 = g.createWriteStream({ _id: rewrite_id, mode: 'w' }); ws2.write("Some more text\n"); ws2.end(); ws2.on('close', function () { g.exist({ _id: rewrite_id }, function (err, result) { if (err) return done(err); assert.ok(result); g.exist({ filename: "filename.txt" }, function (err, result) { if (err) return done(err); assert.ok(result); done(); }); }); }); }); }); it('should be able to store an empty file', function(done){ var readStream = fs.createReadStream(emptyReadPath); var ws = g.createWriteStream({ mode: 'w', filename: 'closeEvent.txt', content_type: "text/plain" }); ws.on('close', function (file) { assert(file.filename === 'closeEvent.txt') assert(file.contentType === 'text/plain') done(); }); var pipe = readStream.pipe(ws); }); it('should create files with an _id of arbitrary type', function(done){ var readStream = fs.createReadStream(imgReadPath, { bufferSize: 1024 }); var ws = g.createWriteStream({ _id: 'an_arbitrary_id', filename: 'file.img'}); ws.on('close', function (file) { assert(file._id === 'an_arbitrary_id'); done(); }); var pipe = readStream.pipe(ws); }); it('should emit finish after the file exists', function(done){ var readStream = fs.createReadStream(imgReadPath); var ws = g.createWriteStream({ filename: 'logo.png'}); ws.on('finish', function () { var rs = g.createReadStream({_id: id}); var file = fixturesDir + 'byid.png'; var writeStream = fs.createWriteStream(file); rs.on('error', function (err) { // should not happen assert(false); }); writeStream.on('finish', function () { var buf1 = fs.readFileSync(imgReadPath); var buf2 = fs.readFileSync(file); assert(buf1.length === buf2.length); for (var i = 0, len = buf1.length; i < len; ++i) { assert(buf1[i] == buf2[i]); } fs.unlinkSync(file); done(); }); rs.pipe(writeStream); }); var pipe = readStream.pipe(ws); }); it('should emit one error on destroy()', function(done){ var readStream = fs.createReadStream(imgReadPath, { bufferSize: 1024 }); var ws = g.createWriteStream({ filename: 'logo.png'}); var error = new Error('test error from destroy'); var errorCounter = 0; ws.on('error', function (err) { errorCounter += 1; assert(errorCounter === 1); assert(err === error); done(); }); ws.on('progress', function (progress) { ws.destroy(error); ws.destroy(); // test multiple destroy call }); var pipe = readStream.pipe(ws); }); it('should emit error on destroy() on nextTick', function(done){ var ws = g.createWriteStream({ filename: 'logo.png'}); ws.destroy(new Error('early destroy')); ws.on('error', function (err) { done(); }); }); it('should emit close if open is emitted on destroy()', function(done){ var ws = g.createWriteStream({ filename: 'logo.png'}); var opened = false; var error = false; ws.on('open', function () { opened = true; }); ws.on('close', function () { assert(opened); assert(error); done(); }); ws.destroy(); ws.on('error', function (err) { error = true; }); }); it('should create GridWriteStream without options.', function(done){ var ws = g.createWriteStream(); ws.on('close', function () { done(); }); ws.destroy(); ws.on('error', function (err) { assert(!err); }); }); }); describe('createReadStream', function(){ it('should be a function', function () { var x = Grid(1); assert('function' == typeof x.createReadStream); }); }); describe('GridReadStream', function(){ var g , rs before(function(){ g = Grid(db); rs = g.createReadStream({ filename: 'logo.png' }); }); it('should create an instance of Stream', function(){ assert(rs instanceof Stream); }); it('should should be readable', function(){ assert(rs.readable); }); it('should store the grid', function(){ assert(rs._grid == g) }); it('should have a name', function(){ assert(rs.name == 'logo.png') }) it('should not have an id', function(){ assert.equal(rs.id, null) }) describe('options', function(){ it('should have no defaults', function(){ // NOTE: filename is required to avoid a throw here, because you can't create a valid // read stream for a non-existing file. assert(Object.keys(g.createReadStream({filename: 'logo.png'}).options).length === 1); }); }) it('mode should default to r', function(){ assert(rs.mode == 'r'); assert(rs._store.mode == 'r'); }) describe('store', function(){ it('should be an instance of mongo.GridStore', function(){ assert(rs._store instanceof mongo.GridStore) }) }) describe('#methods', function(){ describe('setEncoding', function(){ it('should be a function', function(){ assert('function' == typeof rs.setEncoding) // TODO test actual encodings }) }) describe('pause', function(){ it('should be a function', function(){ assert('function' == typeof rs.pause) }) }) describe('destroy', function(){ it('should be a function', function(){ assert('function' == typeof rs.destroy) }) }) describe('resume', function(){ it('should be a function', function(){ assert('function' == typeof rs.resume) }) }) describe('pipe', function(){ it('should be a function', function(){ assert('function' == typeof rs.pipe) }) }) }); it('should provide piping to a writable stream by name', function(done){ var file = fixturesDir + 'byname.png'; var rs = g.createReadStream({ filename: 'logo.png' }); var writeStream = fs.createWriteStream(file); var opened = false; var ended = false; rs.on('open', function () { opened = true; }); rs.on('error', function (err) { throw err; }); rs.on('end', function () { ended = true; }); writeStream.on('close', function () { // check they are identical var buf1 = fs.readFileSync(imgReadPath); var buf2 = fs.readFileSync(file); assert(buf1.length === buf2.length); for (var i = 0, len = buf1.length; i < len; ++i) { assert(buf1[i] == buf2[i]); } assert(opened); assert(ended); fs.unlinkSync(file); done(); }); rs.pipe(writeStream); }); it('should provide piping to a writable stream by id', function(done){ var file = fixturesDir + 'byid.png'; var rs = g.createReadStream({ _id: id }); var writeStream = fs.createWriteStream(file); assert(rs.id instanceof mongo.ObjectID); assert(rs.id == String(id)) var opened = false; var ended = false; rs.on('open', function () { opened = true; }); rs.on('error', function (err) { throw err; }); rs.on('end', function () { ended = true; }); writeStream.on('close', function () { //check they are identical assert(opened); assert(ended); var buf1 = fs.readFileSync(imgReadPath); var buf2 = fs.readFileSync(file); assert(buf1.length === buf2.length); for (var i = 0, len = buf1.length; i < len; ++i) { assert(buf1[i] == buf2[i]); } fs.unlinkSync(file); done(); }); rs.pipe(writeStream); }); it('should provide piping to a writable stream with a range by id', function(done){ var file = fixturesDir + 'byid.png'; var rs = g.createReadStream({ _id: id, range: { startPos: 1000, endPos: 10000 } }); var writeStream = fs.createWriteStream(file); assert(rs.id instanceof mongo.ObjectID); assert(rs.id == String(id)) var opened = false; var ended = false; rs.on('open', function () { opened = true; }); rs.on('error', function (err) { throw err; }); rs.on('end', function () { ended = true; }); writeStream.on('close', function () { //check they are identical assert(opened); assert(ended); var buf1 = fs.readFileSync(imgReadPath); var buf2 = fs.readFileSync(file); assert(buf2.length === rs.options.range.endPos - rs.options.range.startPos + 1); for (var i = 0, len = buf2.length; i < len; ++i) { assert(buf1[i + rs.options.range.startPos] == buf2[i]); } fs.unlinkSync(file); done(); }); rs.pipe(writeStream); }); it('should read files with an _id of arbitrary type', function(done){ var rs = g.createReadStream({ _id: 'an_arbitrary_id'}); rs.on('open', function () { assert(rs.id === 'an_arbitrary_id'); done(); }); }); it('should allow checking for existence of files', function(done){ g.exist({ _id: id }, function (err, result) { if (err) return done(err); assert.ok(result); done(); }); }); it('should allow checking for non existence of files', function(done){ g.exist({ filename: 'does-not-exists.1234' }, function (err, result) { if (err) return done(err); assert.ok(!result); done(); }); }); // See #51 it('should allow checking for existence of files in an alternate root collection', function(done){ var alternateFileOptions = {filename: 'alternateLogo.png', root: 'alternate' }; var readStream = g.createReadStream({filename: 'logo.png'}); var writeStream = g.createWriteStream(alternateFileOptions); readStream.pipe(writeStream); writeStream.on('close', function () { g.exist(alternateFileOptions, function (err, result) { if (err) return done(err); assert.ok(result); done(); }); }); }); it('should get a specific file', function(done){ g.findOne({ _id: id }, function(err, result) { if (err) return done(err); assert.ok(result); done(); }); }); // See #72 it('should be able to find a file in an alternate root collection', function (done){ g.findOne({filename: 'alternateLogo.png', root: 'alternate' }, function (err, file) { assert.equal(err, null); done(); }); }); it('should allow removing files', function(done){ g.remove({ _id: id }, function (err) { if (err) return done(err); g.files.findOne({ _id: id }, function (err, doc) { if (err) return done(err); assert.ok(!doc); done(); }) }); }) it('should be possible to pause a stream after constructing it', function (done) { var rs = g.createReadStream({ filename: 'logo.png' }); rs.pause(); setTimeout(function () { rs.resume(); }, 1000); rs.on('data', function (data) { rs.destroy(); done(); }); }); //issue #46 it('should be able handle multiple streams with multiple chunks', function (done) { var doneCounter = 0; var totalCounter = 100; var checksums = []; this.timeout(10000); function doTest (i) { var copyFileName = tmpDir + 'logo' + i + '.png'; var readStream = g.createReadStream({filename: '1mbBlob'}); var writeStream = fs.createWriteStream(copyFileName); readStream.pipe(writeStream); writeStream.on('close', function () { checksum.file(copyFileName, function (err, sum) { checksums.push(sum); fs.unlinkSync(copyFileName); if (++doneCounter == totalCounter) { assert(checksums.filter(function (value, index, self) { return self.indexOf(value) === index; }).length === 1); done(); } }); }); } var writeStream = g.createWriteStream({filename: '1mbBlob'}); fs.createReadStream(largeBlobPath).pipe(writeStream); writeStream.on('close', function() { for (var i = totalCounter; i-- > 0;) { doTest(i); } }); }); it('should be able to set the encoding of a readstream', function (done) { var rs = g.createReadStream({ filename: 'logo.png' }); rs.setEncoding('utf8'); rs.on('data', function (data) { assert.equal(typeof data, 'string'); rs.destroy(); done(); }); }); it('should be able to pause/resume after a chunk is sent to be able to throttle the stream', function (done) { var rs = g.createReadStream({ filename: '1mbBlob' }); var numChuksSent = 0 // Pause stream after one chunk has been sent rs.on('data', function (data) { numChuksSent += 1; rs.pause(); }); // Only one chunk should have been sent because it was paused after that. 1mbBlob contains 5 with default gridstream chunk size setTimeout(function () { assert.equal( numChuksSent, 1 ); rs.resume(); }, 500); // Now there should be 2 setTimeout(function () { assert.equal( numChuksSent, 2 ); done() }, 1000); }); }); after(function (done) { fs.unlink(largeBlobPath, function (err) { if (err) { done(err); } fs.rmdir(tmpDir, function () { db.dropDatabase(function () { db.close(true, done); }); }); }); }); });
var assert = require('assert'); var battle; describe('Heavy Metal', function () { afterEach(function () { battle.destroy(); }); it('should double the weight of a Pokemon', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Simisear", ability: 'heavymetal', moves: ['nastyplot']}]); battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', moves: ['grassknot']}]); var basePower = 0; battle.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (eventid === 'BasePower' && effect.id === 'grassknot') { basePower = relayVar; } return BattleEngine.Battle.prototype.runEvent.apply(this, arguments); }; battle.commitDecisions(); assert.strictEqual(basePower, 80); }); it('should be negated by Mold Breaker', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Simisear", ability: 'heavymetal', moves: ['nastyplot']}]); battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'moldbreaker', moves: ['grassknot']}]); var basePower = 0; battle.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (eventid === 'BasePower' && effect.id === 'grassknot') { basePower = relayVar; } return BattleEngine.Battle.prototype.runEvent.apply(this, arguments); }; battle.commitDecisions(); assert.strictEqual(basePower, 60); }); }); describe('Light Metal', function () { afterEach(function () { battle.destroy(); }); it('should halve the weight of a Pokemon', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Registeel", ability: 'lightmetal', moves: ['curse']}]); battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', moves: ['grassknot']}]); var basePower = 0; battle.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (eventid === 'BasePower' && effect.id === 'grassknot') { basePower = relayVar; } return BattleEngine.Battle.prototype.runEvent.apply(this, arguments); }; battle.commitDecisions(); assert.strictEqual(basePower, 100); }); it('should be negated by Mold Breaker', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Registeel", ability: 'lightmetal', moves: ['splash']}]); battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'moldbreaker', moves: ['grassknot']}]); var basePower = 0; battle.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (eventid === 'BasePower' && effect.id === 'grassknot') { basePower = relayVar; } return BattleEngine.Battle.prototype.runEvent.apply(this, arguments); }; battle.commitDecisions(); assert.strictEqual(basePower, 120); }); }); describe('Float Stone', function () { afterEach(function () { battle.destroy(); }); it('should halve the weight of a Pokemon', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Registeel", ability: 'clearbody', item: 'floatstone', moves: ['curse']}]); battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', moves: ['grassknot']}]); var basePower = 0; battle.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (eventid === 'BasePower' && effect.id === 'grassknot') { basePower = relayVar; } return BattleEngine.Battle.prototype.runEvent.apply(this, arguments); }; battle.commitDecisions(); assert.strictEqual(basePower, 100); }); }); describe('Autotomize', function () { afterEach(function () { battle.destroy(); }); it('should reduce the weight of a Pokemon by 100 kg with each use', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Registeel", ability: 'clearbody', moves: ['autotomize']}]); battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', item: 'laggingtail', moves: ['grassknot']}]); var basePower = 0; battle.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (eventid === 'BasePower' && effect.id === 'grassknot') { basePower = relayVar; } return BattleEngine.Battle.prototype.runEvent.apply(this, arguments); }; battle.commitDecisions(); assert.strictEqual(basePower, 100); battle.commitDecisions(); assert.strictEqual(basePower, 20); }); it('should factor into weight before Heavy Metal does', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: "Lairon", ability: 'heavymetal', moves: ['autotomize']}]); battle.join('p2', 'Guest 2', 1, [{species: "Simisage", ability: 'gluttony', item: 'laggingtail', moves: ['grassknot']}]); var basePower = 0; battle.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (eventid === 'BasePower' && effect.id === 'grassknot') { basePower = relayVar; } return BattleEngine.Battle.prototype.runEvent.apply(this, arguments); }; battle.commitDecisions(); assert.strictEqual(basePower, 60); }); });
'use strict'; const globalHooks = require('../../../hooks'); const hooks = require('feathers-hooks'); const auth = require('feathers-authentication').hooks; exports.before = { all: [ auth.verifyToken(), auth.populateUser(), auth.restrictToAuthenticated() ], find: [], get: [], create: [], update: [], patch: [], remove: [] }; exports.after = { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] };
import Vue from '../../../dist/vue.runtime.common.js' export default context => { return new Promise(resolve => { context.msg = 'hello' resolve(new Vue({ render (h) { return h('div', context.url) } })) }) }
/*! * OOjs UI v0.11.0 * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2015 OOjs Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2015-04-30T01:42:23Z */ /** * @class * @extends OO.ui.Theme * * @constructor */ OO.ui.MediaWikiTheme = function OoUiMediaWikiTheme() { // Parent constructor OO.ui.MediaWikiTheme.super.call( this ); }; /* Setup */ OO.inheritClass( OO.ui.MediaWikiTheme, OO.ui.Theme ); /* Methods */ /** * @inheritdoc */ OO.ui.MediaWikiTheme.prototype.getElementClasses = function ( element ) { // Parent method var variant, variants = { warning: false, invert: false, progressive: false, constructive: false, destructive: false }, // Parent method classes = OO.ui.MediaWikiTheme.super.prototype.getElementClasses.call( this, element ), isFramed; if ( element.supports( [ 'hasFlag' ] ) ) { isFramed = element.supports( [ 'isFramed' ] ) && element.isFramed(); if ( isFramed && ( element.isDisabled() || element.hasFlag( 'primary' ) ) ) { variants.invert = true; } else { variants.progressive = element.hasFlag( 'progressive' ); variants.constructive = element.hasFlag( 'constructive' ); variants.destructive = element.hasFlag( 'destructive' ); variants.warning = element.hasFlag( 'warning' ); } } for ( variant in variants ) { classes[ variants[ variant ] ? 'on' : 'off' ].push( 'oo-ui-image-' + variant ); } return classes; }; /* Instantiation */ OO.ui.theme = new OO.ui.MediaWikiTheme();
/** * @license Highcharts JS v6.0.3 (2017-11-14) * * Bullet graph series type for Highcharts * * (c) 2010-2017 Kacper Madej * * License: www.highcharts.com/license */ 'use strict'; (function(factory) { if (typeof module === 'object' && module.exports) { module.exports = factory; } else { factory(Highcharts); } }(function(Highcharts) { (function(H) { /** * (c) 2010-2017 Kacper Madej * * License: www.highcharts.com/license */ var each = H.each, pick = H.pick, isNumber = H.isNumber, relativeLength = H.relativeLength, seriesType = H.seriesType, columnProto = H.seriesTypes.column.prototype; /** * The bullet series type. * * @constructor seriesTypes.bullet * @augments seriesTypes.column */ seriesType('bullet', 'column', /** * A bullet graph is a variation of a bar graph. The bullet graph features * a single measure, compares it to a target, and displays it in the context * of qualitative ranges of performance that could be set using * [plotBands](#yAxis.plotBands) on [yAxis](#yAxis). * * @extends {plotOptions.column} * @product highcharts * @sample {highcharts} highcharts/demo/bullet-graph/ Bullet graph * @since 6.0.0 * @excluding allAreas,boostThreshold,colorAxis,compare,compareBase * @optionparent plotOptions.bullet */ { /** * All options related with look and positiong of targets. * * @sample {highcharts} highcharts/plotoptions/bullet-targetoptions/ * Target options * * @type {Object} * @since 6.0.0 * @product highcharts */ targetOptions: { /** * The width of the rectangle representing the target. Could be set as * a pixel value or as a percentage of a column width. * * @type {Number|String} * @since 6.0.0 * @product highcharts */ width: '140%', /** * The height of the rectangle representing the target. * * @since 6.0.0 * @product highcharts */ height: 3 }, tooltip: { pointFormat: '' + // eslint-disable-line no-dupe-keys '<span class="highcharts-color-{point.colorIndex}">' + '\u25CF</span> {series.name}: ' + '<span class="highcharts-strong">{point.y}</span>. ' + 'Target: <span class="highcharts-strong">' + '{point.target}</span><br/>' } }, { pointArrayMap: ['y', 'target'], parallelArrays: ['x', 'y', 'target'], /** * Draws the targets. For inverted chart, the `series.group` is rotated, * so the same coordinates apply. This method is based on * column series drawPoints function. */ drawPoints: function() { var series = this, chart = series.chart, options = series.options, animationLimit = options.animationLimit || 250; columnProto.drawPoints.apply(this); each(series.points, function(point) { var pointOptions = point.options, shapeArgs, targetGraphic = point.targetGraphic, targetShapeArgs, targetVal = point.target, pointVal = point.y, width, height, targetOptions, y; if (isNumber(targetVal) && targetVal !== null) { targetOptions = H.merge( options.targetOptions, pointOptions.targetOptions ); height = targetOptions.height; shapeArgs = point.shapeArgs; width = relativeLength( targetOptions.width, shapeArgs.width ); y = series.yAxis.translate( targetVal, false, true, false, true ) - targetOptions.height / 2 - 0.5; targetShapeArgs = series.crispCol.apply({ // Use fake series object to set borderWidth of target chart: chart, borderWidth: targetOptions.borderWidth, options: { crisp: options.crisp } }, [ shapeArgs.x + shapeArgs.width / 2 - width / 2, y, width, height ]); if (targetGraphic) { // Update targetGraphic[ chart.pointCount < animationLimit ? 'animate' : 'attr' ](targetShapeArgs); // Add or remove tooltip reference if (isNumber(pointVal) && pointVal !== null) { targetGraphic.element.point = point; } else { targetGraphic.element.point = undefined; } } else { point.targetGraphic = targetGraphic = chart.renderer .rect() .attr(targetShapeArgs) .add(series.group); } // Add tooltip reference if (isNumber(pointVal) && pointVal !== null) { targetGraphic.element.point = point; } targetGraphic.addClass(point.getClassName() + ' highcharts-bullet-target', true); } else if (targetGraphic) { point.targetGraphic = targetGraphic.destroy(); // #1269 } }); }, /** * Includes target values to extend extremes from y values. */ getExtremes: function(yData) { var series = this, targetData = series.targetData, yMax, yMin; columnProto.getExtremes.call(this, yData); if (targetData && targetData.length) { yMax = series.dataMax; yMin = series.dataMin; columnProto.getExtremes.call(this, targetData); series.dataMax = Math.max(series.dataMax, yMax); series.dataMin = Math.min(series.dataMin, yMin); } } }, /** @lends seriesTypes.ohlc.prototype.pointClass.prototype */ { /** * Destroys target graphic. */ destroy: function() { if (this.targetGraphic) { this.targetGraphic = this.targetGraphic.destroy(); } columnProto.pointClass.prototype.destroy.apply(this, arguments); } }); /** * A `bullet` series. If the [type](#series.bullet.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * For options that apply to multiple series, it is recommended to add * them to the [plotOptions.series](#plotOptions.series) options structure. * To apply to all series of this specific type, apply it to [plotOptions. * bullet](#plotOptions.bullet). * * @type {Object} * @since 6.0.0 * @extends series,plotOptions.bullet * @excluding dataParser,dataURL * @product highcharts * @apioption series.bullet */ /** * An array of data points for the series. For the `bullet` series type, * points can be given in the following ways: * * 1. An array of arrays with 3 or 2 values. In this case, the values * correspond to `x,y,target`. If the first value is a string, * it is applied as the name of the point, and the `x` value is inferred. * The `x` value can also be omitted, in which case the inner arrays * should be of length 2\. Then the `x` value is automatically calculated, * either starting at 0 and incremented by 1, or from `pointStart` * and `pointInterval` given in the series options. * * ```js * data: [ * [0, 40, 75], * [1, 50, 50], * [2, 60, 40] * ] * ``` * * 2. An array of objects with named values. The objects are point * configuration objects as seen below. If the total number of data * points exceeds the series' [turboThreshold](#series.bullet.turboThreshold), * this option is not available. * * ```js * data: [{ * x: 0, * y: 40, * target: 75, * name: "Point1", * color: "#00FF00" * }, { * x: 1, * y: 60, * target: 40, * name: "Point2", * color: "#FF00FF" * }] * ``` * * @type {Array<Object|Array>} * @since 6.0.0 * @extends series.column.data * @product highcharts * @apioption series.bullet.data */ /** * The target value of a point. * * @type {Number} * @since 6.0.0 * @product highcharts * @apioption series.bullet.data.target */ /** * Individual target options for each point. * * @extends series.bullet.targetOptions * @product highcharts * @apioption series.bullet.data.targetOptions */ }(Highcharts)); }));
// Karma configuration // Generated on Fri Aug 09 2013 14:14:35 GMT-0500 (CDT) module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', frameworks: ["jasmine"], // list of files / patterns to load in the browser files: [ 'http://code.angularjs.org/1.1.4/angular.js', 'http://code.angularjs.org/1.1.4/angular-resource.js', 'http://code.angularjs.org/1.1.4/angular-mocks.js', 'http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.0/lodash.min.js', 'src/restangular.js', 'test/*.js' ], // list of files to exclude exclude: [ ], // test results reporter to use // possible values: 'dots', 'progress', 'junit' reporters: ['progress'], // web server port port: 9876, // cli runner port runnerPort: 9100, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['PhantomJS'], // If browser does not capture in given timeout [ms], kill it captureTimeout: 60000, // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
/*! jsviews.js v0.9.78 (Beta) single-file version: http://jsviews.com/ */ /*! includes JsRender, JsObservable and JsViews - see: http://jsviews.com/#download */ /* Interactive data-driven views using JsRender templates */ //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< JsRender >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /* JsRender: * See http://jsviews.com/#jsrender and http://github.com/BorisMoore/jsrender * Copyright 2016, Boris Moore * Released under the MIT License. */ //jshint -W018, -W041 (function(factory, global) { // global var is the this object, which is window when running in the usual browser environment var $ = global.jQuery; if (typeof exports === "object") { // CommonJS e.g. Browserify module.exports = $ ? factory(global, $) : function($) { // If no global jQuery, take jQuery passed as parameter: require("jsviews")(jQuery) return factory(global, $); }; } else if (typeof define === "function" && define.amd) { // AMD script loader, e.g. RequireJS define(["jquery"], function($) { return factory(global, $); }); // Require jQuery } else { // Browser using plain <script> tag factory(global, false); } } ( // factory (for jsviews.js) function(global, $) { "use strict"; //========================== Top-level vars ========================== // global var is the this object, which is window when running in the usual browser environment var setGlobals = $ === false; // Only set globals if script block in browser (not AMD and not CommonJS) $ = $ || global.jQuery; // $ is jQuery passed in by CommonJS loader (Browserify), or global jQuery. if (!$ || !$.fn) { // jQuery is not loaded. throw "JsViews requires jQuery"; // We require jQuery } var versionNumber = "v0.9.78", jsvStoreName, rTag, rTmplString, topView, $views, $observe, $observable, $expando, //TODO tmplFnsCache = {}, $isFunction, $isArray, $templates, $converters, $helpers, $tags, $sub, $subSettings, $subSettingsAdvanced, $viewsSettings, delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, linkChar, setting, baseOnError, rPath = /^(!*?)(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g, // not object helper view viewProperty pathTokens leafToken rParams = /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(!*?[#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?[#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*(([)\]])(?=\s*[.^]|\s*$|[^([])|[)\]])([([]?))|(\s+)/g, // lftPrn0 lftPrn bound path operator err eq path2 prn comma lftPrn2 apos quot rtPrn rtPrnDot prn2 space // (left paren? followed by (path? followed by operator) or (path followed by left paren?)) or comma or apos or quot or right paren or space isRenderCall, rNewLine = /[ \t]*(\r\n|\n|\r)/g, rUnescapeQuotes = /\\(['"])/g, rEscapeQuotes = /['"\\]/g, // Escape quotes and \ character rBuildHash = /(?:\x08|^)(onerror:)?(?:(~?)(([\w$_\.]+):)?([^\x08]+))\x08(,)?([^\x08]+)/gi, rTestElseIf = /^if\s/, rFirstElem = /<(\w+)[>\s]/, rAttrEncode = /[\x00`><"'&=]/g, // Includes > encoding since rConvertMarkers in JsViews does not skip > characters in attribute strings rIsHtml = /[\x00`><\"'&=]/, rHasHandlers = /^on[A-Z]|^convert(Back)?$/, rHtmlEncode = rAttrEncode, viewId = 0, charEntities = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "\x00": "&#0;", "'": "&#39;", '"': "&#34;", "`": "&#96;", "=": "&#61;" }, HTML = "html", OBJECT = "object", tmplAttr = "data-jsv-tmpl", jsvTmpl = "jsvTmpl", indexStr = "For #index in nested block use #getIndex().", $render = {}, jsr = global.jsrender, jsrToJq = jsr && $ && !$.render, // JsRender already loaded, without jQuery. but we will re-load it now to attach to jQuery jsvStores = { template: { compile: compileTmpl }, tag: { compile: compileTag }, viewModel: { compile: compileViewModel }, helper: {}, converter: {} }; // views object ($.views if jQuery is loaded, jsrender.views if no jQuery, e.g. in Node.js) $views = { jsviews: versionNumber, sub: { // subscription, e.g. JsViews integration View: View, Err: JsViewsError, tmplFn: tmplFn, parse: parseParams, extend: $extend, extendCtx: extendCtx, syntaxErr: syntaxError, onStore: {}, addSetting: addSetting, settings: { allowCode: false }, advSet: noop, // Update advanced settings _ths: tagHandlersFromProps, _tg: function() {}, // Constructor for tagDef _cnvt: convertVal, _tag: renderTag, _er: error, _err: onRenderError, _html: htmlEncode, _sq: function(token) { if (token === "constructor") { syntaxError(""); } return token; } }, settings: { delimiters: $viewsDelimiters, advanced: function(value) { return value ? ( $extend($subSettingsAdvanced, value), $sub.advSet(), $viewsSettings ) : $subSettingsAdvanced; } }, map: dataMap // If jsObservable loaded first, use that definition of dataMap }; function getDerivedMethod(baseMethod, method) { return function() { var ret, tag = this, prevBase = tag.base; tag.base = baseMethod; // Within method call, calling this.base will call the base method ret = method.apply(tag, arguments); // Call the method tag.base = prevBase; // Replace this.base to be the base method of the previous call, for chained calls return ret; }; } function getMethod(baseMethod, method) { // For derived methods (or handlers declared declaratively as in {{:foo onChange=~fooChanged}} replace by a derived method, to allow using this.base(...) // or this.baseApply(arguments) to call the base implementation. (Equivalent to this._super(...) and this._superApply(arguments) in jQuery UI) if ($isFunction(method)) { method = getDerivedMethod( !baseMethod ? noop // no base method implementation, so use noop as base method : baseMethod._d ? baseMethod // baseMethod is a derived method, so us it : getDerivedMethod(noop, baseMethod), // baseMethod is not derived so make its base method be the noop method method ); method._d = 1; // Add flag that this is a derived method } return method; } function tagHandlersFromProps(tag, tagCtx) { for (var prop in tagCtx.props) { if (rHasHandlers.test(prop)) { tag[prop] = getMethod(tag[prop], tagCtx.props[prop]); // Copy over the onFoo props, convert and convertBack from tagCtx.props to tag (overrides values in tagDef). // Note: unsupported scenario: if handlers are dynamically added ^onFoo=expression this will work, but dynamically removing will not work. } } } function retVal(val) { return val; } function noop() { return ""; } function dbgBreak(val) { // Usage examples: {{dbg:...}}, {{:~dbg(...)}}, {{dbg .../}}, {^{for ... onAfterLink=~dbg}} etc. try { console.log("JsRender dbg breakpoint: " + val); throw "dbg breakpoint"; // To break here, stop on caught exceptions. } catch (e) {} return this.base ? this.baseApply(arguments) : val; } function JsViewsError(message) { // Error exception type for JsViews/JsRender // Override of $.views.sub.Error is possible this.name = ($.link ? "JsViews" : "JsRender") + " Error"; this.message = message || this.name; } function $extend(target, source) { for (var name in source) { target[name] = source[name]; } return target; } (JsViewsError.prototype = new Error()).constructor = JsViewsError; //========================== Top-level functions ========================== //=================== // views.delimiters //=================== function $viewsDelimiters(openChars, closeChars, link) { // Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^" // openChars, closeChars: opening and closing strings, each with two characters if (!openChars) { return $subSettings.delimiters; } $subSettings.delimiters = [openChars, closeChars, linkChar = link ? link.charAt(0) : linkChar]; delimOpenChar0 = openChars.charAt(0); // Escape the characters - since they could be regex special characters delimOpenChar1 = openChars.charAt(1); delimCloseChar0 = closeChars.charAt(0); delimCloseChar1 = closeChars.charAt(1); openChars = "\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1; // Default is "{^{" closeChars = "\\" + delimCloseChar0 + "\\" + delimCloseChar1; // Default is "}}" // Build regex with new delimiters // [tag (followed by / space or }) or cvtr+colon or html or code] followed by space+params then convertBack? rTag = "(?:(\\w+(?=[\\/\\s\\" + delimCloseChar0 + "]))|(\\w+)?(:)|(>)|(\\*))\\s*((?:[^\\" + delimCloseChar0 + "]|\\" + delimCloseChar0 + "(?!\\" + delimCloseChar1 + "))*?)"; // make rTag available to JsViews (or other components) for parsing binding expressions $sub.rTag = "(?:" + rTag + ")"; // { ^? { tag+params slash? or closingTag or comment rTag = new RegExp("(?:" + openChars + rTag + "(\\/)?|\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1 + "(?:(?:\\/(\\w+))\\s*|!--[\\s\\S]*?--))" + closeChars, "g"); // Default: bind tagName cvt cln html code params slash bind2 closeBlk comment // /(?:{(\^)?{(?:(\w+(?=[\/\s}]))|(\w+)?(:)|(>)|(\*))\s*((?:[^}]|}(?!}))*?)(\/)?|{(\^)?{(?:(?:\/(\w+))\s*|!--[\s\S]*?--))}} rTmplString = new RegExp("<.*>|([^\\\\]|^)[{}]|" + openChars + ".*" + closeChars); // rTmplString looks for html tags or { or } char not preceded by \\, or JsRender tags {{xxx}}. Each of these strings are considered // NOT to be jQuery selectors return $viewsSettings; } //========= // View.get //========= function getView(inner, type) { //view.get(inner, type) if (!type && inner !== true) { // view.get(type) type = inner; inner = undefined; } var views, i, l, found, view = this, root = !type || type === "root"; // If type is undefined, returns root view (view under top view). if (inner) { // Go through views - this one, and all nested ones, depth-first - and return first one with given type. // If type is undefined, i.e. view.get(true), return first child view. found = type && view.type === type && view; if (!found) { views = view.views; if (view._.useKey) { for (i in views) { if (found = type ? views[i].get(inner, type) : views[i]) { break; } } } else { for (i = 0, l = views.length; !found && i < l; i++) { found = type ? views[i].get(inner, type) : views[i]; } } } } else if (root) { // Find root view. (view whose parent is top view) while (view.parent) { found = view; view = view.parent; } } else { while (view && !found) { // Go through views - this one, and all parent ones - and return first one with given type. found = view.type === type ? view : undefined; view = view.parent; } } return found; } function getNestedIndex() { var view = this.get("item"); return view ? view.index : undefined; } getNestedIndex.depends = function() { return [this.get("item"), "index"]; }; function getIndex() { return this.index; } getIndex.depends = "index"; //========== // View.hlp //========== function getHelper(helper) { // Helper method called as view.hlp(key) from compiled template, for helper functions or template parameters ~foo var wrapped, view = this, ctx = view.linkCtx, res = (view.ctx || {})[helper]; if (res === undefined && ctx && ctx.ctx) { res = ctx.ctx[helper]; } if (res === undefined) { res = $helpers[helper]; } if (res) { if ($isFunction(res) && !res._wrp) { // If it is of type function, and not already wrapped, we will wrap it, so if called with no this pointer it will be called with the // view as 'this' context. If the helper ~foo() was in a data-link expression, the view will have a 'temporary' linkCtx property too. // Note that helper functions on deeper paths will have specific this pointers, from the preceding path. // For example, ~util.foo() will have the ~util object as 'this' pointer wrapped = function() { return res.apply((!this || this === global) ? view : this, arguments); }; wrapped._wrp = view; $extend(wrapped, res); // Attach same expandos (if any) to the wrapped function } } return wrapped || res; } function getTemplate(tmpl) { return tmpl && (tmpl.fn ? tmpl : this.getRsc("templates", tmpl) || $templates(tmpl)); // not yet compiled } //============== // views._cnvt //============== function convertVal(converter, view, tagCtx, onError) { // self is template object or linkCtx object var tag, value, // if tagCtx is an integer, then it is the key for the compiled function to return the boundTag tagCtx boundTag = typeof tagCtx === "number" && view.tmpl.bnds[tagCtx-1], linkCtx = view.linkCtx; // For data-link="{cvt:...}"... if (onError !== undefined) { tagCtx = onError = {props: {}, args: [onError]}; } else if (boundTag) { tagCtx = boundTag(view.data, view, $sub); } value = tagCtx.args[0]; if (converter || boundTag) { tag = linkCtx && linkCtx.tag; if (!tag) { tag = $extend(new $sub._tg(), { _: { inline: !linkCtx, bnd: boundTag, unlinked: true }, tagName: ":", cvt: converter, flow: true, tagCtx: tagCtx }); if (linkCtx) { linkCtx.tag = tag; tag.linkCtx = linkCtx; } tagCtx.ctx = extendCtx(tagCtx.ctx, (linkCtx ? linkCtx.view : view).ctx); } tag._er = onError && value; tagHandlersFromProps(tag, tagCtx); tagCtx.view = view; tag.ctx = tagCtx.ctx || tag.ctx || {}; tagCtx.ctx = undefined; value = tag.cvtArgs(converter !== "true" && converter)[0]; // If there is a convertBack but no convert, converter will be "true" // Call onRender (used by JsViews if present, to add binding annotations around rendered content) value = boundTag && view._.onRender ? view._.onRender(value, view, tag) : value; } return value != undefined ? value : ""; } function convertArgs(converter) { var tag = this, tagCtx = tag.tagCtx, view = tagCtx.view, args = tagCtx.args; converter = converter || tag.convert; converter = converter && ("" + converter === converter ? (view.getRsc("converters", converter) || error("Unknown converter: '" + converter + "'")) : converter); args = !args.length && !tagCtx.index // On the opening tag with no args, bind to the current data context ? [view.data] : converter ? args.slice() // If there is a converter, use a copy of the tagCtx.args array for rendering, and replace the args[0] in // the copied array with the converted value. But we do not modify the value of tag.tagCtx.args[0] (the original args array) : args; // If no converter, get the original tagCtx.args if (converter) { if (converter.depends) { tag.depends = $sub.getDeps(tag.depends, tag, converter.depends, converter); } args[0] = converter.apply(tag, args); } return args; } //============= // views._tag //============= function getResource(resourceType, itemName) { var res, store, view = this; while ((res === undefined) && view) { store = view.tmpl && view.tmpl[resourceType]; res = store && store[itemName]; view = view.parent; } return res || $views[resourceType][itemName]; } function renderTag(tagName, parentView, tmpl, tagCtxs, isUpdate, onError) { parentView = parentView || topView; var tag, tag_, tagDef, template, tags, attr, parentTag, i, l, itemRet, tagCtx, tagCtxCtx, content, callInit, mapDef, thisMap, args, props, initialTmpl, tagDataMap, ret = "", linkCtx = parentView.linkCtx || 0, ctx = parentView.ctx, parentTmpl = tmpl || parentView.tmpl, // if tagCtx is an integer, then it is the key for the compiled function to return the boundTag tagCtxs boundTag = typeof tagCtxs === "number" && parentView.tmpl.bnds[tagCtxs-1]; if (tagName._is === "tag") { tag = tagName; tagName = tag.tagName; tagCtxs = tag.tagCtxs; template = tag.template; } else { tagDef = parentView.getRsc("tags", tagName) || error("Unknown tag: {{" + tagName + "}} "); template = tagDef.template; } if (onError !== undefined) { ret += onError; tagCtxs = onError = [{props: {}, args: []}]; } else if (boundTag) { tagCtxs = boundTag(parentView.data, parentView, $sub); } l = tagCtxs.length; for (i = 0; i < l; i++) { tagCtx = tagCtxs[i]; if (!linkCtx || !linkCtx.tag || i && !linkCtx.tag._.inline || tag._er) { // Initialize tagCtx // For block tags, tagCtx.tmpl is an integer > 0 if (content = parentTmpl.tmpls && tagCtx.tmpl) { content = tagCtx.content = parentTmpl.tmpls[content - 1]; } tagCtx.index = i; tagCtx.tmpl = content; // Set the tmpl property to the content of the block tag tagCtx.render = renderContent; tagCtx.view = parentView; tagCtx.ctx = extendCtx(tagCtx.ctx, ctx); // Clone and extend parentView.ctx } if (tmpl = tagCtx.props.tmpl) { // If the tmpl property is overridden, set the value (when initializing, or, in case of binding: ^tmpl=..., when updating) tagCtx.tmpl = parentView.getTmpl(tmpl); } if (!tag) { // This will only be hit for initial tagCtx (not for {{else}}) - if the tag instance does not exist yet // Instantiate tag if it does not yet exist // If the tag has not already been instantiated, we will create a new instance. // ~tag will access the tag, even within the rendering of the template content of this tag. // From child/descendant tags, can access using ~tag.parent, or ~parentTags.tagName tag = new tagDef._ctr(); callInit = !!tag.init; tag.parent = parentTag = ctx && ctx.tag; tag.tagCtxs = tagCtxs; tagDataMap = tag.dataMap; if (linkCtx) { tag._.inline = false; linkCtx.tag = tag; tag.linkCtx = linkCtx; } if (tag._.bnd = boundTag || linkCtx.fn) { // Bound if {^{tag...}} or data-link="{tag...}" tag._.arrVws = {}; } else if (tag.dataBoundOnly) { error("{^{" + tagName + "}} tag must be data-bound"); } //TODO better perf for childTags() - keep child tag.tags array, (and remove child, when disposed) // tag.tags = []; } tagCtxs = tag.tagCtxs; tagDataMap = tag.dataMap; tagCtx.tag = tag; if (tagDataMap && tagCtxs) { tagCtx.map = tagCtxs[i].map; // Copy over the compiled map instance from the previous tagCtxs to the refreshed ones } if (!tag.flow) { tagCtxCtx = tagCtx.ctx = tagCtx.ctx || {}; // tags hash: tag.ctx.tags, merged with parentView.ctx.tags, tags = tag.parents = tagCtxCtx.parentTags = ctx && extendCtx(tagCtxCtx.parentTags, ctx.parentTags) || {}; if (parentTag) { tags[parentTag.tagName] = parentTag; //TODO better perf for childTags: parentTag.tags.push(tag); } tags[tag.tagName] = tagCtxCtx.tag = tag; } } if (!(tag._er = onError)) { tagHandlersFromProps(tag, tagCtxs[0]); tag.rendering = {}; // Provide object for state during render calls to tag and elses. (Used by {{if}} and {{for}}...) for (i = 0; i < l; i++) { tagCtx = tag.tagCtx = tagCtxs[i]; props = tagCtx.props; args = tag.cvtArgs(); if (mapDef = props.dataMap || tagDataMap) { if (args.length || props.dataMap) { thisMap = tagCtx.map; if (!thisMap || thisMap.src !== args[0] || isUpdate) { if (thisMap && thisMap.src) { thisMap.unmap(); // only called if observable map - not when only used in JsRender, e.g. by {{props}} } thisMap = tagCtx.map = mapDef.map(args[0], props, undefined, !tag._.bnd); } args = [thisMap.tgt]; } } tag.ctx = tagCtx.ctx; if (!i) { if (callInit) { initialTmpl = tag.template; tag.init(tagCtx, linkCtx, tag.ctx); callInit = undefined; } if (linkCtx) { // Set attr on linkCtx to ensure outputting to the correct target attribute. // Setting either linkCtx.attr or this.attr in the init() allows per-instance choice of target attrib. linkCtx.attr = tag.attr = linkCtx.attr || tag.attr; } attr = tag.attr; tag._.noVws = attr && attr !== HTML; } itemRet = undefined; if (tag.render) { itemRet = tag.render.apply(tag, args); } if (!args.length) { args = [parentView]; // no arguments - (e.g. {{else}}) get data context from view. } if (itemRet === undefined) { itemRet = tagCtx.render(args[0], true) || (isUpdate ? undefined : ""); } // No return value from render, and no template/content tagCtx.render(...), so return undefined ret = ret ? ret + (itemRet || "") : itemRet; // If no rendered content, this will be undefined } tag.rendering = undefined; } tag.tagCtx = tagCtxs[0]; tag.ctx = tag.tagCtx.ctx; if (tag._.noVws) { if (tag._.inline) { // inline tag with attr set to "text" will insert HTML-encoded content - as if it was element-based innerText ret = attr === "text" ? $converters.html(ret) : ""; } } return boundTag && parentView._.onRender // Call onRender (used by JsViews if present, to add binding annotations around rendered content) ? parentView._.onRender(ret, parentView, tag) : ret; } //================= // View constructor //================= function View(context, type, parentView, data, template, key, onRender, contentTmpl) { // Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded) var views, parentView_, tag, self_, self = this, isArray = type === "array"; self.content = contentTmpl; self.views = isArray ? [] : {}; self.parent = parentView; self.type = type || "top"; self.data = data; self.tmpl = template; // If the data is an array, this is an 'array view' with a views array for each child 'item view' // If the data is not an array, this is an 'item view' with a views 'hash' object for any child nested views // ._.useKey is non zero if is not an 'array view' (owning a data array). Use this as next key for adding to child views hash self_ = self._ = { key: 0, useKey: isArray ? 0 : 1, id: "" + viewId++, onRender: onRender, bnds: {} }; self.linked = !!onRender; if (parentView) { views = parentView.views; parentView_ = parentView._; if (parentView_.useKey) { // Parent is not an 'array view'. Add this view to its views object // self._key = is the key in the parent view hash views[self_.key = "_" + parentView_.useKey++] = self; self.index = indexStr; self.getIndex = getNestedIndex; } else if (views.length === (self_.key = self.index = key)) { // Parent is an 'array view'. Add this view to its views array views.push(self); // Adding to end of views array. (Using push when possible - better perf than splice) } else { views.splice(key, 0, self); // Inserting in views array } // If no context was passed in, use parent context // If context was passed in, it should have been merged already with parent context self.ctx = context || parentView.ctx; } else { self.ctx = context; } } View.prototype = { get: getView, getIndex: getIndex, getRsc: getResource, getTmpl: getTemplate, hlp: getHelper, _is: "view" }; //==================================================== // Registration //==================================================== function compileChildResources(parentTmpl) { var storeName, resources, resourceName, resource, settings, compile, onStore; for (storeName in jsvStores) { settings = jsvStores[storeName]; if ((compile = settings.compile) && (resources = parentTmpl[storeName + "s"])) { for (resourceName in resources) { // compile child resource declarations (templates, tags, tags["for"] or helpers) resource = resources[resourceName] = compile(resourceName, resources[resourceName], parentTmpl, 0); resource._is = storeName; // Only do this for compiled objects (tags, templates...) if (resource && (onStore = $sub.onStore[storeName])) { // e.g. JsViews integration onStore(resourceName, resource, compile); } } } } } //=============== // compileTag //=============== function compileTag(name, tagDef, parentTmpl) { var tmpl, baseTag, prop, compiledDef = new $sub._tg(); function Tag() { var tag = this; tag._ = { inline: true, unlinked: true }; tag.tagName = name; } if ($isFunction(tagDef)) { // Simple tag declared as function. No presenter instantation. tagDef = { depends: tagDef.depends, render: tagDef }; } else if ("" + tagDef === tagDef) { tagDef = {template: tagDef}; } if (baseTag = tagDef.baseTag) { tagDef.flow = !!tagDef.flow; // Set flow property, so defaults to false even if baseTag has flow=true tagDef.baseTag = baseTag = "" + baseTag === baseTag ? (parentTmpl && parentTmpl.tags[baseTag] || $tags[baseTag]) : baseTag; compiledDef = $extend(compiledDef, baseTag); for (prop in tagDef) { compiledDef[prop] = getMethod(baseTag[prop], tagDef[prop]); } } else { compiledDef = $extend(compiledDef, tagDef); } // Tag declared as object, used as the prototype for tag instantiation (control/presenter) if ((tmpl = compiledDef.template) !== undefined) { compiledDef.template = "" + tmpl === tmpl ? ($templates[tmpl] || $templates(tmpl)) : tmpl; } if (compiledDef.init !== false) { // Set init: false on tagDef if you want to provide just a render method, or render and template, but no constructor or prototype. // so equivalent to setting tag to render function, except you can also provide a template. (Tag.prototype = compiledDef).constructor = compiledDef._ctr = Tag; } if (parentTmpl) { compiledDef._parentTmpl = parentTmpl; } return compiledDef; } function baseApply(args) { // In derived method (or handler declared declaratively as in {{:foo onChange=~fooChanged}} can call base method, // using this.baseApply(arguments) (Equivalent to this._superApply(arguments) in jQuery UI) return this.base.apply(this, args); } //=============== // compileTmpl //=============== function compileTmpl(name, tmpl, parentTmpl, options) { // tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object //==== nested functions ==== function lookupTemplate(value) { // If value is of type string - treat as selector, or name of compiled template // Return the template object, if already compiled, or the markup string var currentName, tmpl; if (("" + value === value) || value.nodeType > 0 && (elem = value)) { if (!elem) { if (/^\.\/[^\\:*?"<>]*$/.test(value)) { // tmpl="./some/file.html" // If the template is not named, use "./some/file.html" as name. if (tmpl = $templates[name = name || value]) { value = tmpl; } else { // BROWSER-SPECIFIC CODE (not on Node.js): // Look for server-generated script block with id "./some/file.html" elem = document.getElementById(value); } } else if ($.fn && !rTmplString.test(value)) { try { elem = $(document).find(value)[0]; // if jQuery is loaded, test for selector returning elements, and get first element } catch (e) {} }// END BROWSER-SPECIFIC CODE } //BROWSER-SPECIFIC CODE if (elem) { // Generally this is a script element. // However we allow it to be any element, so you can for example take the content of a div, // use it as a template, and replace it by the same content rendered against data. // e.g. for linking the content of a div to a container, and using the initial content as template: // $.link("#content", model, {tmpl: "#content"}); if (options) { // We will compile a new template using the markup in the script element value = elem.innerHTML; } else { // We will cache a single copy of the compiled template, and associate it with the name // (renaming from a previous name if there was one). currentName = elem.getAttribute(tmplAttr); if (currentName) { if (currentName !== jsvTmpl) { value = $templates[currentName]; delete $templates[currentName]; } else if ($.fn) { value = $.data(elem)[jsvTmpl]; } } else { name = name || ($.fn ? jsvTmpl : value); value = compileTmpl(name, elem.innerHTML, parentTmpl, options); } value.tmplName = name = name || currentName; if (name !== jsvTmpl) { $templates[name] = value; } elem.setAttribute(tmplAttr, name); if ($.fn) { $.data(elem, jsvTmpl, value); } } } // END BROWSER-SPECIFIC CODE elem = undefined; } else if (!value.fn) { value = undefined; // If value is not a string. HTML element, or compiled template, return undefined } return value; } var elem, compiledTmpl, tmplOrMarkup = tmpl = tmpl || ""; //==== Compile the template ==== if (options === 0) { options = undefined; tmplOrMarkup = lookupTemplate(tmplOrMarkup); // Top-level compile so do a template lookup } // If options, then this was already compiled from a (script) element template declaration. // If not, then if tmpl is a template object, use it for options options = options || (tmpl.markup ? tmpl : {}); options.tmplName = name; if (parentTmpl) { options._parentTmpl = parentTmpl; } // If tmpl is not a markup string or a selector string, then it must be a template object // In that case, get it from the markup property of the object if (!tmplOrMarkup && tmpl.markup && (tmplOrMarkup = lookupTemplate(tmpl.markup))) { if (tmplOrMarkup.fn) { // If the string references a compiled template object, need to recompile to merge any modified options tmplOrMarkup = tmplOrMarkup.markup; } } if (tmplOrMarkup !== undefined) { if (tmplOrMarkup.fn || tmpl.fn) { // tmpl is already compiled, so use it if (tmplOrMarkup.fn) { compiledTmpl = tmplOrMarkup; } } else { // tmplOrMarkup is a markup string, not a compiled template // Create template object tmpl = tmplObject(tmplOrMarkup, options); // Compile to AST and then to compiled function tmplFn(tmplOrMarkup.replace(rEscapeQuotes, "\\$&"), tmpl); } if (!compiledTmpl) { compileChildResources(options); compiledTmpl = $extend(function() { return tmpl.render.apply(tmpl, arguments); }, tmpl); } if (name && !parentTmpl && name !== jsvTmpl) { $render[name] = compiledTmpl; } return compiledTmpl; } } //==== /end of function compileTmpl ==== //================= // compileViewModel //================= function getDefaultVal(defaultVal, data) { return $.isFunction(defaultVal) ? defaultVal.call(data) : defaultVal; } function unmapArray(modelArr) { var i, arr = [], l = modelArr.length; for (i=0; i<l; i++) { arr.push(modelArr[i].unmap()); } return arr; } function compileViewModel(name, type) { var i, constructor, viewModels = this, getters = type.getters, extend = type.extend, id = type.id, proto = $.extend({ _is: name || "unnamed", unmap: unmap, merge: merge }, extend), args = "", body = "", l = getters ? getters.length : 0, $observable = $.observable, getterNames = {}; function GetNew(args) { constructor.apply(this, args); } function vm() { return new GetNew(arguments); } function iterate(data, action) { var j, getterType, defaultVal, prop, ob, m = getters.length; for (j=0; j<m; j++) { prop = getters[j]; getterType = undefined; if (prop + "" !== prop) { getterType = prop; prop = getterType.getter; } if ((ob = data[prop]) === undefined && getterType && (defaultVal = getterType.defaultVal) !== undefined) { ob = getDefaultVal(defaultVal, data); } action(ob, getterType && viewModels[getterType.type], prop); } } function map(data) { data = data + "" === data ? JSON.parse(data) // Accept JSON string : data; // or object/array var i, j, l, m, prop, ob = data, arr = []; if ($.isArray(data)) { data = data || []; l = data.length; for (i=0; i<l; i++) { arr.push(this.map(data[i])); } arr._is = name; arr.unmap = unmap; arr.merge = merge; return arr; } if (data) { iterate(data, function(ob, viewModel) { if (viewModel) { // Iterate to build getters arg array (value, or mapped value) ob = viewModel.map(ob); } arr.push(ob); }); ob = this.apply(this, arr); // Insantiate this View Model, passing getters args array to constructor for (prop in data) { // Copy over any other properties. that are not get/set properties if (prop !== $expando && !getterNames[prop]) { ob[prop] = data[prop]; } } } return ob; } function merge(data) { data = data + "" === data ? JSON.parse(data) // Accept JSON string : data; // or object/array var i, j, l, m, prop, mod, found, assigned, ob, newModArr, model = this; if ($.isArray(model)) { assigned = {}; newModArr = []; l = data.length; m = model.length; for (i=0; i<l; i++) { ob = data[i]; found = false; for (j=0; j<m && !found; j++) { if (assigned[j]) { continue; } mod = model[j]; if (id) { assigned[j] = found = id + "" === id ? (ob[id] && (getterNames[id] ? mod[id]() : mod[id]) === ob[id]) : id(mod, ob); } } if (found) { mod.merge(ob); newModArr.push(mod); } else { newModArr.push(vm.map(ob)); } } if ($observable) { $observable(model).refresh(newModArr, true); } else { model.splice.apply(model, [0, model.length].concat(newModArr)); } return; } iterate(data, function(ob, viewModel, getter) { if (viewModel) { model[getter]().merge(ob); // Update typed property } else { model[getter](ob); // Update non-typed property } }); for (prop in data) { if (prop !== $expando && !getterNames[prop]) { model[prop] = data[prop]; } } } function unmap() { var ob, prop, i, l, getterType, arr, value, model = this; if ($.isArray(model)) { return unmapArray(model); } ob = {}; l = getters.length; for (i=0; i<l; i++) { prop = getters[i]; getterType = undefined; if (prop + "" !== prop) { getterType = prop; prop = getterType.getter; } value = model[prop](); ob[prop] = getterType && value && viewModels[getterType.type] ? $.isArray(value) ? unmapArray(value) : value.unmap() : value; } for (prop in model) { if (prop !== "_is" && !getterNames[prop] && prop !== $expando && (prop.charAt(0) !== "_" || !getterNames[prop.slice(1)]) && !$.isFunction(model[prop])) { ob[prop] = model[prop]; } } return ob; } GetNew.prototype = proto; for (i=0; i<l; i++) { (function(getter) { getter = getter.getter || getter; getterNames[getter] = i+1; var privField = "_" + getter; args += (args ? "," : "") + getter; body += "this." + privField + " = " + getter + ";\n"; proto[getter] = proto[getter] || function(val) { if (!arguments.length) { return this[privField]; // If there is no argument, use as a getter } if ($observable) { $observable(this).setProperty(getter, val); } else { this[privField] = val; } }; if ($observable) { proto[getter].set = proto[getter].set || function(val) { this[privField] = val; // Setter called by observable property change }; } })(getters[i]); } constructor = new Function(args, body.slice(0, -1)); constructor.prototype = proto; proto.constructor = constructor; vm.map = map; vm.getters = getters; vm.extend = extend; vm.id = id; return vm; } function tmplObject(markup, options) { // Template object constructor var htmlTag, wrapMap = $subSettingsAdvanced._wm || {}, // Only used in JsViews. Otherwise empty: {} tmpl = $extend( { tmpls: [], links: {}, // Compiled functions for link expressions bnds: [], _is: "template", render: renderContent }, options ); tmpl.markup = markup; if (!options.htmlTag) { // Set tmpl.tag to the top-level HTML tag used in the template, if any... htmlTag = rFirstElem.exec(markup); tmpl.htmlTag = htmlTag ? htmlTag[1].toLowerCase() : ""; } htmlTag = wrapMap[tmpl.htmlTag]; if (htmlTag && htmlTag !== wrapMap.div) { // When using JsViews, we trim templates which are inserted into HTML contexts where text nodes are not rendered (i.e. not 'Phrasing Content'). // Currently not trimmed for <li> tag. (Not worth adding perf cost) tmpl.markup = $.trim(tmpl.markup); } return tmpl; } //============== // registerStore //============== function registerStore(storeName, storeSettings) { function theStore(name, item, parentTmpl) { // The store is also the function used to add items to the store. e.g. $.templates, or $.views.tags // For store of name 'thing', Call as: // $.views.things(items[, parentTmpl]), // or $.views.things(name, item[, parentTmpl]) var onStore, compile, itemName, thisStore; if (name && typeof name === OBJECT && !name.nodeType && !name.markup && !name.getTgt && !(storeName === "viewModel" && name.getters || name.extend)) { // Call to $.views.things(items[, parentTmpl]), // Adding items to the store // If name is a hash, then item is parentTmpl. Iterate over hash and call store for key. for (itemName in name) { theStore(itemName, name[itemName], item); } return item || $views; } // Adding a single unnamed item to the store if (item === undefined) { item = name; name = undefined; } if (name && "" + name !== name) { // name must be a string parentTmpl = item; item = name; name = undefined; } thisStore = parentTmpl ? storeName === "viewModel" ? parentTmpl : (parentTmpl[storeNames] = parentTmpl[storeNames] || {}) : theStore; compile = storeSettings.compile; if (item === null) { // If item is null, delete this entry if (name) { delete thisStore[name]; } } else { item = compile ? compile.call(thisStore, name, item, parentTmpl, 0) : item; if (name) { thisStore[name] = item; } } if (compile && item) { item._is = storeName; // Only do this for compiled objects (tags, templates...) } if (item && (onStore = $sub.onStore[storeName])) { // e.g. JsViews integration onStore(name, item, compile); } return item; } var storeNames = storeName + "s"; $views[storeNames] = theStore; } function addSetting(st) { $viewsSettings[st] = function(value) { return arguments.length ? ($subSettings[st] = value, $viewsSettings) : $subSettings[st]; }; } //========= // dataMap //========= function dataMap(mapDef) { function Map(source, options) { this.tgt = mapDef.getTgt(source, options); } if ($isFunction(mapDef)) { // Simple map declared as function mapDef = { getTgt: mapDef }; } if (mapDef.baseMap) { mapDef = $extend($extend({}, mapDef.baseMap), mapDef); } mapDef.map = function(source, options) { return new Map(source, options); }; return mapDef; } //============== // renderContent //============== function renderContent(data, context, noIteration, parentView, key, onRender) { var i, l, tag, tmpl, tagCtx, isTopRenderCall, prevData, prevIndex, view = parentView, result = ""; if (context === true) { noIteration = context; // passing boolean as second param - noIteration context = undefined; } else if (typeof context !== OBJECT) { context = undefined; // context must be a boolean (noIteration) or a plain object } if (tag = this.tag) { // This is a call from renderTag or tagCtx.render(...) tagCtx = this; view = view || tagCtx.view; tmpl = view.getTmpl(tag.template || tagCtx.tmpl); if (!arguments.length) { data = view; } } else { // This is a template.render(...) call tmpl = this; } if (tmpl) { if (!view && data && data._is === "view") { view = data; // When passing in a view to render or link (and not passing in a parent view) use the passed-in view as parentView } if (view) { if (data === view) { // Inherit the data from the parent view. // This may be the contents of an {{if}} block data = view.data; } } isTopRenderCall = !view; isRenderCall = isRenderCall || isTopRenderCall; if (!view) { (context = context || {}).root = data; // Provide ~root as shortcut to top-level data. } if (!isRenderCall || $subSettingsAdvanced.useViews || tmpl.useViews || view && view !== topView) { result = renderWithViews(tmpl, data, context, noIteration, view, key, onRender, tag); } else { if (view) { // In a block prevData = view.data; prevIndex = view.index; view.index = indexStr; } else { view = topView; view.data = data; view.ctx = context; } if ($isArray(data) && !noIteration) { // Create a view for the array, whose child views correspond to each data item. (Note: if key and parentView are passed in // along with parent view, treat as insert -e.g. from view.addViews - so parentView is already the view item for array) for (i = 0, l = data.length; i < l; i++) { view.index = i; view.data = data[i]; result += tmpl.fn(data[i], view, $sub); } } else { view.data = data; result += tmpl.fn(data, view, $sub); } view.data = prevData; view.index = prevIndex; } if (isTopRenderCall) { isRenderCall = undefined; } } return result; } function renderWithViews(tmpl, data, context, noIteration, view, key, onRender, tag) { function setItemVar(item) { // When itemVar is specified, set modified ctx with user-named ~item newCtx = $extend({}, context); newCtx[itemVar] = item; } // Render template against data as a tree of subviews (nested rendered template instances), or as a string (top-level template). // If the data is the parent view, treat as noIteration, re-render with the same data context. var i, l, newView, childView, itemResult, swapContent, contentTmpl, outerOnRender, tmplName, itemVar, newCtx, tagCtx, result = ""; if (tag) { // This is a call from renderTag or tagCtx.render(...) tmplName = tag.tagName; tagCtx = tag.tagCtx; context = context ? extendCtx(context, tag.ctx) : tag.ctx; if (tmpl === view.content) { // {{xxx tmpl=#content}} contentTmpl = tmpl !== view.ctx._wrp // We are rendering the #content ? view.ctx._wrp // #content was the tagCtx.props.tmpl wrapper of the block content - so within this view, #content will now be the view.ctx._wrp block content : undefined; // #content was the view.ctx._wrp block content - so within this view, there is no longer any #content to wrap. } else if (tmpl !== tagCtx.content) { if (tmpl === tag.template) { // Rendering {{tag}} tag.template, replacing block content. contentTmpl = tagCtx.tmpl; // Set #content to block content (or wrapped block content if tagCtx.props.tmpl is set) context._wrp = tagCtx.content; // Pass wrapped block content to nested views } else { // Rendering tagCtx.props.tmpl wrapper contentTmpl = tagCtx.content || view.content; // Set #content to wrapped block content } } else { contentTmpl = view.content; // Nested views inherit same wrapped #content property } if (tagCtx.props.link === false) { // link=false setting on block tag // We will override inherited value of link by the explicit setting link=false taken from props // The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect. context = context || {}; context.link = false; } if (itemVar = tagCtx.props.itemVar) { if (itemVar.charAt(0) !== "~") { syntaxError("Use itemVar='~myItem'"); } itemVar = itemVar.slice(1); } } if (view) { onRender = onRender || view._.onRender; context = extendCtx(context, view.ctx); } if (key === true) { swapContent = true; key = 0; } // If link===false, do not call onRender, so no data-linking marker nodes if (onRender && (context && context.link === false || tag && tag._.noVws)) { onRender = undefined; } outerOnRender = onRender; if (onRender === true) { // Used by view.refresh(). Don't create a new wrapper view. outerOnRender = undefined; onRender = view._.onRender; } // Set additional context on views created here, (as modified context inherited from the parent, and to be inherited by child views) context = tmpl.helpers ? extendCtx(tmpl.helpers, context) : context; newCtx = context; if ($isArray(data) && !noIteration) { // Create a view for the array, whose child views correspond to each data item. (Note: if key and view are passed in // along with parent view, treat as insert -e.g. from view.addViews - so view is already the view item for array) newView = swapContent ? view : (key !== undefined && view) || new View(context, "array", view, data, tmpl, key, onRender); if (view && view._.useKey) { // Parent is not an 'array view' newView._.bnd = !tag || tag._.bnd && tag; // For array views that are data bound for collection change events, set the // view._.bnd property to true for top-level link() or data-link="{for}", or to the tag instance for a data-bound tag, e.g. {^{for ...}} } if (itemVar) { newView.it = itemVar; } itemVar = newView.it; for (i = 0, l = data.length; i < l; i++) { // Create a view for each data item. if (itemVar) { setItemVar(data[i]); // use modified ctx with user-named ~item } childView = new View(newCtx, "item", newView, data[i], tmpl, (key || 0) + i, onRender, contentTmpl); itemResult = tmpl.fn(data[i], childView, $sub); result += newView._.onRender ? newView._.onRender(itemResult, childView) : itemResult; } } else { // Create a view for singleton data object. The type of the view will be the tag name, e.g. "if" or "myTag" except for // "item", "array" and "data" views. A "data" view is from programmatic render(object) against a 'singleton'. if (itemVar) { setItemVar(data); } newView = swapContent ? view : new View(newCtx, tmplName || "data", view, data, tmpl, key, onRender, contentTmpl); if (tag && !tag.flow) { newView.tag = tag; } result += tmpl.fn(data, newView, $sub); } return outerOnRender ? outerOnRender(result, newView) : result; } //=========================== // Build and compile template //=========================== // Generate a reusable function that will serve to render a template against data // (Compile AST then build template function) function onRenderError(e, view, fallback) { var message = fallback !== undefined ? $isFunction(fallback) ? fallback.call(view.data, e, view) : fallback || "" : "{Error: " + e.message + "}"; if ($subSettings.onError && (fallback = $subSettings.onError.call(view.data, e, fallback && message, view)) !== undefined) { message = fallback; // There is a settings.debugMode(handler) onError override. Call it, and use return value (if any) to replace message } return view && !view.linkCtx ? $converters.html(message) : message; } function error(message) { throw new $sub.Err(message); } function syntaxError(message) { error("Syntax error\n" + message); } function tmplFn(markup, tmpl, isLinkExpr, convertBack, hasElse) { // Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes // Used for compiling templates, and also by JsViews to build functions for data link expressions //==== nested functions ==== function pushprecedingContent(shift) { shift -= loc; if (shift) { content.push(markup.substr(loc, shift).replace(rNewLine, "\\n")); } } function blockTagCheck(tagName, block) { if (tagName) { tagName += '}}'; // '{{include}} block has {{/for}} with no open {{for}}' syntaxError(( block ? '{{' + block + '}} block has {{/' + tagName + ' without {{' + tagName : 'Unmatched or missing {{/' + tagName) + ', in template:\n' + markup); } } function parseTag(all, bind, tagName, converter, colon, html, codeTag, params, slash, bind2, closeBlock, index) { /* bind tagName cvt cln html code params slash bind2 closeBlk comment /(?:{(\^)?{(?:(\w+(?=[\/\s}]))|(\w+)?(:)|(>)|(\*))\s*((?:[^}]|}(?!}))*?)(\/)?|{(\^)?{(?:(?:\/(\w+))\s*|!--[\s\S]*?--))}}/g (?: {(\^)?{ bind (?: (\w+ tagName (?=[\/\s}]) ) | (\w+)?(:) converter colon | (>) html | (\*) codeTag ) \s* ( params (?:[^}]|}(?!}))*? ) (\/)? slash | {(\^)?{ bind2 (?: (?:\/(\w+))\s* closeBlock | !--[\s\S]*?-- comment ) ) }}/g */ if (codeTag && bind || slash && !tagName || params && params.slice(-1) === ":" || bind2) { syntaxError(all); } // Build abstract syntax tree (AST): [tagName, converter, params, content, hash, bindings, contentMarkup] if (html) { colon = ":"; converter = HTML; } slash = slash || isLinkExpr && !hasElse; var pathBindings = (bind || isLinkExpr) && [[]], props = "", args = "", ctxProps = "", paramsArgs = "", paramsProps = "", paramsCtxProps = "", onError = "", useTrigger = "", // Block tag if not self-closing and not {{:}} or {{>}} (special case) and not a data-link expression block = !slash && !colon; //==== nested helper function ==== tagName = tagName || (params = params || "#data", colon); // {{:}} is equivalent to {{:#data}} pushprecedingContent(index); loc = index + all.length; // location marker - parsed up to here if (codeTag) { if (allowCode) { content.push(["*", "\n" + params.replace(/^:/, "ret+= ").replace(rUnescapeQuotes, "$1") + ";\n"]); } } else if (tagName) { if (tagName === "else") { if (rTestElseIf.test(params)) { syntaxError('for "{{else if expr}}" use "{{else expr}}"'); } pathBindings = current[7] && [[]]; current[8] = markup.substring(current[8], index); // contentMarkup for block tag current = stack.pop(); content = current[2]; block = true; } if (params) { // remove newlines from the params string, to avoid compiled code errors for unterminated strings parseParams(params.replace(rNewLine, " "), pathBindings, tmpl) .replace(rBuildHash, function(all, onerror, isCtx, key, keyToken, keyValue, arg, param) { key = "'" + keyToken + "':"; if (arg) { args += keyValue + ","; paramsArgs += "'" + param + "',"; } else if (isCtx) { ctxProps += key + keyValue + ","; paramsCtxProps += key + "'" + param + "',"; } else if (onerror) { onError += keyValue; } else { if (keyToken === "trigger") { useTrigger += keyValue; } props += key + keyValue + ","; paramsProps += key + "'" + param + "',"; hasHandlers = hasHandlers || rHasHandlers.test(keyToken); } return ""; }).slice(0, -1); } if (pathBindings && pathBindings[0]) { pathBindings.pop(); // Remove the bindings that was prepared for next arg. (There is always an extra one ready). } newNode = [ tagName, converter || !!convertBack || hasHandlers || "", block && [], parsedParam(paramsArgs || (tagName === ":" ? "'#data'," : ""), paramsProps, paramsCtxProps), // {{:}} equivalent to {{:#data}} parsedParam(args || (tagName === ":" ? "data," : ""), props, ctxProps), onError, useTrigger, pathBindings || 0 ]; content.push(newNode); if (block) { stack.push(current); current = newNode; current[8] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag } } else if (closeBlock) { blockTagCheck(closeBlock !== current[0] && current[0] !== "else" && closeBlock, current[0]); current[8] = markup.substring(current[8], index); // contentMarkup for block tag current = stack.pop(); } blockTagCheck(!current && closeBlock); content = current[2]; } //==== /end of nested functions ==== var i, result, newNode, hasHandlers, bindings, allowCode = $subSettings.allowCode || tmpl && tmpl.allowCode || $viewsSettings.allowCode === true, // include direct setting of settings.allowCode true for backward compat only astTop = [], loc = 0, stack = [], content = astTop, current = [,,astTop]; if (allowCode) { tmpl.allowCode = allowCode; } //TODO result = tmplFnsCache[markup]; // Only cache if template is not named and markup length < ..., //and there are no bindings or subtemplates?? Consider standard optimization for data-link="a.b.c" // if (result) { // tmpl.fn = result; // } else { // result = markup; if (isLinkExpr) { if (convertBack !== undefined) { markup = markup.slice(0, -convertBack.length - 2) + delimCloseChar1; } markup = delimOpenChar0 + markup + delimCloseChar1; } blockTagCheck(stack[0] && stack[0][2].pop()[0]); // Build the AST (abstract syntax tree) under astTop markup.replace(rTag, parseTag); pushprecedingContent(markup.length); if (loc = astTop[astTop.length - 1]) { blockTagCheck("" + loc !== loc && (+loc[8] === loc[8]) && loc[0]); } // result = tmplFnsCache[markup] = buildCode(astTop, tmpl); // } if (isLinkExpr) { result = buildCode(astTop, markup, isLinkExpr); bindings = []; i = astTop.length; while (i--) { bindings.unshift(astTop[i][7]); // With data-link expressions, pathBindings array for tagCtx[i] is astTop[i][7] } setPaths(result, bindings); } else { result = buildCode(astTop, tmpl); } return result; } function setPaths(fn, pathsArr) { var key, paths, i = 0, l = pathsArr.length; fn.deps = []; for (; i < l; i++) { paths = pathsArr[i]; for (key in paths) { if (key !== "_jsvto" && paths[key].length) { fn.deps = fn.deps.concat(paths[key]); // deps is the concatenation of the paths arrays for the different bindings } } } fn.paths = paths; // The array of paths arrays for the different bindings } function parsedParam(args, props, ctx) { return [args.slice(0, -1), props.slice(0, -1), ctx.slice(0, -1)]; } function paramStructure(parts, type) { return '\n\t' + (type ? type + ':{' : '') + 'args:[' + parts[0] + ']' + (parts[1] || !type ? ',\n\tprops:{' + parts[1] + '}' : "") + (parts[2] ? ',\n\tctx:{' + parts[2] + '}' : ""); } function parseParams(params, pathBindings, tmpl) { function parseTokens(all, lftPrn0, lftPrn, bound, path, operator, err, eq, path2, prn, comma, lftPrn2, apos, quot, rtPrn, rtPrnDot, prn2, space, index, full) { // /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(!*?[#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?[#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*(([)\]])(?=\s*[.^]|\s*$|[^([])|[)\]])([([]?))|(\s+)/g, // lftPrn0 lftPrn bound path operator err eq path2 prn comma lftPrn2 apos quot rtPrn rtPrnDot prn2 space // (left paren? followed by (path? followed by operator) or (path followed by paren?)) or comma or apos or quot or right paren or space bound = bindings && bound; if (bound && !eq) { path = bound + path; // e.g. some.fn(...)^some.path - so here path is "^some.path" } operator = operator || ""; lftPrn = lftPrn || lftPrn0 || lftPrn2; path = path || path2; // Could do this - but not worth perf cost?? :- // if (!path.lastIndexOf("#data.", 0)) { path = path.slice(6); } // If path starts with "#data.", remove that. prn = prn || prn2 || ""; var expr, exprFn, binds, theOb, newOb, rtSq = ")"; if (prn === "[") { prn ="[j._sq("; rtSq = ")]"; } function parsePath(allPath, not, object, helper, view, viewProperty, pathTokens, leafToken) { //rPath = /^(!*?)(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g, // not object helper view viewProperty pathTokens leafToken var subPath = object === "."; if (object) { path = path.slice(not.length); if (/^\.?constructor$/.test(leafToken||path)) { syntaxError(allPath); } if (!subPath) { allPath = (helper ? 'view.hlp("' + helper + '")' : view ? "view" : "data") + (leafToken ? (viewProperty ? "." + viewProperty : helper ? "" : (view ? "" : "." + object) ) + (pathTokens || "") : (leafToken = helper ? "" : view ? viewProperty || "" : object, "")); allPath = allPath + (leafToken ? "." + leafToken : ""); allPath = not + (allPath.slice(0, 9) === "view.data" ? allPath.slice(5) // convert #view.data... to data... : allPath); } if (bindings) { binds = named === "linkTo" ? (bindto = pathBindings._jsvto = pathBindings._jsvto || []) : bndCtx.bd; if (theOb = subPath && binds[binds.length-1]) { if (theOb._jsv) { while (theOb.sb) { theOb = theOb.sb; } if (theOb.bnd) { path = "^" + path.slice(1); } theOb.sb = path; theOb.bnd = theOb.bnd || path.charAt(0) === "^"; } } else { binds.push(path); } pathStart[parenDepth] = index + (subPath ? 1 : 0); } } return allPath; } if (err && !aposed && !quoted) { syntaxError(params); } else { if (bindings && rtPrnDot && !aposed && !quoted) { // This is a binding to a path in which an object is returned by a helper/data function/expression, e.g. foo()^x.y or (a?b:c)^x.y // We create a compiled function to get the object instance (which will be called when the dependent data of the subexpression changes, to return the new object, and trigger re-binding of the subsequent path) if (!named || boundName || bindto) { expr = pathStart[parenDepth - 1]; if (full.length - 1 > index - (expr || 0)) { // We need to compile a subexpression expr = full.slice(expr, index + all.length); if (exprFn !== true) { // If not reentrant call during compilation binds = bindto || bndStack[parenDepth-1].bd; // Insert exprOb object, to be used during binding to return the computed object theOb = binds[binds.length-1]; if (theOb && theOb.prm) { while (theOb.sb && theOb.sb.prm) { theOb = theOb.sb; } newOb = theOb.sb = {path: theOb.sb, bnd: theOb.bnd}; } else { binds.push(newOb = {path: binds.pop()}); // Insert exprOb object, to be used during binding to return the computed object } // (e.g. "some.object()" in "some.object().a.b" - to be used as context for binding the following tokens "a.b") } rtPrnDot = delimOpenChar1 + ":" + expr // The parameter or function subexpression + " onerror=''" // set onerror='' in order to wrap generated code with a try catch - returning '' as object instance if there is an error/missing parent + delimCloseChar0; exprFn = tmplLinks[rtPrnDot]; if (!exprFn) { tmplLinks[rtPrnDot] = true; // Flag that this exprFn (for rtPrnDot) is being compiled tmplLinks[rtPrnDot] = exprFn = tmplFn(rtPrnDot, tmpl, true); // Compile the expression (or use cached copy already in tmpl.links) } if (exprFn !== true && newOb) { // If not reentrant call during compilation newOb._jsv = exprFn; newOb.prm = bndCtx.bd; newOb.bnd = newOb.bnd || newOb.path && newOb.path.indexOf("^") >= 0; } } } } return (aposed // within single-quoted string ? (aposed = !apos, (aposed ? all : lftPrn2 + '"')) : quoted // within double-quoted string ? (quoted = !quot, (quoted ? all : lftPrn2 + '"')) : ( (lftPrn ? (pathStart[parenDepth] = index++, bndCtx = bndStack[++parenDepth] = {bd: []}, lftPrn) : "") + (space ? (parenDepth ? "" // New arg or prop - so insert backspace \b (\x08) as separator for named params, used subsequently by rBuildHash, and prepare new bindings array : (paramIndex = full.slice(paramIndex, index), named ? (named = boundName = bindto = false, "\b") : "\b,") + paramIndex + (paramIndex = index + all.length, bindings && pathBindings.push(bndCtx.bd = []), "\b") ) : eq // named param. Remove bindings for arg and create instead bindings array for prop ? (parenDepth && syntaxError(params), bindings && pathBindings.pop(), named = path, boundName = bound, paramIndex = index + all.length, bound && (bindings = bndCtx.bd = pathBindings[named] = []), path + ':') : path // path ? (path.split("^").join(".").replace(rPath, parsePath) + (prn // some.fncall( ? (bndCtx = bndStack[++parenDepth] = {bd: []}, fnCall[parenDepth] = rtSq, prn) : operator) ) : operator // operator ? operator : rtPrn // function ? ((rtPrn = fnCall[parenDepth] || rtPrn, fnCall[parenDepth] = false, bndCtx = bndStack[--parenDepth], rtPrn) + (prn // rtPrn and prn, e.g )( in (a)() or a()(), or )[ in a()[] ? (bndCtx = bndStack[++parenDepth], fnCall[parenDepth] = rtSq, prn) : "") ) : comma ? (fnCall[parenDepth] || syntaxError(params), ",") // We don't allow top-level literal arrays or objects : lftPrn0 ? "" : (aposed = apos, quoted = quot, '"') )) ); } } var named, bindto, boundName, quoted, // boolean for string content in double quotes aposed, // or in single quotes bindings = pathBindings && pathBindings[0], // bindings array for the first arg bndCtx = {bd: bindings}, bndStack = {0: bndCtx}, paramIndex = 0, // list, tmplLinks = tmpl ? tmpl.links : bindings && (bindings.links = bindings.links || {}), // The following are used for tracking path parsing including nested paths, such as "a.b(c^d + (e))^f", and chained computed paths such as // "a.b().c^d().e.f().g" - which has four chained paths, "a.b()", "^c.d()", ".e.f()" and ".g" parenDepth = 0, fnCall = {}, // We are in a function call pathStart = {}, // tracks the start of the current path such as c^d() in the above example result = (params + (tmpl ? " " : "")).replace(rParams, parseTokens); return !parenDepth && result || syntaxError(params); // Syntax error if unbalanced parens in params expression } function buildCode(ast, tmpl, isLinkExpr) { // Build the template function code from the AST nodes, and set as property on the passed-in template object // Used for compiling templates, and also by JsViews to build functions for data link expressions var i, node, tagName, converter, tagCtx, hasTag, hasEncoder, getsVal, hasCnvt, useCnvt, tmplBindings, pathBindings, params, boundOnErrStart, boundOnErrEnd, tagRender, nestedTmpls, tmplName, nestedTmpl, tagAndElses, content, markup, nextIsElse, oldCode, isElse, isGetVal, tagCtxFn, onError, tagStart, trigger, tmplBindingKey = 0, useViews = $subSettingsAdvanced.useViews || tmpl.useViews || tmpl.tags || tmpl.templates || tmpl.helpers || tmpl.converters, code = "", tmplOptions = {}, l = ast.length; if ("" + tmpl === tmpl) { tmplName = isLinkExpr ? 'data-link="' + tmpl.replace(rNewLine, " ").slice(1, -1) + '"' : tmpl; tmpl = 0; } else { tmplName = tmpl.tmplName || "unnamed"; if (tmpl.allowCode) { tmplOptions.allowCode = true; } if (tmpl.debug) { tmplOptions.debug = true; } tmplBindings = tmpl.bnds; nestedTmpls = tmpl.tmpls; } for (i = 0; i < l; i++) { // AST nodes: [0: tagName, 1: converter, 2: content, 3: params, 4: code, 5: onError, 6: trigger, 7:pathBindings, 8: contentMarkup] node = ast[i]; // Add newline for each callout to t() c() etc. and each markup string if ("" + node === node) { // a markup string to be inserted code += '\n+"' + node + '"'; } else { // a compiled tag expression to be inserted tagName = node[0]; if (tagName === "*") { // Code tag: {{* }} code += ";\n" + node[1] + "\nret=ret"; } else { converter = node[1]; content = !isLinkExpr && node[2]; tagCtx = paramStructure(node[3], 'params') + '},' + paramStructure(params = node[4]); onError = node[5]; trigger = node[6]; markup = node[8] && node[8].replace(rUnescapeQuotes, "$1"); if (isElse = tagName === "else") { if (pathBindings) { pathBindings.push(node[7]); } } else { tmplBindingKey = 0; if (tmplBindings && (pathBindings = node[7])) { // Array of paths, or false if not data-bound pathBindings = [pathBindings]; tmplBindingKey = tmplBindings.push(1); // Add placeholder in tmplBindings for compiled function } } useViews = useViews || params[1] || params[2] || pathBindings || /view.(?!index)/.test(params[0]); // useViews is for perf optimization. For render() we only use views if necessary - for the more advanced scenarios. // We use views if there are props, contextual properties or args with #... (other than #index) - but you can force // using the full view infrastructure, (and pay a perf price) by opting in: Set useViews: true on the template, manually... if (isGetVal = tagName === ":") { if (converter) { tagName = converter === HTML ? ">" : converter + tagName; } } else { if (content) { // TODO optimize - if content.length === 0 or if there is a tmpl="..." specified - set content to null / don't run this compilation code - since content won't get used!! // Create template object for nested template nestedTmpl = tmplObject(markup, tmplOptions); nestedTmpl.tmplName = tmplName + "/" + tagName; // Compile to AST and then to compiled function nestedTmpl.useViews = nestedTmpl.useViews || useViews; buildCode(content, nestedTmpl); useViews = nestedTmpl.useViews; nestedTmpls.push(nestedTmpl); } if (!isElse) { // This is not an else tag. tagAndElses = tagName; useViews = useViews || tagName && (!$tags[tagName] || !$tags[tagName].flow); // Switch to a new code string for this bound tag (and its elses, if it has any) - for returning the tagCtxs array oldCode = code; code = ""; } nextIsElse = ast[i + 1]; nextIsElse = nextIsElse && nextIsElse[0] === "else"; } tagStart = onError ? ";\ntry{\nret+=" : "\n+"; boundOnErrStart = ""; boundOnErrEnd = ""; if (isGetVal && (pathBindings || trigger || converter && converter !== HTML)) { // For convertVal we need a compiled function to return the new tagCtx(s) tagCtxFn = new Function("data,view,j,u", " // " + tmplName + " " + tmplBindingKey + " " + tagName + "\nreturn {" + tagCtx + "};"); tagCtxFn._er = onError; tagCtxFn._tag = tagName; if (isLinkExpr) { return tagCtxFn; } setPaths(tagCtxFn, pathBindings); tagRender = 'c("' + converter + '",view,'; useCnvt = true; boundOnErrStart = tagRender + tmplBindingKey + ","; boundOnErrEnd = ")"; } code += (isGetVal ? (isLinkExpr ? (onError ? "try{\n" : "") + "return " : tagStart) + (useCnvt // Call _cnvt if there is a converter: {{cnvt: ... }} or {^{cnvt: ... }} ? (useCnvt = undefined, useViews = hasCnvt = true, tagRender + (pathBindings ? ((tmplBindings[tmplBindingKey - 1] = tagCtxFn), tmplBindingKey) // Store the compiled tagCtxFn in tmpl.bnds, and pass the key to convertVal() : "{" + tagCtx + "}") + ")") : tagName === ">" ? (hasEncoder = true, "h(" + params[0] + ")") : (getsVal = true, "((v=" + params[0] + ')!=null?v:' + (isLinkExpr ? 'null)' : '"")')) // Non strict equality so data-link="title{:expr}" with expr=null/undefined removes title attribute ) : (hasTag = true, "\n{view:view,tmpl:" // Add this tagCtx to the compiled code for the tagCtxs to be passed to renderTag() + (content ? nestedTmpls.length : "0") + "," // For block tags, pass in the key (nestedTmpls.length) to the nested content template + tagCtx + "},")); if (tagAndElses && !nextIsElse) { // This is a data-link expression or an inline tag without any elses, or the last {{else}} of an inline tag // We complete the code for returning the tagCtxs array code = "[" + code.slice(0, -1) + "]"; tagRender = 't("' + tagAndElses + '",view,this,'; if (isLinkExpr || pathBindings) { // This is a bound tag (data-link expression or inline bound tag {^{tag ...}}) so we store a compiled tagCtxs function in tmp.bnds code = new Function("data,view,j,u", " // " + tmplName + " " + tmplBindingKey + " " + tagAndElses + "\nreturn " + code + ";"); code._er = onError; code._tag = tagAndElses; if (pathBindings) { setPaths(tmplBindings[tmplBindingKey - 1] = code, pathBindings); } if (isLinkExpr) { return code; // For a data-link expression we return the compiled tagCtxs function } boundOnErrStart = tagRender + tmplBindingKey + ",undefined,"; boundOnErrEnd = ")"; } // This is the last {{else}} for an inline tag. // For a bound tag, pass the tagCtxs fn lookup key to renderTag. // For an unbound tag, include the code directly for evaluating tagCtxs array code = oldCode + tagStart + tagRender + (tmplBindingKey || code) + ")"; pathBindings = 0; tagAndElses = 0; } if (onError) { useViews = true; code += ';\n}catch(e){ret' + (isLinkExpr ? "urn " : "+=") + boundOnErrStart + 'j._err(e,view,' + onError + ')' + boundOnErrEnd + ';}' + (isLinkExpr ? "" : 'ret=ret'); } } } } // Include only the var references that are needed in the code code = "// " + tmplName + "\nvar v" + (hasTag ? ",t=j._tag" : "") // has tag + (hasCnvt ? ",c=j._cnvt" : "") // converter + (hasEncoder ? ",h=j._html" : "") // html converter + (isLinkExpr ? ";\n" : ',ret=""\n') + (tmplOptions.debug ? "debugger;" : "") + code + (isLinkExpr ? "\n" : ";\nreturn ret;"); if ($subSettings.debugMode !== false) { code = "try {\n" + code + "\n}catch(e){\nreturn j._err(e, view);\n}"; } try { code = new Function("data,view,j,u", code); } catch (e) { syntaxError("Compiled template code:\n\n" + code + '\n: "' + e.message + '"'); } if (tmpl) { tmpl.fn = code; tmpl.useViews = !!useViews; } return code; } //========== // Utilities //========== // Merge objects, in particular contexts which inherit from parent contexts function extendCtx(context, parentContext) { // Return copy of parentContext, unless context is defined and is different, in which case return a new merged context // If neither context nor parentContext are defined, return undefined return context && context !== parentContext ? (parentContext ? $extend($extend({}, parentContext), context) : context) : parentContext && $extend({}, parentContext); } // Get character entity for HTML and Attribute encoding function getCharEntity(ch) { return charEntities[ch] || (charEntities[ch] = "&#" + ch.charCodeAt(0) + ";"); } function getTargetProps(source) { // this pointer is theMap - which has tagCtx.props too // arguments: tagCtx.args. var key, prop, props = []; if (typeof source === OBJECT) { for (key in source) { prop = source[key]; if (key !== $expando && !$isFunction(prop)) { props.push({key: key, prop: prop}); } } } return props; } function $fnRender(data, context, noIteration) { var tmplElem = this.jquery && (this[0] || error('Unknown template: "' + this.selector + '"')), tmpl = tmplElem.getAttribute(tmplAttr); return renderContent.call(tmpl ? $.data(tmplElem)[jsvTmpl] : $templates(tmplElem), data, context, noIteration); } //========================== Register converters ========================== function htmlEncode(text) { // HTML encode: Replace < > & ' and " by corresponding entities. return text != undefined ? rIsHtml.test(text) && ("" + text).replace(rHtmlEncode, getCharEntity) || text : ""; } //========================== Initialize ========================== $sub = $views.sub; $viewsSettings = $views.settings; if (!(jsr || $ && $.render)) { // JsRender not already loaded, or loaded without jQuery, and we are now moving from jsrender namespace to jQuery namepace for (jsvStoreName in jsvStores) { registerStore(jsvStoreName, jsvStores[jsvStoreName]); } $converters = $views.converters; $helpers = $views.helpers; $tags = $views.tags; $sub._tg.prototype = { baseApply: baseApply, cvtArgs: convertArgs }; topView = $sub.topView = new View(); //BROWSER-SPECIFIC CODE if ($) { //////////////////////////////////////////////////////////////////////////////////////////////// // jQuery (= $) is loaded $.fn.render = $fnRender; $expando = $.expando; if ($.observable) { $extend($sub, $.views.sub); // jquery.observable.js was loaded before jsrender.js $views.map = $.views.map; } } else { //////////////////////////////////////////////////////////////////////////////////////////////// // jQuery is not loaded. $ = {}; if (setGlobals) { global.jsrender = $; // We are loading jsrender.js from a script element, not AMD or CommonJS, so set global } // Error warning if jsrender.js is used as template engine on Node.js (e.g. Express or Hapi...) // Use jsrender-node.js instead... $.renderFile = $.__express = $.compile = function() { throw "Node.js: use npm jsrender, or jsrender-node.js"; }; //END BROWSER-SPECIFIC CODE $.isFunction = function(ob) { return typeof ob === "function"; }; $.isArray = Array.isArray || function(obj) { return ({}.toString).call(obj) === "[object Array]"; }; $sub._jq = function(jq) { // private method to move from JsRender APIs from jsrender namespace to jQuery namespace if (jq !== $) { $extend(jq, $); // map over from jsrender namespace to jQuery namespace $ = jq; $.fn.render = $fnRender; delete $.jsrender; $expando = $.expando; } }; $.jsrender = versionNumber; } $subSettings = $sub.settings; $subSettings.allowCode = false; $isFunction = $.isFunction; $isArray = $.isArray; $.render = $render; $.views = $views; $.templates = $templates = $views.templates; for (setting in $subSettings) { addSetting(setting); } ($viewsSettings.debugMode = function(debugMode) { return debugMode === undefined ? $subSettings.debugMode : ( $subSettings.debugMode = debugMode, $subSettings.onError = debugMode + "" === debugMode ? new Function("", "return '" + debugMode + "';" ) : $isFunction(debugMode) ? debugMode : undefined, $viewsSettings); })(false); // jshint ignore:line $subSettingsAdvanced = $subSettings.advanced = { useViews: false, _jsv: false // For global access to JsViews store }; //========================== Register tags ========================== $tags({ "if": { render: function(val) { // This function is called once for {{if}} and once for each {{else}}. // We will use the tag.rendering object for carrying rendering state across the calls. // If not done (a previous block has not been rendered), look at expression for this block and render the block if expression is truthy // Otherwise return "" var self = this, tagCtx = self.tagCtx, ret = (self.rendering.done || !val && (arguments.length || !tagCtx.index)) ? "" : (self.rendering.done = true, self.selected = tagCtx.index, // Test is satisfied, so render content on current context. We call tagCtx.render() rather than return undefined // (which would also render the tmpl/content on the current context but would iterate if it is an array) tagCtx.render(tagCtx.view, true)); // no arg, so renders against parentView.data return ret; }, flow: true }, "for": { render: function(val) { // This function is called once for {{for}} and once for each {{else}}. // We will use the tag.rendering object for carrying rendering state across the calls. var finalElse = !arguments.length, value, self = this, tagCtx = self.tagCtx, result = "", done = 0; if (!self.rendering.done) { value = finalElse ? tagCtx.view.data : val; // For the final else, defaults to current data without iteration. if (value !== undefined) { result += tagCtx.render(value, finalElse); // Iterates except on final else, if data is an array. (Use {{include}} to compose templates without array iteration) done += $isArray(value) ? value.length : 1; } if (self.rendering.done = done) { self.selected = tagCtx.index; } // If nothing was rendered we will look at the next {{else}}. Otherwise, we are done. } return result; }, flow: true }, props: { baseTag: "for", dataMap: dataMap(getTargetProps), flow: true }, include: { flow: true }, "*": { // {{* code... }} - Ignored if template.allowCode and $.views.settings.allowCode are false. Otherwise include code in compiled template render: retVal, flow: true }, ":*": { // {{:* returnedExpression }} - Ignored if template.allowCode and $.views.settings.allowCode are false. Otherwise include code in compiled template render: retVal, flow: true }, dbg: $helpers.dbg = $converters.dbg = dbgBreak // Register {{dbg/}}, {{dbg:...}} and ~dbg() to throw and catch, as breakpoints for debugging. }); $converters({ html: htmlEncode, attr: htmlEncode, // Includes > encoding since rConvertMarkers in JsViews does not skip > characters in attribute strings url: function(text) { // URL encoding helper. return text != undefined ? encodeURI("" + text) : text === null ? text : ""; // null returns null, e.g. to remove attribute. undefined returns "" } }); } //========================== Define default delimiters ========================== $subSettings = $sub.settings; $viewsSettings.delimiters("{{", "}}", "^"); if (jsrToJq) { // Moving from jsrender namespace to jQuery namepace - copy over the stored items (templates, converters, helpers...) jsr.views.sub._jq($); } //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< JsObservable >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /* JsObservable: * See http://www.jsviews.com/#jsobservable and http://github.com/borismoore/jsviews * Copyright 2016, Boris Moore * Released under the MIT License. */ //========================== Top-level vars ========================== $views = $.views; $sub = $views.sub; $isFunction = $.isFunction; $isArray = $.isArray; $expando = $.expando; if (!$.observe) { var $eventSpecial = $.event.special, slice = [].slice, splice = [].splice, concat = [].concat, PARSEINT = parseInt, rNotWhite = /\S+/g, propertyChangeStr = $sub.propChng = $sub.propChng || "propertyChange",// These two settings can be overridden on settings after loading arrayChangeStr = $sub.arrChng = $sub.arrChng || "arrayChange", // jsRender, and prior to loading jquery.observable.js and/or JsViews cbBindingsStore = {}, observeStr = propertyChangeStr + ".observe", observeObjKey = 1, observeCbKey = 1, observeInnerCbKey = 1, $hasData = $.hasData, $data = $.data, remove = {}, // flag for removeProperty //========================== Top-level functions ========================== getCbKey = function(cb) { return cb._cId = cb._cId || (".obs" + observeCbKey++); }, ObjectObservable = function(ns, data) { this._data = data; this._ns = ns; return this; }, ArrayObservable = function(ns, data) { this._data = data; this._ns = ns; return this; }, wrapArray = function(data) { return $isArray(data) ? [data] : data; }, resolvePathObjects = function(paths, root, callback) { paths = paths ? $isArray(paths) ? paths : [paths] : []; var i, path, object = root, nextObj = object, l = paths && paths.length, out = []; for (i = 0; i < l; i++) { path = paths[i]; if ($isFunction(path)) { out = out.concat(resolvePathObjects(path.call(root, root, callback), root)); continue; } else if ("" + path !== path) { root = nextObj = path; if (nextObj !== object) { out.push(object = nextObj); } continue; } if (nextObj !== object) { out.push(object = nextObj); } out.push(path); } return out; }, removeCbBindings = function(cbBindings, cbBindingsId) { // If the cbBindings collection is empty we will remove it from the cbBindingsStore for (var cb in cbBindings) { return; } delete cbBindingsStore[cbBindingsId]; // This binding collection is empty, so remove from store }, onObservableChange = function(ev, eventArgs) { function isOb(val) { return typeof val === OBJECT && (paths[0] || allowArray && $isArray(val)); } if (!(ev.data && ev.data.off)) { // Skip if !!ev.data.off: - a handler that has already been removed (maybe was on handler collection at call time - then removed by another handler) var allPath, filter, parentObs, oldValue = eventArgs.oldValue, value = eventArgs.value, ctx = ev.data, observeAll = ctx.observeAll, cb = ctx.cb, allowArray = !cb.noArray, paths = ctx.paths, ns = ctx.ns; if (ev.type === arrayChangeStr) { (cb.array || cb).call(ctx, ev, eventArgs); // If there is an arrayHandler expando on the regular handler, use it, otherwise use the regular handler for arrayChange events also - for example: $.observe(array, handler) // or observeAll() with an array in the graph. Note that on data-link bindings we ensure always to have an array handler - $.noop if none is specified e.g. on the data-linked tag. } else if (ctx.prop === eventArgs.path || ctx.prop === "*") { if (observeAll) { allPath = observeAll._path + "." + eventArgs.path; filter = observeAll.filter; parentObs = [ev.target].concat(observeAll.parents()); if (isOb(oldValue)) { observe_apply(allowArray, ns, [oldValue], paths, cb, true, filter, [parentObs], allPath); // unobserve } if (isOb(value)) { observe_apply(allowArray, ns, [value], paths, cb, undefined, filter, [parentObs], allPath); } } else { if (isOb(oldValue)) { // oldValue is an object, so unobserve observe_apply(allowArray, ns, [oldValue], paths, cb, true); // unobserve } if (isOb(value)) { // value is an object, so observe observe_apply(allowArray, ns, [value], paths, cb); } } ctx.cb(ev, eventArgs); } } }, observe_apply = function() { // $.observe(), but allowing you to include arrays within the arguments - which you want flattened. var args = concat.apply([], arguments); // Flatten the arguments return $observe.apply(args.shift(), args); }, $observeAll = function(cb, filter, unobserve) { observeAll(this._ns, this._data, cb, filter, [], "root", unobserve); }, $unobserveAll = function(cb, filter) { $observeAll.call(this, cb, filter, true); }, observeAll = function(namespace, object, cb, filter, parentObs, allPath, unobserve, objMap) { function observeArrayItems(arr, unobs) { l = arr.length; newAllPath = allPath + "[]"; while (l--) { filterAndObserveAll(arr, l, unobs, 1); } } function filterAndObserveAll(obj, prop, unobs, nestedArray) { var newObject, newParentObs; if (prop !== $expando) { if (newObject = $observable._fltr(newAllPath, obj[prop], nextParentObs, filter)) { newParentObs = nextParentObs.slice(); if (nestedArray && updatedTgt && newParentObs[0] !== updatedTgt) { newParentObs.unshift(updatedTgt); // For array change events when observing an array which is not the root, need to add updated array to parentObs } observeAll(namespace, newObject, cb, filter || (nestedArray ? undefined : 0), newParentObs, newAllPath, unobs, objMap); // If nested array, need to observe the array too - so set filter to undefined } } } function wrappedCb(ev, eventArgs) { // This object is changing. allPath = ev.data.observeAll._path; updatedTgt = ev.target; switch (eventArgs.change) { // observeAll/unobserveAll on added or removed objects case "insert": observeArrayItems(eventArgs.items); break; case "remove": observeArrayItems(eventArgs.items, true); // unobserveAll on removed items break; case "set": newAllPath = allPath + "." + eventArgs.path; filterAndObserveAll(eventArgs, "oldValue", true); // unobserve old value filterAndObserveAll(eventArgs, "value"); // observe new value } updatedTgt = undefined; cb.apply(this, arguments); // Observe this object (invoke the callback) } var l, isObject, newAllPath, nextParentObs, updatedTgt, obId, notRemoving = !objMap || objMap.un || !unobserve; // true unless it is an observeAll call (not unobserveAll) and we are removing a listener (not adding one) if (object && typeof object === OBJECT) { nextParentObs = [object].concat(parentObs); // The parentObs chain for the next depth of observeAll isObject = $isArray(object) ? "" : "*"; if (objMap && notRemoving && $hasData(object) && objMap[obId = $data(object).obId]) { objMap[obId]++; return; // This object has already being observed/unobserved by this observeAll/unobserveAll call (must be a cyclic object graph) so skip, to avoid // stack overflow/multiple instances of listener. See jsviews/pull/305 // NOTE - WE DO NOT support ObserveAll on data with cyclic graphs which include DUPLICATE REFERENCES TO ARRAY PROPERTIES - such as data.children = data.descendants = [] } if (!objMap) { objMap = {un: unobserve}; // Map object to register observed objects for this observeAll } if (cb) { // Observe this object or array - and also listen for changes to object graph, to add or remove observers from the modified object graph if (isObject || filter !== 0) { // If an object, observe the object. If an array, only add arrayChange binding if has filter or if filter is undefined (!== 0) - which // is the case for top-level calls or for nested array (array item of an array - e.g. member of 2-dimensional array). // For array properties lower in the tree, with no filter, filter is set to 0 in filterAndObserveAll, so no arrayChange binding here, // since they get arrayChange binding added during regular $.observe(array ...) binding. wrappedCb._cId = getCbKey(cb); // Identify wrapped callback with unwrapped callback, so unobserveAll will // remove previous observeAll wrapped callback, if inner callback was the same; if (notRemoving) { $observe(namespace, object, isObject, wrappedCb, unobserve, filter, nextParentObs, allPath); obId = $data(object).obId; objMap[obId] = (objMap[obId] || 0) + 1; // Register on map of objects observed/unobserved by this observeAll/unobserveAll call //- or remove from map if we are removing this object from observeAll call. (Avoid dups, for cyclic graphs) } else { if (--objMap[$data(object).obId]) { // Register on map of objects observed/unobserved by this observeAll/unobserveAll call //- or remove from map if we are removing this object from observeAll call. (Avoid dups, for cyclic graphs) return; } $observe(namespace, object, isObject, wrappedCb, unobserve, filter, nextParentObs, allPath); } } } else { // No callback. Just unobserve if unobserve === true. if (objMap) { objMap[$data(object).obId] = 1; // Register on map of objects unobserved by this unobserveAll call. (Avoid dups, for cyclic graphs) } $observe(namespace, object, isObject, undefined, unobserve, filter, nextParentObs, allPath); } if (isObject) { // Continue stepping through object graph, observing object and arrays // To override filtering, pass in filter function, or replace $.observable._fltr for (l in object) { newAllPath = allPath + "." + l; filterAndObserveAll(object, l, unobserve); } } else { // Observe items in Array observeArrayItems(object, unobserve); } } }, shallowFilter = function(allPath /*, object, parentObs*/) { return allPath.indexOf(".") < 0 && allPath.indexOf("[") < 0; }, $unobserve = function() { [].push.call(arguments, true); // Add true as additional final argument return $observe.apply(this, arguments); }; $observe = function() { // $.observe([namespace, ]root, [1 or more objects, path or path Array params...], callback[, contextCallback][, unobserve]) function innerObserve() { function observeOnOff(namespace, pathStr, isArrayBinding, off) { var j, evData, obIdExpando = $hasData(object), boundObOrArr = wrapArray(object), prntObs = parentObs, allPth = allPath; namespace = initialNs ? namespace + "." + initialNs : namespace; if (!unobserve && (off || isArrayBinding)) { events = obIdExpando && $._data(object); events = events && events.events; events = events && events[isArrayBinding ? arrayChangeStr : propertyChangeStr]; el = events && events.length; while (el--) { // Skip duplicates data = events[el] && events[el].data; if (data && (off && data.ns !== initialNs // When observing, don't unbind dups unless they have the same namespace || !off && data.ns === initialNs && data.cb && data.cb._cId === callback._cId)) // When observing and doing array binding, don't bind dups if they have the same namespace (Dups can happen e.g. with {^{for people ~foo=people}}) { return; } } } if (unobserve || off) { $(boundObOrArr).off(namespace, onObservableChange); } else { evData = isArrayBinding ? {} : { fullPath: path, paths: pathStr ? [pathStr] : [], prop: prop }; evData.ns = initialNs; evData.cb = callback; if (allPath) { // This is an observeAll call evData.observeAll = { _path: allPth, path: function() { // Step through path and parentObs parent chain, replacing '[]' by '[n]' based on current index of objects in parent arrays. j = prntObs.length; return allPth.replace(/[[.]/g, function(all) { j--; return all === "[" ? "[" + $.inArray(prntObs[j - 1], prntObs[j]) : "."; }); }, parents: function() { return prntObs; // The chain of parents between the modified object and the root object used in the observeAll() call }, filter: filter }; } $(boundObOrArr).on(namespace, null, evData, onObservableChange); if (cbBindings) { // Add object to cbBindings cbBindings[$data(object).obId || $data(object, "obId", observeObjKey++)] = object; } } } function getInnerCb(exprOb) { // Returns the innerCb used for updating a computed in a compiled expression (setting the new instance as exprOb.ob, unobserving the previous object, // and observing the new one), then calling the outerCB - i.e. the handler for the whole compiled expression. // Initialized exprOb.ob to the current object. // Uses the contextCb callback to execute the compiled exprOb template in the context of the view/data etc. to get the returned value, typically an object or array. // If it is an array, registers array binding var origRt = root; // Note: For jsviews/issues/292 ctxCb will need var ctxCb = contextCb || function(exprOb, origRt) {return exprOb._jsv(origRt);}; exprOb.ob = contextCb(exprOb, origRt); // Initialize object return exprOb.cb = function(ev, eventArgs) { var obj = exprOb.ob, // The old object sub = exprOb.sb, newObj = contextCb(exprOb, origRt); if (newObj !== obj) { if (typeof obj === OBJECT) { bindArray(obj, true); if (sub || allowArray && $isArray(obj)) { innerObserve([obj], sub, callback, contextCb, true); // unobserve on the old object } } exprOb.ob = newObj; // Put the updated object instance onto the exprOb in the paths array, so subsequent string paths are relative to this object if (typeof newObj === OBJECT) { bindArray(newObj); if (sub || allowArray && $isArray(newObj)) { // Register array binding innerObserve([newObj], sub, callback, contextCb); } } } // Call the outerCb - to execute the compiled expression that this computed is part of callback(ev, eventArgs); }; } function bindArray(arr, unbind, isArray, relPath) { if (allowArray) { // This is a call to observe that does not come from observeAndBind (tag binding), so we allow arrayChange binding var prevObj = object, prevAllPath = allPath; object = arr; if (relPath) { object = arr[relPath]; allPath += "." + relPath; } if (filter && object) { object = $observable._fltr(allPath, object, relPath ? [arr].concat(parentObs) : parentObs, filter); } if (object && (isArray || $isArray(object))) { observeOnOff(arrayChangeStr + ".observe" + (callback ? getCbKey(callback) : ""), undefined, true, unbind); } object = prevObj; allPath = prevAllPath; } } var i, p, skip, parts, prop, path, dep, unobserve, callback, cbId, inId, el, data, events, contextCb, items, cbBindings, depth, innerCb, parentObs, allPath, filter, initNsArr, initNsArrLen, ns = observeStr, paths = this != 1 // Using != for IE<10 bug- see jsviews/issues/237 ? concat.apply([], arguments) // Flatten the arguments - this is a 'recursive call' with params using the 'wrapped array' // style - such as innerObserve([object], path.path, [origRoot], path.prm, innerCb, ...); : slice.call(arguments), // Don't flatten - this is the first 'top-level call, to innerObserve.apply(1, paths) lastArg = paths.pop() || false, root = paths.shift(), object = root, l = paths.length; if (lastArg + "" === lastArg) { // If last arg is a string then this observe call is part of an observeAll call, allPath = lastArg; // and the last three args are the parentObs array, the filter, and the allPath string. parentObs = paths.pop(); filter = paths.pop(); lastArg = !!paths.pop(); // unobserve l -= 3; } if (lastArg === !!lastArg) { unobserve = lastArg; lastArg = paths[l-1]; lastArg = l && lastArg + "" !== lastArg && (!lastArg || $isFunction(lastArg)) ? (l--, paths.pop()) : undefined; if (unobserve && !l && $isFunction(root)) { lastArg = root; root = undefined; } } callback = lastArg; if (l && $isFunction(paths[l - 1])) { contextCb = callback; callback = paths.pop(); l--; } if (unobserve && callback && !callback._cId) { return; } // Use a unique namespace (e.g. obs7) associated with each observe() callback to allow unobserve to remove handlers ns += callback ? ((inId = callback._inId || ""), unobserve) ? callback._cId + inId : (cbId = getCbKey(callback)) + inId : ""; if (cbId && !unobserve) { cbBindings = cbBindingsStore[cbId] = cbBindingsStore[cbId] || {}; } initNsArr = initialNs && initialNs.match(rNotWhite) || [""]; initNsArrLen = initNsArr.length; while (initNsArrLen--) { initialNs = initNsArr[initNsArrLen]; if (root && (path = paths[0], !path || path + "" !== path)) { if ($isArray(root)) { bindArray(root, unobserve, true); } else if (unobserve) { // remove onObservableChange handlers that wrap that callback observeOnOff(ns, ""); } } if (unobserve && !l && !root) { // unobserve() - unobserves all for (p in cbBindingsStore) { p = cbBindingsStore[p]; for (data in p) { object = p[data]; if ($isArray(object)) { bindArray(object, unobserve, unobserve); } else { // remove onObservableChange handlers that wrap that callback observeOnOff(ns, ""); } } } } depth = 0; for (i = 0; i < l; i++) { path = paths[i]; if (path === "") { continue; } object = root; if ("" + path === path) { // Consider support for computed paths: jsviews/issues/292 //if (/[\(\[\+]/.test(path)) { // var b={links:{}}, t = $sub.tmplFn("{:"+path+"}", b, true), items = t.paths[0]; // l += items.length - 1; // splice.apply(paths, [i--, 1].concat(items)); // continue; //} parts = path.split("^"); if (parts[1]) { // We bind the leaf, plus additional nodes based on depth. // "a.b.c^d.e" is depth 2, so listens to changes of e, plus changes of d and of c depth = parts[0].split(".").length; path = parts.join("."); depth = path.split(".").length - depth; // if more than one ^ in the path, the first one determines depth } if (contextCb && (items = contextCb(path, root))) { // If contextCb returns an array of objects and paths, we will insert them // into the sequence, replacing the current item (path) l += items.length - 1; splice.apply(paths, [i--, 1].concat(items)); continue; } parts = path.split("."); } else { if (!$isFunction(path)) { if (path && path._jsv) { // This is a compiled function for binding to an object returned by a helper/data function. // Set current object on exprOb.ob, and get innerCb for updating the object innerCb = unobserve ? path.cb : getInnerCb(path); innerCb.noArray = !allowArray; // innerCb._ctx = callback._ctx; Could pass context (e.g. linkCtx) for use in a depends = function() {} call, so depends is different for different linkCtx's innerCb._cId = callback._cId; // Set the same cbBindingsStore key as for callback, so when callback is disposed, disposal of innerCb happens too. innerCb._inId = innerCb._inId || ".obIn" + observeInnerCbKey++; if (path.bnd || path.prm && path.prm.length || !path.sb) { // If the exprOb is bound e.g. foo()^sub.path, or has parameters e.g. foo(bar) or is a leaf object (so no sub path) e.g. foo() // then observe changes on the object, or its parameters and sub-path innerObserve([object], path.path, [origRoot], path.prm, innerCb, contextCb, unobserve); } if (path.sb) { // subPath innerObserve([path.ob], path.sb, callback, contextCb, unobserve); } path = origRoot; object = undefined; } else { object = path; // For top-level calls, objects in the paths array become the origRoot for subsequent paths. } } parts = [root = path]; } while (object && (prop = parts.shift()) !== undefined) { if (typeof object === OBJECT) { if ("" + prop === prop) { if (prop === "") { continue; } if ((parts.length < depth + 1) && !object.nodeType) { // Add observer for each token in path starting at depth, and on to the leaf if (!unobserve && (events = $hasData(object) && $._data(object))) { events = events.events; events = events && events[propertyChangeStr]; el = events && events.length; skip = 0; while (el--) { // Skip duplicates data = events[el].data; if (data && data.ns === initialNs && data.cb._cId === callback._cId && data.cb._inId === callback._inId && (data.prop === prop || data.prop === "*" || data.prop === "**")) { if (p = parts.join(".")) { data.paths.push(p); // We will skip this binding, but if it is not a leaf binding, // need to keep bindings for rest of path, ready for if the object gets swapped. } skip++; } } if (skip) { // Duplicate binding(s) found, so move on object = object[prop]; continue; } } if (prop === "*" || prop === "**") { // "*" => all properties. "**" => all properties and sub-properties (i.e. deep observeAll behavior) if (!unobserve && events && events.length) { // Remove existing bindings, since they will be duplicates with "*" or "**" observeOnOff(ns, "", false, true); } if (prop === "*") { observeOnOff(ns, ""); // observe the object for any property change for (p in object) { // observing "*": So (in addition to listening to prop change, above) listen to arraychange on props of type array if (p !== $expando) { bindArray(object, unobserve, undefined, p); } } } else { $.observable(initialNs, object)[(unobserve ? "un" : "") + "observeAll"](callback); // observe or unobserve the object for any property change } break; } else if (prop) { observeOnOff(ns + ".p_" + prop, parts.join("^")); // By using "^" rather than "." we ensure that deep binding will be used on newly inserted object graphs } } if (allPath) { allPath += "." + prop; } prop = object[prop]; } if ($isFunction(prop)) { if (dep = prop.depends) { // This is a computed observable. We will observe any declared dependencies innerObserve([object], resolvePathObjects(dep, object, callback), callback, contextCb, unobserve); } break; } object = prop; if (unobserve && object === root && (i>l-2 || paths[i+1] + "" !== paths[i+1])) { // unobserve all handlers of object, if not followed by string path. // e.g.$.unobserve(object1, object2, "path", object3) will unobserve all from object1 and object3, and just "path" listener from object2 observeOnOff(ns, ""); } } } bindArray(object, unobserve); } } if (cbId) { removeCbBindings(cbBindings, cbId); } // Return the cbBindings to the top-level caller, along with the cbId return {cbId: cbId, bnd: cbBindings}; } var initialNs, allowArray = this != false, // If this === false, this is a call from observeAndBind - doing binding of datalink expressions. We don't bind // arrayChange events in this scenario. Instead, {^{for}} and similar do specific arrayChange binding to the tagCtx.args[0] value, in onAfterLink. // Note deliberately using this != false, rather than this !== false because of IE<10 bug- see jsviews/issues/237 paths = slice.call(arguments), origRoot = paths[0]; if (origRoot + "" === origRoot && allowArray) { initialNs = origRoot; // The first arg is a namespace, since it is a string, and this call is not from observeAndBind paths.shift(); origRoot = paths[0]; } return innerObserve.apply(1, paths); }; $observable = function(ns, data) { if (arguments.length === 1) { data = ns; ns = ""; } return $isArray(data) ? new ArrayObservable(ns, data) : new ObjectObservable(ns, data); }; //========================== Initialize ========================== $sub.getDeps = function() { var args = arguments; return function() { var arg, dep, deps = [], l = args.length; while (l--) { arg = args[l--]; dep = args[l]; if (dep) { deps = deps.concat($isFunction(dep) ? dep(arg, arg) : dep); } } return deps; }; }; $.observable = $observable; $observable._fltr = function(allPath, object, parentObs, filter) { if (filter && $isFunction(filter) ? filter(allPath, object, parentObs) : true // TODO Consider supporting filter being a string or strings to do RegEx filtering based on key and/or allPath ) { object = $isFunction(object) ? object.set && object.call(parentObs[0]) // It is a getter/setter : object; return typeof object === OBJECT && object; } }; $observable.Object = ObjectObservable; $observable.Array = ArrayObservable; $.observe = $observable.observe = $observe; $.unobserve = $observable.unobserve = $unobserve; $observable._apply = observe_apply; ObjectObservable.prototype = { _data: null, observeAll: $observeAll, unobserveAll: $unobserveAll, data: function() { return this._data; }, setProperty: function(path, value, nonStrict) { path = path || ""; var key, pair, parts, multi = path + "" !== path, self = this, object = self._data; if (object) { if (multi) { nonStrict = value; if ($isArray(path)) { // This is the array format generated by serializeArray. However, this has the problem that it coerces types to string, // and does not provide simple support of convertTo and convertFrom functions. key = path.length; while (key--) { pair = path[key]; self.setProperty(pair.name, pair.value, nonStrict === undefined || nonStrict); //If nonStrict not specified, default to true; } } else { // Object representation where property name is path and property value is value. for (key in path) { self.setProperty(key, path[key], nonStrict); } } } else if (path !== $expando) { // Simple single property case. parts = path.split("."); while (object && parts.length > 1) { object = object[parts.shift()]; } if (object) { self._setProperty(object, parts[0], value, nonStrict); } } } return self; }, removeProperty: function(path) { this.setProperty(path, remove); return this; }, _setProperty: function(leaf, path, value, nonStrict) { var setter, getter, removeProp, property = path ? leaf[path] : leaf; if ($isFunction(property)) { if (property.set) { // Case of property setter/getter - with convention that property is getter and property.set is setter leaf = leaf._wrp // Case of JsViews 2-way data-linking to a helper function as getter, with a setter. // The view will be the this pointer for getter and setter. Note: this is the one scenario where path is "". || leaf; getter = property; setter = getter.set === true ? getter : getter.set; property = getter.call(leaf); // get - only treated as getter if also a setter. Otherwise it is simply a property of type function. See unit tests 'Can observe properties of type function'. } } if (property !== value || nonStrict && property != value) { // Optional non-strict equality, since serializeArray, and form-based editors can map numbers to strings, etc. // Date objects don't support != comparison. Treat as special case. if (!(property instanceof Date) || property > value || property < value) { if (setter) { setter.call(leaf, value); //set value = getter.call(leaf); //get updated value } else if (removeProp = value === remove) { if (property !== undefined) { delete leaf[path]; value = undefined; } else { path = undefined; // If value was already undefined, don't trigger handler for removeProp } } else if (path) { leaf[path] = value; } if (path) { this._trigger(leaf, {change: "set", path: path, value: value, oldValue: property, remove: removeProp}); } } } }, _trigger: function(target, eventArgs) { $(target).triggerHandler(propertyChangeStr + (this._ns ? "." + /^\S+/.exec(this._ns)[0] : ""), eventArgs); // If white-space separated namespaces, use first one only } }; ArrayObservable.prototype = { _data: null, observeAll: $observeAll, unobserveAll: $unobserveAll, data: function() { return this._data; }, insert: function(index, data) { var _data = this._data; if (arguments.length === 1) { data = index; index = _data.length; } index = PARSEINT(index); if (index > -1) { data = $isArray(data) ? data : [data]; // data can be a single item (including a null/undefined value) or an array of items. // Note the provided items are inserted without being cloned, as direct references to the provided objects if (data.length) { this._insert(index, data); } } return this; }, _insert: function(index, data) { var _data = this._data, oldLength = _data.length; if (index > oldLength) { index = oldLength; } splice.apply(_data, [index, 0].concat(data)); this._trigger({change: "insert", index: index, items: data}, oldLength); }, remove: function(index, numToRemove) { var items, _data = this._data; if (index === undefined) { index = _data.length - 1; } index = PARSEINT(index); numToRemove = numToRemove ? PARSEINT(numToRemove) : numToRemove === 0 ? 0 : 1; // if null or undefined: remove 1 if (numToRemove > 0 && index > -1) { items = _data.slice(index, index + numToRemove); if (numToRemove = items.length) { this._remove(index, numToRemove, items); } } return this; }, _remove: function(index, numToRemove, items) { var _data = this._data, oldLength = _data.length; _data.splice(index, numToRemove); this._trigger({change: "remove", index: index, items: items}, oldLength); }, move: function(oldIndex, newIndex, numToMove) { numToMove = numToMove ? PARSEINT(numToMove) : numToMove === 0 ? 0 : 1; // if null or undefined: move 1 oldIndex = PARSEINT(oldIndex); newIndex = PARSEINT(newIndex); if (numToMove > 0 && oldIndex > -1 && newIndex > -1 && oldIndex !== newIndex) { this._move(oldIndex, newIndex, numToMove); } return this; }, _move: function(oldIndex, newIndex, numToMove) { var items, _data = this._data, oldLength = _data.length, excess = oldIndex + numToMove - oldLength; if (excess > 0) { numToMove -= excess; } if (numToMove) { items = _data.splice(oldIndex, numToMove); // remove if (newIndex > _data.length) { newIndex = _data.length; } splice.apply(_data, [newIndex, 0].concat(items)); //re-insert this._trigger({change: "move", oldIndex: oldIndex, index: newIndex, items: items}, oldLength); } }, refresh: function(newItems, sort) { function insertAdded() { if (k) { self.insert(j-k, addedItems); // Not found in original array - so insert dataLength += k; i += k; k = 0; addedItems = []; } } // For refresh operation we iteratively step through the target array and sort by move/add/remove operations on the source array until they match var i, j, k, newItem, num, self = this, addedItems = [], data = self._data, oldItems = data.slice(), oldLength = data.length, dataLength = oldLength, newLength = newItems.length; self._srt = true; // Flag for sorting during refresh for (j=k=0; j<newLength; j++) { if ((newItem = newItems[j]) === data[j-k]) { insertAdded(); } else { for (i=j-k; i<dataLength; i++) { if (newItem === data[i]) { break; } } if (i<dataLength) { insertAdded(); num = 0; while (num++ < newLength-i && newItems[j+num] === data[i+num]); self.move(i, j, num); // Found newItem in original array - so move it to new position j += num - 1; } else { k++; addedItems.push(newItem); // Not found in original array - so insert } } } insertAdded(); if (dataLength > j) { self.remove(j, dataLength - j); } self._srt = undefined; // We have finished sort operations during refresh self._trigger({change: "refresh", oldItems: oldItems}, oldLength); return self; }, _trigger: function(eventArgs, oldLength) { var self = this, _data = self._data, length = _data.length, $_data = $([_data]); if (self._srt) { eventArgs.refresh = true; // We are sorting during refresh } else if (length !== oldLength) { // We have finished sort operations during refresh $_data.triggerHandler(propertyChangeStr, {change: "set", path: "length", value: length, oldValue: oldLength}); } $_data.triggerHandler(arrayChangeStr + (self._ns ? "." + /^\S+/.exec(self._ns)[0] : ""), eventArgs); // If white-space separated namespaces, use first one only } }; $eventSpecial[propertyChangeStr] = $eventSpecial[arrayChangeStr] = { // Register a jQuery special 'remove' event, to access the data associated with handlers being removed by jQuery.off(). // We get data.cb._cId from the event handleObj and get the corresponding cbBindings hash from the cbBindingsStore, // then remove this object from that bindings hash - if the object does not have any other handlers associated with the same callback. remove: function (handleObj) { var cbBindings, found, events, l, data, evData = handleObj.data; if ((evData) && (evData.off = true, evData = evData.cb)) { //Set off = true as marker for disposed event // Get the cb._cId from handleObj.data.cb._cId if (cbBindings = cbBindingsStore[evData._cId]) { // There were bindings for this callback. If this was the last one, we'll remove it. events = $._data(this).events[handleObj.type]; l = events.length; while (l-- && !found) { found = (data = events[l].data) && data.cb && data.cb._cId === evData._cId; // Found another one with same callback (though may be a different innerCallback) } if (!found) { // This was the last handler for this callback and object, so remove the binding entry delete cbBindings[$data(this).obId]; removeCbBindings(cbBindings, evData._cId); } } } } }; $views.map = function(mapDef) { function Map(source, options, target, unbound) { var changing, map = this; if (this.src) { this.unmap(); // We are re-mapping a new source } if (typeof source === OBJECT) { map.src = source; map.tgt = target || map.tgt || []; map.options = options || map.options; map.update(); if (!unbound) { if (mapDef.obsSrc) { $observable(map.src).observeAll(map.obs = function(ev, eventArgs) { if (!changing) { changing = true; mapDef.obsSrc(map, ev, eventArgs); changing = undefined; } }, map.srcFlt); } if (mapDef.obsTgt ) { $observable(map.tgt).observeAll(map.obt = function(ev, eventArgs) { if (!changing) { changing = true; mapDef.obsTgt(map, ev, eventArgs); changing = undefined; } }, map.tgtFlt); } } } } if ($isFunction(mapDef)) { // Simple map declared as function mapDef = { getTgt: mapDef }; } if (mapDef.baseMap) { mapDef = $.extend({}, mapDef.baseMap, mapDef); } mapDef.map = function(source, options, target, unbound) { return new Map(source, options, target, unbound); }; (Map.prototype = { srcFlt: mapDef.srcFlt || shallowFilter, // default to shallowFilter tgtFlt: mapDef.tgtFlt || shallowFilter, update: function(options) { var map = this; $observable(map.tgt).refresh(mapDef.getTgt(map.src, map.options = options || map.options)); }, unmap: function() { var map = this; if (map.src) { if (map.obs) { $observable(map.src).unobserveAll(map.obs, map.srcFlt); } if (map.obt) { $observable(map.tgt).unobserveAll(map.obt, map.tgtFlt); } map.src = undefined; } }, map: Map, _def: mapDef }).constructor = Map; return mapDef; }; $sub.advSet = function() { // refresh advanced settings global._jsv = $subSettings.advanced._jsv ? { // create global _jsv, for accessing views, etc cbBindings: cbBindingsStore } : undefined; // In IE8 cannot do delete global._jsv }; } //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< JsViews >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /* JsViews: * Interactive data-driven views using templates and data-linking. * See http://www.jsviews.com/#jsviews and http://github.com/BorisMoore/jsviews * Copyright 2016, Boris Moore * Released under the MIT License. */ //========================== Top-level vars ========================== $viewsSettings = $views.settings; $subSettings = $sub.settings; $subSettingsAdvanced = $subSettings.advanced; $converters = $views.converters; $.templates = $templates = $views.templates; $tags = $views.tags; rFirstElem = /<(?!script)(\w+)[>\s]/; if ($.link) { return $; } // JsViews is already loaded $subSettings.trigger = true; var activeBody, rTagDatalink, $view, $viewsLinkAttr, linkViewsSel, wrapMap, viewStore, oldAdvSet, jsvAttrStr = "data-jsv", elementChangeStr = "change.jsv", onBeforeChangeStr = "onBeforeChange", onAfterChangeStr = "onAfterChange", onAfterCreateStr = "onAfterCreate", CHECKED = "checked", CHECKBOX = "checkbox", RADIO = "radio", RADIOINPUT = "input[type=radio]", NONE = "none", SCRIPT = "SCRIPT", TRUE = "true", closeScript = '"></script>', openScript = '<script type="jsv', deferAttr = jsvAttrStr + "-df", bindElsSel = "script,[" + jsvAttrStr + "]", fnSetters = { value: "val", input: "val", html: HTML, text: "text" }, valueBinding = {from: "value", to: "value"}, isCleanCall = 0, oldCleanData = $.cleanData, oldJsvDelimiters = $viewsSettings.delimiters, safeFragment = document.createDocumentFragment(), qsa = document.querySelector, // elContent maps tagNames which have only element content, so may not support script nodes. elContent = {ol: 1, ul: 1, table: 1, tbody: 1, thead: 1, tfoot: 1, tr: 1, colgroup: 1, dl: 1, select: 1, optgroup: 1, svg: 1, svg_ns: 1}, badParent = {tr: "table"}, voidElems = {br: 1, img: 1, input: 1, hr: 1, area: 1, base: 1, col: 1, link: 1, meta: 1, command: 1, embed: 1, keygen: 1, param: 1, source: 1, track: 1, wbr: 1}, displayStyles = {}, bindingStore = {}, bindingKey = 1, rViewPath = /^#(view\.?)?/, rConvertMarkers = /((\/>)|<\/(\w+)>|)(\s*)([#\/]\d+(?:_|(\^)))`(\s*)(<\w+(?=[\s\/>]))?|\s*(?:(<\w+(?=[\s\/>]))|<\/(\w+)>(\s*)|(\/>)\s*|(>)|$)/g, rOpenViewMarkers = /(#)()(\d+)(_)/g, rOpenMarkers = /(#)()(\d+)([_^])/g, rViewMarkers = /(?:(#)|(\/))(\d+)(_)/g, rOpenTagMarkers = /(#)()(\d+)(\^)/g, rMarkerTokens = /(?:(#)|(\/))(\d+)([_^])([-+@\d]+)?/g, rSplitBindings = /&(\d+)\+?/g, getComputedStyle = global.getComputedStyle; $observable = $.observable; if (!$observable) { // JsObservable is not loaded. throw requiresStr + "JsObservable"; // jquery.observable.js must be loaded before JsViews } $observe = $observable.observe; //========================== Top-level functions ========================== //=============== // Event handlers //=============== function elemChangeHandler(ev, params, sourceValue) { var setter, cancel, fromAttr, linkCtx, cvtBack, cnvtName, target, $source, view, binding, oldLinkCtx, onBeforeChange, onAfterChange, tag, to, eventArgs, exprOb, source = ev.target, bindings = source._jsvBnd; // _jsvBnd is a string with the syntax: "&bindingId1&bindingId2" if (bindings) { while (binding = rSplitBindings.exec(bindings)) { if (binding = bindingStore[binding[1]]) { if (to = binding.to) { // The binding has a 'to' field, which is of the form [[targetObject, toPath], cvtBack] linkCtx = binding.linkCtx; view = linkCtx.view; tag = linkCtx.tag; $source = $(source); onBeforeChange = view.hlp(onBeforeChangeStr); // TODO Can we optimize this and other instances of same? onAfterChange = view.hlp(onAfterChangeStr); // TODO Can we optimize this and other instances of same fromAttr = defaultAttr(source); setter = fnSetters[fromAttr]; if (sourceValue === undefined) { sourceValue = $isFunction(fromAttr) ? fromAttr(source) : setter ? $source[setter]() : $source.attr(fromAttr); } cnvtName = to[1]; to = to[0]; // [object, path] to = to + "" === to ? [linkCtx.data, to] : to; if (cnvtName) { if ($isFunction(cnvtName)) { cvtBack = cnvtName; } else { cvtBack = view.getRsc("converters", cnvtName); } } if (linkCtx.elem.nodeName === "SELECT") { linkCtx.elem._jsvSel = sourceValue = sourceValue || (linkCtx.elem.multiple ? [] : sourceValue); // data-link <select> to string or (multiselect) array of strings } if (cvtBack) { sourceValue = cvtBack.call(tag, sourceValue); } // Set linkCtx on view, dynamically, just during this handler call oldLinkCtx = view.linkCtx; view.linkCtx = linkCtx; eventArgs = { change: "change", oldValue: linkCtx._val, value: sourceValue }; if ((!onBeforeChange || !(cancel = onBeforeChange.call(linkCtx, ev, eventArgs) === false)) && (!tag || !tag.onBeforeChange || !(cancel = tag.onBeforeChange(ev, eventArgs) === false)) && sourceValue !== undefined) { target = to[0]; // [object, path] if (sourceValue !== undefined && target) { if (target._jsv) { exprOb = target; target = linkCtx.data; while (exprOb && exprOb.sb) { target = linkCtx._ctxCb(exprOb, target); exprOb = exprOb.sb; } } if (tag) { tag._.chging = true; // marker to prevent tag change event triggering its own refresh } $observable(target).setProperty(to[2] || to[1], sourceValue); if (onAfterChange) { onAfterChange.call(linkCtx, ev, eventArgs); } if (tag) { if (tag.onAfterChange) { tag.onAfterChange(ev, eventArgs); } tag._.chging = undefined; // clear the marker } linkCtx._val = sourceValue; } } view.linkCtx = oldLinkCtx; } } } } } function propertyChangeHandler(ev, eventArgs, linkFn) { var attr, sourceValue, noUpdate, forceUpdate, hasError, onError, linkCtx = this, tag = linkCtx.tag, source = linkCtx.data, target = linkCtx.elem, cvt = linkCtx.convert, parentElem = target.parentNode, view = linkCtx.view, oldLinkCtx = view.linkCtx, onEvent = view.hlp(onBeforeChangeStr); // Set linkCtx on view, dynamically, just during this handler call view.linkCtx = linkCtx; if (parentElem && (!onEvent || !(eventArgs && onEvent.call(linkCtx, ev, eventArgs) === false)) // If data changed, the ev.data is set to be the path. Use that to filter the handler action... && !(eventArgs && ev.data.prop !== "*" && ev.data.prop !== eventArgs.path)) { if (eventArgs) { linkCtx.eventArgs = eventArgs; } if (eventArgs || linkCtx._toLk) { // If eventArgs are defined, this is a data update // Otherwise this is the initial data-link rendering call. Bind on this the first time it get called linkCtx._toLk = 0; // Remove flag to skip unneccessary rebinding next time if (linkFn._er) { // data-link="exprUsingTagOrCvt with onerror=..." - e.g. {tag ... {cvt:... {:... convert='cvt' try { sourceValue = linkFn(source, view); } catch (e) { hasError = linkFn._er; onError = onRenderError(e,view,(new Function("data,view", "return " + hasError + ";"))(source, view)); sourceValue = [{props: {}, args: [onError]}]; } } else { sourceValue = linkFn(source, view, $sub); } // Compiled link expression for linkTag: return value for data-link="{:xxx}" with no cvt or cvtBk, otherwise tagCtx or tagCtxs attr = getTargetVal(sourceValue, linkCtx, tag = linkCtx.tag, linkCtx.attr || defaultAttr(target, true, cvt !== undefined) ); if (tag) { // Existing tag instance forceUpdate = hasError || tag._er; // If the new tagCtxs hasError or the previous tagCtxs had error, then force update sourceValue = sourceValue[0] ? sourceValue : [sourceValue]; noUpdate = !forceUpdate && eventArgs && tag.onUpdate && tag.onUpdate(ev, eventArgs, sourceValue) === false; mergeCtxs(tag, sourceValue, forceUpdate); if (noUpdate || attr === NONE) { // onUpdate returned false, or attr === "none", or this is an update coming from the tag's own change event // - so don't refresh the tag: we just use the new tagCtxs merged from the sourceValue, // (which may optionally have been modifed in onUpdate()...) and then bind, and we are done if (attr === HTML && tag.onBeforeLink) { tag.onBeforeLink(); } callAfterLink(tag); observeAndBind(linkCtx, source, target); view.linkCtx = oldLinkCtx; return; } if (tag._.chging) { return; } sourceValue = tag.tagName === ":" // Call convertVal if it is a {{cvt:...}} - otherwise call renderTag ? $sub._cnvt(tag.cvt, view, sourceValue[0]) : $sub._tag(tag, view, view.tmpl, sourceValue, true, onError); } else if (linkFn._tag) { // For {{: ...}} without a convert or convertBack, we already have the sourceValue, and we are done // For {{: ...}} with either cvt or cvtBack we call convertVal to get the sourceValue and instantiate the tag // If cvt is undefined then this is a tag, and we call renderTag to get the rendered content and instantiate the tag cvt = cvt === "" ? TRUE : cvt; // If there is a cvtBack but no cvt, set cvt to "true" sourceValue = cvt // Call convertVal if it is a {{cvt:...}} - otherwise call renderTag ? $sub._cnvt(cvt, view, sourceValue[0] || sourceValue) // convertVal : $sub._tag(linkFn._tag, view, view.tmpl, sourceValue, true, onError); // renderTag addLinkMethods(tag = linkCtx.tag, true); // In both convertVal and renderTag we have instantiated a tag attr = linkCtx.attr || attr; // linkCtx.attr may have been set to tag.attr during tag instantiation in renderTag } if (updateContent(sourceValue, linkCtx, attr, tag) && eventArgs && (onEvent = view.hlp(onAfterChangeStr))) { onEvent.call(linkCtx, ev, eventArgs); } linkCtx._noUpd = 0; // For data-link="^{...}" remove _noUpd flag so updates on subsequent calls if (tag) { tag._er = hasError; callAfterLink(tag, eventArgs); } } observeAndBind(linkCtx, source, target); // Remove dynamically added linkCtx from view view.linkCtx = oldLinkCtx; } } function getTargetVal(sourceValue, linkCtx, tag, attr) { var currentValue, setter, css, $target, target = tag && tag.parentElem || linkCtx.elem; if (sourceValue !== undefined) { $target = $(target); attr = tag && tag.attr || attr; if ($isFunction(sourceValue)) { error(linkCtx.expr + ": missing parens"); } if (css = /^css-/.test(attr) && attr.slice(4)) { currentValue = $.style(target, css); if (+sourceValue === sourceValue) { // Optimization for perf on integer values - e.g. css-width{:width+'px'} currentValue = parseInt(currentValue); } } else if (attr !== "link") { // attr === "link" is for tag controls which do data binding but have no rendered output or target if (attr === "value") { if (target.type === CHECKBOX) { currentValue = $target.prop(attr = CHECKED); } } else if (attr === RADIO) { if (target.value === ("" + sourceValue)) { currentValue = $target.prop(CHECKED); } else { return attr; } } if (currentValue === undefined) { setter = fnSetters[attr]; currentValue = setter ? $target[setter]() : $target.attr(attr); } } linkCtx._val = currentValue; } return attr; } function setDefer(elem, value) { elem._df = value; // Use both an expando and an attribute to track defered tokens. Attribute is needed for querySelectorAll for getViewInfos (childTags) elem[(value ? "set" : "remove") + "Attribute"](deferAttr, ""); } function updateContent(sourceValue, linkCtx, attr, tag) { // When called for a tag, either in tag.refresh() or propertyChangeHandler(), returns a promise (and supports async) // When called (in propertyChangeHandler) for target HTML returns true // When called (in propertyChangeHandler) for other targets returns boolean for "changed" var setter, prevNode, nextNode, promise, nodesToRemove, useProp, tokens, id, openIndex, closeIndex, testElem, nodeName, cStyle, jsvSel, renders = attr !== NONE && sourceValue !== undefined && !linkCtx._noUpd, // For data-link="^{...}", don't update the first time (no initial render) - e.g. to leave server rendered values. source = linkCtx.data, target = tag && tag.parentElem || linkCtx.elem, targetParent = target.parentNode, $target = $(target), view = linkCtx.view, targetVal = linkCtx._val, oldLinkCtx = view.linkCtx, // If not a tag we can use the ._val obtained from getTargetVal() // and only update when the new value (sourceValue) has changed from the previous one change = tag; if (tag) { // Initialize the tag with element references tag.parentElem = tag.parentElem || (linkCtx.expr || tag._elCnt) ? target : targetParent; prevNode = tag._prv; nextNode = tag._nxt; } if (!renders) { if (attr === HTML && tag && tag.onBeforeLink) { tag.onBeforeLink(); } return; } if (attr === "visible") { attr = "css-display"; } if (/^css-/.test(attr)) { if (linkCtx.attr === "visible") { // Get the current display style cStyle = (target.currentStyle || getComputedStyle.call(global, target, "")).display; if (sourceValue) { // We are showing the element. // Get the cached 'visible' display value from the -jsvd expando sourceValue = target._jsvd // Or, if not yet cached, get the current display value || cStyle; if (sourceValue === NONE && !(sourceValue = displayStyles[nodeName = target.nodeName])) { // Currently display value is 'none', and the 'visible' style has not been cached. // We create an element to find the correct 'visible' display style for this nodeName testElem = document.createElement(nodeName); document.body.appendChild(testElem); // Get the default style for this HTML tag to use as 'visible' style sourceValue // and cache it as a hash against nodeName = displayStyles[nodeName] = (testElem.currentStyle || getComputedStyle.call(global, testElem, "")).display; document.body.removeChild(testElem); } } else { // We are hiding the element. // Cache the current display value as 'visible' style, on _jsvd expando, for when we show the element again target._jsvd = cStyle; sourceValue = NONE; // Hide the element } } if (change = change || targetVal !== sourceValue) { $.style(target, attr.slice(4), sourceValue); } } else if (attr !== "link") { // attr === "link" is for tag controls which do data binding but have no rendered output or target if (/^data-/.test(attr)) { $.data(target, attr.slice(5), sourceValue); // Support for binding to data attributes: data-foo{:expr}: data-foo attribute will be // expr.toString(), but $.data(element, "foo") and $(element).data("foo") will actually return value of expr, even if of type object } if (attr === CHECKED) { useProp = true; sourceValue = sourceValue && sourceValue !== "false"; // The string value "false" can occur with data-link="checked{attr:expr}" - as a result of attr, and hence using convertVal() // We will set the "checked" property // We will compare this with the current value } else if (attr === RADIO) { // This is a special binding attribute for radio buttons, which corresponds to the default 'to' binding. // This allows binding both to value (for each input) and to the default checked radio button (for each input in named group, // e.g. binding to parent data). // Place value binding first: <input type="radio" data-link="value{:name} {:#get('data').data.currency:} " .../> // or (allowing any order for the binding expressions): // <input type="radio" value="{{:name}}" data-link="{:#get('data').data.currency:} value^{:name}" .../> if (target.value === ("" + sourceValue)) { // If the data value corresponds to the value attribute of this radio button input, set the checked property to true sourceValue = useProp = true; attr = CHECKED; } else { // Otherwise, go straight to observeAndBind, without updating. // (The browser will remove the 'checked' attribute, when another radio button in the group is checked). observeAndBind(linkCtx, source, target); return; } } else if (attr === "selected" || attr === "disabled" || attr === "multiple" || attr === "readonly") { sourceValue = (sourceValue && sourceValue !== "false") ? attr : null; // Use attr, not prop, so when the options (for example) are changed dynamically, but include the previously selected value, // they will still be selected after the change } else if (attr === "value" && target.nodeName === "SELECT") { target._jsvSel = $isArray(sourceValue) ? sourceValue : "" + sourceValue; // If not array, coerce to string } if (setter = fnSetters[attr]) { if (attr === HTML) { // Set linkCtx on view, dynamically, just during this handler call view.linkCtx = linkCtx; if (tag && tag._.inline) { nodesToRemove = tag.nodes(true); if (tag._elCnt) { if (prevNode && prevNode !== nextNode) { // This prevNode will be removed from the DOM, so transfer the view tokens on prevNode to nextNode of this 'viewToRefresh' transferViewTokens(prevNode, nextNode, target, tag._tgId, "^", true); } else if (tokens = target._df) { // This occurs when there is no nextNode, and so the target._df may include tokens referencing // view and tag bindings contained within the open and close tokens of the updated tag control. They need to be processed (disposed) id = tag._tgId + "^"; openIndex = tokens.indexOf("#" + id) + 1; closeIndex = tokens.indexOf("/" + id); if (openIndex && closeIndex > 0) { openIndex += id.length; if (closeIndex > openIndex) { setDefer(target, tokens.slice(0, openIndex) + tokens.slice(closeIndex)); disposeTokens(tokens.slice(openIndex, closeIndex)); } } } prevNode = prevNode ? prevNode.previousSibling : nextNode ? nextNode.previousSibling : target.lastChild; } // Remove HTML nodes $(nodesToRemove).remove(); // Note if !tag._elCnt removing the nodesToRemove will process and dispose view and tag bindings contained within the updated tag control if (tag && tag.onBeforeLink) { tag.onBeforeLink(); } // Insert and link new content promise = view.link(view.data, target, prevNode, nextNode, sourceValue, tag && {tag: tag._tgId, lazyLink: tag.tagCtx.props.lazyLink}); } else { // data-linked value targeting innerHTML: data-link="html{:expr}" or contenteditable="true" renders = renders && targetVal !== sourceValue; if (renders) { $target.empty(); } if (tag && tag.onBeforeLink) { tag.onBeforeLink(); } if (renders) { promise = view.link(source, target, prevNode, nextNode, sourceValue, tag && {tag: tag._tgId}); } } // Remove dynamically added linkCtx and ctx from view view.linkCtx = oldLinkCtx; } else { if (change = change || targetVal !== sourceValue) { if (attr === "text" && target.children && !target.children[0]) { // This code is faster then $target.text() if (target.textContent !== undefined) { target.textContent = sourceValue; } else { target.innerText = sourceValue === null ? "" : sourceValue; } } else { $target[setter](sourceValue); } } if ((jsvSel = targetParent._jsvSel) // Setting value of <option> element && (attr === "value" || !$target.attr("value"))) { // Setting value attribute, or setting textContent if attribute is null // Set/unselect selection based on value set on parent <select>. Works for multiselect too target.selected = $.inArray("" + sourceValue, $isArray(jsvSel) ? jsvSel : [jsvSel]) > -1; } } } else if (change = change || targetVal !== sourceValue) { // Setting an attribute to undefined should remove the attribute $target[useProp ? "prop" : "attr"](attr, sourceValue === undefined && !useProp ? null : sourceValue); } linkCtx._val = sourceValue; } return promise || change; } function arrayChangeHandler(ev, eventArgs) { var self = this, onBeforeChange = self.hlp(onBeforeChangeStr), onAfterChange = self.hlp(onAfterChangeStr); if (!onBeforeChange || onBeforeChange.call(this, ev, eventArgs) !== false) { if (eventArgs) { // This is an observable action (not a trigger/handler call from pushValues, or similar, for which eventArgs will be null) var action = eventArgs.change, index = eventArgs.index, items = eventArgs.items; self._.srt = eventArgs.refresh; // true if part of a 'sort' on refresh switch (action) { case "insert": self.addViews(index, items); break; case "remove": self.removeViews(index, items.length); break; case "move": self.removeViews(eventArgs.oldIndex, items.length, undefined, true); // remove self.addViews(index, items); // re-insert break; case "refresh": self._.srt = undefined; self.fixIndex(0); // Other cases: (e.g.undefined, for setProperty on observable object) etc. do nothing } } if (onAfterChange) { onAfterChange.call(this, ev, eventArgs); } } } //============================= // Utilities for event handlers //============================= function setArrayChangeLink(view) { // Add/remove arrayChange handler on view var handler, arrayBinding, type = view.type, // undefined if view is being removed data = view.data, bound = view._.bnd; // true for top-level link() or data-link="{for}", or the for tag instance for {^{for}} (or for any custom tag that has an onArrayChange handler) if (!view._.useKey && bound) { // This is an array view. (view._.useKey not defined => data is array), and is data-bound to collection change events if (arrayBinding = view._.bndArr) { // First remove the current handler if there is one $([arrayBinding[1]]).off(arrayChangeStr, arrayBinding[0]); view._.bndArr = undefined; } if (bound !== !!bound) { // bound is not a boolean, so it is the data-linked tag that 'owns' this array binding - e.g. {^{for...}} if (type) { bound._.arrVws[view._.id] = view; } else { delete bound._.arrVws[view._.id]; // if view.type is undefined, view is being removed } } else if (type && data) { // If this view is not being removed, but the data array has been replaced, then bind to the new data array handler = function(ev) { if (!(ev.data && ev.data.off)) { // Skip if !!ev.data.off: - a handler that has already been removed (maybe was on handler collection at call time - then removed by another handler) // If view.type is undefined, do nothing. (Corresponds to case where there is another handler on the same data whose // effect was to remove this view, and which happened to precede this event in the trigger sequence. So although this // event has been removed now, it is still called since already on the trigger sequence) arrayChangeHandler.apply(view, arguments); } }; $([data]).on(arrayChangeStr, handler); view._.bndArr = [handler, data]; } } } function defaultAttr(elem, to, linkGetVal) { // to: true - default attribute for setting data value on HTML element; false: default attribute for getting value from HTML element // Merge in the default attribute bindings for this target element var nodeName = elem.nodeName.toLowerCase(), attr = $subSettingsAdvanced._fe[nodeName] // get form element binding settings for input textarea select or optgroup || elem.contentEditable === TRUE && {to: HTML, from: HTML}; // Or if contentEditable set to "true" set attr to "html" return attr ? (to ? ((nodeName === "input" && elem.type === RADIO) // For radio buttons, bind from value, but bind to 'radio' - special value. ? RADIO : attr.to) : attr.from) : to ? linkGetVal ? "text" : HTML // Default innerText for data-link="a.b.c" or data-link="{:a.b.c}" (with or without converters)- otherwise innerHTML : ""; // Default is not to bind from } //============================== // Rendering and DOM insertion //============================== function renderAndLink(view, index, tmpl, views, data, context, refresh) { var html, linkToNode, prevView, nodesToRemove, bindId, parentNode = view.parentElem, prevNode = view._prv, nextNode = view._nxt, elCnt = view._elCnt; if (prevNode && prevNode.parentNode !== parentNode) { error("Missing parentNode"); // Abandon, since node has already been removed, or wrapper element has been inserted between prevNode and parentNode } if (refresh) { nodesToRemove = view.nodes(); if (elCnt && prevNode && prevNode !== nextNode) { // This prevNode will be removed from the DOM, so transfer the view tokens on prevNode to nextNode of this 'viewToRefresh' transferViewTokens(prevNode, nextNode, parentNode, view._.id, "_", true); } // Remove child views view.removeViews(undefined, undefined, true); linkToNode = nextNode; if (elCnt) { prevNode = prevNode ? prevNode.previousSibling : nextNode ? nextNode.previousSibling : parentNode.lastChild; } // Remove HTML nodes $(nodesToRemove).remove(); for (bindId in view._.bnds) { // The view bindings may have already been removed above in: $(nodesToRemove).remove(); // If not, remove them here: removeViewBinding(bindId); } } else { // addViews. Only called if view is of type "array" if (index) { // index is a number, so indexed view in view array prevView = views[index - 1]; if (!prevView) { return false; // If subview for provided index does not exist, do nothing } prevNode = prevView._nxt; } if (elCnt) { linkToNode = prevNode; prevNode = linkToNode ? linkToNode.previousSibling // There is a linkToNode, so insert after previousSibling, or at the beginning : parentNode.lastChild; // If no prevView and no prevNode, index is 0 and the container is empty, // so prevNode = linkToNode = null. But if prevView._nxt is null then we set prevNode to parentNode.lastChild // (which must be before the prevView) so we insert after that node - and only link the inserted nodes } else { linkToNode = prevNode.nextSibling; } } html = tmpl.render(data, context, view._.useKey && refresh, view, refresh || index, true); // Pass in view._.useKey as test for noIteration (which corresponds to when self._.useKey > 0 and self.data is an array) // Link the new HTML nodes to the data view.link(data, parentNode, prevNode, linkToNode, html, prevView); //}, 0); } //===================== // addBindingMarkers //===================== function addBindingMarkers(value, view, tag) { // Insert binding markers into the rendered template output, which will get converted to appropriate // data-jsv attributes (element-only content) or script marker nodes (phrasing or flow content), in convertMarkers, // within view.link, prior to inserting into the DOM. Linking will then bind based on these markers in the DOM. // Added view markers: #m_...VIEW.../m_ // Added tag markers: #m^...TAG..../m^ var id, end; if (tag) { // This is a binding marker for a data-linked tag {^{...}} end = "^`"; addLinkMethods(tag, true); // This is {^{>...}} or {^{tag ...}}, {{cvt:...} or {^{:...}}, and tag was defined in convertVal or renderTag id = tag._tgId; if (!id) { bindingStore[id = bindingKey++] = tag; // Store the tag temporarily, ready for databinding. // During linking, in addDataBinding, the tag will be attached to the linkCtx, // and then in observeAndBind, bindingStore[bindId] will be replaced by binding info. tag._tgId = "" + id; } } else { // This is a binding marker for a view // Add the view to the store of current linked views end = "_`"; addLinkMethods(viewStore[id = view._.id] = view); } // Example: "#23^TheValue/23^" return "#" + id + end + (value != undefined ? value : "") // For {^{:name}} this gives the equivalent semantics to compiled // (v=data.name)!=null?v:""; used in {{:name}} or data-link="name" + "/" + id + end; } //============================== // Data-linking and data binding //============================== //--------------- // observeAndBind //--------------- function observeAndBind(linkCtx, source, target) { //TODO? linkFnArgs) {; var binding, l, linkedElem, exprFnDeps, exprOb, tag = linkCtx.tag, cvtBk = linkCtx.convertBack, depends = [], bindId = linkCtx._bndId || "" + bindingKey++, handler = linkCtx._hdl; linkCtx._bndId = undefined; if (tag) { // Use the 'depends' paths set on linkCtx.tag - which may have been set on declaration // or in events: init, render, onBeforeLink, onAfterLink etc. depends = tag.depends || depends; depends = $isFunction(depends) ? tag.depends(tag) : depends; linkedElem = tag.linkedElem; } if (!linkCtx._depends || ("" + linkCtx._depends !== "" + depends)) { // Only bind the first time, or if the new depends (toString) has changed from when last bound if (linkCtx._depends) { // Unobserve previous binding $observable._apply(false, [source], linkCtx._depends, handler, true); } exprFnDeps = linkCtx.fn.deps.slice(); // Make a copy of the dependency paths for the compiled linkCtx expression - to pass to observe(). In getInnerCb(), // (and whenever the object is updated, in innerCb), we will set exprOb.ob to the current object returned by that computed expression, for this view. l = exprFnDeps.length; while (l--) { exprOb = exprFnDeps[l]; if (exprOb._jsv) { // This path is an 'exprOb', corresponding to a computed, returning an object. We replace the exprOb by // a view-binding-specific exprOb instance. The current object will be stored as exprOb.ob. exprFnDeps[l] = $extend({}, exprOb); } } binding = $observable._apply( false, [source], exprFnDeps, // flatten the paths - to gather all the dependencies across args and bound params depends, handler, linkCtx._ctxCb); // The binding returned by $observe has a bnd array with the source objects of the individual bindings. binding.elem = target; // The target of all the individual bindings binding.linkCtx = linkCtx; binding._tgId = bindId; // Add to the _jsvBnd on the target the view id and binding id - for unbinding when the target element is removed target._jsvBnd = target._jsvBnd || ""; target._jsvBnd += "&" + bindId; linkCtx._depends = depends; // Store the binding key on the view, for disposal when the view is removed linkCtx.view._.bnds[bindId] = bindId; // Store the binding. bindingStore[bindId] = binding; // Note: If this corresponds to a data-linked tag, we are replacing the // temporarily stored tag by the stored binding. The tag will now be at binding.linkCtx.tag if (linkedElem) { binding.to = [[], cvtBk]; } if (linkedElem || cvtBk !== undefined) { bindTo(binding, tag, linkedElem && linkedElem[0] || target, cvtBk); } if (tag) { if (tag.onAfterBind) { tag.onAfterBind(binding); } if (!tag.flow && !tag._.inline) { target.setAttribute(jsvAttrStr, (target.getAttribute(jsvAttrStr)||"") + "#" + bindId + "^/" + bindId + "^"); tag._tgId = "" + bindId; } } } if (linkedElem && linkedElem[0]) { if (tag._.radio) { linkedElem = linkedElem.find(RADIOINPUT); } l = linkedElem.length; while (l--) { linkedElem[l]._jsvBnd = linkedElem[l]._jsvBnd || (target._jsvBnd + "+"); // Add a "+" for cloned binding - so removing elems with cloned bindings will not remove the 'parent' binding from the bindingStore. linkedElem[l]._jsvLkEl = tag; } } } //------- // $.link //------- function tmplLink(to, from, context, noIteration, parentView, prevNode, nextNode) { return $link(this, to, from, context, noIteration, parentView, prevNode, nextNode); } function $link(tmplOrLinkExpr, to, from, context, noIteration, parentView, prevNode, nextNode) { // When linking from a template, prevNode and nextNode parameters are ignored if (context === true) { noIteration = context; // passing boolean as third param - noIteration context = undefined; } else if (typeof context !== "object") { context = undefined; // context must be a boolean (noIteration) or a plain object } else { context = $extend({}, context); } if (tmplOrLinkExpr && to) { to = to.jquery ? to : $(to); // to is a jquery object or an element or selector if (!activeBody) { activeBody = document.body; $(activeBody) .on(elementChangeStr, elemChangeHandler) .on('blur', '[contenteditable]', elemChangeHandler); } var i, k, html, vwInfos, view, placeholderParent, targetEl, refresh, topLevelCall, onRender = addBindingMarkers, replaceMode = context && context.target === "replace", l = to.length; while (l--) { targetEl = to[l]; parentView = parentView || $view(targetEl); if (topLevelCall = parentView === topView) { topView.data = (topView.ctx = context || {}).root = from; } if ("" + tmplOrLinkExpr === tmplOrLinkExpr) { // tmplOrLinkExpr is a string: treat as data-link expression. addDataBinding(tmplOrLinkExpr, targetEl, parentView, undefined, true, from, context); } else { if (tmplOrLinkExpr.markup !== undefined) { // This is a call to template.link() if (replaceMode) { placeholderParent = targetEl.parentNode; } html = tmplOrLinkExpr.render(from, context, noIteration, parentView, undefined, onRender); // TODO Consider finding a way to bind data (link) within template without html being different for each view, the HTML can // be evaluated once outside the while (l--), and pushed into a document fragment, then cloned and inserted at each target. if (placeholderParent) { // This is target="replace" mode prevNode = targetEl.previousSibling; nextNode = targetEl.nextSibling; $.cleanData([targetEl], true); placeholderParent.removeChild(targetEl); targetEl = placeholderParent; } else { prevNode = nextNode = undefined; // When linking from a template, prevNode and nextNode parameters are ignored $(targetEl).empty(); } } else if (tmplOrLinkExpr === true && parentView === topView) { // $.link(true, selector, data, ctx) - where selector points to elem in top-level content. (If not top-level content, no-op) refresh = {lnk: 1}; } else { break; } // TODO Consider deferred linking API feature on per-template basis - {@{ instead of {^{ which allows the user to see the rendered content // before that content is linked, with better perceived perf. Have view.link return a deferred, and pass that to onAfterLink... // or something along those lines. // setTimeout(function() { if (targetEl._df && !nextNode) { // We are inserting new content and the target element has some deferred binding annotations,and there is no nextNode. // Those views may be stale views (that will be recreated in this new linking action) so we will first remove them // (if not already removed). vwInfos = viewInfos(targetEl._df, true, rOpenViewMarkers); for (i = 0, k = vwInfos.length; i < k; i++) { view = vwInfos[i]; if ((view = viewStore[view.id]) && view.data !== undefined) { // If this is the _prv (prevNode) for a view, remove the view // - unless view.data is undefined, in which case it is already being removed view.parent.removeViews(view._.key, undefined, true); } } setDefer(targetEl); // remove defer tokens } // Link the content of the element, since this is a call to template.link(), or to $(el).link(true, ...), parentView.link(from, targetEl, prevNode, nextNode, html, refresh, context); //}, 0); } if (topLevelCall) { topView.data = topView.ctx = undefined; } } } return to; // Allow chaining, to attach event handlers, etc. } //---------- // view.link //---------- function viewLink(outerData, parentNode, prevNode, nextNode, html, refresh, context, validateOnly) { // Optionally insert HTML into DOM using documentFragments (and wrapping HTML appropriately). // Data-link existing contents of parentNode, or the inserted HTML, if provided // Depending on the content model for the HTML elements, the standard data-linking markers inserted in the HTML by addBindingMarkers during // template rendering will be converted either to script marker nodes or, for element-only content sections, to data-jsv element annotations. // Data-linking will then add _prv and _nxt to views, where: // _prv: References the previous node (script element of type "jsv123"), or (for elCnt=true), the first element node in the view (or if none, set _prv = _nxt) // _nxt: References the last node (script element of type "jsv/123"), or (for elCnt=true), the next element node after the view. //==== nested functions ==== function convertMarkers(all, preceding, selfClose, closeTag, spaceBefore, id, boundId, spaceAfter, tag1, tag2, closeTag2, spaceAfterClose, selfClose2, endOpenTag) { // rConvertMarkers = /(^|(\/>)|<\/(\w+)>|)(\s*)([#\/]\d+(?:_|(\^)))`(\s*)(<\w+(?=[\s\/>]))?|\s*(?:(<\w+(?=[\s\/>]))|<\/(\w+)>(\s*)|(\/>)\s*|(>))/g, // prec, slfCl, clsTag, spBefore, id, bndId spAfter,tag1, tag2, clTag2,sac slfCl2, endOpenTag // Convert the markers that were included by addBindingMarkers in template output, to appropriate DOM annotations: // data-jsv attributes (for element-only content) or script marker nodes (within phrasing or flow content). // TODO consider detecting 'quoted' contexts (attribute strings) so that attribute encoding does not need to encode > // Currently rAttrEncode = /[><"'&]/g includes '>' encoding in order to avoid erroneous parsing of <span title="&lt;a/>"></span>"> var errorMsg, bndId, endOfElCnt = ""; if (endOpenTag) { inTag = 0; return all; } tag = tag1 || tag2 || ""; closeTag = closeTag || closeTag2; selfClose = selfClose || selfClose2; if (isVoid && !selfClose && ( !all || closeTag || tag || id && !inTag)) { // !all = end of string isVoid = undefined; parentTag = tagStack.shift(); // preceding tag was a void element, with no closing slash, such as <br>. } closeTag = closeTag || selfClose; if (closeTag) { inTag = 0; isVoid = undefined; // TODO: smart insertion of <tbody> - to be completed for robust insertion of deferred bindings etc. //if (closeTag === "table" && parentTag === "tbody") { // preceding = "</tbody>" + preceding; // parentTag = "table"; // tagStack.shift(); //} if (validate) { if (selfClose || selfClose2) { if (!voidElems[parentTag] && !/;svg;|;math;/.test(";" + tagStack.join(";") + ";")) { // Only self-closing elements must be legitimate void elements, such as <br/>, per HTML schema, // or under svg or math foreign namespace elements. errorMsg = "'<" + parentTag + ".../"; } } else if (voidElems[closeTag]) { errorMsg = "'</" + closeTag; // closing tag such as </input> } else if (!tagStack.length || closeTag !== parentTag) { errorMsg = "Mismatch: '</" + closeTag; } if (errorMsg) { syntaxError(errorMsg + ">' in:\n" + html); } } prevElCnt = elCnt; parentTag = tagStack.shift(); elCnt = elContent[parentTag]; closeTag2 = closeTag2 ? ("</" + closeTag2 + ">") : ""; if (prevElCnt) { // If there are ids (markers since the last tag), move them to the defer string defer += ids; ids = ""; if (!elCnt) { endOfElCnt = closeTag2 + openScript + "@" + defer + closeScript + (spaceAfterClose || ""); defer = deferStack.shift(); } else { defer += "-"; // Will be used for stepping back through deferred tokens } } } if (elCnt) { // elContent maps tagNames which have only element content, so may not support script nodes. // We are in element-only content, can remove white space, and use data-jsv attributes on elements as markers // Example: <tr data-jsv="/2_#6_"> - close marker for view 2 and open marker for view 6 if (id) { // append marker for this id, to ids string ids += id; } else { preceding = (closeTag2 || selfClose2 || ""); } if (tag) { // TODO: smart insertion of <tbody> - to be completed for robust insertion of deferred bindings etc. //if (tag === "<tr" && parentTag === "table") { // tagStack.unshift(parentTag); // parentTag = "tbody"; // preceding += "<" + parentTag + ">"; // if (defer) { // defer += "+"; // Will be used for stepping back through deferred tokens // } // // TODO: move this to design-time validation check // // error('"' + parentTag + '" has incorrect parent tag'); //} preceding += tag; if (ids) { preceding += ' ' + jsvAttrStr + '="' + ids + '"'; ids = ""; } } } else { // We are in phrasing or flow content, so use script marker nodes // Example: <script type="jsv3/"></script> - data-linked tag, close marker // We validate with inTag so no script markers are inserted in attribute context e.g. for: // "<table {{if ...}}...{{/if}}... >" or "<table {{if ...}}...> ...{{/if}}..." preceding = id ? (preceding + endOfElCnt + spaceBefore + (inTag ? "" : openScript + id + closeScript)+ spaceAfter + tag) : endOfElCnt || all; } if (validate && boundId) { if (inTag) { // JsViews data-linking tags are not allowed within element markup. // See jsviews/issues/303 syntaxError('{^{ within elem markup (' + inTag + ' ). Use data-link="..."'); } if (id.charAt(0) === "#") { tagStack.unshift(id.slice(1)); } else if (id.slice(1) !== (bndId = tagStack.shift())) { // See jsviews/issues/213 syntaxError('Closing tag for {^{...}} under different elem: <' + bndId + '>'); } } if (tag) { inTag = tag; // If there are ids (markers since the last tag), move them to the defer string tagStack.unshift(parentTag); parentTag = tag.slice(1); if (validate && tagStack[0] && tagStack[0] === badParent[parentTag]) { // Missing <tbody> // TODO: replace this by smart insertion of <tbody> tags error('Parent of <tr> must be <tbody>'); } isVoid = voidElems[parentTag]; if ((elCnt = elContent[parentTag]) && !prevElCnt) { deferStack.unshift(defer); defer = ""; } prevElCnt = elCnt; //TODO Consider providing validation which throws if you place <span> as child of <tr>, etc. - since if not caught, //this can cause errors subsequently which are difficult to debug. // if (elContent[tagStack[0]]>2 && !elCnt) { // error(parentTag + " in " + tagStack[0]); // } if (defer && elCnt) { defer += "+"; // Will be used for stepping back through deferred tokens } } return preceding; } function processViewInfos(vwInfos, targetParent) { // If targetParent, we are processing viewInfos (which may include navigation through '+-' paths) and hooking up to the right parentElem etc. // (and elem may also be defined - the next node) // If no targetParent, then we are processing viewInfos on newly inserted content var deferPath, deferChar, bindChar, parentElem, id, onAftCr, deep, addedBindEls = []; // In elCnt context (element-only content model), prevNode is the first node after the open, nextNode is the first node after the close. // If both are null/undefined, then open and close are at end of parent content, so the view is empty, and its placeholder is the // 'lastChild' of the parentNode. If there is a prevNode, then it is either the first node in the view, or the view is empty and // its placeholder is the 'previousSibling' of the prevNode, which is also the nextNode. if (vwInfos) { if (vwInfos._tkns.charAt(0) === "@") { // We are processing newly inserted content. This is a special script element that was created in convertMarkers() to process deferred bindings, // and inserted following the target parent element - because no element tags (outside elCnt) were encountered to carry those binding tokens. // We will step back from the preceding sibling of this element, looking at targetParent elements until we find the one that the current binding // token belongs to. Set elem to null (the special script element), and remove it from the DOM. targetParent = elem.previousSibling; elem.parentNode.removeChild(elem); elem = undefined; } len = vwInfos.length; while (len--) { vwInfo = vwInfos[len]; //if (prevIds.indexOf(vwInfo.token) < 0) { // This token is a newly created view or tag binding bindChar = vwInfo.ch; if (deferPath = vwInfo.path) { // We have a 'deferred path' j = deferPath.length - 1; while (deferChar = deferPath.charAt(j--)) { // Use the "+" and"-" characters to navigate the path back to the original parent node where the deferred bindings ocurred if (deferChar === "+") { if (deferPath.charAt(j) === "-") { j--; targetParent = targetParent.previousSibling; } else { targetParent = targetParent.parentNode; } } else { targetParent = targetParent.lastChild; } // Note: Can use previousSibling and lastChild, not previousElementSibling and lastElementChild, // since we have removed white space within elCnt. Hence support IE < 9 } } if (bindChar === "^") { if (tag = bindingStore[id = vwInfo.id]) { // The binding may have been deleted, for example in a different handler to an array collectionChange event // This is a tag binding deep = targetParent && (!elem || elem.parentNode !== targetParent); // We are stepping back looking for the right targetParent, // or we are linking existing content and this element is in elCnt, not an immediate child of the targetParent. if (!elem || deep) { tag.parentElem = targetParent; } if (vwInfo.elCnt && deep) { // With element only content, if there is no following element, or if the binding is deeper than the following element // then we need to set the open or close token as a deferred binding annotation on the parent setDefer(targetParent, (vwInfo.open ? "#" : "/") + id + bindChar + (targetParent._df || "")); } // This is an open or close marker for a data-linked tag {^{...}}. Add it to bindEls. addedBindEls.push([deep ? null : elem, vwInfo]); } } else if (view = viewStore[id = vwInfo.id]) { // The view may have been deleted, for example in a different handler to an array collectionChange event if (!view.parentElem) { // If view is not already extended for JsViews, extend and initialize the view object created in JsRender, as a JsViews view view.parentElem = targetParent || elem && elem.parentNode || parentNode; view._.onRender = addBindingMarkers; view._.onArrayChange = arrayChangeHandler; setArrayChangeLink(view); } parentElem = view.parentElem; if (vwInfo.open) { // This is an 'open view' node (preceding script marker node, // or if elCnt, the first element in the view, with a data-jsv annotation) for binding view._elCnt = vwInfo.elCnt; if (targetParent && !elem) { setDefer(targetParent, "#" + id + bindChar + (targetParent._df || "")); } else { // No targetParent, so there is a ._nxt elem (and this is processing tokens on the elem) if (!view._prv) { setDefer(parentElem, removeSubStr(parentElem._df, "#" + id + bindChar)); } view._prv = elem; } } else { // This is a 'close view' marker node for binding if (targetParent && (!elem || elem.parentNode !== targetParent)) { // There is no ._nxt so add token to _df. It is deferred. setDefer(targetParent, "/" + id + bindChar + (targetParent._df || "")); view._nxt = undefined; } else if (elem) { // This view did not have a ._nxt, but has one now, so token may be in _df, and must be removed. (No longer deferred) if (!view._nxt) { setDefer(parentElem, removeSubStr(parentElem._df, "/" + id + bindChar)); } view._nxt = elem; } linkCtx = view.linkCtx; if (onAftCr = view.ctx && view.ctx.onAfterCreate || onAfterCreate) { onAftCr.call(linkCtx, view); } } //} } } len = addedBindEls.length; while (len--) { // These were added in reverse order to addedBindEls. We push them in BindEls in the correct order. bindEls.push(addedBindEls[len]); } } return !vwInfos || vwInfos.elCnt; } function getViewInfos(vwInfos) { // Used by view.childTags() and tag.childTags() // Similar to processViewInfos in how it steps through bindings to find tags. Only finds data-linked tags. var level, parentTag, named; if (vwInfos) { len = vwInfos.length; for (j = 0; j < len; j++) { vwInfo = vwInfos[j]; // This is an open marker for a data-linked tag {^{...}}, within the content of the tag whose id is get.id. Add it to bindEls. // Note - if bindingStore[vwInfo.id]._is === "tag" then getViewInfos is being called too soon - during first linking pass parentTag = tag = bindingStore[vwInfo.id].linkCtx.tag; named = tag.tagName === tagName; if (!tag.flow || named) { if (!deep) { level = 1; while (parentTag = parentTag.parent) { level++; } tagDepth = tagDepth || level; // The level of the first tag encountered. } if ((deep || level === tagDepth) && (!tagName || named)) { // Filter on top-level or tagName as appropriate tags.push(tag); } } } } } function dataLink() { //================ Data-link and fixup of data-jsv annotations ================ var j, index, tokens = "", wrap = {}, selector = linkViewsSel + (get ? ",[" + deferAttr + "]" : ""); // If a childTags() call, get = ",[" + deferAttr + "]" - since we need to include elements that have a ._df expando for deferred tokens elems = qsa ? parentNode.querySelectorAll(selector) : $(selector, parentNode).get(); l = elems.length; // The prevNode will be in the returned query, since we called markPrevOrNextNode() on it. // But it may have contained nodes that satisfy the selector also. if (prevNode && prevNode.innerHTML) { // Find the last contained node of prevNode, to use as the prevNode - so we only link subsequent elems in the query prevNodes = qsa ? prevNode.querySelectorAll(selector) : $(selector, prevNode).get(); prevNode = prevNodes.length ? prevNodes[prevNodes.length - 1] : prevNode; } tagDepth = 0; for (i = 0; i < l; i++) { elem = elems[i]; if (prevNode && !found) { // If prevNode is set, not false, skip linking. If this element is the prevNode, set to false so subsequent elements will link. found = (elem === prevNode); } else if (nextNode && elem === nextNode) { // If nextNode is set then break when we get to nextNode if (get) { tokens += markerNodeInfo(elem); } break; } else if (elem.parentNode) { // elem has not been removed from DOM if (get) { tokens += markerNodeInfo(elem); if (elem._df) { j = i + 1; while (j < l && elem.contains(elems[j])) { j++; } // Add defered tokens after any tokens on descendant elements of this one wrap[j-1] = elem._df; } if (wrap[i]) { tokens += wrap[i] || ""; } } else { if (isLink && (vwInfo = viewInfos(elem, undefined, rViewMarkers)) && (vwInfo = vwInfo[0])) { // If this is a link(trueOrString ...) call we will avoid re-binding to elems that are within template-rendered views skip = skip ? (vwInfo.id !== skip && skip) : vwInfo.open && vwInfo.id; } if (!skip && processInfos(viewInfos(elem)) // If a link() call, processViewInfos() adds bindings to bindEls, and returns true for non-script nodes, for adding data-link bindings // If a childTags() call, getViewInfos returns array of tag bindings. && elem.getAttribute($viewsLinkAttr)) { bindEls.push([elem]); // A data-linked element so add to bindEls too } } } } if (get) { tokens += parentNode._df || ""; if (index = tokens.indexOf("#" + get.id) + 1) { // We are looking for view.childTags() or tag.childTags() - so start after the open token of the parent view or tag. tokens = tokens.slice(index + get.id.length); } index = tokens.indexOf("/" + get.id); if (index + 1) { // We are looking for view.childTags() or tag.childTags() - so don't look beyond the close token of the parent view or tag. tokens = tokens.slice(0, index); } // Call getViewInfos to add the found childTags to the tags array getViewInfos(viewInfos(tokens, undefined, rOpenTagMarkers)); } if (html === undefined && parentNode.getAttribute($viewsLinkAttr)) { bindEls.push([parentNode]); // Support data-linking top-level element directly (not within a data-linked container) } // Remove temporary marker script nodes they were added by markPrevOrNextNode unmarkPrevOrNextNode(prevNode, elCnt); unmarkPrevOrNextNode(nextNode, elCnt); if (get) { if (lazyLink) { lazyLink.resolve(); } return; // We have added childTags to the tags array, so we are done } if (elCnt && defer + ids) { // There are some views with elCnt, for which the open or close did not precede any HTML tag - so they have not been processed yet elem = nextNode; if (defer) { if (nextNode) { processViewInfos(viewInfos(defer + "+", true), nextNode); } else { processViewInfos(viewInfos(defer, true), parentNode); } } processViewInfos(viewInfos(ids, true), parentNode); // If there were any tokens on nextNode which have now been associated with inserted HTML tags, remove them from nextNode if (nextNode) { tokens = nextNode.getAttribute(jsvAttrStr); if (l = tokens.indexOf(prevIds) + 1) { tokens = tokens.slice(l + prevIds.length - 1); } nextNode.setAttribute(jsvAttrStr, ids + tokens); } } //================ Bind the data-linked elements and tags ================ l = bindEls.length; for (i = 0; i < l; i++) { elem = bindEls[i]; linkInfo = elem[1]; elem = elem[0]; if (linkInfo) { if (tag = bindingStore[linkInfo.id]) { if (linkCtx = tag.linkCtx) { // The tag may have been stored temporarily on the bindingStore - or may have already been replaced by the actual binding tag = linkCtx.tag; tag.linkCtx = linkCtx; } if (linkInfo.open) { // This is an 'open linked tag' binding annotation for a data-linked tag {^{...}} if (elem) { tag.parentElem = elem.parentNode; tag._prv = elem; } tag._elCnt = linkInfo.elCnt; if (tag.onBeforeLink) { tag.onBeforeLink(); } // We data-link depth-first ("on the way in"), which is better for perf - and allows setting parent tags etc. view = tag.tagCtx.view; addDataBinding(undefined, tag._prv, view, linkInfo.id); } else { tag._nxt = elem; if (tag._.unlinked) { // This is a 'close linked tag' binding annotation // Add data binding tagCtx = tag.tagCtx; view = tagCtx.view; callAfterLink(tag); } } } } else { // Add data binding for a data-linked element (with data-link attribute) addDataBinding(elem.getAttribute($viewsLinkAttr), elem, $view(elem), undefined, isLink, outerData, context); } } if (lazyLink) { lazyLink.resolve(); } } //==== /end of nested functions ==== var inTag, linkCtx, tag, i, l, j, len, elems, elem, view, vwInfo, linkInfo, prevNodes, token, prevView, nextView, node, tags, deep, tagName, tagCtx, validate, tagDepth, depth, fragment, copiedNode, firstTag, parentTag, isVoid, wrapper, div, tokens, elCnt, prevElCnt, htmlTag, ids, prevIds, found, skip, lazyLink, isLink, get, self = this, thisId = self._.id + "_", defer = "", // The marker ids for which no tag was encountered (empty views or final closing markers) which we carry over to container tag bindEls = [], tagStack = [], deferStack = [], onAfterCreate = self.hlp(onAfterCreateStr), processInfos = processViewInfos; if (refresh) { lazyLink = refresh.lazyLink && $.Deferred(); if (refresh.tmpl) { // refresh is the prevView, passed in from addViews() prevView = "/" + refresh._.id + "_"; } else { isLink = refresh.lnk; // Top-level linking if (refresh.tag) { thisId = refresh.tag + "^"; refresh = true; } if (get = refresh.get) { processInfos = getViewInfos; tags = get.tags; deep = get.deep; tagName = get.name; } } refresh = refresh === true; } parentNode = parentNode ? ("" + parentNode === parentNode ? $(parentNode)[0] // It is a string, so treat as selector : parentNode.jquery ? parentNode[0] // A jQuery object - take first element. : parentNode) : (self.parentElem // view.link() || document.body); // link(null, data) to link the whole document validate = !$subSettingsAdvanced.noValidate && parentNode.contentEditable !== TRUE; parentTag = parentNode.tagName.toLowerCase(); elCnt = !!elContent[parentTag]; prevNode = prevNode && markPrevOrNextNode(prevNode, elCnt); nextNode = nextNode && markPrevOrNextNode(nextNode, elCnt) || null; if (html != undefined) { //================ Insert html into DOM using documentFragments (and wrapping HTML appropriately). ================ // Also convert markers to DOM annotations, based on content model. // Corresponds to nextNode ? $(nextNode).before(html) : $(parentNode).html(html); // but allows insertion to wrap correctly even with inserted script nodes. jQuery version will fail e.g. under tbody or select. // This version should also be slightly faster div = document.createElement("div"); wrapper = div; prevIds = ids = ""; htmlTag = parentNode.namespaceURI === "http://www.w3.org/2000/svg" ? "svg_ns" : (firstTag = rFirstElem.exec(html)) && firstTag[1] || ""; if (elCnt) { // Now look for following view, and find its tokens, or if not found, get the parentNode._df tokens node = nextNode; while (node && !(nextView = viewInfos(node))) { node = node.nextSibling; } if (tokens = nextView ? nextView._tkns : parentNode._df) { token = prevView || ""; if (refresh || !prevView) { token += "#" + thisId; } j = tokens.indexOf(token); if (j + 1) { j += token.length; // Transfer the initial tokens to inserted nodes, by setting them as the ids variable, picked up in convertMarkers prevIds = ids = tokens.slice(0, j); tokens = tokens.slice(j); if (nextView) { node.setAttribute(jsvAttrStr, tokens); } else { setDefer(parentNode, tokens); } } } } //================ Convert the markers to DOM annotations, based on content model. ================ // oldElCnt = elCnt; isVoid = undefined; html = ("" + html).replace(rConvertMarkers, convertMarkers); // if (!!oldElCnt !== !!elCnt) { // error("Parse: " + html); // Parse error. Content not well-formed? // } if (validate && tagStack.length) { syntaxError("Mismatched '<" + parentTag + "...>' in:\n" + html); // Unmatched tag } if (validateOnly) { return; } // Append wrapper element to doc fragment safeFragment.appendChild(div); // Go to html and back, then peel off extra wrappers // Corresponds to jQuery $(nextNode).before(html) or $(parentNode).html(html); // but supports svg elements, and other features missing from jQuery version (and this version should also be slightly faster) htmlTag = wrapMap[htmlTag] || wrapMap.div; depth = htmlTag[0]; wrapper.innerHTML = htmlTag[1] + html + htmlTag[2]; while (depth--) { wrapper = wrapper.lastChild; } safeFragment.removeChild(div); fragment = document.createDocumentFragment(); while (copiedNode = wrapper.firstChild) { fragment.appendChild(copiedNode); } // Insert into the DOM parentNode.insertBefore(fragment, nextNode); } if (lazyLink) { setTimeout(dataLink, 0); } else { dataLink(); } return lazyLink && lazyLink.promise(); } function addDataBinding(linkMarkup, node, currentView, boundTagId, isLink, data, context) { // Add data binding for data-linked elements or {^{...}} data-linked tags var tmpl, tokens, attr, convertBack, params, trimLen, tagExpr, linkFn, linkCtx, tag, rTagIndex, hasElse, lastIndex, linkExpressions = []; if (boundTagId) { // boundTagId is a string for {^{...}} data-linked tag. So only one linkTag in linkMarkup // data and context parameters are undefined tag = bindingStore[boundTagId]; tag = tag.linkCtx ? tag.linkCtx.tag : tag; linkCtx = tag.linkCtx || { data: currentView.data, // source elem: tag._elCnt ? tag.parentElem : node, // target view: currentView, ctx: currentView.ctx, attr: HTML, // Script marker nodes are associated with {^{ and always target HTML. fn: tag._.bnd, tag: tag, // Pass the boundTagId in the linkCtx, so that it can be picked up in observeAndBind _bndId: boundTagId }; bindDataLinkTarget(linkCtx, linkCtx.fn); } else if (linkMarkup && node) { // If isLink then this is a top-level linking: .link(expression, target, data, ....) or // .link(true, target, data, ....) scenario - and data and context are passed in separately from the view data = isLink ? data : currentView.data; // Compiled linkFn expressions could be stored in the tmpl.links array of the template // TODO - consider also caching globally so that if {{:foo}} or data-link="foo" occurs in different places, // the compiled template for this is cached and only compiled once... //links = currentView.links || currentView.tmpl.links; tmpl = currentView.tmpl; // if (!(linkTags = links[linkMarkup])) { // This is the first time this view template has been linked, so we compile the data-link expressions, and store them on the template. linkMarkup = normalizeLinkTag(linkMarkup, defaultAttr(node)); lastIndex = rTagDatalink.lastIndex = 0; while (tokens = rTagDatalink.exec(linkMarkup)) { // TODO require } to be followed by whitespace or $, and remove the \}(!\}) option. linkExpressions.push(tokens); lastIndex = rTagDatalink.lastIndex; } if (lastIndex < linkMarkup.length) { syntaxError(linkMarkup); } while (tokens = linkExpressions.shift()) { // Iterate over the data-link expressions, for different target attrs, // e.g. <input data-link="{:firstName:} title{>~description(firstName, lastName)}" // tokens: [all, attr, bindOnly, tagExpr, tagName, converter, colon, html, comment, code, params] rTagIndex = rTagDatalink.lastIndex; attr = tokens[1]; tagExpr = tokens[3]; while (linkExpressions[0] && linkExpressions[0][4] === "else") { // If this is {someTag...} and is followed by an {else...} add to tagExpr tagExpr += "}{" + linkExpressions.shift()[3]; hasElse = true; } if (hasElse) { // If an {else} has been added, need also to add closing {{/someTag}} tagExpr += "}{{/" + tokens[4] + "}"; } params = tokens[9]; linkCtx = { data: data, // source elem: node, // target view: currentView, ctx: context, attr: attr, isLk: isLink, // top-level linking? _toLk : 1, // Flag to data-link on initial data-link call rendering call _noUpd : tokens[2] // Flag for data-link="^{...}" so on initial data-link call will bind, but not render) }; convertBack = undefined; if (tokens[6]) { convertBack = tokens[10] || undefined; linkCtx.convert = tokens[5] || ""; if (!attr && convertBack !== undefined && defaultAttr(node)) { // Default target, so allow 2 way binding linkCtx.convertBack = convertBack = convertBack.slice(1); } } // Compile the linkFn expression which evaluates and binds a data-link expression // TODO - optimize for the case of simple data path with no conversion, helpers, etc.: // i.e. data-link="a.b.c". Avoid creating new instances of Function every time. Can use a default function for all of these... linkCtx.expr = attr + tagExpr; linkFn = tmpl.links[tagExpr]; if (!linkFn) { tmpl.links[tagExpr] = linkFn = $sub.tmplFn(tagExpr, tmpl, true, convertBack, hasElse); } linkCtx.fn = linkFn; bindDataLinkTarget(linkCtx, linkFn); // We store rTagIndex in local scope, since this addDataBinding method can sometimes be called recursively, // and each is using the same rTagDatalink instance. rTagDatalink.lastIndex = rTagIndex; } // } } } function bindDataLinkTarget(linkCtx, linkFn) { // Add data link bindings for a link expression in data-link attribute markup function handler(ev, eventArgs) { propertyChangeHandler.call(linkCtx, ev, eventArgs, linkFn); // If the link expression uses a custom tag, the propertyChangeHandler call will call renderTag, which will set tagCtx on linkCtx } handler.noArray = true; if (linkCtx.isLk) { // Top-level linking: .link(expressionOrTrue, data, context) - so we need to create a view for the linking, with the data and ctx // which may be different than the current context of the target. Note that this view is not a standard data-linked view, so it will // be disposed only when its parent view is disposed. addLinkMethods(linkCtx.view = new $sub.View( $sub.extendCtx(linkCtx.ctx, linkCtx.view.ctx), "link", linkCtx.view, linkCtx.data, linkCtx.expr, undefined, addBindingMarkers)); } linkCtx._ctxCb = getContextCb(linkCtx.view); // _ctxCb is for filtering/appending to dependency paths: function(path, object) { return [(object|path)*]} linkCtx._hdl = handler; // handler._ctx = linkCtx; Could pass linkCtx for use in a depends = function() {} call, so depends is different for different linkCtx's handler(true); } //===================== // Data-linking helpers //===================== function removeSubStr(str, substr) { var k; return str ? (k = str.indexOf(substr), (k + 1 ? str.slice(0, k) + str.slice(k + substr.length) : str)) : ""; } function markerNodeInfo(node) { return node && ("" + node === node ? node : node.tagName === SCRIPT ? node.type.slice(3) : node.nodeType === 1 && node.getAttribute(jsvAttrStr) || ""); } function viewInfos(node, isVal, rBinding) { // Test whether node is a script marker node, and if so, return metadata function getInfos(all, open, close, id, ch, elPath) { infos.push({ elCnt: elCnt, id: id, ch: ch, open: open, close: close, path: elPath, token: all }); } var elCnt, tokens, infos = []; if (tokens = isVal ? node : markerNodeInfo(node)) { elCnt = infos.elCnt = node.tagName !== SCRIPT; elCnt = tokens.charAt(0) === "@" || elCnt; infos._tkns = tokens; // rMarkerTokens = /(?:(#)|(\/))(\d+)([_^])([-+@\d]+)?/g; tokens.replace(rBinding || rMarkerTokens, getInfos); return infos; } } function unmarkPrevOrNextNode(node, elCnt) { if (node) { if (node.type === "jsv") { node.parentNode.removeChild(node); } else if (elCnt && node.getAttribute($viewsLinkAttr) === "") { node.removeAttribute($viewsLinkAttr); } } } function markPrevOrNextNode(node, elCnt) { var marker = node; while (elCnt && marker && marker.nodeType !== 1) { marker = marker.previousSibling; } if (marker) { if (marker.nodeType !== 1) { // For text nodes, we will add a script node before marker = document.createElement(SCRIPT); marker.type = "jsv"; node.parentNode.insertBefore(marker, node); } else if (!markerNodeInfo(marker) && !marker.getAttribute($viewsLinkAttr)) { // For element nodes, we will add a data-link attribute (unless there is already one) // so that this node gets included in the node linking process. marker.setAttribute($viewsLinkAttr, ""); } } return marker; } function normalizeLinkTag(linkMarkup, twoway) { linkMarkup = $.trim(linkMarkup).replace(rEscapeQuotes, "\\$&"); return linkMarkup.slice(-1) !== delimCloseChar0 // If simplified syntax is used: data-link="expression", convert to data-link="{:expression}", // or for inputs, data-link="{:expression:}" for (default) two-way binding ? linkMarkup = delimOpenChar1 + ":" + linkMarkup + (twoway ? ":" : "") + delimCloseChar0 : linkMarkup; } //=========================== // Methods for views and tags //=========================== function callAfterLink(tag, eventArgs) { var $linkedElem, linkedElem, radioButtons, val, l, linkedTag, oldTrig, newTrig, tagCtx = tag.tagCtx, view = tagCtx.view, props = tagCtx.props, linkCtx = tag.linkCtx = tag.linkCtx || { tag: tag, data: view.data, view: view, ctx: view.ctx }; if (tag.onAfterLink) { tag.onAfterLink(tagCtx, linkCtx, eventArgs); } tag._.unlinked = undefined; $linkedElem = tag.targetTag ? tag.targetTag.linkedElem : tag.linkedElem; if (!tag.noVal && (linkedElem = $linkedElem && $linkedElem[0])) { if (radioButtons = tag._.radio) { $linkedElem = $linkedElem.find(RADIOINPUT); } if (radioButtons || !tag._.chging) { val = tag.cvtArgs()[0]; if (radioButtons || linkedElem !== linkCtx.elem) { l = $linkedElem.length; while (l--) { linkedElem = $linkedElem[l]; linkedTag = linkedElem._jsvLkEl; if (tag._.inline && (!linkedTag || linkedTag !== tag && linkedTag.targetTag !== tag)) { // For data-linked tags, identify the linkedElem with the tag, for "to" binding // (For data-linked elements, if not yet bound, we identify later when the linkCtx.elem is bound) linkedElem._jsvLkEl = tag; bindTo(bindingStore[tag._tgId], tag, linkedElem); linkedElem._jsvBnd = "&" + tag._tgId + "+"; // Add a "+" for cloned binding - so removing // elems with cloned bindings will not remove the 'parent' binding from the bindingStore. } if (radioButtons) { // For radio button, set to if val === value. For others set val() to val, below linkedElem[CHECKED] = val === linkedElem.value; } } linkCtx._val = val; } if (val !== undefined) { if (!radioButtons && linkedElem.value !== undefined) { if (linkedElem.type === CHECKBOX) { linkedElem[CHECKED] = val && val !== "false"; } else { $linkedElem.val(val); } } else if (linkedElem.contentEditable === TRUE) { linkedElem.innerHTML = val; } } } if (tag.setSize) { if (props.height) { $linkedElem.height(props.height); } if (props.width) { $linkedElem.width(props.width); } } if (props["class"]) { $linkedElem.addClass(props["class"]); } if (props.id) { $linkedElem[0].id = props.id; } if (props.name) { $linkedElem.attr("name", props.name); } } } function asyncElemChangeHandler(ev) { setTimeout(function() { elemChangeHandler(ev); }, 0); } function bindElChange($elem, trig, onoff) { if (trig) { trig = "" + trig === trig ? trig : "keydown"; // Set trigger to (true || truey non-string (e.g. 1) || 'keydown'): Get 'keydown' with async $elem[onoff](trig, trig === "keydown" ? asyncElemChangeHandler : elemChangeHandler); } } function bindTo(binding, tag, linkedElem, cvtBk) { // Two-way binding. // We set the binding.to[1] to be the cvtBack, and binding.to[0] to be either the path to the target, or [object, path] where the target is the path on the provided object. // So for a computed path with an object call: a.b.getObject().d.e, then we set to[0] to be [exprOb, "d.e"], and we bind to the path on the returned object, exprOb.ob, as target // Otherwise our target is the first path, paths[0], which we will convert with contextCb() for paths like ~a.b.c or #x.y.z var bindto, pathIndex, path, lastPath, bindtoOb, $linkedElem, newTrig, oldTrig, linkCtx = binding.linkCtx, source = linkCtx.data, paths = linkCtx.fn.paths; if (binding && paths) { oldTrig = linkedElem._jsvTr || false; if (tag) { cvtBk = tag.convertBack || cvtBk; newTrig = tag.tagCtx.props.trigger; } newTrig = newTrig === undefined ? $subSettings.trigger : newTrig; if (oldTrig !== newTrig) { $linkedElem = $(linkedElem); bindElChange($linkedElem, oldTrig, "off"); bindElChange( $linkedElem, linkedElem._jsvTr // Trigger is noop except for text box, textarea, contenteditable... = (linkedElem.tagName === "INPUT" && linkedElem.type !== CHECKBOX && linkedElem.type !== RADIO || linkedElem.type === "textarea" || linkedElem.contentEditable === TRUE) && newTrig, "on" ); } paths = (bindto = paths._jsvto) || paths[0]; pathIndex = paths && paths.length; if (pathIndex && (!tag || tag.tagCtx.args.length)) { lastPath = paths[pathIndex - 1]; if (lastPath._jsv) { bindtoOb = lastPath; while (lastPath.sb && lastPath.sb._jsv) { path = lastPath = lastPath.sb; } path = lastPath.sb || path && path.path; lastPath = path ? path.slice(1) : bindtoOb.path; } binding.to = path ? [ // "...someexpr().lastpath..." - so need to get the bindtoOb 'exprOb' object for this view-binding [ bindtoOb, // 'exprOb' for this expression and view-binding. So bindtoOb.ob is current object returned by expression. lastPath ], cvtBk ] : [ linkCtx._ctxCb(path = lastPath.split("^").join(".")) || [source, path], cvtBk ]; } else { binding.to = [[], cvtBk]; } } } function mergeCtxs(tag, newCtxs, replace) { // Merge updated tagCtxs into tag.tagCtxs var tagCtx, newTagCtx, view = tag.tagCtx.view, tagCtxs = tag.tagCtxs || [tag.tagCtx], l = tagCtxs.length, refresh = !newCtxs; newCtxs = newCtxs || tag._.bnd.call(view.tmpl, (tag.linkCtx || view).data, view, $sub); if (replace) { // Replace previous tagCtxs by new ones, rather than merging tagCtxs = tag.tagCtxs = newCtxs; tag.tagCtx = tagCtxs[0]; } else { while (l--) { tagCtx = tagCtxs[l]; newTagCtx = newCtxs[l]; $observable(tagCtx.props).setProperty(newTagCtx.props); $extend(tagCtx.ctx, newTagCtx.ctx); // We don't support propagating ctx variables, ~foo, observably, to nested views. So extend, not setProperty... tagCtx.args = newTagCtx.args; if (refresh) { tagCtx.tmpl = newTagCtx.tmpl; } } } $sub._ths(tag, tagCtxs[0]); // tagHandlersFromProps return tagCtxs; } //========= // Disposal //========= function clean(elems) { // Remove data-link bindings, or contained views var l, elem, bindings, elemArray = [], len = elems.length, i = len; while (i--) { // Copy into an array, so that deletion of nodes from DOM will not cause our 'i' counter to get shifted // (Note: This seems as fast or faster than elemArray = [].slice.call(elems); ...) elemArray.push(elems[i]); } i = len; while (i--) { elem = elemArray[i]; if (elem.parentNode) { // Has not already been removed from the DOM if (bindings = elem._jsvBnd) { // Get propertyChange bindings for this element // This may be an element with data-link, or the opening script marker node for a data-linked tag {^{...}} // bindings is a string with the syntax: "(&bindingId)*" bindings = bindings.slice(1).split("&"); elem._jsvBnd = ""; l = bindings.length; while (l--) { // Remove associated bindings removeViewBinding(bindings[l], elem._jsvLkEl, elem); // unbind bindings with this bindingId on this view } } disposeTokens(markerNodeInfo(elem) + (elem._df || "")); } } } function removeViewBinding(bindId, linkedElemTag, elem) { // Unbind var objId, linkCtx, tag, object, obsId, tagCtxs, l, map, $linkedElem, linkedElem, trigger, view, binding = bindingStore[bindId]; if (linkedElemTag) { if (elem === linkedElemTag.linkedElem[0]) { elem._jsvLkEl = undefined; linkedElemTag.linkedElem = undefined; } } else if (binding) { delete bindingStore[bindId]; // Delete already, so call to onDispose handler below cannot trigger recursive deletion (through recursive call to jQuery cleanData) for (objId in binding.bnd) { object = binding.bnd[objId]; obsId = binding.cbId; if ($isArray(object)) { $([object]).off(arrayChangeStr + obsId).off(propertyChangeStr + obsId); // There may be either or both of arrayChange and propertyChange } else { $(object).off(propertyChangeStr + obsId); } delete binding.bnd[objId]; } if (linkCtx = binding.linkCtx) { if (tag = linkCtx.tag) { if (tagCtxs = tag.tagCtxs) { l = tagCtxs.length; while (l--) { if (map = tagCtxs[l].map) { map.unmap(); //unobserve } } } $linkedElem = tag.linkedElem; if (tag.onDispose) { tag.onDispose(); } if (!tag._elCnt) { if (tag._prv) { tag._prv.parentNode.removeChild(tag._prv); } if (tag._nxt) { tag._nxt.parentNode.removeChild(tag._nxt); } } } linkedElem = $linkedElem && $linkedElem[0] || linkCtx.elem; if (trigger = linkedElem && linkedElem._jsvTr) { bindElChange($linkedElem || $(linkedElem), trigger, "off"); linkedElem._jsvTr = undefined; } view = linkCtx.view; if (view.type === "link") { view.parent.removeViews(view._.key, undefined, true); // A "link" view is associated with the binding, so should be disposed with binding. } else { delete view._.bnds[bindId]; } } delete cbBindingsStore[binding.cbId]; } } function $unlink(to) { if (to) { to = to.jquery ? to : $(to); to.each(function() { var innerView; //TODO fix this for better perf. Rather that calling inner view multiple times which does querySelectorAll each time, consider a single querySelectorAll // or simply call view.removeViews() on the top-level views under the target 'to' node, then clean(...) while ((innerView = $view(this, true)) && innerView.parent) { innerView.parent.removeViews(innerView._.key, undefined, true); } clean(this.getElementsByTagName("*")); }); clean(to); } else { // Call to $.unlink() is equivalent to $.unlink(true, "body") if (activeBody) { $(activeBody) .off(elementChangeStr, elemChangeHandler) .off('blur', '[contenteditable]', elemChangeHandler); activeBody = undefined; } topView.removeViews(); clean(document.body.getElementsByTagName("*")); } } //======== // Helpers //======== function getContextCb(view) { // TODO Consider exposing or allowing override, as public API return function(path, object) { // TODO consider only calling the contextCb on the initial token in path '~a.b.c' and not calling again on // the individual tokens, 'a', 'b', 'c'... Currently it is called multiple times var tokens, tag, items = [object]; if (view && path) { if (path._jsv) { return path._jsv.call(view.tmpl, object, view, $sub); } if (path.charAt(0) === "~") { // We return new items to insert into the sequence, replacing the "~a.b.c" string: // [helperObject 'a', "a.b.c" currentDataItem] so currentDataItem becomes the object for subsequent paths. if (path.slice(0, 4) === "~tag") { tag = view.ctx; if (path.charAt(4) === ".") { // "~tag.xxx" tokens = path.slice(5).split("."); tag = tag.tag; } if (tokens) { return tag ? [tag, tokens.join("."), object] : []; } } path = path.slice(1).split("."); if (object = view.hlp(path.shift())) { if (path.length) { items.unshift(path.join(".")); } items.unshift(object); } return object ? items : []; } if (path.charAt(0) === "#") { // We return new items to insert into the sequence, replacing the "#a.b.c" string: [view, "a.b.c" currentDataItem] // so currentDataItem becomes the object for subsequent paths. The 'true' flag makes the paths bind only to leaf changes. return path === "#data" ? [] : [view, path.replace(rViewPath, ""), object]; } } }; } function inputAttrib(elem) { return elem.type === CHECKBOX ? elem[CHECKED] : elem.value; } //========================== Initialize ========================== //===================== // JsRender integration //===================== $sub.onStore.template = function(name, item) { item.link = tmplLink; if (name) { $.link[name] = function() { return tmplLink.apply(item, arguments); }; } }; $sub.viewInfos = viewInfos; // Expose viewInfos() as public helper method // Define JsViews version of delimiters(), and initialize ($viewsSettings.delimiters = function() { // Run delimiters initialization in context of jsrender.js var ret = oldJsvDelimiters.apply(0, arguments); if (oldJsvDelimiters !== $viewsDelimiters) { // If JsRender was loaded before JsViews, then need also to initialize and set globals in that JsRender instance ret = $viewsDelimiters.apply(0, arguments); } // Data-linking must use new delimiters rTagDatalink = new RegExp("(?:^|\\s*)([\\w-]*)(\\" + linkChar + ")?(\\" + delimOpenChar1 + $sub.rTag + "(:\\w*)?\\" + delimCloseChar0 + ")", "g"); return ret; })(); // jshint ignore:line $sub.addSetting("trigger"); //==================================== // Additional members for linked views //==================================== function transferViewTokens(prevNode, nextNode, parentElem, id, viewOrTagChar, refresh) { // Transfer tokens on prevNode of viewToRemove/viewToRefresh to nextNode or parentElem._df var i, l, vwInfos, vwInfo, viewOrTag, viewId, tokens, precedingLength = 0, emptyView = prevNode === nextNode; if (prevNode) { // prevNode is either the first node in the viewOrTag, or has been replaced by the vwInfos tokens string vwInfos = viewInfos(prevNode) || []; for (i = 0, l = vwInfos.length; i < l; i++) { // Step through views or tags on the prevNode vwInfo = vwInfos[i]; viewId = vwInfo.id; if (viewId === id && vwInfo.ch === viewOrTagChar) { if (refresh) { // This is viewOrTagToRefresh, this is the last viewOrTag to process... l = 0; } else { // This is viewOrTagToRemove, so we are done... break; } } if (!emptyView) { viewOrTag = vwInfo.ch === "_" ? viewStore[viewId] : bindingStore[viewId].linkCtx.tag; if (vwInfo.open) { // A "#m" token viewOrTag._prv = nextNode; } else if (vwInfo.close) { // A "/m" token viewOrTag._nxt = nextNode; } } precedingLength += viewId.length + 2; } if (precedingLength) { prevNode.setAttribute(jsvAttrStr, prevNode.getAttribute(jsvAttrStr).slice(precedingLength)); } tokens = nextNode ? nextNode.getAttribute(jsvAttrStr) : parentElem._df; if (l = tokens.indexOf("/" + id + viewOrTagChar) + 1) { tokens = vwInfos._tkns.slice(0, precedingLength) + tokens.slice(l + (refresh ? -1 : id.length + 1)); } if (tokens) { if (nextNode) { // If viewOrTagToRemove was an empty viewOrTag, we will remove both #n and /n // (and any intervening tokens) from the nextNode (=== prevNode) // If viewOrTagToRemove was not empty, we will take tokens preceding #n from prevNode, // and concatenate with tokens following /n on nextNode nextNode.setAttribute(jsvAttrStr, tokens); } else { setDefer(parentElem, tokens); } } } else { // !prevNode, so there may be a deferred nodes token on the parentElem. Remove it. setDefer(parentElem, removeSubStr(parentElem._df, "#" + id + viewOrTagChar)); if (!refresh && !nextNode) { // If this viewOrTag is being removed, and there was no .nxt, remove closing token from deferred tokens setDefer(parentElem, removeSubStr(parentElem._df, "/" + id + viewOrTagChar)); } } } function disposeTokens(tokens) { var i, l, vwItem, vwInfos; if (vwInfos = viewInfos(tokens, true, rOpenMarkers)) { for (i = 0, l = vwInfos.length; i < l; i++) { vwItem = vwInfos[i]; if (vwItem.ch === "_") { if ((vwItem = viewStore[vwItem.id]) && vwItem.type) { // If this is the _prv (prevNode) for a view, remove the view // - unless view.type is undefined, in which case it is already being removed vwItem.parent.removeViews(vwItem._.key, undefined, true); } } else { removeViewBinding(vwItem.id); // unbind bindings with this bindingId on this view } } } } //==================================== // Add link methods to data-linked view or tag //==================================== function addLinkMethods(tagOrView, isTag) { tagOrView.contents = function(deep, select) { // For a view or a tag, return jQuery object with the content nodes, if (deep !== !!deep) { // deep not boolean, so this is contents(selector) select = deep; deep = undefined; } var filtered, nodes = $(this.nodes()); if (nodes[0]) { filtered = select ? nodes.filter(select) : nodes; nodes = deep && select ? filtered.add(nodes.find(select)) : filtered; } return nodes; }; tagOrView.nodes = function(withMarkers, prevNode, nextNode) { // For a view or a tag, return top-level nodes // Do not return any script marker nodes, unless withMarkers is true // Optionally limit range, by passing in prevNode or nextNode parameters var node, self = this, elCnt = self._elCnt, prevIsFirstNode = !prevNode && elCnt, nodes = []; prevNode = prevNode || self._prv; nextNode = nextNode || self._nxt; node = prevIsFirstNode ? (prevNode === self._nxt ? self.parentElem.lastSibling : prevNode) : (self._.inline === false ? prevNode || self.linkCtx.elem.firstChild : prevNode && prevNode.nextSibling); while (node && (!nextNode || node !== nextNode)) { if (withMarkers || elCnt || node.tagName !== SCRIPT) { // All the top-level nodes in the view // (except script marker nodes, unless withMarkers = true) // (Note: If a script marker node, viewInfo.elCnt undefined) nodes.push(node); } node = node.nextSibling; } return nodes; }; tagOrView.childTags = function(deep, tagName) { // For a view or a tag, return child tags - at any depth, or as immediate children only. if (deep !== !!deep) { // deep not boolean, so this is childTags(tagName) - which looks for top-level tags of given tagName tagName = deep; deep = undefined; } var self = this, view = self.link ? self : self.tagCtx.view, // this may be a view or a tag. If a tag, get the view from tag.view.tagCtx prevNode = self._prv, elCnt = self._elCnt, tags = []; view.link( undefined, self.parentElem, elCnt ? prevNode && prevNode.previousSibling : prevNode, self._nxt, undefined, {get:{ tags: tags, deep: deep, name: tagName, id: self.link ? self._.id + "_" : self._tgId + "^" }} ); return tags; }; tagOrView.refresh = function(sourceValue) { var promise, attr, tag = this, linkCtx = tag.linkCtx, view = tag.tagCtx.view; if (tag.disposed) { error("Removed tag"); } if (sourceValue === undefined) { sourceValue = $sub._tag(tag, view, view.tmpl, mergeCtxs(tag), true); // Get rendered HTML for tag, based on refreshed tagCtxs } if (sourceValue + "" === sourceValue) { // If no rendered content, sourceValue will not be a string (can be 0 or undefined) attr = tag._.inline ? HTML : (linkCtx.attr || defaultAttr(tag.parentElem, true)); promise = updateContent(sourceValue, linkCtx, attr, tag); } callAfterLink(tag); return promise || tag; }; tagOrView.update = function(value) { var linkedElem = this.linkedElem; if (linkedElem) { elemChangeHandler({ target: linkedElem[0] }, undefined, value); } }; if (isTag) { // This is a TAG tagOrView.domChange = function() { // domChange notification support var elem = this.parentElem, hasListener = $.hasData(elem) && $._data(elem).events, domChangeNotification = "jsv-domchange"; if (hasListener && hasListener[domChangeNotification]) { // Only trigger handler if there is a handler listening for this event. (Note using triggerHandler - so no event bubbling.) $(elem).triggerHandler(domChangeNotification, arguments); } }; } else { // This is a VIEW // Note: a linked view will also, after linking have nodes[], _prv (prevNode), _nxt (nextNode) ... tagOrView.addViews = function(index, dataItems) { // if view is not an array view, do nothing var i, viewsCount, self = this, itemsCount = dataItems.length, views = self.views; if (!self._.useKey && itemsCount) { // view is of type "array" viewsCount = views.length + itemsCount; if (viewsCount === self.data.length // If views not already synced to array (e.g. triggered by array.length propertyChange - jsviews/issues/301) && renderAndLink(self, index, self.tmpl, views, dataItems, self.ctx) !== false) { if (!self._.srt) { // Not part of a 'sort' on refresh self.fixIndex(index + itemsCount); } } } }; tagOrView.removeViews = function(index, itemsCount, keepNodes, isMove) { // view.removeViews() removes all the child views // view.removeViews(index) removes the child view with specified index or key // view.removeViews(index, count) removes the specified nummber of child views, starting with the specified index function removeView(index) { var id, bindId, parentElem, prevNode, nextNode, nodesToRemove, viewToRemove = views[index]; if (viewToRemove && viewToRemove.link) { id = viewToRemove._.id; if (!keepNodes) { // Remove the HTML nodes from the DOM, unless they have already been removed, including nodes of child views nodesToRemove = viewToRemove.nodes(); } // Remove child views, without removing nodes viewToRemove.removeViews(undefined, undefined, true); viewToRemove.type = undefined; // Set type to undefined: used as a flag that this view is being removed prevNode = viewToRemove._prv; nextNode = viewToRemove._nxt; parentElem = viewToRemove.parentElem; // If prevNode and nextNode are the same, the view is empty if (!keepNodes) { // Remove the HTML nodes from the DOM, unless they have already been removed, including nodes of child views if (viewToRemove._elCnt) { // if keepNodes is false (and transferring of tokens has not already been done at a higher level) // then transfer tokens from prevNode which is being removed, to nextNode. transferViewTokens(prevNode, nextNode, parentElem, id, "_"); } $(nodesToRemove).remove(); } if (!viewToRemove._elCnt) { try { prevNode.parentNode.removeChild(prevNode); // (prevNode.parentNode is parentElem, except if jQuery Mobile or similar has inserted an intermediate wrapper nextNode.parentNode.removeChild(nextNode); } catch (e) {} } setArrayChangeLink(viewToRemove); for (bindId in viewToRemove._.bnds) { removeViewBinding(bindId); } delete viewStore[id]; } } var current, view, viewsCount, self = this, isArray = !self._.useKey, views = self.views; if (isArray) { viewsCount = views.length; } if (index === undefined) { // Remove all child views if (isArray) { // views and data are arrays current = viewsCount; while (current--) { removeView(current); } self.views = []; } else { // views and data are objects for (view in views) { // Remove by key removeView(view); } self.views = {}; } } else { if (itemsCount === undefined) { if (isArray) { // The parentView is data array view. // Set itemsCount to 1, to remove this item itemsCount = 1; } else { // Remove child view with key 'index' removeView(index); delete views[index]; } } if (isArray && itemsCount && (isMove || viewsCount - itemsCount === self.data.length)) { // If views not already synced to array (e.g. triggered by array.length propertyChange - jsviews/issues/301) current = index + itemsCount; // Remove indexed items (parentView is data array view); while (current-- > index) { removeView(current); } views.splice(index, itemsCount); if (!self._.sort) { self.fixIndex(index); } } } }; tagOrView.refresh = function() { var self = this, parent = self.parent; if (parent) { renderAndLink(self, self.index, self.tmpl, parent.views, self.data, undefined, true); setArrayChangeLink(self); } }; tagOrView.fixIndex = function(fromIndex) { // Fixup index on following view items... var views = this.views, index = views.length; while (fromIndex < index--) { if (views[index].index !== index) { $observable(views[index]).setProperty("index", index); // This is fixing up index, but not key, and not index on child views. From child views, use view.getIndex() } } }; tagOrView.link = viewLink; } } //======================== // JsViews-specific converters //======================== $converters.merge = function(val) { // Special converter used in data-linking to space-separated lists, such as className: // Currently only supports toggle semantics - and has no effect if toggle string is not specified // data-link="class{merge:boolExpr toggle=className}" var regularExpression, currentValue = this.linkCtx._val || "", toggle = this.tagCtx.props.toggle; if (toggle) { // We are toggling the class specified by the toggle property, // and the boolean val binding is driving the insert/remove toggle regularExpression = toggle.replace(/[\\^$.|?*+()[{]/g, "\\$&"); // Escape any regular expression special characters (metacharacters) within the toggle string regularExpression = "(\\s(?=" + regularExpression + "$)|(\\s)|^)(" + regularExpression + "(\\s|$))"; // Example: /(\s(?=myclass$)|(\s)|^)?(myclass(\s|$))/ - so matches (" myclass" or " " or ^ ) followed by ("myclass " or "myclass$") where ^/$ are beginning/end of string currentValue = currentValue.replace(new RegExp(regularExpression), "$2"); val = currentValue + (val ? (currentValue && " ") + toggle : ""); } return val; }; //======================== // JsViews-specific tags //======================== function evHandler(ev, params, sourceValue) { var setter, cancel, fromAttr, linkCtx, cvtBack, cnvtName, target, $source, view, binding, oldLinkCtx, onBeforeChange, onAfterChange, tag, to, eventArgs, exprOb, source = ev.target, bindings = source._jsvBnd; console.log("x"); } $tags("on", { attr: NONE, init: function(tagCtx) { var props, elemProp, classProp, content, tag = this, i = 0, args = tagCtx.args, // [events,] [selector,] handler l = args.length; for (; i<l && !$isFunction(args[i]); i++); // Handler is first arg of type function tag._hi = l>i && i+1; // handler index if (tag._.inline) { tag.attr = HTML; content = tagCtx.content; content = content && content.markup; props = tagCtx.props; elemProp = props.elem || "button"; classProp = props["class"]; tag.template = rFirstElem.exec(content) && content || "<" + elemProp + (classProp ? ' class="' + classProp + '">' : ">") + ($.trim(content) || props.label || tagCtx.params.args[i] || "noop") + "</" + elemProp + ">"; } }, render: function() { var tagCtx = this.tagCtx; return tagCtx.render(tagCtx.view, true); // no arg, so renders against parentView.data }, onAfterLink: function(tagCtx, linkCtx) { var handler, params, tag = this, i = tag._hi, args = tagCtx.args, // [events,] [selector,] handler l = args.length, props = tagCtx.props, data = props.data, view = tagCtx.view, contextOb = props.context; // Context ('this' pointer) for attached handler if (i) { // There is a handler handler = args[i-1]; params = args.slice(i); // Subsequent args are params args = args.slice(0, i-1); // Preceding args (if any) are events and selector tag._sel = args[1]; tag.activeElem = tag.activeElem || (tag._.inline ? (tag._elCnt && error('Use data-link="{on...}"'), tag._sel = undefined, tag.contents(true, args[1] || "*")) : $(linkCtx.elem)); if (!contextOb) { // Get the path for the preceding object (context object) of handler (which is the last arg), compile function // to return that context object, and run compiled function against data contextOb = /^(.*)[\.^][\w$]+$/.exec(tagCtx.params.args.slice(-params.length - 1)[0]); contextOb = contextOb && $sub.tmplFn("{:" + contextOb[1] + "}", view.tmpl, true)(linkCtx.data, view); } if (tag._evs) { tag.onDispose(); } tag.activeElem.on( tag._evs = args[0] || "click", // events defaults to "click" tag._sel, data == undefined ? null : data, tag._hlr = function(ev) { return handler.apply(contextOb || linkCtx.data, [].concat( params, // e.g. par1, par2 ev, {change: ev.type, view: view, linkCtx: linkCtx}, params.slice.call(arguments, 1) // If triggering event (e.g. jsv-domchange) has additional arguments after ev, pass them too )); // for {on 'click' handler par1 par2} use handler(par1, par2, ev, domchangeEventArgs) // for {on 'jsv-domchange' handler par1 par2} use handler(par1, par2, ev, domchangeEventArgs, tagCtx, linkCtx, observableEventArgs) } ); } }, onUpdate: function() { return false; }, onDispose: function() { this.activeElem.off(this._evs, this._sel, this._hlr); }, flow: true, dataBoundOnly: true }); $extend($tags["for"], { //onUpdate: function(ev, eventArgs, tagCtxs) { //Consider adding filtering for perf optimization. However the below prevents update on some scenarios which _should_ update - namely when there is another array on which for also depends. //var i, l, tci, prevArg; //for (tci = 0; (prevArg = this.tagCtxs[tci]) && prevArg.args.length; tci++) { // if (prevArg.args[0] !== tagCtxs[tci].args[0]) { // return true; // } //} //return false; //}, onArrayChange: function(ev, eventArgs, tagCtx, linkCtx) { var arrayView, target = ev.target, targetLength = target.length, tag = this, change = eventArgs.change; if (tag._.noVws // Child views not supported because target is not html - e.g. data-link="title{for ...}" || tag.tagCtxs[1] && ( // There is an {{else}} change === "insert" && targetLength === eventArgs.items.length // inserting, and new length is same as inserted length, so going from 0 to n || change === "remove" && !targetLength // removing , and new length 0, so going from n to 0 )) { tag.refresh(); } else { for (arrayView in tag._.arrVws) { arrayView = tag._.arrVws[arrayView]; if (arrayView.data === target) { arrayView._.onArrayChange.apply(arrayView, arguments); } } } tag.domChange(tagCtx, linkCtx, eventArgs); ev.done = true; }, onAfterLink: function(tagCtx, linkCtx) { var i, arrHandler, arrBinding, data, tag = this, arrayBindings = tag._ars || {}, tagCtxs = tag.tagCtxs, l = tagCtxs.length, selected = tag.selected || 0; for (i = 0; i <= selected; i++) { tagCtx = tagCtxs[i]; // loop through tagCtxs up to selected data = tagCtx.map ? tagCtx.map.tgt // 'data' is mapped data : tagCtx.args.length ? tagCtx.args[0] // or args[0] : tagCtx.view.data; // or defaults to current data. if ((arrBinding = arrayBindings[i]) && data !== arrBinding[0]) { // Is there previous array data on this tagCtx, different from new data $observe(arrBinding[0], arrBinding[1], true); //unobserve previous array delete arrayBindings[i]; } if (!arrayBindings[i] && $isArray(data)) { $observe(data, arrHandler = function(ev, eventArgs) { var tagCt = tagCtx; tag.onArrayChange(ev, eventArgs, tagCt, linkCtx); }); arrayBindings[i] = [data, arrHandler]; // Store array data and arrayChangeHandler on tag._ars[i] } } for (i = selected + 1; i < l; i++) { // If there were previous bindings on later tagCtxs, remove them if (arrBinding = arrayBindings[i]) { $observe(arrBinding[0], arrBinding[1], true); //unobserve previous binding delete arrayBindings[i]; } } tag._ars = arrayBindings; }, onDispose: function() { var l, tag = this; for (l in tag._ars) { $observe(tag._ars[l][0], tag._ars[l][1], true); //unobserve } } }); $extend($tags["if"], { onUpdate: function(ev, eventArgs, tagCtxs) { var tci, prevArg, different; for (tci = 0; (prevArg = this.tagCtxs[tci]); tci++) { different = prevArg.props.tmpl !== tagCtxs[tci].props.tmpl || prevArg.args.length && !(prevArg = prevArg.args[0]) !== !tagCtxs[tci].args[0]; if ((!this.convert && !!prevArg) || different) { return different; // If there is not a change of template, and there is no converter, and newArg and prevArg are both truthy, return false to cancel update. // (Even if values on later elses are different, we still don't want to update, since rendered output would be unchanged) // If newArg and prevArg are different, return true, to update // If newArg and prevArg are both falsey, move to the next {{else ...}} } } // Boolean value of all args are unchanged (falsey), so return false to cancel update return false; }, onAfterLink: function(tagCtx, linkCtx, eventArgs) { if (eventArgs) { this.domChange(tagCtx, linkCtx, eventArgs); } } }); function observeProps(map, ev, eventArgs) { if (eventArgs.change === "set") { var target = map.tgt, l = target.length; while (l--) { if (target[l].key === eventArgs.path) { break; } } if (l === -1) { if (eventArgs.path && !eventArgs.remove) { $observable(target).insert({key: eventArgs.path, prop: eventArgs.value}); } } else if (eventArgs.remove) { $observable(target).remove(l); } else { $observable(target[l]).setProperty("prop", eventArgs.value); } } } function observeMappedProps(map, ev, eventArgs) { var item, source = map.src, change = eventArgs.change; if (change === "set") { if (eventArgs.path === "prop") { $observable(source).setProperty(ev.target.key, eventArgs.value); } else { // path === "key" $observable(source).removeProperty(eventArgs.oldValue); // When key is modified observably, remove old one and set new one $observable(source).setProperty(eventArgs.value, ev.target.prop); } } else if (change === "remove") { item = eventArgs.items[0]; $observable(source).removeProperty(item.key); delete source[item.key]; } else if (change === "insert") { item = eventArgs.items[0]; if (item.key) { $observable(source).setProperty(item.key, item.prop); } } } function shallowArrayFilter(allPath /*, object, parentObs*/) { // Filter used by {{props}} for the mappedProps target array return allPath.indexOf(".") < 0; } $tags("props", { baseTag: "for", dataMap: $views.map({ getTgt: $tags.props.dataMap.getTgt, obsSrc: observeProps, obsTgt: observeMappedProps, tgtFlt: shallowArrayFilter }), flow: true }); //======================== // Extend jQuery namespace //======================== $extend($, { //======================= // jQuery $.view() plugin //======================= view: $view = function(node, inner, type) { // $.view() returns top view // $.view(node) returns view that contains node // $.view(selector) returns view that contains first selected element // $.view(nodeOrSelector, type) returns nearest containing view of given type // $.view(nodeOrSelector, "root") returns root containing view (child of top view) // $.view(nodeOrSelector, true, type) returns nearest inner (contained) view of given type function getInnerView(nd, isVl) { if (nd) { vwInfos = viewInfos(nd, isVl, rOpenViewMarkers); for (j = 0, k = vwInfos.length; j < k; j++) { if ((view = viewStore[vwInfos[j].id]) && (view = view && type ? view.get(true, type) : view)) { break; } } } } if (inner !== !!inner) { // inner not boolean, so this is view(nodeOrSelector, type) type = inner; inner = undefined; } var view, vwInfos, i, j, k, l, elems, level = 0, body = document.body; if (node && node !== body && topView._.useKey > 1) { // Perf optimization for common cases node = "" + node === node ? $(node)[0] : node.jquery ? node[0] : node; if (node) { if (inner) { getInnerView(node._df, true); if (!view) { // Treat supplied node as a container element and return the first view encountered. elems = qsa ? node.querySelectorAll(bindElsSel) : $(bindElsSel, node).get(); l = elems.length; for (i = 0; !view && i < l; i++) { getInnerView(elems[i]); } } return view; } while (node) { // Move back through siblings and up through parents to find preceding node which is a _prv (prevNode) // script marker node for a non-element-content view, or a _prv (first node) for an elCnt view if (vwInfos = viewInfos(node, undefined, rViewMarkers)) { l = vwInfos.length; while (l--) { view = vwInfos[l]; if (view.open) { if (level < 1) { view = viewStore[view.id]; return view && type ? view.get(type) : view || topView; } level--; } else { // level starts at zero. If we hit a view.close, then we move level to 1, and we don't return a view until // we are back at level zero (or a parent view with level < 0) level++; } } } node = node.previousSibling || node.parentNode; } } } return topView; }, link: $link, unlink: $unlink, //===================== // override $.cleanData //===================== cleanData: function(elems) { if (elems.length && isCleanCall) { // Remove JsViews bindings. Also, remove from the DOM any corresponding script marker nodes clean(elems); } oldCleanData.apply($, arguments); } }); // Possible future addition - e.g. for ckeditor tag control //$views.utility = { // validate: function(html) { // try { // topView.link(undefined, document.createElement("div"), undefined, undefined, html, undefined, undefined, 1); // } // catch (e) { // return e.message; // } // } //}; //=============================== // Extend jQuery instance plugins //=============================== $extend($.fn, { link: function(expr, from, context, noIteration, parentView, prevNode, nextNode) { return $link(expr, this, from, context, noIteration, parentView, prevNode, nextNode); }, unlink: function() { return $unlink(this); }, view: function(inner, type) { return $view(this[0], inner, type); } }); //============================================================================== // Override jQuery methods that call our overridden cleanData, for disposal etc. //============================================================================== $.each([HTML, "replaceWith", "empty", "remove"], function(i, name) { var oldFn = $.fn[name]; $.fn[name] = function() { var result; isCleanCall = 1; // Make sure cleanData does disposal only when coming from these calls. try { result = oldFn.apply(this, arguments); } finally { isCleanCall = 0; } return result; }; }); //=============== // Extend topView //=============== addLinkMethods($extend(topView = $sub.topView, {tmpl: {links: {}}})); viewStore = {0: topView}; // Top-level view //========================= // Extend $.views.settings //========================= oldAdvSet = $sub.advSet; $sub.advSet = function() { // refresh advanced settings oldAdvSet(); global._jsv = $subSettingsAdvanced._jsv ? $extend(global._jsv || {}, { // create global _jsv, for accessing views, etc views: viewStore, bindings: bindingStore }) : undefined; // In IE8 cannot do delete global._jsv $viewsLinkAttr = $subSettingsAdvanced.linkAttr; linkViewsSel = bindElsSel + ",[" + $viewsLinkAttr + "]"; wrapMap = $subSettingsAdvanced._wm; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; }; $viewsSettings.advanced({ linkAttr: "data-link", useViews: false, noValidate: false, // wrapMap provide appropriate wrappers for inserting innerHTML, used in insertBefore // We have to close these tags to support XHTML (#13200) // TODO investigate whether more recent jQuery implementation using wrapMap in domManip/$().html() etc. is better optimized now... _wm: { option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], area: [1, "<map>", "</map>"], param: [1, "<object>", "</object>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], svg_ns: [1, "<svg>", "</svg>"], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. div: $.support.htmlSerialize ? [0, "", ""] : [1, "X<div>", "</div>"] }, _fe: { input: { from: inputAttrib, to: "value" }, textarea: valueBinding, select: valueBinding, optgroup: { to: "label" } } }); return $; }, window));
'use strict'; module.exports = function(Chart) { var helpers = Chart.helpers; // Default config for a category scale var defaultConfig = { position: 'bottom' }; var DatasetScale = Chart.Scale.extend({ /** * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those * else fall back to data.labels * @private */ getLabels: function() { var data = this.chart.data; return (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels; }, // Implement this so that determineDataLimits: function() { var me = this; var labels = me.getLabels(); me.minIndex = 0; me.maxIndex = labels.length - 1; var findIndex; if (me.options.ticks.min !== undefined) { // user specified min value findIndex = helpers.indexOf(labels, me.options.ticks.min); me.minIndex = findIndex !== -1 ? findIndex : me.minIndex; } if (me.options.ticks.max !== undefined) { // user specified max value findIndex = helpers.indexOf(labels, me.options.ticks.max); me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex; } me.min = labels[me.minIndex]; me.max = labels[me.maxIndex]; }, buildTicks: function() { var me = this; var labels = me.getLabels(); // If we are viewing some subset of labels, slice the original array me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1); }, getLabelForIndex: function(index, datasetIndex) { var me = this; var data = me.chart.data; var isHorizontal = me.isHorizontal(); if ((data.xLabels && isHorizontal) || (data.yLabels && !isHorizontal)) { return me.getRightValue(data.datasets[datasetIndex].data[index]); } return me.ticks[index]; }, // Used to get data value locations. Value can either be an index or a numerical value getPixelForValue: function(value, index, datasetIndex, includeOffset) { var me = this; // 1 is added because we need the length but we have the indexes var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); if (value !== undefined && isNaN(index)) { var labels = me.getLabels(); var idx = labels.indexOf(value); index = idx !== -1 ? idx : index; } if (me.isHorizontal()) { var innerWidth = me.width - (me.paddingLeft + me.paddingRight); var valueWidth = innerWidth / offsetAmt; var widthOffset = (valueWidth * (index - me.minIndex)) + me.paddingLeft; if (me.options.gridLines.offsetGridLines && includeOffset || me.maxIndex === me.minIndex && includeOffset) { widthOffset += (valueWidth / 2); } return me.left + Math.round(widthOffset); } var innerHeight = me.height - (me.paddingTop + me.paddingBottom); var valueHeight = innerHeight / offsetAmt; var heightOffset = (valueHeight * (index - me.minIndex)) + me.paddingTop; if (me.options.gridLines.offsetGridLines && includeOffset) { heightOffset += (valueHeight / 2); } return me.top + Math.round(heightOffset); }, getPixelForTick: function(index, includeOffset) { return this.getPixelForValue(this.ticks[index], index + this.minIndex, null, includeOffset); }, getValueForPixel: function(pixel) { var me = this; var value; var offsetAmt = Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); var horz = me.isHorizontal(); var innerDimension = horz ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom); var valueDimension = innerDimension / offsetAmt; pixel -= horz ? me.left : me.top; if (me.options.gridLines.offsetGridLines) { pixel -= (valueDimension / 2); } pixel -= horz ? me.paddingLeft : me.paddingTop; if (pixel <= 0) { value = 0; } else { value = Math.round(pixel / valueDimension); } return value; }, getBasePixel: function() { return this.bottom; } }); Chart.scaleService.registerScaleType('category', DatasetScale, defaultConfig); };
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.0.0-alpha.4 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var logger_1 = require("./logger"); var context_1 = require("./context/context"); var context_2 = require("./context/context"); var ExpressionService = (function () { function ExpressionService() { this.expressionToFunctionCache = {}; } ExpressionService.prototype.setBeans = function (loggerFactory) { this.logger = loggerFactory.create('ExpressionService'); }; ExpressionService.prototype.evaluate = function (expression, params) { try { var javaScriptFunction = this.createExpressionFunction(expression); var result = javaScriptFunction(params.value, params.context, params.node, params.data, params.colDef, params.rowIndex, params.api, params.getValue); return result; } catch (e) { // the expression failed, which can happen, as it's the client that // provides the expression. so print a nice message this.logger.log('Processing of the expression failed'); this.logger.log('Expression = ' + expression); this.logger.log('Exception = ' + e); return null; } }; ExpressionService.prototype.createExpressionFunction = function (expression) { // check cache first if (this.expressionToFunctionCache[expression]) { return this.expressionToFunctionCache[expression]; } // if not found in cache, return the function var functionBody = this.createFunctionBody(expression); var theFunction = new Function('x, ctx, node, data, colDef, rowIndex, api, getValue', functionBody); // store in cache this.expressionToFunctionCache[expression] = theFunction; return theFunction; }; ExpressionService.prototype.createFunctionBody = function (expression) { // if the expression has the 'return' word in it, then use as is, // if not, then wrap it with return and ';' to make a function if (expression.indexOf('return') >= 0) { return expression; } else { return 'return ' + expression + ';'; } }; __decorate([ __param(0, context_2.Qualifier('loggerFactory')), __metadata('design:type', Function), __metadata('design:paramtypes', [logger_1.LoggerFactory]), __metadata('design:returntype', void 0) ], ExpressionService.prototype, "setBeans", null); ExpressionService = __decorate([ context_1.Bean('expressionService'), __metadata('design:paramtypes', []) ], ExpressionService); return ExpressionService; })(); exports.ExpressionService = ExpressionService;
'use strict'; angular.module('ngAudio', []) .directive('ngAudio', ['$compile', '$q', 'ngAudio', function($compile, $q, ngAudio) { return { restrict: 'AEC', scope: { volume: '=', start: '=', currentTime: '=', loop: '=', clickPlay: '=' }, controller: function($scope, $attrs, $element, $timeout) { var audio = ngAudio.load($attrs.ngAudio); $scope.$audio = audio; audio.unbind(); $element.on('click', function() { if ($scope.clickPlay === false) { return; } audio.audio.play(); audio.volume = $scope.volume || audio.volume; audio.loop = $scope.loop; audio.currentTime = $scope.start || 0; }); } }; }]) .directive('ngAudioHover', ['$compile', '$q', 'ngAudio', function($compile, $q, ngAudio) { return { restrict: 'AEC', controller: function($scope, $attrs, $element, $timeout) { var audio = ngAudio.load($attrs.ngAudioHover); $element.on('mouseover rollover hover', function() { audio.audio.play(); audio.volume = $attrs.volumeHover || audio.volume; audio.loop = $attrs.loop; audio.currentTime = $attrs.startHover || 0; }); } }; }]) .service('localAudioFindingService', ['$q', function($q) { this.find = function(id) { var deferred = $q.defer(); var $sound = document.getElementById(id); if ($sound) { deferred.resolve($sound); } else { deferred.reject(id); } return deferred.promise; }; }]) .service('remoteAudioFindingService', ['$q', function($q) { this.find = function(url) { var deferred = $q.defer(); var audio = new Audio(); audio.addEventListener('error', function() { deferred.reject(); }); audio.addEventListener('loadstart', function() { deferred.resolve(audio); }); // bugfix for chrome... setTimeout(function() { audio.src = url; }, 1); return deferred.promise; }; }]) .service('cleverAudioFindingService', ['$q', 'localAudioFindingService', 'remoteAudioFindingService', function($q, localAudioFindingService, remoteAudioFindingService) { this.find = function(id) { var deferred = $q.defer(); id = id.replace('|', '/'); localAudioFindingService.find(id) .then(deferred.resolve, function() { return remoteAudioFindingService.find(id); }) .then(deferred.resolve, deferred.reject); return deferred.promise; }; }]) .value('ngAudioGlobals', { muting: false, songmuting: false, performance: 25, unlock: true }) .factory('NgAudioObject', ['cleverAudioFindingService', '$rootScope', '$interval', '$timeout', 'ngAudioGlobals', function(cleverAudioFindingService, $rootScope, $interval, $timeout, ngAudioGlobals) { return function(id) { if (ngAudioGlobals.unlock) { window.addEventListener("click",function twiddle(){ audio.play(); audio.pause(); window.removeEventListener("click",twiddle); }); } var $audioWatch, $willPlay = false, $willPause = false, $willRestart = false, $willChangePlaybackRate = false, $newPlaybackRate = false, $volumeToSet, $looping, $isMuting = false, $observeProperties = true, audio, audioObject = this; this.id = id; this.safeId = id.replace('/', '|'); this.loop = 0; this.unbind = function() { $observeProperties = false; }; this.play = function() { $willPlay = true; }; this.pause = function() { $willPause = true; }; this.restart = function() { $willRestart = true; }; this.stop = function() { this.restart(); }; this.setVolume = function(volume) { $volumeToSet = volume; }; this.setPlaybackRate = function(rate) { $newPlaybackRate = rate; $willChangePlaybackRate = true; }; this.setMuting = function(muting) { $isMuting = muting; }; this.setProgress = function(progress) { if (audio && audio.duration) { audio.currentTime = audio.duration * progress; } }; this.setCurrentTime = function(currentTime) { if (audio && audio.duration) { audio.currentTime = currentTime; } }; function $setWatch() { $audioWatch = $rootScope.$watch(function() { return { volume: audioObject.volume, currentTime: audioObject.currentTime, progress: audioObject.progress, muting: audioObject.muting, loop: audioObject.loop, playbackRate: audioObject.playbackRate }; }, function(newValue, oldValue) { if (newValue.currentTime !== oldValue.currentTime) { audioObject.setCurrentTime(newValue.currentTime); } if (newValue.progress !== oldValue.progress) { audioObject.setProgress(newValue.progress); } if (newValue.volume !== oldValue.volume) { audioObject.setVolume(newValue.volume); } if (newValue.playbackRate !== oldValue.playbackRate) { audioObject.setPlaybackRate(newValue.playbackRate); } $looping = newValue.loop; if (newValue.muting !== oldValue.muting) { audioObject.setMuting(newValue.muting); } }, true); } cleverAudioFindingService.find(id) .then(function(nativeAudio) { audio = nativeAudio; audio.addEventListener('canplay', function() { audioObject.canPlay = true; }); }, function(error) { audioObject.error = true; console.warn(error); }); $interval(function() { if ($audioWatch) { $audioWatch(); } if (audio) { if ($isMuting || ngAudioGlobals.isMuting) { audio.volume = 0; } else { audio.volume = audioObject.volume !== undefined ? audioObject.volume : 1; } if ($willPlay) { audio.play(); $willPlay = false; } if ($willRestart) { audio.pause(); audio.currentTime = 0; $willRestart = false; } if ($willPause) { audio.pause(); $willPause = false; } if ($willChangePlaybackRate) { audio.playbackRate = $newPlaybackRate; $willChangePlaybackRate = false; } if ($volumeToSet) { audio.volume = $volumeToSet; $volumeToSet = undefined; } if ($observeProperties) { audioObject.currentTime = audio.currentTime; audioObject.duration = audio.duration; audioObject.remaining = audio.duration - audio.currentTime; audioObject.progress = audio.currentTime / audio.duration; audioObject.paused = audio.paused; audioObject.src = audio.src; if ($looping && audioObject.currentTime >= audioObject.duration) { if ($looping !== true) { $looping--; audioObject.loop--; // if (!$looping) return; } audioObject.setCurrentTime(0); audioObject.play(); } } if (!$isMuting && !ngAudioGlobals.isMuting) { audioObject.volume = audio.volume; } audioObject.audio = audio; } $setWatch(); }, ngAudioGlobals.performance); }; }]) .service('ngAudio', ['NgAudioObject', 'ngAudioGlobals', function(NgAudioObject, ngAudioGlobals) { this.play = function(id) { var audio = new NgAudioObject(id); audio.play(); return audio; }; this.load = function(id) { return new NgAudioObject(id); }; this.mute = function() { ngAudioGlobals.muting = true; }; this.unmute = function() { ngAudioGlobals.muting = false; }; this.toggleMute = function() { ngAudioGlobals.muting = !ngAudioGlobals.muting; }; }]);
/* This file is part of Ext JS 3.4 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-04-03 15:07:25 */ Ext.ns('Ext.ux.form'); /** * @class Ext.ux.form.FileUploadField * @extends Ext.form.TextField * Creates a file upload field. * @xtype fileuploadfield */ Ext.ux.form.FileUploadField = Ext.extend(Ext.form.TextField, { /** * @cfg {String} buttonText The button text to display on the upload button (defaults to * 'Browse...'). Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text * value will be used instead if available. */ buttonText: 'Browse...', /** * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible * text field (defaults to false). If true, all inherited TextField members will still be available. */ buttonOnly: false, /** * @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field * (defaults to 3). Note that this only applies if {@link #buttonOnly} = false. */ buttonOffset: 3, /** * @cfg {Object} buttonCfg A standard {@link Ext.Button} config object. */ // private readOnly: true, /** * @hide * @method autoSize */ autoSize: Ext.emptyFn, // private initComponent: function(){ Ext.ux.form.FileUploadField.superclass.initComponent.call(this); this.addEvents( /** * @event fileselected * Fires when the underlying file input field's value has changed from the user * selecting a new file from the system file selection dialog. * @param {Ext.ux.form.FileUploadField} this * @param {String} value The file value returned by the underlying file input field */ 'fileselected' ); }, // private onRender : function(ct, position){ Ext.ux.form.FileUploadField.superclass.onRender.call(this, ct, position); this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'}); this.el.addClass('x-form-file-text'); this.el.dom.removeAttribute('name'); this.createFileInput(); var btnCfg = Ext.applyIf(this.buttonCfg || {}, { text: this.buttonText }); this.button = new Ext.Button(Ext.apply(btnCfg, { renderTo: this.wrap, cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '') })); if(this.buttonOnly){ this.el.hide(); this.wrap.setWidth(this.button.getEl().getWidth()); } this.bindListeners(); this.resizeEl = this.positionEl = this.wrap; }, bindListeners: function(){ this.fileInput.on({ scope: this, mouseenter: function() { this.button.addClass(['x-btn-over','x-btn-focus']) }, mouseleave: function(){ this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click']) }, mousedown: function(){ this.button.addClass('x-btn-click') }, mouseup: function(){ this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click']) }, change: function(){ var v = this.fileInput.dom.value; this.setValue(v); this.fireEvent('fileselected', this, v); } }); }, createFileInput : function() { this.fileInput = this.wrap.createChild({ id: this.getFileInputId(), name: this.name||this.getId(), cls: 'x-form-file', tag: 'input', type: 'file', size: 1 }); }, reset : function(){ if (this.rendered) { this.fileInput.remove(); this.createFileInput(); this.bindListeners(); } Ext.ux.form.FileUploadField.superclass.reset.call(this); }, // private getFileInputId: function(){ return this.id + '-file'; }, // private onResize : function(w, h){ Ext.ux.form.FileUploadField.superclass.onResize.call(this, w, h); this.wrap.setWidth(w); if(!this.buttonOnly){ var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset; this.el.setWidth(w); } }, // private onDestroy: function(){ Ext.ux.form.FileUploadField.superclass.onDestroy.call(this); Ext.destroy(this.fileInput, this.button, this.wrap); }, onDisable: function(){ Ext.ux.form.FileUploadField.superclass.onDisable.call(this); this.doDisable(true); }, onEnable: function(){ Ext.ux.form.FileUploadField.superclass.onEnable.call(this); this.doDisable(false); }, // private doDisable: function(disabled){ this.fileInput.dom.disabled = disabled; this.button.setDisabled(disabled); }, // private preFocus : Ext.emptyFn, // private alignErrorIcon : function(){ this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]); } }); Ext.reg('fileuploadfield', Ext.ux.form.FileUploadField); // backwards compat Ext.form.FileUploadField = Ext.ux.form.FileUploadField;
/** * Tabslet | tabs jQuery plugin * * @copyright Copyright 2015, Dimitris Krestos * @license Apache License, Version 2.0 (http://www.opensource.org/licenses/apache2.0.php) * @link http://vdw.staytuned.gr * @version v1.6.0 */ /* Sample html structure <div class='tabs'> <ul class='horizontal'> <li><a href="#tab-1">Tab 1</a></li> <li><a href="#tab-2">Tab 2</a></li> <li><a href="#tab-3">Tab 3</a></li> </ul> <div id='tab-1'></div> <div id='tab-2'></div> <div id='tab-3'></div> </div> OR <div class='tabs'> <ul class='horizontal'> <li><a href="#tab-1">Tab 1</a></li> <li><a href="#tab-2">Tab 2</a></li> <li><a href="#tab-3">Tab 3</a></li> </ul> </div> <div id='tabs_container'> <div id='tab-1'></div> <div id='tab-2'></div> <div id='tab-3'></div> </div> */ ;(function($, window, undefined) { "use strict"; $.fn.tabslet = function(options) { var defaults = { mouseevent: 'click', attribute: 'href', animation: false, autorotate: false, deeplinking: false, pauseonhover: true, delay: 2000, active: 1, container: false, controls: { prev: '.prev', next: '.next' } }; var options = $.extend(defaults, options); return this.each(function() { var $this = $(this), _cache_li = [], _cache_div = []; var _container = options.container ? $(options.container) : $this; var _tabs = _container.find('> div'); // Caching _tabs.each(function() { _cache_div.push($(this).css('display')); }); // Autorotate var elements = $this.find('> ul li'), i = options.active - 1; // ungly if ( !$this.data( 'tabslet-init' ) ) { $this.data( 'tabslet-init', true ); // Ungly overwrite options.mouseevent = $this.data('mouseevent') || options.mouseevent; options.attribute = $this.data('attribute') || options.attribute; options.animation = $this.data('animation') || options.animation; options.autorotate = $this.data('autorotate') || options.autorotate; options.deeplinking = $this.data('deeplinking') || options.deeplinking; options.pauseonhover = $this.data('pauseonhover') || options.pauseonhover; options.delay = $this.data('delay') || options.delay; options.active = options.deeplinking ? deep_link() : ( $this.data('active') || options.active ) options.container = $this.data('container') || options.container; _tabs.hide(); if ( options.active ) { _tabs.eq(options.active - 1).show(); $this.find('> ul li').eq(options.active - 1).addClass('active'); } var fn = eval( function() { $(this).trigger('_before'); $this.find('> ul li').removeClass('active'); $(this).addClass('active'); _tabs.hide(); i = elements.index($(this)); var currentTab = $(this).find('a').attr(options.attribute); if (options.animation) { _container.find(currentTab).animate( { opacity: 'show' }, 'slow', function() { $(this).trigger('_after'); }); } else { _container.find(currentTab).show(); $(this).trigger('_after'); } return false; } ); var init = eval("$this.find('> ul li')." + options.mouseevent + "(fn)"); init; var t; var forward = function() { i = ++i % elements.length; // wrap around options.mouseevent == 'hover' ? elements.eq(i).trigger('mouseover') : elements.eq(i).click(); if (options.autorotate) { clearTimeout(t); t = setTimeout(forward, options.delay); $this.mouseover(function () { if (options.pauseonhover) clearTimeout(t); }); } } if (options.autorotate) { t = setTimeout(forward, options.delay); $this.hover(function() { if (options.pauseonhover) clearTimeout(t); }, function() { t = setTimeout(forward, options.delay); }); if (options.pauseonhover) $this.on( "mouseleave", function() { clearTimeout(t); t = setTimeout(forward, options.delay); }); } function deep_link() { var ids = []; elements.find('a').each(function() { ids.push($(this).attr(options.attribute)); }); var index = $.inArray(location.hash, ids) if (index > -1) { return index + 1 } else { return ($this.data('active') || options.active) } } var move = function(direction) { if (direction == 'forward') i = ++i % elements.length; // wrap around if (direction == 'backward') i = --i % elements.length; // wrap around elements.eq(i).click(); } $this.find(options.controls.next).click(function() { move('forward'); }); $this.find(options.controls.prev).click(function() { move('backward'); }); $this.on ('destroy', function() { $(this) .removeData() .find('> ul li').each( function(i) { $(this).removeClass('active'); }); _tabs.each( function(i) { $(this).removeAttr('style').css( 'display', _cache_div[i] ); }); }); } }); }; $(document).ready(function () { $('[data-toggle="tabslet"]').tabslet(); }); })(jQuery);
"use strict"; exports.__esModule = true; exports.AnyTypeAnnotation = AnyTypeAnnotation; exports.ArrayTypeAnnotation = ArrayTypeAnnotation; exports.BooleanTypeAnnotation = BooleanTypeAnnotation; exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; exports.DeclareClass = DeclareClass; exports.DeclareFunction = DeclareFunction; exports.DeclareModule = DeclareModule; exports.DeclareVariable = DeclareVariable; exports.FunctionTypeAnnotation = FunctionTypeAnnotation; exports.FunctionTypeParam = FunctionTypeParam; exports.InterfaceExtends = InterfaceExtends; exports._interfaceish = _interfaceish; exports.InterfaceDeclaration = InterfaceDeclaration; exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; exports.MixedTypeAnnotation = MixedTypeAnnotation; exports.NullableTypeAnnotation = NullableTypeAnnotation; exports.NumberTypeAnnotation = NumberTypeAnnotation; exports.StringLiteralTypeAnnotation = StringLiteralTypeAnnotation; exports.StringTypeAnnotation = StringTypeAnnotation; exports.TupleTypeAnnotation = TupleTypeAnnotation; exports.TypeofTypeAnnotation = TypeofTypeAnnotation; exports.TypeAlias = TypeAlias; exports.TypeAnnotation = TypeAnnotation; exports.TypeParameterInstantiation = TypeParameterInstantiation; exports.ObjectTypeAnnotation = ObjectTypeAnnotation; exports.ObjectTypeCallProperty = ObjectTypeCallProperty; exports.ObjectTypeIndexer = ObjectTypeIndexer; exports.ObjectTypeProperty = ObjectTypeProperty; exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; exports.UnionTypeAnnotation = UnionTypeAnnotation; exports.TypeCastExpression = TypeCastExpression; exports.VoidTypeAnnotation = VoidTypeAnnotation; // istanbul ignore next function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _types = require("../../types"); /** * Prints AnyTypeAnnotation. */ var t = _interopRequireWildcard(_types); function AnyTypeAnnotation() { this.push("any"); } /** * Prints ArrayTypeAnnotation, prints elementType. */ function ArrayTypeAnnotation(node, print) { print.plain(node.elementType); this.push("["); this.push("]"); } /** * Prints BooleanTypeAnnotation. */ function BooleanTypeAnnotation(node) { this.push("bool"); } /** * Prints BooleanLiteralTypeAnnotation. */ function BooleanLiteralTypeAnnotation(node) { this.push(node.value ? "true" : "false"); } /** * Prints DeclareClass, prints node. */ function DeclareClass(node, print) { this.push("declare class "); this._interfaceish(node, print); } /** * Prints DeclareFunction, prints id and id.typeAnnotation. */ function DeclareFunction(node, print) { this.push("declare function "); print.plain(node.id); print.plain(node.id.typeAnnotation.typeAnnotation); this.semicolon(); } /** * Prints DeclareModule, prints id and body. */ function DeclareModule(node, print) { this.push("declare module "); print.plain(node.id); this.space(); print.plain(node.body); } /** * Prints DeclareVariable, prints id and id.typeAnnotation. */ function DeclareVariable(node, print) { this.push("declare var "); print.plain(node.id); print.plain(node.id.typeAnnotation); this.semicolon(); } /** * Prints FunctionTypeAnnotation, prints typeParameters, params, and rest. */ function FunctionTypeAnnotation(node, print, parent) { print.plain(node.typeParameters); this.push("("); print.list(node.params); if (node.rest) { if (node.params.length) { this.push(","); this.space(); } this.push("..."); print.plain(node.rest); } this.push(")"); // this node type is overloaded, not sure why but it makes it EXTREMELY annoying if (parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") { this.push(":"); } else { this.space(); this.push("=>"); } this.space(); print.plain(node.returnType); } /** * Prints FunctionTypeParam, prints name and typeAnnotation, handles optional. */ function FunctionTypeParam(node, print) { print.plain(node.name); if (node.optional) this.push("?"); this.push(":"); this.space(); print.plain(node.typeAnnotation); } /** * Prints InterfaceExtends, prints id and typeParameters. */ function InterfaceExtends(node, print) { print.plain(node.id); print.plain(node.typeParameters); } /** * Alias InterfaceExtends printer as ClassImplements, * and InterfaceExtends printer as GenericTypeAnnotation. */ exports.ClassImplements = InterfaceExtends; /** * Prints interface-like node, prints id, typeParameters, extends, and body. */ exports.GenericTypeAnnotation = InterfaceExtends; function _interfaceish(node, print) { print.plain(node.id); print.plain(node.typeParameters); if (node["extends"].length) { this.push(" extends "); print.join(node["extends"], { separator: ", " }); } this.space(); print.plain(node.body); } /** * Prints InterfaceDeclaration, prints node. */ function InterfaceDeclaration(node, print) { this.push("interface "); this._interfaceish(node, print); } /** * Prints IntersectionTypeAnnotation, prints types. */ function IntersectionTypeAnnotation(node, print) { print.join(node.types, { separator: " & " }); } /** * Prints MixedTypeAnnotation. */ function MixedTypeAnnotation() { this.push("mixed"); } /** * Prints NullableTypeAnnotation, prints typeAnnotation. */ function NullableTypeAnnotation(node, print) { this.push("?"); print.plain(node.typeAnnotation); } /** * Prints NumberLiteralTypeAnnotation, prints value. */ var _types2 = require("./types"); /** * Prints NumberTypeAnnotation. */ exports.NumberLiteralTypeAnnotation = _types2.Literal; function NumberTypeAnnotation() { this.push("number"); } /** * Prints StringLiteralTypeAnnotation, prints value. */ function StringLiteralTypeAnnotation(node) { this.push(this._stringLiteral(node.value)); } /** * Prints StringTypeAnnotation. */ function StringTypeAnnotation() { this.push("string"); } /** * Prints TupleTypeAnnotation, prints types. */ function TupleTypeAnnotation(node, print) { this.push("["); print.join(node.types, { separator: ", " }); this.push("]"); } /** * Prints TypeofTypeAnnotation, prints argument. */ function TypeofTypeAnnotation(node, print) { this.push("typeof "); print.plain(node.argument); } /** * Prints TypeAlias, prints id, typeParameters, and right. */ function TypeAlias(node, print) { this.push("type "); print.plain(node.id); print.plain(node.typeParameters); this.space(); this.push("="); this.space(); print.plain(node.right); this.semicolon(); } /** * Prints TypeAnnotation, prints typeAnnotation, handles optional. */ function TypeAnnotation(node, print) { this.push(":"); this.space(); if (node.optional) this.push("?"); print.plain(node.typeAnnotation); } /** * Prints TypeParameterInstantiation, prints params. */ function TypeParameterInstantiation(node, print) { this.push("<"); print.join(node.params, { separator: ", ", iterator: function iterator(node) { print.plain(node.typeAnnotation); } }); this.push(">"); } /** * Alias TypeParameterInstantiation printer as TypeParameterDeclaration */ exports.TypeParameterDeclaration = TypeParameterInstantiation; /** * Prints ObjectTypeAnnotation, prints properties, callProperties, and indexers. */ function ObjectTypeAnnotation(node, print) { // istanbul ignore next var _this = this; this.push("{"); var props = node.properties.concat(node.callProperties, node.indexers); if (props.length) { this.space(); print.list(props, { separator: false, indent: true, iterator: function iterator() { if (props.length !== 1) { _this.semicolon(); _this.space(); } } }); this.space(); } this.push("}"); } /** * Prints ObjectTypeCallProperty, prints value, handles static. */ function ObjectTypeCallProperty(node, print) { if (node["static"]) this.push("static "); print.plain(node.value); } /** * Prints ObjectTypeIndexer, prints id, key, and value, handles static. */ function ObjectTypeIndexer(node, print) { if (node["static"]) this.push("static "); this.push("["); print.plain(node.id); this.push(":"); this.space(); print.plain(node.key); this.push("]"); this.push(":"); this.space(); print.plain(node.value); } /** * Prints ObjectTypeProperty, prints static, key, and value. */ function ObjectTypeProperty(node, print) { if (node["static"]) this.push("static "); print.plain(node.key); if (node.optional) this.push("?"); if (!t.isFunctionTypeAnnotation(node.value)) { this.push(":"); this.space(); } print.plain(node.value); } /** * Prints QualifiedTypeIdentifier, prints qualification and id. */ function QualifiedTypeIdentifier(node, print) { print.plain(node.qualification); this.push("."); print.plain(node.id); } /** * Prints UnionTypeAnnotation, prints types. */ function UnionTypeAnnotation(node, print) { print.join(node.types, { separator: " | " }); } /** * Prints TypeCastExpression, prints expression and typeAnnotation. */ function TypeCastExpression(node, print) { this.push("("); print.plain(node.expression); print.plain(node.typeAnnotation); this.push(")"); } /** * Prints VoidTypeAnnotation. */ function VoidTypeAnnotation(node) { this.push("void"); }
/*! * inferno-mobx v1.0.0-beta35 * (c) 2016 Ryan Megidov * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component'), require('mobx'), require('./inferno-create-class'), require('./inferno-create-element')) : typeof define === 'function' && define.amd ? define(['inferno-component', 'mobx', 'inferno-create-class', 'inferno-create-element'], factory) : (global.Inferno = global.Inferno || {}, global.Inferno.Mobx = factory(global.Inferno.Component,global.mobx,global.Inferno.createClass,global.Inferno.createElement)); }(this, (function (Component,mobx,createClass,createElement) { 'use strict'; Component = 'default' in Component ? Component['default'] : Component; createClass = 'default' in createClass ? createClass['default'] : createClass; createElement = 'default' in createElement ? createElement['default'] : createElement; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } function warning(condition, message) { if (!condition) { console.error(message); } } var specialKeys = { children: true, key: true, ref: true }; var Provider = (function (Component$$1) { function Provider(props, context) { Component$$1.call(this, props, context); this.contextTypes = { mobxStores: function mobxStores() { } }; this.childContextTypes = { mobxStores: function mobxStores$1() { } }; this.store = props.store; } if ( Component$$1 ) Provider.__proto__ = Component$$1; Provider.prototype = Object.create( Component$$1 && Component$$1.prototype ); Provider.prototype.constructor = Provider; Provider.prototype.render = function render () { return this.props.children; }; Provider.prototype.getChildContext = function getChildContext () { var this$1 = this; var stores = {}; // inherit stores var baseStores = this.context.mobxStores; if (baseStores) { for (var key in baseStores) { stores[key] = baseStores[key]; } } // add own stores for (var key$1 in this.props) { if (!specialKeys[key$1]) { stores[key$1] = this$1.props[key$1]; } } return { mobxStores: stores }; }; return Provider; }(Component)); if (process.env.NODE_ENV !== 'production') { Provider.prototype.componentWillReceiveProps = function (nextProps) { var this$1 = this; // Maybe this warning is to aggressive? warning(Object.keys(nextProps).length === Object.keys(this.props).length, 'MobX Provider: The set of provided stores has changed. ' + 'Please avoid changing stores as the change might not propagate to all children'); for (var key in nextProps) { warning(specialKeys[key] || this$1.props[key] === nextProps[key], "MobX Provider: Provided store '" + key + "' has changed. " + "Please avoid replacing stores as the change might not propagate to all children"); } }; } var EventEmitter = function EventEmitter() { this.listeners = []; }; EventEmitter.prototype.on = function on (cb) { var this$1 = this; this.listeners.push(cb); return function () { var index = this$1.listeners.indexOf(cb); if (index !== -1) { this$1.listeners.splice(index, 1); } }; }; EventEmitter.prototype.emit = function emit (data) { this.listeners.forEach(function (fn) { return fn(data); }); }; EventEmitter.prototype.getTotalListeners = function getTotalListeners () { return this.listeners.length; }; EventEmitter.prototype.clearListeners = function clearListeners () { this.listeners = []; }; /** * Dev tools support */ var isDevtoolsEnabled = false; var componentByNodeRegistery = new WeakMap(); var renderReporter = new EventEmitter(); function reportRendering(component) { var node = component._vNode.dom; if (node && componentByNodeRegistery) { componentByNodeRegistery.set(node, component); } renderReporter.emit({ event: 'render', renderTime: component.__$mobRenderEnd - component.__$mobRenderStart, totalTime: Date.now() - component.__$mobRenderStart, component: component, node: node }); } function trackComponents() { if (typeof WeakMap === 'undefined') { throwError('[inferno-mobx] tracking components is not supported in this browser.'); } if (!isDevtoolsEnabled) { isDevtoolsEnabled = true; } } function makeReactive(componentClass) { var target = componentClass.prototype || componentClass; var baseDidMount = target.componentDidMount; var baseWillMount = target.componentWillMount; var baseUnmount = target.componentWillUnmount; target.componentWillMount = function () { var this$1 = this; // Call original baseWillMount && baseWillMount.call(this); var reaction; var isRenderingPending = false; var initialName = this.displayName || this.name || (this.constructor && (this.constructor.displayName || this.constructor.name)) || '<component>'; var baseRender = this.render.bind(this); var initialRender = function (nextProps, nextContext) { reaction = new mobx.Reaction((initialName + ".render()"), function () { if (!isRenderingPending) { isRenderingPending = true; if (this$1.__$mobxIsUnmounted !== true) { var hasError = true; try { Component.prototype.forceUpdate.call(this$1); hasError = false; } finally { if (hasError) { reaction.dispose(); } } } } }); reactiveRender.$mobx = reaction; this$1.render = reactiveRender; return reactiveRender(nextProps, nextContext); }; var reactiveRender = function (nextProps, nextContext) { isRenderingPending = false; var rendering = undefined; reaction.track(function () { if (isDevtoolsEnabled) { this$1.__$mobRenderStart = Date.now(); } rendering = mobx.extras.allowStateChanges(false, baseRender.bind(this$1, nextProps, nextContext)); if (isDevtoolsEnabled) { this$1.__$mobRenderEnd = Date.now(); } }); return rendering; }; this.render = initialRender; }; target.componentDidMount = function () { isDevtoolsEnabled && reportRendering(this); // Call original baseDidMount && baseDidMount.call(this); }; target.componentWillUnmount = function () { // Call original baseUnmount && baseUnmount.call(this); // Dispose observables this.render.$mobx && this.render.$mobx.dispose(); this.__$mobxIsUnmounted = true; if (isDevtoolsEnabled) { var node = this._vNode.dom; if (node && componentByNodeRegistery) { componentByNodeRegistery.delete(node); } renderReporter.emit({ event: 'destroy', component: this, node: node }); } }; target.shouldComponentUpdate = function (nextProps, nextState) { var this$1 = this; // Update on any state changes (as is the default) if (this.state !== nextState) { return true; } // Update if props are shallowly not equal, inspired by PureRenderMixin var keys = Object.keys(this.props); if (keys.length !== Object.keys(nextProps).length) { return true; } for (var i = keys.length - 1; i >= 0; i--) { var key = keys[i]; var newValue = nextProps[key]; if (newValue !== this$1.props[key]) { return true; } else if (newValue && typeof newValue === 'object' && !mobx.isObservable(newValue)) { // If the newValue is still the same object, but that object is not observable, // fallback to the default behavior: update, because the object *might* have changed. return true; } } return true; }; return componentClass; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var index$1 = createCommonjsModule(function (module) { 'use strict'; var INFERNO_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, arguments: true, arity: true }; var isGetOwnPropertySymbolsAvailable = typeof Object.getOwnPropertySymbols === 'function'; function hoistNonReactStatics(targetComponent, sourceComponent, customStatics) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var keys = Object.getOwnPropertyNames(sourceComponent); /* istanbul ignore else */ if (isGetOwnPropertySymbolsAvailable) { keys = keys.concat(Object.getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { if (!INFERNO_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]] && (!customStatics || !customStatics[keys[i]])) { try { targetComponent[keys[i]] = sourceComponent[keys[i]]; } catch (error) { } } } } return targetComponent; } module.exports = hoistNonReactStatics; module.exports.default = module.exports; }); /** * Store Injection */ function createStoreInjector(grabStoresFn, component) { var Injector = createClass({ displayName: component.name, render: function render() { var this$1 = this; var newProps = {}; for (var key in this.props) { if (this$1.props.hasOwnProperty(key)) { newProps[key] = this$1.props[key]; } } var additionalProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context) || {}; for (var key$1 in additionalProps) { newProps[key$1] = additionalProps[key$1]; } newProps.ref = function (instance) { this$1.wrappedInstance = instance; }; return createElement(component, newProps); } }); Injector.contextTypes = { mobxStores: function mobxStores() { } }; index$1(Injector, component); return Injector; } var grabStoresByName = function (storeNames) { return function (baseStores, nextProps) { storeNames.forEach(function (storeName) { // Prefer props over stores if (storeName in nextProps) { return; } if (!(storeName in baseStores)) { throw new Error("MobX observer: Store \"" + storeName + "\" is not available! " + "Make sure it is provided by some Provider"); } nextProps[storeName] = baseStores[storeName]; }); return nextProps; }; }; /** * Higher order component that injects stores to a child. * takes either a varargs list of strings, which are stores read from the context, * or a function that manually maps the available stores from the context to props: * storesToProps(mobxStores, props, context) => newProps */ function inject(grabStoresFn) { var arguments$1 = arguments; if (typeof grabStoresFn !== 'function') { var storesNames = []; for (var i = 0; i < arguments.length; i++) { storesNames[i] = arguments$1[i]; } grabStoresFn = grabStoresByName(storesNames); } return function (componentClass) { return createStoreInjector(grabStoresFn, componentClass); }; } /** * Wraps a component and provides stores as props */ function connect(arg1, arg2) { if ( arg2 === void 0 ) arg2 = null; if (typeof arg1 === 'string') { throwError('Store names should be provided as array'); } if (Array.isArray(arg1)) { // component needs stores if (!arg2) { // invoked as decorator return function (componentClass) { return connect(arg1, componentClass); }; } else { // TODO: deprecate this invocation style return inject.apply(null, arg1)(connect(arg2)); } } var componentClass = arg1; // Stateless function component: // If it is function but doesn't seem to be a Inferno class constructor, // wrap it to a Inferno class automatically if (typeof componentClass === 'function' && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !Component.isPrototypeOf(componentClass)) { var newClass = createClass({ displayName: componentClass.displayName || componentClass.name, propTypes: componentClass.propTypes, contextTypes: componentClass.contextTypes, getDefaultProps: function () { return componentClass.defaultProps; }, render: function render() { return componentClass.call(this, this.props, this.context); } }); return connect(newClass); } if (!componentClass) { throwError('Please pass a valid component to "observer"'); } componentClass.isMobXReactObserver = true; return makeReactive(componentClass); } var index = { Provider: Provider, inject: inject, connect: connect, observer: connect, trackComponents: trackComponents, renderReporter: renderReporter, componentByNodeRegistery: componentByNodeRegistery }; return index; })));
import App from './src/app'; const app = new App();
var someVar = obj[ "key" ] || 0 function f() { function g() { } }
/** * Maplace.js 0.1.31 * * Copyright (c) 2013 Daniele Moraschi * Licensed under the MIT license * For all details and documentation: * http://maplacejs.com */ ;(function(g,s,f,n){var q,m,p;q={activateCurrent:function(e){this.html_element.find("select").val(e)},getHtml:function(){var e=this,a="",b;if(1<this.ln){a+='<select class="dropdown controls '+this.o.controls_cssclass+'">';this.ShowOnMenu(this.view_all_key)&&(a+='<option value="'+this.view_all_key+'">'+this.o.view_all_text+"</option>");for(b=0;b<this.ln;b+=1)this.ShowOnMenu(b)&&(a+='<option value="'+(b+1)+'">'+(this.o.locations[b].title||"#"+(b+1))+"</option>");a=g(a+"</select>").bind("change",function(){e.ViewOnMap(this.value)})}(b= this.o.controls_title)&&(b=g('<div class="controls_title"></div>').css(this.o.controls_applycss?{fontWeight:"bold",fontSize:this.o.controls_on_map?"12px":"inherit",padding:"3px 10px 5px 0"}:{}).append(this.o.controls_title));return this.html_element=g('<div class="wrap_controls"></div>').append(b).append(a)}};m={html_a:function(e,a,b){var c=this;a=a||e+1;b=b||this.o.locations[e].title;e=g('<a data-load="'+a+'" id="ullist_a_'+a+'" href="#'+a+'" title="'+b+'"><span>'+(b||"#"+(e+1))+"</span></a>");e.css(this.o.controls_applycss? {color:"#666",display:"block",padding:"5px",fontSize:this.o.controls_on_map?"12px":"inherit",textDecoration:"none"}:{});e.on("click",function(a){a.preventDefault();a=g(this).attr("data-load");c.ViewOnMap(a)});return e},activateCurrent:function(e){this.html_element.find("li").removeClass("active");this.html_element.find("#ullist_a_"+e).parent().addClass("active")},getHtml:function(){var e=g("<ul class='ullist controls "+this.o.controls_cssclass+"'></ul>").css(this.o.controls_applycss?{margin:0,padding:0, listStyleType:"none"}:{}),a;this.ShowOnMenu(this.view_all_key)&&e.append(g("<li></li>").append(m.html_a.call(this,!1,this.view_all_key,this.o.view_all_text)));for(a=0;a<this.ln;a++)this.ShowOnMenu(a)&&e.append(g("<li></li>").append(m.html_a.call(this,a)));(a=this.o.controls_title)&&(a=g('<div class="controls_title"></div>').css(this.o.controls_applycss?{fontWeight:"bold",padding:"3px 10px 5px 0",fontSize:this.o.controls_on_map?"12px":"inherit"}:{}).append(this.o.controls_title));return this.html_element= g('<div class="wrap_controls"></div>').append(a).append(e)}};p=function(){function e(a){this.VERSION="0.1.31";this.loaded=!1;this.markers=[];this.circles=[];this.oMap=!1;this.view_all_key="all";this.infowindow=null;this.ln=0;this.oMap=!1;this.directionsDisplay=this.directionsService=this.Fusion=this.Polygon=this.Polyline=this.current_index=this.current_control=this.controls_wrapper=this.canvas_map=this.map_div=this.oBounds=null;this.o={debug:!1,map_div:"#gmap",controls_div:"#controls",generate_controls:!0, controls_type:"dropdown",controls_cssclass:"",controls_title:"",controls_on_map:!0,controls_applycss:!0,controls_position:f.maps.ControlPosition.RIGHT_TOP,type:"marker",view_all:!0,view_all_text:"View All",pan_on_click:!0,start:0,locations:[],shared:{},map_options:{mapTypeId:f.maps.MapTypeId.ROADMAP},stroke_options:{strokeColor:"#0000FF",strokeOpacity:.8,strokeWeight:2,fillColor:"#0000FF",fillOpacity:.4},directions_options:{travelMode:f.maps.TravelMode.DRIVING,unitSystem:f.maps.UnitSystem.METRIC, optimizeWaypoints:!1,provideRouteAlternatives:!1,avoidHighways:!1,avoidTolls:!1},circle_options:{radius:100,visible:!0},styles:{},fusion_options:{},directions_panel:null,draggable:!1,editable:!1,show_infowindows:!0,show_markers:!0,infowindow_type:"bubble",listeners:{},beforeViewAll:function(){},afterViewAll:function(){},beforeShow:function(a,c,d){},afterShow:function(a,c,d){},afterCreateMarker:function(a,c,d){},beforeCloseInfowindow:function(a,c){},afterCloseInfowindow:function(a,c){},beforeOpenInfowindow:function(a, c,d){},afterOpenInfowindow:function(a,c,d){},afterRoute:function(a,c,d){},onPolylineClick:function(a){},onPolygonClick:function(a){},circleRadiusChanged:function(a,c,d){},circleCenterChanged:function(a,c,d){},drag:function(a,c,d){},dragEnd:function(a,c,d){},dragStart:function(a,c,d){}};this.AddControl("dropdown",q);this.AddControl("list",m);a&&"directions"===a.type&&(!a.show_markers&&(a.show_markers=!1),!a.show_infowindows&&(a.show_infowindows=!1));g.extend(!0,this.o,a)}e.prototype.controls={};e.prototype.create_objMap= function(){var a=0,b;for(b in this.o.styles)this.o.styles.hasOwnProperty(b)&&(0===a&&(this.o.map_options.mapTypeControlOptions={mapTypeIds:[f.maps.MapTypeId.ROADMAP]}),a++,this.o.map_options.mapTypeControlOptions.mapTypeIds.push("map_style_"+a));if(this.loaded)this.oMap.setOptions(this.o.map_options);else try{this.map_div.css({position:"relative",overflow:"hidden"}),this.canvas_map=g("<div>").addClass("canvas_map").css({width:"100%",height:"100%"}).appendTo(this.map_div),this.oMap=new f.maps.Map(this.canvas_map.get(0), this.o.map_options)}catch(c){this.debug("create_objMap::"+this.map_div.selector,c.toString())}a=0;for(b in this.o.styles)this.o.styles.hasOwnProperty(b)&&(a++,this.oMap.mapTypes.set("map_style_"+a,new f.maps.StyledMapType(this.o.styles[b],{name:b})),this.oMap.setMapTypeId("map_style_"+a))};e.prototype.add_markers_to_objMap=function(){var a,b;a=this.o.type||"marker";switch(a){case "marker":for(a=0;a<this.ln;a++)b=this.create_objPoint(a),this.create.marker.call(this,a,b);break;default:this.create[a].apply(this)}}; e.prototype.create_objPoint=function(a){a=g.extend({},this.o.locations[a]);var b=a.visible===n?n:a.visible;!a.type&&(a.type=this.o.type);a.position=new f.maps.LatLng(a.lat,a.lon);a.map=this.oMap;a.zIndex=1E4;a.visible=b===n?this.o.show_markers:b;a.image&&(a.icon=new f.maps.MarkerImage(a.image,new f.maps.Size(a.image_w||32,a.image_h||32),new f.maps.Point(0,0),new f.maps.Point(image_w/2,image_h/2)));return a};e.prototype.create_objCircle=function(a){var b,c,d;d=g.extend({},a);b=g.extend({},this.o.stroke_options); c=g.extend({},this.o.circle_options);g.extend(b,a.stroke_options||{});g.extend(d,b);g.extend(c,a.circle_options||{});g.extend(d,c);d.center=a.position;d.draggable=!1;d.zIndex=9E3;return d};e.prototype.add_markerEv=function(a,b,c){var d=this;f.maps.event.addListener(c,"click",function(e){d.o.beforeShow(a,b,c);d.o.show_infowindows&&!1!==b.show_infowindow&&d.open_infowindow(a,c,e);d.o.pan_on_click&&!1!==b.pan_on_click&&(d.oMap.panTo(b.position),b.zoom&&d.oMap.setZoom(b.zoom));d.current_control&&d.o.generate_controls&& d.current_control.activateCurrent&&d.current_control.activateCurrent.call(d,a+1);d.current_index=a;d.o.afterShow(a,b,c)});b.draggable&&this.add_dragEv(a,b,c)};e.prototype.add_circleEv=function(a,b,c){var d=this;f.maps.event.addListener(c,"click",function(){d.ViewOnMap(a+1)});f.maps.event.addListener(c,"center_changed",function(){d.o.circleCenterChanged(a,b,c)});f.maps.event.addListener(c,"radius_changed",function(){d.o.circleRadiusChanged(a,b,c)});b.draggable&&this.add_dragEv(a,b,c)};e.prototype.add_dragEv= function(a,b,c){var d=this;f.maps.event.addListener(c,"drag",function(e){var g;if(c.getPosition)e=c.getPosition();else if(c.getCenter)e=c.getCenter();else return;d.circles[a]&&d.circles[a].setCenter(e);d.Polyline?g="Polyline":d.Polygon&&(g="Polygon");if(g){for(var k=d[g].getPath().getArray(),h=[],l=0;l<k.length;++l)h[l]=a===l?new f.maps.LatLng(e.lat(),e.lng()):new f.maps.LatLng(k[l].lat(),k[l].lng());d[g].setPath(new f.maps.MVCArray(h));d.add_polyEv(g)}d.o.drag(a,b,c)});f.maps.event.addListener(c, "dragend",function(){d.o.dragEnd(a,b,c)});f.maps.event.addListener(c,"dragstart",function(){d.o.dragStart(a,b,c)});f.maps.event.addListener(c,"center_changed",function(){d.markers[a]&&c.getCenter&&d.markers[a].setPosition(c.getCenter());d.o.drag(a,b,c)})};e.prototype.add_polyEv=function(a){var b=this;f.maps.event.addListener(this[a].getPath(),"set_at",function(c,d){var e=b[a].getPath().getAt(c),e=new f.maps.LatLng(e.lat(),e.lng());b.markers[c]&&b.markers[c].setPosition(e);b.circles[c]&&b.circles[c].setCenter(e); b.o["on"+a+"Changed"](c,d,b[a].getPath().getArray())})};e.prototype.create={marker:function(a,b,c){var d;"circle"!=b.type||c||(d=this.create_objCircle(b),b.visible||(d.draggable=b.draggable),c=new f.maps.Circle(d),this.add_circleEv(a,d,c),this.circles[a]=c);b.type="marker";c=new f.maps.Marker(b);this.add_markerEv(a,b,c);this.oBounds.extend(b.position);this.markers[a]=c;this.o.afterCreateMarker(a,b,c);return c},circle:function(){var a,b,c,d;for(a=0;a<this.ln;a++)b=this.create_objPoint(a),"circle"== b.type&&(c=this.create_objCircle(b),b.visible||(c.draggable=b.draggable),d=new f.maps.Circle(c),this.add_circleEv(a,c,d),this.circles[a]=d),b.type="marker",this.create.marker.call(this,a,b,d)},polyline:function(){var a,b,c=g.extend({},this.o.stroke_options);c.path=[];c.draggable=this.o.draggable;c.editable=this.o.editable;c.map=this.oMap;c.zIndex=11E3;for(a=0;a<this.ln;a++)b=this.create_objPoint(a),this.create.marker.call(this,a,b),c.path.push(b.position);this.Polyline?this.Polyline.setOptions(c): this.Polyline=new f.maps.Polyline(c);this.add_polyEv("Polyline")},polygon:function(){var a=this,b,c,d=g.extend({},this.o.stroke_options);d.path=[];d.draggable=this.o.draggable;d.editable=this.o.editable;d.map=this.oMap;d.zIndex=11E3;for(b=0;b<this.ln;b++)c=this.create_objPoint(b),this.create.marker.call(this,b,c),d.path.push(c.position);this.Polygon?this.Polygon.setOptions(d):this.Polygon=new f.maps.Polygon(d);f.maps.event.addListener(this.Polygon,"click",function(b){a.o.onPolygonClick(b)});this.add_polyEv("Polygon")}, fusion:function(){this.o.fusion_options.styles=[this.o.stroke_options];this.o.fusion_options.map=this.oMap;this.Fusion?this.Fusion.setOptions(this.o.fusion_options):this.Fusion=new f.maps.FusionTablesLayer(this.o.fusion_options)},directions:function(){var a=this,b,c,d,e,r,k=[],h=0;for(b=0;b<this.ln;b++)c=this.create_objPoint(b),0===b?e=c.position:b===this.ln-1?r=c.position:(d=!0===this.o.locations[b].stopover?!0:!1,k.push({location:c.position,stopover:d})),this.create.marker.call(this,b,c);this.o.directions_options.origin= e;this.o.directions_options.destination=r;this.o.directions_options.waypoints=k;this.directionsService||(this.directionsService=new f.maps.DirectionsService);this.directionsDisplay?this.directionsDisplay.setOptions({draggable:this.o.draggable}):this.directionsDisplay=new f.maps.DirectionsRenderer({draggable:this.o.draggable});this.directionsDisplay.setMap(this.oMap);this.o.directions_panel&&(this.o.directions_panel=g(this.o.directions_panel),this.directionsDisplay.setPanel(this.o.directions_panel.get(0))); this.o.draggable&&f.maps.event.addListener(this.directionsDisplay,"directions_changed",function(){h=a.compute_distance(a.directionsDisplay.directions);a.o.afterRoute(h)});this.directionsService.route(this.o.directions_options,function(b,c){c===f.maps.DirectionsStatus.OK&&(h=a.compute_distance(b),a.directionsDisplay.setDirections(b));a.o.afterRoute(h,c,b)})}};e.prototype.compute_distance=function(a){var b=0,c=a.routes[0],d=c.legs.length;for(a=0;a<d;a++)b+=c.legs[a].distance.value;return b};e.prototype.type_to_open= {bubble:function(a){this.infowindow=new f.maps.InfoWindow({content:a.html||""})}};e.prototype.open_infowindow=function(a,b,c){this.CloseInfoWindow();c=this.o.locations[a];var d=this.o.infowindow_type;c.html&&this.type_to_open[d]&&(this.o.beforeOpenInfowindow(a,c,b),this.type_to_open[d].call(this,c),this.infowindow.open(this.oMap,b),this.o.afterOpenInfowindow(a,c,b))};e.prototype.get_html_controls=function(){return this.controls[this.o.controls_type]&&this.controls[this.o.controls_type].getHtml?(this.current_control= this.controls[this.o.controls_type],this.current_control.getHtml.apply(this)):""};e.prototype.generate_controls=function(){if(this.o.controls_on_map){var a=g('<div class="on_gmap '+this.o.controls_type+' gmap_controls"></div>').css(this.o.controls_applycss?{margin:"5px"}:{}),b=g(this.get_html_controls()).css(this.o.controls_applycss?{background:"#fff",padding:"5px",border:"1px solid rgb(113,123,135)",boxShadow:"rgba(0, 0, 0, 0.4) 0px 2px 4px",maxHeight:this.map_div.find(".canvas_map").outerHeight()- 80,minWidth:100,overflowY:"auto",overflowX:"hidden"}:{});a.append(b);this.oMap.controls[this.o.controls_position].push(a.get(0))}else this.controls_wrapper.empty(),this.controls_wrapper.append(this.get_html_controls())};e.prototype.init_map=function(){var a=this;this.Polyline&&this.Polyline.setMap(null);this.Polygon&&this.Polygon.setMap(null);this.Fusion&&this.Fusion.setMap(null);this.directionsDisplay&&this.directionsDisplay.setMap(null);for(var b=this.markers.length-1;0<=b;b-=1)try{this.markers[b]&& this.markers[b].setMap(null)}catch(c){a.debug("init_map::markers::setMap",c.stack)}this.markers.length=0;this.markers=[];for(b=this.circles.length-1;0<=b;b-=1)try{this.circles[b]&&this.circles[b].setMap(null)}catch(d){a.debug("init_map::circles::setMap",d.stack)}this.circles.length=0;this.circles=[];this.o.controls_on_map&&this.oMap.controls&&this.oMap.controls[this.o.controls_position].forEach(function(b,c){try{a.oMap.controls[this.o.controls_position].removeAt(c)}catch(d){a.debug("init_map::removeAt", d.stack)}});this.oBounds=new f.maps.LatLngBounds};e.prototype.perform_load=function(){1===this.ln?(this.o.map_options.set_center?this.oMap.setCenter(new f.maps.LatLng(this.o.map_options.set_center[0],this.o.map_options.set_center[1])):(this.oMap.setCenter(this.markers[0].getPosition()),this.ViewOnMap(1)),this.o.map_options.zoom&&this.oMap.setZoom(this.o.map_options.zoom)):0===this.ln?(this.o.map_options.set_center?this.oMap.setCenter(new f.maps.LatLng(this.o.map_options.set_center[0],this.o.map_options.set_center[1])): this.oMap.fitBounds(this.oBounds),this.oMap.setZoom(this.o.map_options.zoom||1)):(this.oMap.fitBounds(this.oBounds),"number"===typeof(this.o.start-0)&&0<this.o.start&&this.o.start<=this.ln?this.ViewOnMap(this.o.start):this.o.map_options.set_center?this.oMap.setCenter(new f.maps.LatLng(this.o.map_options.set_center[0],this.o.map_options.set_center[1])):this.ViewOnMap(this.view_all_key),this.o.map_options.zoom&&this.oMap.setZoom(this.o.map_options.zoom))};e.prototype.debug=function(a,b){this.o.debug&& console.log(a,b);return this};e.prototype.AddControl=function(a,b){if(!a||!b)return self.debug("AddControl",'Missing "name" and "func" callback.'),!1;this.controls[a]=b;return this};e.prototype.CloseInfoWindow=function(){this.infowindow&&(this.current_index||0===this.current_index)&&(this.o.beforeCloseInfowindow(this.current_index,this.o.locations[this.current_index]),this.infowindow.close(),this.infowindow=null,this.o.afterCloseInfowindow(this.current_index,this.o.locations[this.current_index])); return this};e.prototype.ShowOnMenu=function(a){if(a===this.view_all_key&&this.o.view_all&&1<this.ln)return!0;a=parseInt(a,10);return"number"===typeof(a-0)&&0<=a&&a<this.ln&&!1!==this.o.locations[a].on_menu?!0:!1};e.prototype.ViewOnMap=function(a){if(a===this.view_all_key)this.o.beforeViewAll(),this.current_index=a,0<this.o.locations.length&&this.o.generate_controls&&this.current_control&&this.current_control.activateCurrent&&this.current_control.activateCurrent.apply(this,[a]),this.oMap.fitBounds(this.oBounds), this.CloseInfoWindow(),this.o.afterViewAll();else if(a=parseInt(a,10),"number"===typeof(a-0)&&0<a&&a<=this.ln)try{f.maps.event.trigger(this.markers[a-1],"click")}catch(b){this.debug("ViewOnMap::trigger",b.stack)}return this};e.prototype.SetLocations=function(a,b){this.o.locations=a;b&&this.Load();return this};e.prototype.AddLocations=function(a,b){var c=this;g.isArray(a)&&g.each(a,function(a,b){c.o.locations.push(b)});g.isPlainObject(a)&&this.o.locations.push(a);b&&this.Load();return this};e.prototype.AddLocation= function(a,b,c){g.isPlainObject(a)&&this.o.locations.splice(b,0,a);c&&this.Load();return this};e.prototype.RemoveLocations=function(a,b){var c=this,d=0;g.isArray(a)?g.each(a,function(a,b){b-d<c.ln&&c.o.locations.splice(b-d,1);d++}):a<this.ln&&this.o.locations.splice(a,1);b&&this.Load();return this};e.prototype.Loaded=function(){return this.loaded};e.prototype._init=function(){this.ln=this.o.locations.length;for(var a=0;a<this.ln;a++){var b=g.extend({},this.o.shared);this.o.locations[a]=g.extend(b, this.o.locations[a]);this.o.locations[a].html&&(this.o.locations[a].html=this.o.locations[a].html.replace("%index",a+1),this.o.locations[a].html=this.o.locations[a].html.replace("%title",this.o.locations[a].title||""))}this.map_div=g(this.o.map_div);this.controls_wrapper=g(this.o.controls_div);return this};e.prototype.Load=function(a){g.extend(!0,this.o,a);a&&a.locations&&(this.o.locations=a.locations);this._init();!1===this.o.visualRefresh?f.maps.visualRefresh=!1:f.maps.visualRefresh=!0;this.init_map(); this.create_objMap();this.add_markers_to_objMap();1<this.ln&&this.o.generate_controls||this.o.force_generate_controls?(this.o.generate_controls=!0,this.generate_controls()):this.o.generate_controls=!1;var b=this;if(this.loaded)this.perform_load();else{f.maps.event.addListenerOnce(this.oMap,"idle",function(){b.perform_load()});f.maps.event.addListener(this.oMap,"resize",function(){b.canvas_map.css({width:b.map_div.width(),height:b.map_div.height()})});for(var c in this.o.listeners){var d=this.oMap, e=this.o.listeners[c];this.o.listeners.hasOwnProperty(c)&&f.maps.event.addListener(this.oMap,c,function(a){e(d,a)})}}this.loaded=!0;return this};return e}();"function"==typeof define&&define.amd?define(function(){return p}):s.Maplace=p})(jQuery,this,google);
// Version: v1.0.0-pre.4 // Last commit: 855db1a (2013-01-17 23:06:53 -0800) (function() { /*global __fail__*/ /** Ember Debug @module ember @submodule ember-debug */ /** @class Ember */ if ('undefined' === typeof Ember) { Ember = {}; if ('undefined' !== typeof window) { window.Em = window.Ember = Em = Ember; } } Ember.ENV = 'undefined' === typeof ENV ? {} : ENV; if (!('MANDATORY_SETTER' in Ember.ENV)) { Ember.ENV.MANDATORY_SETTER = true; // default to true for debug dist } /** Define an assertion that will throw an exception if the condition is not met. Ember build tools will remove any calls to `Ember.assert()` when doing a production build. Example: ```javascript // Test for truthiness Ember.assert('Must pass a valid object', obj); // Fail unconditionally Ember.assert('This code path should never be run') ``` @method assert @param {String} desc A description of the assertion. This will become the text of the Error thrown if the assertion fails. @param {Boolean} test Must be truthy for the assertion to pass. If falsy, an exception will be thrown. */ Ember.assert = function(desc, test) { if (!test) throw new Error("assertion failed: "+desc); }; /** Display a warning with the provided message. Ember build tools will remove any calls to `Ember.warn()` when doing a production build. @method warn @param {String} message A warning to display. @param {Boolean} test An optional boolean. If falsy, the warning will be displayed. */ Ember.warn = function(message, test) { if (!test) { Ember.Logger.warn("WARNING: "+message); if ('trace' in Ember.Logger) Ember.Logger.trace(); } }; /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). Ember build tools will remove any calls to `Ember.deprecate()` when doing a production build. @method deprecate @param {String} message A description of the deprecation. @param {Boolean} test An optional boolean. If falsy, the deprecation will be displayed. */ Ember.deprecate = function(message, test) { if (Ember && Ember.TESTING_DEPRECATION) { return; } if (arguments.length === 1) { test = false; } if (test) { return; } if (Ember && Ember.ENV.RAISE_ON_DEPRECATION) { throw new Error(message); } var error; // When using new Error, we can't do the arguments check for Chrome. Alternatives are welcome try { __fail__.fail(); } catch (e) { error = e; } if (Ember.LOG_STACKTRACE_ON_DEPRECATION && error.stack) { var stack, stackStr = ''; if (error['arguments']) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, ''). replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2'). replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n'); stack.shift(); } else { // Firefox stack = error.stack.replace(/(?:\n@:0)?\s+$/m, ''). replace(/^\(/gm, '{anonymous}(').split('\n'); } stackStr = "\n " + stack.slice(2).join("\n "); message = message + stackStr; } Ember.Logger.warn("DEPRECATION: "+message); }; /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only) when the wrapped method is called. Ember build tools will not remove calls to `Ember.deprecateFunc()`, though no warnings will be shown in production. @method deprecateFunc @param {String} message A description of the deprecation. @param {Function} func The function to be deprecated. */ Ember.deprecateFunc = function(message, func) { return function() { Ember.deprecate(message); return func.apply(this, arguments); }; }; if ('undefined' !== typeof window) { window.ember_assert = Ember.deprecateFunc("ember_assert is deprecated. Please use Ember.assert instead.", Ember.assert); window.ember_warn = Ember.deprecateFunc("ember_warn is deprecated. Please use Ember.warn instead.", Ember.warn); window.ember_deprecate = Ember.deprecateFunc("ember_deprecate is deprecated. Please use Ember.deprecate instead.", Ember.deprecate); window.ember_deprecateFunc = Ember.deprecateFunc("ember_deprecateFunc is deprecated. Please use Ember.deprecateFunc instead.", Ember.deprecateFunc); } })(); // Version: v1.0.0-pre.3-19-g015138e // Last commit: 015138e (2013-01-17 23:02:17 -0800) (function() { var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen[name]) { return seen[name]; } seen[name] = {}; var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(deps[i])); } } var value = callback.apply(this, reified); return seen[name] = exports || value; }; })(); (function() { /*globals Em:true ENV */ /** @module ember @submodule ember-metal */ /** All Ember methods and functions are defined inside of this namespace. You generally should not add new properties to this namespace as it may be overwritten by future versions of Ember. You can also use the shorthand `Em` instead of `Ember`. Ember-Runtime is a framework that provides core functions for Ember including cross-platform functions, support for property observing and objects. Its focus is on small size and performance. You can use this in place of or along-side other cross-platform libraries such as jQuery. The core Runtime framework is based on the jQuery API with a number of performance optimizations. @class Ember @static @version 1.0.0-pre.4 */ if ('undefined' === typeof Ember) { // Create core object. Make it act like an instance of Ember.Namespace so that // objects assigned to it are given a sane string representation. Ember = {}; } // Default imports, exports and lookup to the global object; var imports = Ember.imports = Ember.imports || this; var exports = Ember.exports = Ember.exports || this; var lookup = Ember.lookup = Ember.lookup || this; // aliases needed to keep minifiers from removing the global context exports.Em = exports.Ember = Em = Ember; // Make sure these are set whether Ember was already defined or not Ember.isNamespace = true; Ember.toString = function() { return "Ember"; }; /** @property VERSION @type String @default '1.0.0-pre.4' @final */ Ember.VERSION = '1.0.0-pre.4'; /** Standard environmental variables. You can define these in a global `ENV` variable before loading Ember to control various configuration settings. @property ENV @type Hash */ Ember.ENV = Ember.ENV || ('undefined' === typeof ENV ? {} : ENV); Ember.config = Ember.config || {}; // .......................................................... // BOOTSTRAP // /** Determines whether Ember should enhances some built-in object prototypes to provide a more friendly API. If enabled, a few methods will be added to `Function`, `String`, and `Array`. `Object.prototype` will not be enhanced, which is the one that causes most trouble for people. In general we recommend leaving this option set to true since it rarely conflicts with other code. If you need to turn it off however, you can define an `ENV.EXTEND_PROTOTYPES` config to disable it. @property EXTEND_PROTOTYPES @type Boolean @default true */ Ember.EXTEND_PROTOTYPES = Ember.ENV.EXTEND_PROTOTYPES; if (typeof Ember.EXTEND_PROTOTYPES === 'undefined') { Ember.EXTEND_PROTOTYPES = true; } /** Determines whether Ember logs a full stack trace during deprecation warnings @property LOG_STACKTRACE_ON_DEPRECATION @type Boolean @default true */ Ember.LOG_STACKTRACE_ON_DEPRECATION = (Ember.ENV.LOG_STACKTRACE_ON_DEPRECATION !== false); /** Determines whether Ember should add ECMAScript 5 shims to older browsers. @property SHIM_ES5 @type Boolean @default Ember.EXTEND_PROTOTYPES */ Ember.SHIM_ES5 = (Ember.ENV.SHIM_ES5 === false) ? false : Ember.EXTEND_PROTOTYPES; /** Empty function. Useful for some operations. @method K @private @return {Object} */ Ember.K = function() { return this; }; // Stub out the methods defined by the ember-debug package in case it's not loaded if ('undefined' === typeof Ember.assert) { Ember.assert = Ember.K; } if ('undefined' === typeof Ember.warn) { Ember.warn = Ember.K; } if ('undefined' === typeof Ember.deprecate) { Ember.deprecate = Ember.K; } if ('undefined' === typeof Ember.deprecateFunc) { Ember.deprecateFunc = function(_, func) { return func; }; } // These are deprecated but still supported if ('undefined' === typeof ember_assert) { exports.ember_assert = Ember.K; } if ('undefined' === typeof ember_warn) { exports.ember_warn = Ember.K; } if ('undefined' === typeof ember_deprecate) { exports.ember_deprecate = Ember.K; } if ('undefined' === typeof ember_deprecateFunc) { exports.ember_deprecateFunc = function(_, func) { return func; }; } /** Previously we used `Ember.$.uuid`, however `$.uuid` has been removed from jQuery master. We'll just bootstrap our own uuid now. @property uuid @type Number @private */ Ember.uuid = 0; // .......................................................... // LOGGER // /** Inside Ember-Metal, simply uses the `imports.console` object. Override this to provide more robust logging functionality. @class Logger @namespace Ember */ Ember.Logger = imports.console || { log: Ember.K, warn: Ember.K, error: Ember.K, info: Ember.K, debug: Ember.K }; // .......................................................... // ERROR HANDLING // /** A function may be assigned to `Ember.onerror` to be called when Ember internals encounter an error. This is useful for specialized error handling and reporting code. @event onerror @for Ember @param {Exception} error the error object */ Ember.onerror = null; /** @private Wrap code block in a try/catch if {{#crossLink "Ember/onerror"}}{{/crossLink}} is set. @method handleErrors @for Ember @param {Function} func @param [context] */ Ember.handleErrors = function(func, context) { // Unfortunately in some browsers we lose the backtrace if we rethrow the existing error, // so in the event that we don't have an `onerror` handler we don't wrap in a try/catch if ('function' === typeof Ember.onerror) { try { return func.apply(context || this); } catch (error) { Ember.onerror(error); } } else { return func.apply(context || this); } }; Ember.merge = function(original, updates) { for (var prop in updates) { if (!updates.hasOwnProperty(prop)) { continue; } original[prop] = updates[prop]; } }; })(); (function() { /*globals Node */ /** @module ember-metal */ /** Platform specific methods and feature detectors needed by the framework. @class platform @namespace Ember @static */ var platform = Ember.platform = {}; /** Identical to `Object.create()`. Implements if not available natively. @method create @for Ember */ Ember.create = Object.create; // STUB_OBJECT_CREATE allows us to override other libraries that stub // Object.create different than we would prefer if (!Ember.create || Ember.ENV.STUB_OBJECT_CREATE) { var K = function() {}; Ember.create = function(obj, props) { K.prototype = obj; obj = new K(); if (props) { K.prototype = obj; for (var prop in props) { K.prototype[prop] = props[prop].value; } obj = new K(); } K.prototype = null; return obj; }; Ember.create.isSimulated = true; } var defineProperty = Object.defineProperty; var canRedefineProperties, canDefinePropertyOnDOM; // Catch IE8 where Object.defineProperty exists but only works on DOM elements if (defineProperty) { try { defineProperty({}, 'a',{get:function(){}}); } catch (e) { defineProperty = null; } } if (defineProperty) { // Detects a bug in Android <3.2 where you cannot redefine a property using // Object.defineProperty once accessors have already been set. canRedefineProperties = (function() { var obj = {}; defineProperty(obj, 'a', { configurable: true, enumerable: true, get: function() { }, set: function() { } }); defineProperty(obj, 'a', { configurable: true, enumerable: true, writable: true, value: true }); return obj.a === true; })(); // This is for Safari 5.0, which supports Object.defineProperty, but not // on DOM nodes. canDefinePropertyOnDOM = (function(){ try { defineProperty(document.createElement('div'), 'definePropertyOnDOM', {}); return true; } catch(e) { } return false; })(); if (!canRedefineProperties) { defineProperty = null; } else if (!canDefinePropertyOnDOM) { defineProperty = function(obj, keyName, desc){ var isNode; if (typeof Node === "object") { isNode = obj instanceof Node; } else { isNode = typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string"; } if (isNode) { // TODO: Should we have a warning here? return (obj[keyName] = desc.value); } else { return Object.defineProperty(obj, keyName, desc); } }; } } /** @class platform @namespace Ember */ /** Identical to `Object.defineProperty()`. Implements as much functionality as possible if not available natively. @method defineProperty @param {Object} obj The object to modify @param {String} keyName property name to modify @param {Object} desc descriptor hash @return {void} */ platform.defineProperty = defineProperty; /** Set to true if the platform supports native getters and setters. @property hasPropertyAccessors @final */ platform.hasPropertyAccessors = true; if (!platform.defineProperty) { platform.hasPropertyAccessors = false; platform.defineProperty = function(obj, keyName, desc) { if (!desc.get) { obj[keyName] = desc.value; } }; platform.defineProperty.isSimulated = true; } if (Ember.ENV.MANDATORY_SETTER && !platform.hasPropertyAccessors) { Ember.ENV.MANDATORY_SETTER = false; } })(); (function() { /** @module ember-metal */ var o_defineProperty = Ember.platform.defineProperty, o_create = Ember.create, // Used for guid generation... GUID_KEY = '__ember'+ (+ new Date()), uuid = 0, numberCache = [], stringCache = {}; var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; /** @private A unique key used to assign guids and other private metadata to objects. If you inspect an object in your browser debugger you will often see these. They can be safely ignored. On browsers that support it, these properties are added with enumeration disabled so they won't show up when you iterate over your properties. @property GUID_KEY @for Ember @type String @final */ Ember.GUID_KEY = GUID_KEY; var GUID_DESC = { writable: false, configurable: false, enumerable: false, value: null }; /** @private Generates a new guid, optionally saving the guid to the object that you pass in. You will rarely need to use this method. Instead you should call `Ember.guidFor(obj)`, which return an existing guid if available. @method generateGuid @for Ember @param {Object} [obj] Object the guid will be used for. If passed in, the guid will be saved on the object and reused whenever you pass the same object again. If no object is passed, just generate a new guid. @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. @return {String} the guid */ Ember.generateGuid = function generateGuid(obj, prefix) { if (!prefix) prefix = 'ember'; var ret = (prefix + (uuid++)); if (obj) { GUID_DESC.value = ret; o_defineProperty(obj, GUID_KEY, GUID_DESC); } return ret ; }; /** @private Returns a unique id for the object. If the object does not yet have a guid, one will be assigned to it. You can call this on any object, `Ember.Object`-based or not, but be aware that it will add a `_guid` property. You can also use this method on DOM Element objects. @method guidFor @for Ember @param obj {Object} any object, string, number, Element, or primitive @return {String} the unique guid for this instance. */ Ember.guidFor = function guidFor(obj) { // special cases where we don't want to add a key to object if (obj === undefined) return "(undefined)"; if (obj === null) return "(null)"; var cache, ret; var type = typeof obj; // Don't allow prototype changes to String etc. to change the guidFor switch(type) { case 'number': ret = numberCache[obj]; if (!ret) ret = numberCache[obj] = 'nu'+obj; return ret; case 'string': ret = stringCache[obj]; if (!ret) ret = stringCache[obj] = 'st'+(uuid++); return ret; case 'boolean': return obj ? '(true)' : '(false)'; default: if (obj[GUID_KEY]) return obj[GUID_KEY]; if (obj === Object) return '(Object)'; if (obj === Array) return '(Array)'; ret = 'ember'+(uuid++); GUID_DESC.value = ret; o_defineProperty(obj, GUID_KEY, GUID_DESC); return ret; } }; // .......................................................... // META // var META_DESC = { writable: true, configurable: false, enumerable: false, value: null }; var META_KEY = Ember.GUID_KEY+'_meta'; /** The key used to store meta information on object for property observing. @property META_KEY @for Ember @private @final @type String */ Ember.META_KEY = META_KEY; // Placeholder for non-writable metas. var EMPTY_META = { descs: {}, watching: {} }; if (MANDATORY_SETTER) { EMPTY_META.values = {}; } Ember.EMPTY_META = EMPTY_META; if (Object.freeze) Object.freeze(EMPTY_META); var isDefinePropertySimulated = Ember.platform.defineProperty.isSimulated; function Meta(obj) { this.descs = {}; this.watching = {}; this.cache = {}; this.source = obj; } if (isDefinePropertySimulated) { // on platforms that don't support enumerable false // make meta fail jQuery.isPlainObject() to hide from // jQuery.extend() by having a property that fails // hasOwnProperty check. Meta.prototype.__preventPlainObject__ = true; // Without non-enumerable properties, meta objects will be output in JSON // unless explicitly suppressed Meta.prototype.toJSON = function () { }; } /** Retrieves the meta hash for an object. If `writable` is true ensures the hash is writable for this object as well. The meta object contains information about computed property descriptors as well as any watched properties and other information. You generally will not access this information directly but instead work with higher level methods that manipulate this hash indirectly. @method meta @for Ember @private @param {Object} obj The object to retrieve meta for @param {Boolean} [writable=true] Pass `false` if you do not intend to modify the meta hash, allowing the method to avoid making an unnecessary copy. @return {Hash} */ Ember.meta = function meta(obj, writable) { var ret = obj[META_KEY]; if (writable===false) return ret || EMPTY_META; if (!ret) { if (!isDefinePropertySimulated) o_defineProperty(obj, META_KEY, META_DESC); ret = new Meta(obj); if (MANDATORY_SETTER) { ret.values = {}; } obj[META_KEY] = ret; // make sure we don't accidentally try to create constructor like desc ret.descs.constructor = null; } else if (ret.source !== obj) { if (!isDefinePropertySimulated) o_defineProperty(obj, META_KEY, META_DESC); ret = o_create(ret); ret.descs = o_create(ret.descs); ret.watching = o_create(ret.watching); ret.cache = {}; ret.source = obj; if (MANDATORY_SETTER) { ret.values = o_create(ret.values); } obj[META_KEY] = ret; } return ret; }; Ember.getMeta = function getMeta(obj, property) { var meta = Ember.meta(obj, false); return meta[property]; }; Ember.setMeta = function setMeta(obj, property, value) { var meta = Ember.meta(obj, true); meta[property] = value; return value; }; /** @private In order to store defaults for a class, a prototype may need to create a default meta object, which will be inherited by any objects instantiated from the class's constructor. However, the properties of that meta object are only shallow-cloned, so if a property is a hash (like the event system's `listeners` hash), it will by default be shared across all instances of that class. This method allows extensions to deeply clone a series of nested hashes or other complex objects. For instance, the event system might pass `['listeners', 'foo:change', 'ember157']` to `prepareMetaPath`, which will walk down the keys provided. For each key, if the key does not exist, it is created. If it already exists and it was inherited from its constructor, the constructor's key is cloned. You can also pass false for `writable`, which will simply return undefined if `prepareMetaPath` discovers any part of the path that shared or undefined. @method metaPath @for Ember @param {Object} obj The object whose meta we are examining @param {Array} path An array of keys to walk down @param {Boolean} writable whether or not to create a new meta (or meta property) if one does not already exist or if it's shared with its constructor */ Ember.metaPath = function metaPath(obj, path, writable) { var meta = Ember.meta(obj, writable), keyName, value; for (var i=0, l=path.length; i<l; i++) { keyName = path[i]; value = meta[keyName]; if (!value) { if (!writable) { return undefined; } value = meta[keyName] = { __ember_source__: obj }; } else if (value.__ember_source__ !== obj) { if (!writable) { return undefined; } value = meta[keyName] = o_create(value); value.__ember_source__ = obj; } meta = value; } return value; }; /** @private Wraps the passed function so that `this._super` will point to the superFunc when the function is invoked. This is the primitive we use to implement calls to super. @method wrap @for Ember @param {Function} func The function to call @param {Function} superFunc The super function. @return {Function} wrapped function. */ Ember.wrap = function(func, superFunc) { function K() {} function superWrapper() { var ret, sup = this._super; this._super = superFunc || K; ret = func.apply(this, arguments); this._super = sup; return ret; } superWrapper.wrappedFunction = func; superWrapper.__ember_observes__ = func.__ember_observes__; superWrapper.__ember_observesBefore__ = func.__ember_observesBefore__; return superWrapper; }; /** Returns true if the passed object is an array or Array-like. Ember Array Protocol: - the object has an objectAt property - the object is a native Array - the object is an Object, and has a length property Unlike `Ember.typeOf` this method returns true even if the passed object is not formally array but appears to be array-like (i.e. implements `Ember.Array`) ```javascript Ember.isArray(); // false Ember.isArray([]); // true Ember.isArray( Ember.ArrayProxy.create({ content: [] }) ); // true ``` @method isArray @for Ember @param {Object} obj The object to test @return {Boolean} */ Ember.isArray = function(obj) { if (!obj || obj.setInterval) { return false; } if (Array.isArray && Array.isArray(obj)) { return true; } if (Ember.Array && Ember.Array.detect(obj)) { return true; } if ((obj.length !== undefined) && 'object'===typeof obj) { return true; } return false; }; /** Forces the passed object to be part of an array. If the object is already an array or array-like, returns the object. Otherwise adds the object to an array. If obj is `null` or `undefined`, returns an empty array. ```javascript Ember.makeArray(); // [] Ember.makeArray(null); // [] Ember.makeArray(undefined); // [] Ember.makeArray('lindsay'); // ['lindsay'] Ember.makeArray([1,2,42]); // [1,2,42] var controller = Ember.ArrayProxy.create({ content: [] }); Ember.makeArray(controller) === controller; // true ``` @method makeArray @for Ember @param {Object} obj the object @return {Array} */ Ember.makeArray = function(obj) { if (obj === null || obj === undefined) { return []; } return Ember.isArray(obj) ? obj : [obj]; }; function canInvoke(obj, methodName) { return !!(obj && typeof obj[methodName] === 'function'); } /** Checks to see if the `methodName` exists on the `obj`. @method canInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for */ Ember.canInvoke = canInvoke; /** Checks to see if the `methodName` exists on the `obj`, and if it does, invokes it with the arguments passed. @method tryInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @param {Array} [args] The arguments to pass to the method @return {anything} the return value of the invoked method or undefined if it cannot be invoked */ Ember.tryInvoke = function(obj, methodName, args) { if (canInvoke(obj, methodName)) { return obj[methodName].apply(obj, args || []); } }; // https://github.com/emberjs/ember.js/pull/1617 var needsFinallyFix = (function() { var count = 0; try{ try { } finally { count++; throw new Error('needsFinallyFixTest'); } } catch (e) {} return count !== 1; })(); /** Provides try { } finally { } functionality, while working around Safari's double finally bug. @method tryFinally @for Ember @param {Function} function The function to run the try callback @param {Function} function The function to run the finally callback @param [binding] @return {anything} The return value is the that of the finalizer, unless that valueis undefined, in which case it is the return value of the tryable */ if (needsFinallyFix) { Ember.tryFinally = function(tryable, finalizer, binding) { var result, finalResult, finalError; binding = binding || this; try { result = tryable.call(binding); } finally { try { finalResult = finalizer.call(binding); } catch (e){ finalError = e; } } if (finalError) { throw finalError; } return (finalResult === undefined) ? result : finalResult; }; } else { Ember.tryFinally = function(tryable, finalizer, binding) { var result, finalResult; binding = binding || this; try { result = tryable.call(binding); } finally { finalResult = finalizer.call(binding); } return (finalResult === undefined) ? result : finalResult; }; } /** Provides try { } catch finally { } functionality, while working around Safari's double finally bug. @method tryCatchFinally @for Ember @param {Function} function The function to run the try callback @param {Function} function The function to run the catchable callback @param {Function} function The function to run the finally callback @param [binding] @return {anything} The return value is the that of the finalizer, unless that value is undefined, in which case it is the return value of the tryable. */ if (needsFinallyFix) { Ember.tryCatchFinally = function(tryable, catchable, finalizer, binding) { var result, finalResult, finalError, finalReturn; binding = binding || this; try { result = tryable.call(binding); } catch(error) { result = catchable.call(binding, error); } finally { try { finalResult = finalizer.call(binding); } catch (e){ finalError = e; } } if (finalError) { throw finalError; } return (finalResult === undefined) ? result : finalResult; }; } else { Ember.tryCatchFinally = function(tryable, catchable, finalizer, binding) { var result, finalResult; binding = binding || this; try { result = tryable.call(binding); } catch(error) { result = catchable.call(binding, error); } finally { finalResult = finalizer.call(binding); } return (finalResult === undefined) ? result : finalResult; }; } })(); (function() { // Ember.tryCatchFinally /** The purpose of the Ember Instrumentation module is to provide efficient, general-purpose instrumentation for Ember. Subscribe to a listener by using `Ember.subscribe`: ```javascript Ember.subscribe("render", { before: function(name, timestamp, payload) { }, after: function(name, timestamp, payload) { } }); ``` If you return a value from the `before` callback, that same value will be passed as a fourth parameter to the `after` callback. Instrument a block of code by using `Ember.instrument`: ```javascript Ember.instrument("render.handlebars", payload, function() { // rendering logic }, binding); ``` Event names passed to `Ember.instrument` are namespaced by periods, from more general to more specific. Subscribers can listen for events by whatever level of granularity they are interested in. In the above example, the event is `render.handlebars`, and the subscriber listened for all events beginning with `render`. It would receive callbacks for events named `render`, `render.handlebars`, `render.container`, or even `render.handlebars.layout`. @class Instrumentation @namespace Ember @static */ Ember.Instrumentation = {}; var subscribers = [], cache = {}; var populateListeners = function(name) { var listeners = [], subscriber; for (var i=0, l=subscribers.length; i<l; i++) { subscriber = subscribers[i]; if (subscriber.regex.test(name)) { listeners.push(subscriber.object); } } cache[name] = listeners; return listeners; }; var time = (function() { var perf = 'undefined' !== typeof window ? window.performance || {} : {}; var fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow; // fn.bind will be available in all the browsers that support the advanced window.performance... ;-) return fn ? fn.bind(perf) : function() { return +new Date(); }; })(); Ember.Instrumentation.instrument = function(name, payload, callback, binding) { var listeners = cache[name], timeName, ret; if (Ember.STRUCTURED_PROFILE) { timeName = name + ": " + payload.object; console.time(timeName); } if (!listeners) { listeners = populateListeners(name); } if (listeners.length === 0) { ret = callback.call(binding); if (Ember.STRUCTURED_PROFILE) { console.timeEnd(timeName); } return ret; } var beforeValues = [], listener, i, l; function tryable(){ for (i=0, l=listeners.length; i<l; i++) { listener = listeners[i]; beforeValues[i] = listener.before(name, time(), payload); } return callback.call(binding); } function catchable(e){ payload = payload || {}; payload.exception = e; } function finalizer() { for (i=0, l=listeners.length; i<l; i++) { listener = listeners[i]; listener.after(name, time(), payload, beforeValues[i]); } if (Ember.STRUCTURED_PROFILE) { console.timeEnd(timeName); } } return Ember.tryCatchFinally(tryable, catchable, finalizer); }; Ember.Instrumentation.subscribe = function(pattern, object) { var paths = pattern.split("."), path, regex = []; for (var i=0, l=paths.length; i<l; i++) { path = paths[i]; if (path === "*") { regex.push("[^\\.]*"); } else { regex.push(path); } } regex = regex.join("\\."); regex = regex + "(\\..*)?"; var subscriber = { pattern: pattern, regex: new RegExp("^" + regex + "$"), object: object }; subscribers.push(subscriber); cache = {}; return subscriber; }; Ember.Instrumentation.unsubscribe = function(subscriber) { var index; for (var i=0, l=subscribers.length; i<l; i++) { if (subscribers[i] === subscriber) { index = i; } } subscribers.splice(index, 1); cache = {}; }; Ember.Instrumentation.reset = function() { subscribers = []; cache = {}; }; Ember.instrument = Ember.Instrumentation.instrument; Ember.subscribe = Ember.Instrumentation.subscribe; })(); (function() { /*jshint newcap:false*/ /** @module ember-metal */ // NOTE: There is a bug in jshint that doesn't recognize `Object()` without `new` // as being ok unless both `newcap:false` and not `use strict`. // https://github.com/jshint/jshint/issues/392 // Testing this is not ideal, but we want to use native functions // if available, but not to use versions created by libraries like Prototype var isNativeFunc = function(func) { // This should probably work in all browsers likely to have ES5 array methods return func && Function.prototype.toString.call(func).indexOf('[native code]') > -1; }; // From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/map var arrayMap = isNativeFunc(Array.prototype.map) ? Array.prototype.map : function(fun /*, thisp */) { //"use strict"; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(); } var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) { res[i] = fun.call(thisp, t[i], i, t); } } return res; }; // From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach var arrayForEach = isNativeFunc(Array.prototype.forEach) ? Array.prototype.forEach : function(fun /*, thisp */) { //"use strict"; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError(); } var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) { fun.call(thisp, t[i], i, t); } } }; var arrayIndexOf = isNativeFunc(Array.prototype.indexOf) ? Array.prototype.indexOf : function (obj, fromIndex) { if (fromIndex === null || fromIndex === undefined) { fromIndex = 0; } else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex, j = this.length; i < j; i++) { if (this[i] === obj) { return i; } } return -1; }; Ember.ArrayPolyfills = { map: arrayMap, forEach: arrayForEach, indexOf: arrayIndexOf }; var utils = Ember.EnumerableUtils = { map: function(obj, callback, thisArg) { return obj.map ? obj.map.call(obj, callback, thisArg) : arrayMap.call(obj, callback, thisArg); }, forEach: function(obj, callback, thisArg) { return obj.forEach ? obj.forEach.call(obj, callback, thisArg) : arrayForEach.call(obj, callback, thisArg); }, indexOf: function(obj, element, index) { return obj.indexOf ? obj.indexOf.call(obj, element, index) : arrayIndexOf.call(obj, element, index); }, indexesOf: function(obj, elements) { return elements === undefined ? [] : utils.map(elements, function(item) { return utils.indexOf(obj, item); }); }, addObject: function(array, item) { var index = utils.indexOf(array, item); if (index === -1) { array.push(item); } }, removeObject: function(array, item) { var index = utils.indexOf(array, item); if (index !== -1) { array.splice(index, 1); } }, replace: function(array, idx, amt, objects) { if (array.replace) { return array.replace(idx, amt, objects); } else { var args = Array.prototype.concat.apply([idx, amt], objects); return array.splice.apply(array, args); } } }; if (Ember.SHIM_ES5) { if (!Array.prototype.map) { Array.prototype.map = arrayMap; } if (!Array.prototype.forEach) { Array.prototype.forEach = arrayForEach; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = arrayIndexOf; } } })(); (function() { /** @module ember-metal */ /* JavaScript (before ES6) does not have a Map implementation. Objects, which are often used as dictionaries, may only have Strings as keys. Because Ember has a way to get a unique identifier for every object via `Ember.guidFor`, we can implement a performant Map with arbitrary keys. Because it is commonly used in low-level bookkeeping, Map is implemented as a pure JavaScript object for performance. This implementation follows the current iteration of the ES6 proposal for maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets), with two exceptions. First, because we need our implementation to be pleasant on older browsers, we do not use the `delete` name (using `remove` instead). Second, as we do not have the luxury of in-VM iteration, we implement a forEach method for iteration. Map is mocked out to look like an Ember object, so you can do `Ember.Map.create()` for symmetry with other Ember classes. */ var guidFor = Ember.guidFor, indexOf = Ember.ArrayPolyfills.indexOf; var copy = function(obj) { var output = {}; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { output[prop] = obj[prop]; } } return output; }; var copyMap = function(original, newObject) { var keys = original.keys.copy(), values = copy(original.values); newObject.keys = keys; newObject.values = values; return newObject; }; /** This class is used internally by Ember and Ember Data. Please do not use it at this time. We plan to clean it up and add many tests soon. @class OrderedSet @namespace Ember @constructor @private */ var OrderedSet = Ember.OrderedSet = function() { this.clear(); }; /** @method create @static @return {Ember.OrderedSet} */ OrderedSet.create = function() { return new OrderedSet(); }; OrderedSet.prototype = { /** @method clear */ clear: function() { this.presenceSet = {}; this.list = []; }, /** @method add @param obj */ add: function(obj) { var guid = guidFor(obj), presenceSet = this.presenceSet, list = this.list; if (guid in presenceSet) { return; } presenceSet[guid] = true; list.push(obj); }, /** @method remove @param obj */ remove: function(obj) { var guid = guidFor(obj), presenceSet = this.presenceSet, list = this.list; delete presenceSet[guid]; var index = indexOf.call(list, obj); if (index > -1) { list.splice(index, 1); } }, /** @method isEmpty @return {Boolean} */ isEmpty: function() { return this.list.length === 0; }, /** @method has @param obj @return {Boolean} */ has: function(obj) { var guid = guidFor(obj), presenceSet = this.presenceSet; return guid in presenceSet; }, /** @method forEach @param {Function} function @param target */ forEach: function(fn, self) { // allow mutation during iteration var list = this.list.slice(); for (var i = 0, j = list.length; i < j; i++) { fn.call(self, list[i]); } }, /** @method toArray @return {Array} */ toArray: function() { return this.list.slice(); }, /** @method copy @return {Ember.OrderedSet} */ copy: function() { var set = new OrderedSet(); set.presenceSet = copy(this.presenceSet); set.list = this.list.slice(); return set; } }; /** A Map stores values indexed by keys. Unlike JavaScript's default Objects, the keys of a Map can be any JavaScript object. Internally, a Map has two data structures: 1. `keys`: an OrderedSet of all of the existing keys 2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)` When a key/value pair is added for the first time, we add the key to the `keys` OrderedSet, and create or replace an entry in `values`. When an entry is deleted, we delete its entry in `keys` and `values`. @class Map @namespace Ember @private @constructor */ var Map = Ember.Map = function() { this.keys = Ember.OrderedSet.create(); this.values = {}; }; /** @method create @static */ Map.create = function() { return new Map(); }; Map.prototype = { /** Retrieve the value associated with a given key. @method get @param {anything} key @return {anything} the value associated with the key, or `undefined` */ get: function(key) { var values = this.values, guid = guidFor(key); return values[guid]; }, /** Adds a value to the map. If a value for the given key has already been provided, the new value will replace the old value. @method set @param {anything} key @param {anything} value */ set: function(key, value) { var keys = this.keys, values = this.values, guid = guidFor(key); keys.add(key); values[guid] = value; }, /** Removes a value from the map for an associated key. @method remove @param {anything} key @return {Boolean} true if an item was removed, false otherwise */ remove: function(key) { // don't use ES6 "delete" because it will be annoying // to use in browsers that are not ES6 friendly; var keys = this.keys, values = this.values, guid = guidFor(key), value; if (values.hasOwnProperty(guid)) { keys.remove(key); value = values[guid]; delete values[guid]; return true; } else { return false; } }, /** Check whether a key is present. @method has @param {anything} key @return {Boolean} true if the item was present, false otherwise */ has: function(key) { var values = this.values, guid = guidFor(key); return values.hasOwnProperty(guid); }, /** Iterate over all the keys and values. Calls the function once for each key, passing in the key and value, in that order. The keys are guaranteed to be iterated over in insertion order. @method forEach @param {Function} callback @param {anything} self if passed, the `this` value inside the callback. By default, `this` is the map. */ forEach: function(callback, self) { var keys = this.keys, values = this.values; keys.forEach(function(key) { var guid = guidFor(key); callback.call(self, key, values[guid]); }); }, /** @method copy @return {Ember.Map} */ copy: function() { return copyMap(this, new Map()); } }; /** @class MapWithDefault @namespace Ember @extends Ember.Map @private @constructor @param [options] @param {anything} [options.defaultValue] */ var MapWithDefault = Ember.MapWithDefault = function(options) { Map.call(this); this.defaultValue = options.defaultValue; }; /** @method create @static @param [options] @param {anything} [options.defaultValue] @return {Ember.MapWithDefault|Ember.Map} If options are passed, returns `Ember.MapWithDefault` otherwise returns `Ember.Map` */ MapWithDefault.create = function(options) { if (options) { return new MapWithDefault(options); } else { return new Map(); } }; MapWithDefault.prototype = Ember.create(Map.prototype); /** Retrieve the value associated with a given key. @method get @param {anything} key @return {anything} the value associated with the key, or the default value */ MapWithDefault.prototype.get = function(key) { var hasValue = this.has(key); if (hasValue) { return Map.prototype.get.call(this, key); } else { var defaultValue = this.defaultValue(key); this.set(key, defaultValue); return defaultValue; } }; /** @method copy @return {Ember.MapWithDefault} */ MapWithDefault.prototype.copy = function() { return copyMap(this, new MapWithDefault({ defaultValue: this.defaultValue })); }; })(); (function() { /** @module ember-metal */ var META_KEY = Ember.META_KEY, get, set; var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; var IS_GLOBAL_PATH = /^([A-Z$]|([0-9][A-Z$])).*[\.\*]/; var HAS_THIS = /^this[\.\*]/; var FIRST_KEY = /^([^\.\*]+)/; // .......................................................... // GET AND SET // // If we are on a platform that supports accessors we can get use those. // Otherwise simulate accessors by looking up the property directly on the // object. /** Gets the value of a property on an object. If the property is computed, the function will be invoked. If the property is not defined but the object implements the `unknownProperty` method then that will be invoked. If you plan to run on IE8 and older browsers then you should use this method anytime you want to retrieve a property on an object that you don't know for sure is private. (Properties beginning with an underscore '_' are considered private.) On all newer browsers, you only need to use this method to retrieve properties if the property might not be defined on the object and you want to respect the `unknownProperty` handler. Otherwise you can ignore this method. Note that if the object itself is `undefined`, this method will throw an error. @method get @for Ember @param {Object} obj The object to retrieve from. @param {String} keyName The property key to retrieve @return {Object} the property value or `null`. */ get = function get(obj, keyName) { // Helpers that operate with 'this' within an #each if (keyName === '') { return obj; } if (!keyName && 'string'===typeof obj) { keyName = obj; obj = null; } if (!obj || keyName.indexOf('.') !== -1) { Ember.assert("Cannot call get with '"+ keyName +"' on an undefined object.", obj !== undefined); return getPath(obj, keyName); } Ember.assert("You need to provide an object and key to `get`.", !!obj && keyName); var meta = obj[META_KEY], desc = meta && meta.descs[keyName], ret; if (desc) { return desc.get(obj, keyName); } else { if (MANDATORY_SETTER && meta && meta.watching[keyName] > 0) { ret = meta.values[keyName]; } else { ret = obj[keyName]; } if (ret === undefined && 'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) { return obj.unknownProperty(keyName); } return ret; } }; /** Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the `unknownProperty` method then that will be invoked as well. If you plan to run on IE8 and older browsers then you should use this method anytime you want to set a property on an object that you don't know for sure is private. (Properties beginning with an underscore '_' are considered private.) On all newer browsers, you only need to use this method to set properties if the property might not be defined on the object and you want to respect the `unknownProperty` handler. Otherwise you can ignore this method. @method set @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set @return {Object} the passed value. */ set = function set(obj, keyName, value, tolerant) { if (typeof obj === 'string') { Ember.assert("Path '" + obj + "' must be global if no obj is given.", IS_GLOBAL.test(obj)); value = keyName; keyName = obj; obj = null; } if (!obj || keyName.indexOf('.') !== -1) { return setPath(obj, keyName, value, tolerant); } Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined); Ember.assert('calling set on destroyed object', !obj.isDestroyed); var meta = obj[META_KEY], desc = meta && meta.descs[keyName], isUnknown, currentValue; if (desc) { desc.set(obj, keyName, value); } else { isUnknown = 'object' === typeof obj && !(keyName in obj); // setUnknownProperty is called if `obj` is an object, // the property does not already exist, and the // `setUnknownProperty` method exists on the object if (isUnknown && 'function' === typeof obj.setUnknownProperty) { obj.setUnknownProperty(keyName, value); } else if (meta && meta.watching[keyName] > 0) { if (MANDATORY_SETTER) { currentValue = meta.values[keyName]; } else { currentValue = obj[keyName]; } // only trigger a change if the value has changed if (value !== currentValue) { Ember.propertyWillChange(obj, keyName); if (MANDATORY_SETTER) { if (currentValue === undefined && !(keyName in obj)) { Ember.defineProperty(obj, keyName, null, value); // setup mandatory setter } else { meta.values[keyName] = value; } } else { obj[keyName] = value; } Ember.propertyDidChange(obj, keyName); } } else { obj[keyName] = value; } } return value; }; // Currently used only by Ember Data tests if (Ember.config.overrideAccessors) { Ember.get = get; Ember.set = set; Ember.config.overrideAccessors(); get = Ember.get; set = Ember.set; } function firstKey(path) { return path.match(FIRST_KEY)[0]; } // assumes path is already normalized function normalizeTuple(target, path) { var hasThis = HAS_THIS.test(path), isGlobal = !hasThis && IS_GLOBAL_PATH.test(path), key; if (!target || isGlobal) target = Ember.lookup; if (hasThis) path = path.slice(5); if (target === Ember.lookup) { key = firstKey(path); target = get(target, key); path = path.slice(key.length+1); } // must return some kind of path to be valid else other things will break. if (!path || path.length===0) throw new Error('Invalid Path'); return [ target, path ]; } function getPath(root, path) { var hasThis, parts, tuple, idx, len; // If there is no root and path is a key name, return that // property from the global object. // E.g. get('Ember') -> Ember if (root === null && path.indexOf('.') === -1) { return get(Ember.lookup, path); } // detect complicated paths and normalize them hasThis = HAS_THIS.test(path); if (!root || hasThis) { tuple = normalizeTuple(root, path); root = tuple[0]; path = tuple[1]; tuple.length = 0; } parts = path.split("."); len = parts.length; for (idx=0; root && idx<len; idx++) { root = get(root, parts[idx], true); if (root && root.isDestroyed) { return undefined; } } return root; } function setPath(root, path, value, tolerant) { var keyName; // get the last part of the path keyName = path.slice(path.lastIndexOf('.') + 1); // get the first part of the part path = path.slice(0, path.length-(keyName.length+1)); // unless the path is this, look up the first part to // get the root if (path !== 'this') { root = getPath(root, path); } if (!keyName || keyName.length === 0) { throw new Error('You passed an empty path'); } if (!root) { if (tolerant) { return; } else { throw new Error('Object in path '+path+' could not be found or was destroyed.'); } } return set(root, keyName, value); } /** @private Normalizes a target/path pair to reflect that actual target/path that should be observed, etc. This takes into account passing in global property paths (i.e. a path beginning with a captial letter not defined on the target) and * separators. @method normalizeTuple @for Ember @param {Object} target The current target. May be `null`. @param {String} path A path on the target or a global property path. @return {Array} a temporary array with the normalized target/path pair. */ Ember.normalizeTuple = function(target, path) { return normalizeTuple(target, path); }; Ember.getWithDefault = function(root, key, defaultValue) { var value = get(root, key); if (value === undefined) { return defaultValue; } return value; }; Ember.get = get; Ember.getPath = Ember.deprecateFunc('getPath is deprecated since get now supports paths', Ember.get); Ember.set = set; Ember.setPath = Ember.deprecateFunc('setPath is deprecated since set now supports paths', Ember.set); /** Error-tolerant form of `Ember.set`. Will not blow up if any part of the chain is `undefined`, `null`, or destroyed. This is primarily used when syncing bindings, which may try to update after an object has been destroyed. @method trySet @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set */ Ember.trySet = function(root, path, value) { return set(root, path, value, true); }; Ember.trySetPath = Ember.deprecateFunc('trySetPath has been renamed to trySet', Ember.trySet); /** Returns true if the provided path is global (e.g., `MyApp.fooController.bar`) instead of local (`foo.bar.baz`). @method isGlobalPath @for Ember @private @param {String} path @return Boolean */ Ember.isGlobalPath = function(path) { return IS_GLOBAL.test(path); }; })(); (function() { /** @module ember-metal */ var GUID_KEY = Ember.GUID_KEY, META_KEY = Ember.META_KEY, EMPTY_META = Ember.EMPTY_META, metaFor = Ember.meta, o_create = Ember.create, objectDefineProperty = Ember.platform.defineProperty; var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; // .......................................................... // DESCRIPTOR // /** Objects of this type can implement an interface to responds requests to get and set. The default implementation handles simple properties. You generally won't need to create or subclass this directly. @class Descriptor @namespace Ember @private @constructor */ var Descriptor = Ember.Descriptor = function() {}; // .......................................................... // DEFINING PROPERTIES API // /** @private NOTE: This is a low-level method used by other parts of the API. You almost never want to call this method directly. Instead you should use `Ember.mixin()` to define new properties. Defines a property on an object. This method works much like the ES5 `Object.defineProperty()` method except that it can also accept computed properties and other special descriptors. Normally this method takes only three parameters. However if you pass an instance of `Ember.Descriptor` as the third param then you can pass an optional value as the fourth parameter. This is often more efficient than creating new descriptor hashes for each property. ## Examples ```javascript // ES5 compatible mode Ember.defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' }); // define a simple property Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); // define a computed property Ember.defineProperty(contact, 'fullName', Ember.computed(function() { return this.firstName+' '+this.lastName; }).property('firstName', 'lastName')); ``` @method defineProperty @for Ember @param {Object} obj the object to define this property on. This may be a prototype. @param {String} keyName the name of the property @param {Ember.Descriptor} [desc] an instance of `Ember.Descriptor` (typically a computed property) or an ES5 descriptor. You must provide this or `data` but not both. @param {anything} [data] something other than a descriptor, that will become the explicit value of this property. */ Ember.defineProperty = function(obj, keyName, desc, data, meta) { var descs, existingDesc, watching, value; if (!meta) meta = metaFor(obj); descs = meta.descs; existingDesc = meta.descs[keyName]; watching = meta.watching[keyName] > 0; if (existingDesc instanceof Ember.Descriptor) { existingDesc.teardown(obj, keyName); } if (desc instanceof Ember.Descriptor) { value = desc; descs[keyName] = desc; if (MANDATORY_SETTER && watching) { objectDefineProperty(obj, keyName, { configurable: true, enumerable: true, writable: true, value: undefined // make enumerable }); } else { obj[keyName] = undefined; // make enumerable } desc.setup(obj, keyName); } else { descs[keyName] = undefined; // shadow descriptor in proto if (desc == null) { value = data; if (MANDATORY_SETTER && watching) { meta.values[keyName] = data; objectDefineProperty(obj, keyName, { configurable: true, enumerable: true, set: function() { Ember.assert('Must use Ember.set() to access this property', false); }, get: function() { var meta = this[META_KEY]; return meta && meta.values[keyName]; } }); } else { obj[keyName] = data; } } else { value = desc; // compatibility with ES5 objectDefineProperty(obj, keyName, desc); } } // if key is being watched, override chains that // were initialized with the prototype if (watching) { Ember.overrideChains(obj, keyName, meta); } // The `value` passed to the `didDefineProperty` hook is // either the descriptor or data, whichever was passed. if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); } return this; }; })(); (function() { // Ember.tryFinally /** @module ember-metal */ var AFTER_OBSERVERS = ':change'; var BEFORE_OBSERVERS = ':before'; var guidFor = Ember.guidFor; var deferred = 0; /* this.observerSet = { [senderGuid]: { // variable name: `keySet` [keyName]: listIndex } }, this.observers = [ { sender: obj, keyName: keyName, eventName: eventName, listeners: [ [target, method, onceFlag, suspendedFlag] ] }, ... ] */ function ObserverSet() { this.clear(); } ObserverSet.prototype.add = function(sender, keyName, eventName) { var observerSet = this.observerSet, observers = this.observers, senderGuid = Ember.guidFor(sender), keySet = observerSet[senderGuid], index; if (!keySet) { observerSet[senderGuid] = keySet = {}; } index = keySet[keyName]; if (index === undefined) { index = observers.push({ sender: sender, keyName: keyName, eventName: eventName, listeners: [] }) - 1; keySet[keyName] = index; } return observers[index].listeners; }; ObserverSet.prototype.flush = function() { var observers = this.observers, i, len, observer, sender; this.clear(); for (i=0, len=observers.length; i < len; ++i) { observer = observers[i]; sender = observer.sender; if (sender.isDestroying || sender.isDestroyed) { continue; } Ember.sendEvent(sender, observer.eventName, [sender, observer.keyName], observer.listeners); } }; ObserverSet.prototype.clear = function() { this.observerSet = {}; this.observers = []; }; var beforeObserverSet = new ObserverSet(), observerSet = new ObserverSet(); /** @method beginPropertyChanges @chainable */ Ember.beginPropertyChanges = function() { deferred++; }; /** @method endPropertyChanges */ Ember.endPropertyChanges = function() { deferred--; if (deferred<=0) { beforeObserverSet.clear(); observerSet.flush(); } }; /** Make a series of property changes together in an exception-safe way. ```javascript Ember.changeProperties(function() { obj1.set('foo', mayBlowUpWhenSet); obj2.set('bar', baz); }); ``` @method changeProperties @param {Function} callback @param [binding] */ Ember.changeProperties = function(cb, binding){ Ember.beginPropertyChanges(); Ember.tryFinally(cb, Ember.endPropertyChanges, binding); }; /** Set a list of properties on an object. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. @method setProperties @param target @param {Hash} properties @return target */ Ember.setProperties = function(self, hash) { Ember.changeProperties(function(){ for(var prop in hash) { if (hash.hasOwnProperty(prop)) Ember.set(self, prop, hash[prop]); } }); return self; }; function changeEvent(keyName) { return keyName+AFTER_OBSERVERS; } function beforeEvent(keyName) { return keyName+BEFORE_OBSERVERS; } /** @method addObserver @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ Ember.addObserver = function(obj, path, target, method) { Ember.addListener(obj, changeEvent(path), target, method); Ember.watch(obj, path); return this; }; Ember.observersFor = function(obj, path) { return Ember.listenersFor(obj, changeEvent(path)); }; /** @method removeObserver @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ Ember.removeObserver = function(obj, path, target, method) { Ember.unwatch(obj, path); Ember.removeListener(obj, changeEvent(path), target, method); return this; }; /** @method addBeforeObserver @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ Ember.addBeforeObserver = function(obj, path, target, method) { Ember.addListener(obj, beforeEvent(path), target, method); Ember.watch(obj, path); return this; }; // Suspend observer during callback. // // This should only be used by the target of the observer // while it is setting the observed path. Ember._suspendBeforeObserver = function(obj, path, target, method, callback) { return Ember._suspendListener(obj, beforeEvent(path), target, method, callback); }; Ember._suspendObserver = function(obj, path, target, method, callback) { return Ember._suspendListener(obj, changeEvent(path), target, method, callback); }; var map = Ember.ArrayPolyfills.map; Ember._suspendBeforeObservers = function(obj, paths, target, method, callback) { var events = map.call(paths, beforeEvent); return Ember._suspendListeners(obj, events, target, method, callback); }; Ember._suspendObservers = function(obj, paths, target, method, callback) { var events = map.call(paths, changeEvent); return Ember._suspendListeners(obj, events, target, method, callback); }; Ember.beforeObserversFor = function(obj, path) { return Ember.listenersFor(obj, beforeEvent(path)); }; /** @method removeBeforeObserver @param obj @param {String} path @param {Object|Function} targetOrMethod @param {Function|String} [method] */ Ember.removeBeforeObserver = function(obj, path, target, method) { Ember.unwatch(obj, path); Ember.removeListener(obj, beforeEvent(path), target, method); return this; }; Ember.notifyBeforeObservers = function(obj, keyName) { if (obj.isDestroying) { return; } var eventName = beforeEvent(keyName), listeners, listenersDiff; if (deferred) { listeners = beforeObserverSet.add(obj, keyName, eventName); listenersDiff = Ember.listenersDiff(obj, eventName, listeners); Ember.sendEvent(obj, eventName, [obj, keyName], listenersDiff); } else { Ember.sendEvent(obj, eventName, [obj, keyName]); } }; Ember.notifyObservers = function(obj, keyName) { if (obj.isDestroying) { return; } var eventName = changeEvent(keyName), listeners; if (deferred) { listeners = observerSet.add(obj, keyName, eventName); Ember.listenersUnion(obj, eventName, listeners); } else { Ember.sendEvent(obj, eventName, [obj, keyName]); } }; })(); (function() { /** @module ember-metal */ var guidFor = Ember.guidFor, // utils.js metaFor = Ember.meta, // utils.js get = Ember.get, // accessors.js set = Ember.set, // accessors.js normalizeTuple = Ember.normalizeTuple, // accessors.js GUID_KEY = Ember.GUID_KEY, // utils.js META_KEY = Ember.META_KEY, // utils.js // circular reference observer depends on Ember.watch // we should move change events to this file or its own property_events.js notifyObservers = Ember.notifyObservers, // observer.js forEach = Ember.ArrayPolyfills.forEach, // array.js FIRST_KEY = /^([^\.\*]+)/, IS_PATH = /[\.\*]/; var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER, o_defineProperty = Ember.platform.defineProperty; function firstKey(path) { return path.match(FIRST_KEY)[0]; } // returns true if the passed path is just a keyName function isKeyName(path) { return path==='*' || !IS_PATH.test(path); } // .......................................................... // DEPENDENT KEYS // function iterDeps(method, obj, depKey, seen, meta) { var guid = guidFor(obj); if (!seen[guid]) seen[guid] = {}; if (seen[guid][depKey]) return; seen[guid][depKey] = true; var deps = meta.deps; deps = deps && deps[depKey]; if (deps) { for(var key in deps) { var desc = meta.descs[key]; if (desc && desc._suspended === obj) continue; method(obj, key); } } } var WILL_SEEN, DID_SEEN; // called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...) function dependentKeysWillChange(obj, depKey, meta) { if (obj.isDestroying) { return; } var seen = WILL_SEEN, top = !seen; if (top) { seen = WILL_SEEN = {}; } iterDeps(propertyWillChange, obj, depKey, seen, meta); if (top) { WILL_SEEN = null; } } // called whenever a property has just changed to update dependent keys function dependentKeysDidChange(obj, depKey, meta) { if (obj.isDestroying) { return; } var seen = DID_SEEN, top = !seen; if (top) { seen = DID_SEEN = {}; } iterDeps(propertyDidChange, obj, depKey, seen, meta); if (top) { DID_SEEN = null; } } // .......................................................... // CHAIN // function addChainWatcher(obj, keyName, node) { if (!obj || ('object' !== typeof obj)) { return; } // nothing to do var m = metaFor(obj), nodes = m.chainWatchers; if (!m.hasOwnProperty('chainWatchers')) { nodes = m.chainWatchers = {}; } if (!nodes[keyName]) { nodes[keyName] = []; } nodes[keyName].push(node); Ember.watch(obj, keyName); } function removeChainWatcher(obj, keyName, node) { if (!obj || 'object' !== typeof obj) { return; } // nothing to do var m = metaFor(obj, false); if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do var nodes = m.chainWatchers; if (nodes[keyName]) { nodes = nodes[keyName]; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i] === node) { nodes.splice(i, 1); } } } Ember.unwatch(obj, keyName); } var pendingQueue = []; // attempts to add the pendingQueue chains again. If some of them end up // back in the queue and reschedule is true, schedules a timeout to try // again. function flushPendingChains() { if (pendingQueue.length === 0) { return; } // nothing to do var queue = pendingQueue; pendingQueue = []; forEach.call(queue, function(q) { q[0].add(q[1]); }); Ember.warn('Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos', pendingQueue.length === 0); } function isProto(pvalue) { return metaFor(pvalue, false).proto === pvalue; } // A ChainNode watches a single key on an object. If you provide a starting // value for the key then the node won't actually watch it. For a root node // pass null for parent and key and object for value. var ChainNode = function(parent, key, value) { var obj; this._parent = parent; this._key = key; // _watching is true when calling get(this._parent, this._key) will // return the value of this node. // // It is false for the root of a chain (because we have no parent) // and for global paths (because the parent node is the object with // the observer on it) this._watching = value===undefined; this._value = value; this._paths = {}; if (this._watching) { this._object = parent.value(); if (this._object) { addChainWatcher(this._object, this._key, this); } } // Special-case: the EachProxy relies on immediate evaluation to // establish its observers. // // TODO: Replace this with an efficient callback that the EachProxy // can implement. if (this._parent && this._parent._key === '@each') { this.value(); } }; var ChainNodePrototype = ChainNode.prototype; ChainNodePrototype.value = function() { if (this._value === undefined && this._watching) { var obj = this._parent.value(); this._value = (obj && !isProto(obj)) ? get(obj, this._key) : undefined; } return this._value; }; ChainNodePrototype.destroy = function() { if (this._watching) { var obj = this._object; if (obj) { removeChainWatcher(obj, this._key, this); } this._watching = false; // so future calls do nothing } }; // copies a top level object only ChainNodePrototype.copy = function(obj) { var ret = new ChainNode(null, null, obj), paths = this._paths, path; for (path in paths) { if (paths[path] <= 0) { continue; } // this check will also catch non-number vals. ret.add(path); } return ret; }; // called on the root node of a chain to setup watchers on the specified // path. ChainNodePrototype.add = function(path) { var obj, tuple, key, src, paths; paths = this._paths; paths[path] = (paths[path] || 0) + 1; obj = this.value(); tuple = normalizeTuple(obj, path); // the path was a local path if (tuple[0] && tuple[0] === obj) { path = tuple[1]; key = firstKey(path); path = path.slice(key.length+1); // global path, but object does not exist yet. // put into a queue and try to connect later. } else if (!tuple[0]) { pendingQueue.push([this, path]); tuple.length = 0; return; // global path, and object already exists } else { src = tuple[0]; key = path.slice(0, 0-(tuple[1].length+1)); path = tuple[1]; } tuple.length = 0; this.chain(key, path, src); }; // called on the root node of a chain to teardown watcher on the specified // path ChainNodePrototype.remove = function(path) { var obj, tuple, key, src, paths; paths = this._paths; if (paths[path] > 0) { paths[path]--; } obj = this.value(); tuple = normalizeTuple(obj, path); if (tuple[0] === obj) { path = tuple[1]; key = firstKey(path); path = path.slice(key.length+1); } else { src = tuple[0]; key = path.slice(0, 0-(tuple[1].length+1)); path = tuple[1]; } tuple.length = 0; this.unchain(key, path); }; ChainNodePrototype.count = 0; ChainNodePrototype.chain = function(key, path, src) { var chains = this._chains, node; if (!chains) { chains = this._chains = {}; } node = chains[key]; if (!node) { node = chains[key] = new ChainNode(this, key, src); } node.count++; // count chains... // chain rest of path if there is one if (path && path.length>0) { key = firstKey(path); path = path.slice(key.length+1); node.chain(key, path); // NOTE: no src means it will observe changes... } }; ChainNodePrototype.unchain = function(key, path) { var chains = this._chains, node = chains[key]; // unchain rest of path first... if (path && path.length>1) { key = firstKey(path); path = path.slice(key.length+1); node.unchain(key, path); } // delete node if needed. node.count--; if (node.count<=0) { delete chains[node._key]; node.destroy(); } }; ChainNodePrototype.willChange = function() { var chains = this._chains; if (chains) { for(var key in chains) { if (!chains.hasOwnProperty(key)) { continue; } chains[key].willChange(); } } if (this._parent) { this._parent.chainWillChange(this, this._key, 1); } }; ChainNodePrototype.chainWillChange = function(chain, path, depth) { if (this._key) { path = this._key + '.' + path; } if (this._parent) { this._parent.chainWillChange(this, path, depth+1); } else { if (depth > 1) { Ember.propertyWillChange(this.value(), path); } path = 'this.' + path; if (this._paths[path] > 0) { Ember.propertyWillChange(this.value(), path); } } }; ChainNodePrototype.chainDidChange = function(chain, path, depth) { if (this._key) { path = this._key + '.' + path; } if (this._parent) { this._parent.chainDidChange(this, path, depth+1); } else { if (depth > 1) { Ember.propertyDidChange(this.value(), path); } path = 'this.' + path; if (this._paths[path] > 0) { Ember.propertyDidChange(this.value(), path); } } }; ChainNodePrototype.didChange = function(suppressEvent) { // invalidate my own value first. if (this._watching) { var obj = this._parent.value(); if (obj !== this._object) { removeChainWatcher(this._object, this._key, this); this._object = obj; addChainWatcher(obj, this._key, this); } this._value = undefined; // Special-case: the EachProxy relies on immediate evaluation to // establish its observers. if (this._parent && this._parent._key === '@each') this.value(); } // then notify chains... var chains = this._chains; if (chains) { for(var key in chains) { if (!chains.hasOwnProperty(key)) { continue; } chains[key].didChange(suppressEvent); } } if (suppressEvent) { return; } // and finally tell parent about my path changing... if (this._parent) { this._parent.chainDidChange(this, this._key, 1); } }; // get the chains for the current object. If the current object has // chains inherited from the proto they will be cloned and reconfigured for // the current object. function chainsFor(obj) { var m = metaFor(obj), ret = m.chains; if (!ret) { ret = m.chains = new ChainNode(null, null, obj); } else if (ret.value() !== obj) { ret = m.chains = ret.copy(obj); } return ret; } Ember.overrideChains = function(obj, keyName, m) { chainsDidChange(obj, keyName, m, true); }; function chainsWillChange(obj, keyName, m, arg) { if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do var nodes = m.chainWatchers; nodes = nodes[keyName]; if (!nodes) { return; } for(var i = 0, l = nodes.length; i < l; i++) { nodes[i].willChange(arg); } } function chainsDidChange(obj, keyName, m, arg) { if (!m.hasOwnProperty('chainWatchers')) { return; } // nothing to do var nodes = m.chainWatchers; nodes = nodes[keyName]; if (!nodes) { return; } // looping in reverse because the chainWatchers array can be modified inside didChange for (var i = nodes.length - 1; i >= 0; i--) { nodes[i].didChange(arg); } } // .......................................................... // WATCH // /** @private Starts watching a property on an object. Whenever the property changes, invokes `Ember.propertyWillChange` and `Ember.propertyDidChange`. This is the primitive used by observers and dependent keys; usually you will never call this method directly but instead use higher level methods like `Ember.addObserver()` @method watch @for Ember @param obj @param {String} keyName */ Ember.watch = function(obj, keyName) { // can't watch length on Array - it is special... if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; } var m = metaFor(obj), watching = m.watching, desc; // activate watching first time if (!watching[keyName]) { watching[keyName] = 1; if (isKeyName(keyName)) { desc = m.descs[keyName]; if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } if ('function' === typeof obj.willWatchProperty) { obj.willWatchProperty(keyName); } if (MANDATORY_SETTER && keyName in obj) { m.values[keyName] = obj[keyName]; o_defineProperty(obj, keyName, { configurable: true, enumerable: true, set: function() { Ember.assert('Must use Ember.set() to access this property', false); }, get: function() { var meta = this[META_KEY]; return meta && meta.values[keyName]; } }); } } else { chainsFor(obj).add(keyName); } } else { watching[keyName] = (watching[keyName] || 0) + 1; } return this; }; Ember.isWatching = function isWatching(obj, key) { var meta = obj[META_KEY]; return (meta && meta.watching[key]) > 0; }; Ember.watch.flushPending = flushPendingChains; Ember.unwatch = function(obj, keyName) { // can't watch length on Array - it is special... if (keyName === 'length' && Ember.typeOf(obj) === 'array') { return this; } var m = metaFor(obj), watching = m.watching, desc; if (watching[keyName] === 1) { watching[keyName] = 0; if (isKeyName(keyName)) { desc = m.descs[keyName]; if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); } if ('function' === typeof obj.didUnwatchProperty) { obj.didUnwatchProperty(keyName); } if (MANDATORY_SETTER && keyName in obj) { o_defineProperty(obj, keyName, { configurable: true, enumerable: true, writable: true, value: m.values[keyName] }); delete m.values[keyName]; } } else { chainsFor(obj).remove(keyName); } } else if (watching[keyName]>1) { watching[keyName]--; } return this; }; /** @private Call on an object when you first beget it from another object. This will setup any chained watchers on the object instance as needed. This method is safe to call multiple times. @method rewatch @for Ember @param obj */ Ember.rewatch = function(obj) { var m = metaFor(obj, false), chains = m.chains; // make sure the object has its own guid. if (GUID_KEY in obj && !obj.hasOwnProperty(GUID_KEY)) { Ember.generateGuid(obj, 'ember'); } // make sure any chained watchers update. if (chains && chains.value() !== obj) { m.chains = chains.copy(obj); } return this; }; Ember.finishChains = function(obj) { var m = metaFor(obj, false), chains = m.chains; if (chains) { if (chains.value() !== obj) { m.chains = chains = chains.copy(obj); } chains.didChange(true); } }; // .......................................................... // PROPERTY CHANGES // /** This function is called just before an object property is about to change. It will notify any before observers and prepare caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyDidChange()` which you should call just after the property value changes. @method propertyWillChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} */ function propertyWillChange(obj, keyName, value) { var m = metaFor(obj, false), watching = m.watching[keyName] > 0 || keyName === 'length', proto = m.proto, desc = m.descs[keyName]; if (!watching) { return; } if (proto === obj) { return; } if (desc && desc.willChange) { desc.willChange(obj, keyName); } dependentKeysWillChange(obj, keyName, m); chainsWillChange(obj, keyName, m); Ember.notifyBeforeObservers(obj, keyName); } Ember.propertyWillChange = propertyWillChange; /** This function is called just after an object property has changed. It will notify any observers and clear caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyWilLChange()` which you should call just before the property value changes. @method propertyDidChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} */ function propertyDidChange(obj, keyName) { var m = metaFor(obj, false), watching = m.watching[keyName] > 0 || keyName === 'length', proto = m.proto, desc = m.descs[keyName]; if (proto === obj) { return; } // shouldn't this mean that we're watching this key? if (desc && desc.didChange) { desc.didChange(obj, keyName); } if (!watching && keyName !== 'length') { return; } dependentKeysDidChange(obj, keyName, m); chainsDidChange(obj, keyName, m); Ember.notifyObservers(obj, keyName); } Ember.propertyDidChange = propertyDidChange; var NODE_STACK = []; /** Tears down the meta on an object so that it can be garbage collected. Multiple calls will have no effect. @method destroy @for Ember @param {Object} obj the object to destroy @return {void} */ Ember.destroy = function (obj) { var meta = obj[META_KEY], node, nodes, key, nodeObject; if (meta) { obj[META_KEY] = null; // remove chainWatchers to remove circular references that would prevent GC node = meta.chains; if (node) { NODE_STACK.push(node); // process tree while (NODE_STACK.length > 0) { node = NODE_STACK.pop(); // push children nodes = node._chains; if (nodes) { for (key in nodes) { if (nodes.hasOwnProperty(key)) { NODE_STACK.push(nodes[key]); } } } // remove chainWatcher in node object if (node._watching) { nodeObject = node._object; if (nodeObject) { removeChainWatcher(nodeObject, node._key, node); } } } } } }; })(); (function() { /** @module ember-metal */ Ember.warn("The CP_DEFAULT_CACHEABLE flag has been removed and computed properties are always cached by default. Use `volatile` if you don't want caching.", Ember.ENV.CP_DEFAULT_CACHEABLE !== false); var get = Ember.get, set = Ember.set, metaFor = Ember.meta, guidFor = Ember.guidFor, a_slice = [].slice, o_create = Ember.create, META_KEY = Ember.META_KEY, watch = Ember.watch, unwatch = Ember.unwatch; // .......................................................... // DEPENDENT KEYS // // data structure: // meta.deps = { // 'depKey': { // 'keyName': count, // } // } /* This function returns a map of unique dependencies for a given object and key. */ function keysForDep(obj, depsMeta, depKey) { var keys = depsMeta[depKey]; if (!keys) { // if there are no dependencies yet for a the given key // create a new empty list of dependencies for the key keys = depsMeta[depKey] = {}; } else if (!depsMeta.hasOwnProperty(depKey)) { // otherwise if the dependency list is inherited from // a superclass, clone the hash keys = depsMeta[depKey] = o_create(keys); } return keys; } /* return obj[META_KEY].deps */ function metaForDeps(obj, meta) { var deps = meta.deps; // If the current object has no dependencies... if (!deps) { // initialize the dependencies with a pointer back to // the current object deps = meta.deps = {}; } else if (!meta.hasOwnProperty('deps')) { // otherwise if the dependencies are inherited from the // object's superclass, clone the deps deps = meta.deps = o_create(deps); } return deps; } function addDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // add all of its dependent keys. var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys; if (!depKeys) return; depsMeta = metaForDeps(obj, meta); for(idx = 0, len = depKeys.length; idx < len; idx++) { depKey = depKeys[idx]; // Lookup keys meta for depKey keys = keysForDep(obj, depsMeta, depKey); // Increment the number of times depKey depends on keyName. keys[keyName] = (keys[keyName] || 0) + 1; // Watch the depKey watch(obj, depKey); } } function removeDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // add all of its dependent keys. var depKeys = desc._dependentKeys, depsMeta, idx, len, depKey, keys; if (!depKeys) return; depsMeta = metaForDeps(obj, meta); for(idx = 0, len = depKeys.length; idx < len; idx++) { depKey = depKeys[idx]; // Lookup keys meta for depKey keys = keysForDep(obj, depsMeta, depKey); // Increment the number of times depKey depends on keyName. keys[keyName] = (keys[keyName] || 0) - 1; // Watch the depKey unwatch(obj, depKey); } } // .......................................................... // COMPUTED PROPERTY // /** @class ComputedProperty @namespace Ember @extends Ember.Descriptor @constructor */ function ComputedProperty(func, opts) { this.func = func; this._cacheable = (opts && opts.cacheable !== undefined) ? opts.cacheable : true; this._dependentKeys = opts && opts.dependentKeys; } Ember.ComputedProperty = ComputedProperty; ComputedProperty.prototype = new Ember.Descriptor(); var ComputedPropertyPrototype = ComputedProperty.prototype; /** Call on a computed property to set it into cacheable mode. When in this mode the computed property will automatically cache the return value of your function until one of the dependent keys changes. ```javascript MyApp.president = Ember.Object.create({ fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); // After calculating the value of this function, Ember will // return that value without re-executing this function until // one of the dependent properties change. }.property('firstName', 'lastName') }); ``` Properties are cacheable by default. @method cacheable @param {Boolean} aFlag optional set to `false` to disable caching @chainable */ ComputedPropertyPrototype.cacheable = function(aFlag) { this._cacheable = aFlag !== false; return this; }; /** Call on a computed property to set it into non-cached mode. When in this mode the computed property will not automatically cache the return value. ```javascript MyApp.outsideService = Ember.Object.create({ value: function() { return OutsideService.getValue(); }.property().volatile() }); ``` @method volatile @chainable */ ComputedPropertyPrototype.volatile = function() { return this.cacheable(false); }; /** Sets the dependent keys on this computed property. Pass any number of arguments containing key paths that this computed property depends on. ```javascript MyApp.president = Ember.Object.create({ fullName: Ember.computed(function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember that this computed property depends on firstName // and lastName }).property('firstName', 'lastName') }); ``` @method property @param {String} path* zero or more property paths @chainable */ ComputedPropertyPrototype.property = function() { var args = []; for (var i = 0, l = arguments.length; i < l; i++) { args.push(arguments[i]); } this._dependentKeys = args; return this; }; /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ``` person: function() { var personId = this.get('personId'); return App.Person.create({ id: personId }); }.property().meta({ type: App.Person }) ``` The hash that you pass to the `meta()` function will be saved on the computed property descriptor under the `_meta` key. Ember runtime exposes a public API for retrieving these values from classes, via the `metaForProperty()` function. @method meta @param {Hash} meta @chainable */ ComputedPropertyPrototype.meta = function(meta) { if (arguments.length === 0) { return this._meta || {}; } else { this._meta = meta; return this; } }; /* impl descriptor API */ ComputedPropertyPrototype.willWatch = function(obj, keyName) { // watch already creates meta for this instance var meta = obj[META_KEY]; Ember.assert('watch should have setup meta to be writable', meta.source === obj); if (!(keyName in meta.cache)) { addDependentKeys(this, obj, keyName, meta); } }; ComputedPropertyPrototype.didUnwatch = function(obj, keyName) { var meta = obj[META_KEY]; Ember.assert('unwatch should have setup meta to be writable', meta.source === obj); if (!(keyName in meta.cache)) { // unwatch already creates meta for this instance removeDependentKeys(this, obj, keyName, meta); } }; /* impl descriptor API */ ComputedPropertyPrototype.didChange = function(obj, keyName) { // _suspended is set via a CP.set to ensure we don't clear // the cached value set by the setter if (this._cacheable && this._suspended !== obj) { var meta = metaFor(obj); if (keyName in meta.cache) { delete meta.cache[keyName]; if (!meta.watching[keyName]) { removeDependentKeys(this, obj, keyName, meta); } } } }; /* impl descriptor API */ ComputedPropertyPrototype.get = function(obj, keyName) { var ret, cache, meta; if (this._cacheable) { meta = metaFor(obj); cache = meta.cache; if (keyName in cache) { return cache[keyName]; } ret = cache[keyName] = this.func.call(obj, keyName); if (!meta.watching[keyName]) { addDependentKeys(this, obj, keyName, meta); } } else { ret = this.func.call(obj, keyName); } return ret; }; /* impl descriptor API */ ComputedPropertyPrototype.set = function(obj, keyName, value) { var cacheable = this._cacheable, func = this.func, meta = metaFor(obj, cacheable), watched = meta.watching[keyName], oldSuspended = this._suspended, hadCachedValue = false, cache = meta.cache, cachedValue, ret; this._suspended = obj; try { if (cacheable && cache.hasOwnProperty(keyName)) { cachedValue = cache[keyName]; hadCachedValue = true; } // Check if the CP has been wrapped if (func.wrappedFunction) { func = func.wrappedFunction; } // For backwards-compatibility with computed properties // that check for arguments.length === 2 to determine if // they are being get or set, only pass the old cached // value if the computed property opts into a third // argument. if (func.length === 3) { ret = func.call(obj, keyName, value, cachedValue); } else if (func.length === 2) { ret = func.call(obj, keyName, value); } else { Ember.defineProperty(obj, keyName, null, cachedValue); Ember.set(obj, keyName, value); return; } if (hadCachedValue && cachedValue === ret) { return; } if (watched) { Ember.propertyWillChange(obj, keyName); } if (hadCachedValue) { delete cache[keyName]; } if (cacheable) { if (!watched && !hadCachedValue) { addDependentKeys(this, obj, keyName, meta); } cache[keyName] = ret; } if (watched) { Ember.propertyDidChange(obj, keyName); } } finally { this._suspended = oldSuspended; } return ret; }; /* called when property is defined */ ComputedPropertyPrototype.setup = function(obj, keyName) { var meta = obj[META_KEY]; if (meta && meta.watching[keyName]) { addDependentKeys(this, obj, keyName, metaFor(obj)); } }; /* called before property is overridden */ ComputedPropertyPrototype.teardown = function(obj, keyName) { var meta = metaFor(obj); if (meta.watching[keyName] || keyName in meta.cache) { removeDependentKeys(this, obj, keyName, meta); } if (this._cacheable) { delete meta.cache[keyName]; } return null; // no value to restore }; /** This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with mixins or via `Ember.defineProperty()`. The function you pass will be used to both get and set property values. The function should accept two parameters, key and value. If value is not undefined you should set the value first. In either case return the current value of the property. @method computed @for Ember @param {Function} func The computed property function. @return {Ember.ComputedProperty} property descriptor instance */ Ember.computed = function(func) { var args; if (arguments.length > 1) { args = a_slice.call(arguments, 0, -1); func = a_slice.call(arguments, -1)[0]; } var cp = new ComputedProperty(func); if (args) { cp.property.apply(cp, args); } return cp; }; /** Returns the cached value for a property, if one exists. This can be useful for peeking at the value of a computed property that is generated lazily, without accidentally causing it to be created. @method cacheFor @for Ember @param {Object} obj the object whose property you want to check @param {String} key the name of the property whose cached value you want to return */ Ember.cacheFor = function cacheFor(obj, key) { var cache = metaFor(obj, false).cache; if (cache && key in cache) { return cache[key]; } }; /** @method computed.not @for Ember @param {String} dependentKey */ Ember.computed.not = function(dependentKey) { return Ember.computed(dependentKey, function(key) { return !get(this, dependentKey); }); }; /** @method computed.empty @for Ember @param {String} dependentKey */ Ember.computed.empty = function(dependentKey) { return Ember.computed(dependentKey, function(key) { var val = get(this, dependentKey); return val === undefined || val === null || val === '' || (Ember.isArray(val) && get(val, 'length') === 0); }); }; /** @method computed.bool @for Ember @param {String} dependentKey */ Ember.computed.bool = function(dependentKey) { return Ember.computed(dependentKey, function(key) { return !!get(this, dependentKey); }); }; /** @method computed.alias @for Ember @param {String} dependentKey */ Ember.computed.alias = function(dependentKey) { return Ember.computed(dependentKey, function(key, value){ if (arguments.length === 1) { return get(this, dependentKey); } else { set(this, dependentKey, value); return value; } }); }; })(); (function() { /** @module ember-metal */ var o_create = Ember.create, metaFor = Ember.meta, metaPath = Ember.metaPath, META_KEY = Ember.META_KEY; /* The event system uses a series of nested hashes to store listeners on an object. When a listener is registered, or when an event arrives, these hashes are consulted to determine which target and action pair to invoke. The hashes are stored in the object's meta hash, and look like this: // Object's meta hash { listeners: { // variable name: `listenerSet` "foo:changed": [ // variable name: `actions` [target, method, onceFlag, suspendedFlag] ] } } */ function indexOf(array, target, method) { var index = -1; for (var i = 0, l = array.length; i < l; i++) { if (target === array[i][0] && method === array[i][1]) { index = i; break; } } return index; } function actionsFor(obj, eventName) { var meta = metaFor(obj, true), actions; if (!meta.listeners) { meta.listeners = {}; } if (!meta.hasOwnProperty('listeners')) { // setup inherited copy of the listeners object meta.listeners = o_create(meta.listeners); } actions = meta.listeners[eventName]; // if there are actions, but the eventName doesn't exist in our listeners, then copy them from the prototype if (actions && !meta.listeners.hasOwnProperty(eventName)) { actions = meta.listeners[eventName] = meta.listeners[eventName].slice(); } else if (!actions) { actions = meta.listeners[eventName] = []; } return actions; } function actionsUnion(obj, eventName, otherActions) { var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return; } for (var i = actions.length - 1; i >= 0; i--) { var target = actions[i][0], method = actions[i][1], once = actions[i][2], suspended = actions[i][3], actionIndex = indexOf(otherActions, target, method); if (actionIndex === -1) { otherActions.push([target, method, once, suspended]); } } } function actionsDiff(obj, eventName, otherActions) { var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName], diffActions = []; if (!actions) { return; } for (var i = actions.length - 1; i >= 0; i--) { var target = actions[i][0], method = actions[i][1], once = actions[i][2], suspended = actions[i][3], actionIndex = indexOf(otherActions, target, method); if (actionIndex !== -1) { continue; } otherActions.push([target, method, once, suspended]); diffActions.push([target, method, once, suspended]); } return diffActions; } /** Add an event listener @method addListener @for Ember @param obj @param {String} eventName @param {Object|Function} targetOrMethod A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` */ function addListener(obj, eventName, target, method, once) { Ember.assert("You must pass at least an object and event name to Ember.addListener", !!obj && !!eventName); if (!method && 'function' === typeof target) { method = target; target = null; } var actions = actionsFor(obj, eventName), actionIndex = indexOf(actions, target, method); if (actionIndex !== -1) { return; } actions.push([target, method, once, undefined]); if ('function' === typeof obj.didAddListener) { obj.didAddListener(eventName, target, method); } } /** Remove an event listener Arguments should match those passed to {{#crossLink "Ember/addListener"}}{{/crossLink}} @method removeListener @for Ember @param obj @param {String} eventName @param {Object|Function} targetOrMethod A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` */ function removeListener(obj, eventName, target, method) { Ember.assert("You must pass at least an object and event name to Ember.removeListener", !!obj && !!eventName); if (!method && 'function' === typeof target) { method = target; target = null; } function _removeListener(target, method, once) { var actions = actionsFor(obj, eventName), actionIndex = indexOf(actions, target, method); // action doesn't exist, give up silently if (actionIndex === -1) { return; } actions.splice(actionIndex, 1); if ('function' === typeof obj.didRemoveListener) { obj.didRemoveListener(eventName, target, method); } } if (method) { _removeListener(target, method); } else { var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return; } for (var i = actions.length - 1; i >= 0; i--) { _removeListener(actions[i][0], actions[i][1]); } } } /** @private Suspend listener during callback. This should only be used by the target of the event listener when it is taking an action that would cause the event, e.g. an object might suspend its property change listener while it is setting that property. @method suspendListener @for Ember @param obj @param {String} eventName @param {Object|Function} targetOrMethod A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListener(obj, eventName, target, method, callback) { if (!method && 'function' === typeof target) { method = target; target = null; } var actions = actionsFor(obj, eventName), actionIndex = indexOf(actions, target, method), action; if (actionIndex !== -1) { action = actions[actionIndex].slice(); // copy it, otherwise we're modifying a shared object action[3] = true; // mark the action as suspended actions[actionIndex] = action; // replace the shared object with our copy } function tryable() { return callback.call(target); } function finalizer() { if (action) { action[3] = undefined; } } return Ember.tryFinally(tryable, finalizer); } /** @private Suspend listener during callback. This should only be used by the target of the event listener when it is taking an action that would cause the event, e.g. an object might suspend its property change listener while it is setting that property. @method suspendListener @for Ember @param obj @param {Array} eventName Array of event names @param {Object|Function} targetOrMethod A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListeners(obj, eventNames, target, method, callback) { if (!method && 'function' === typeof target) { method = target; target = null; } var suspendedActions = [], eventName, actions, action, i, l; for (i=0, l=eventNames.length; i<l; i++) { eventName = eventNames[i]; actions = actionsFor(obj, eventName); var actionIndex = indexOf(actions, target, method); if (actionIndex !== -1) { action = actions[actionIndex].slice(); action[3] = true; actions[actionIndex] = action; suspendedActions.push(action); } } function tryable() { return callback.call(target); } function finalizer() { for (i = 0, l = suspendedActions.length; i < l; i++) { suspendedActions[i][3] = undefined; } } return Ember.tryFinally(tryable, finalizer); } /** @private Return a list of currently watched events @method watchedEvents @for Ember @param obj */ function watchedEvents(obj) { var listeners = obj[META_KEY].listeners, ret = []; if (listeners) { for(var eventName in listeners) { if (listeners[eventName]) { ret.push(eventName); } } } return ret; } /** @method sendEvent @for Ember @param obj @param {String} eventName @param {Array} params @return true */ function sendEvent(obj, eventName, params, actions) { // first give object a chance to handle it if (obj !== Ember && 'function' === typeof obj.sendEvent) { obj.sendEvent(eventName, params); } if (!actions) { var meta = obj[META_KEY]; actions = meta && meta.listeners && meta.listeners[eventName]; } if (!actions) { return; } for (var i = actions.length - 1; i >= 0; i--) { // looping in reverse for once listeners if (!actions[i] || actions[i][3] === true) { continue; } var target = actions[i][0], method = actions[i][1], once = actions[i][2]; if (once) { removeListener(obj, eventName, target, method); } if (!target) { target = obj; } if ('string' === typeof method) { method = target[method]; } if (params) { method.apply(target, params); } else { method.apply(target); } } return true; } /** @private @method hasListeners @for Ember @param obj @param {String} eventName */ function hasListeners(obj, eventName) { var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName]; return !!(actions && actions.length); } /** @private @method listenersFor @for Ember @param obj @param {String} eventName */ function listenersFor(obj, eventName) { var ret = []; var meta = obj[META_KEY], actions = meta && meta.listeners && meta.listeners[eventName]; if (!actions) { return ret; } for (var i = 0, l = actions.length; i < l; i++) { var target = actions[i][0], method = actions[i][1]; ret.push([target, method]); } return ret; } Ember.addListener = addListener; Ember.removeListener = removeListener; Ember._suspendListener = suspendListener; Ember._suspendListeners = suspendListeners; Ember.sendEvent = sendEvent; Ember.hasListeners = hasListeners; Ember.watchedEvents = watchedEvents; Ember.listenersFor = listenersFor; Ember.listenersDiff = actionsDiff; Ember.listenersUnion = actionsUnion; })(); (function() { // Ember.Logger // Ember.watch.flushPending // Ember.beginPropertyChanges, Ember.endPropertyChanges // Ember.guidFor, Ember.tryFinally /** @module ember-metal */ // .......................................................... // HELPERS // var slice = [].slice, forEach = Ember.ArrayPolyfills.forEach; // invokes passed params - normalizing so you can pass target/func, // target/string or just func function invoke(target, method, args, ignore) { if (method === undefined) { method = target; target = undefined; } if ('string' === typeof method) { method = target[method]; } if (args && ignore > 0) { args = args.length > ignore ? slice.call(args, ignore) : null; } return Ember.handleErrors(function() { // IE8's Function.prototype.apply doesn't accept undefined/null arguments. return method.apply(target || this, args || []); }, this); } // .......................................................... // RUNLOOP // var timerMark; // used by timers... /** Ember RunLoop (Private) @class RunLoop @namespace Ember @private @constructor */ var RunLoop = function(prev) { this._prev = prev || null; this.onceTimers = {}; }; RunLoop.prototype = { /** @method end */ end: function() { this.flush(); }, /** @method prev */ prev: function() { return this._prev; }, // .......................................................... // Delayed Actions // /** @method schedule @param {String} queueName @param target @param method */ schedule: function(queueName, target, method) { var queues = this._queues, queue; if (!queues) { queues = this._queues = {}; } queue = queues[queueName]; if (!queue) { queue = queues[queueName] = []; } var args = arguments.length > 3 ? slice.call(arguments, 3) : null; queue.push({ target: target, method: method, args: args }); return this; }, /** @method flush @param {String} queueName */ flush: function(queueName) { var queueNames, idx, len, queue, log; if (!this._queues) { return this; } // nothing to do function iter(item) { invoke(item.target, item.method, item.args); } function tryable() { forEach.call(queue, iter); } Ember.watch.flushPending(); // make sure all chained watchers are setup if (queueName) { while (this._queues && (queue = this._queues[queueName])) { this._queues[queueName] = null; // the sync phase is to allow property changes to propagate. don't // invoke observers until that is finished. if (queueName === 'sync') { log = Ember.LOG_BINDINGS; if (log) { Ember.Logger.log('Begin: Flush Sync Queue'); } Ember.beginPropertyChanges(); Ember.tryFinally(tryable, Ember.endPropertyChanges); if (log) { Ember.Logger.log('End: Flush Sync Queue'); } } else { forEach.call(queue, iter); } } } else { queueNames = Ember.run.queues; len = queueNames.length; idx = 0; outerloop: while (idx < len) { queueName = queueNames[idx]; queue = this._queues && this._queues[queueName]; delete this._queues[queueName]; if (queue) { // the sync phase is to allow property changes to propagate. don't // invoke observers until that is finished. if (queueName === 'sync') { log = Ember.LOG_BINDINGS; if (log) { Ember.Logger.log('Begin: Flush Sync Queue'); } Ember.beginPropertyChanges(); Ember.tryFinally(tryable, Ember.endPropertyChanges); if (log) { Ember.Logger.log('End: Flush Sync Queue'); } } else { forEach.call(queue, iter); } } // Loop through prior queues for (var i = 0; i <= idx; i++) { if (this._queues && this._queues[queueNames[i]]) { // Start over at the first queue with contents idx = i; continue outerloop; } } idx++; } } timerMark = null; return this; } }; Ember.RunLoop = RunLoop; // .......................................................... // Ember.run - this is ideally the only public API the dev sees // /** Runs the passed target and method inside of a RunLoop, ensuring any deferred actions including bindings and views updates are flushed at the end. Normally you should not need to invoke this method yourself. However if you are implementing raw event handlers when interfacing with other libraries or plugins, you should probably wrap all of your code inside this call. ```javascript Ember.run(function(){ // code to be execute within a RunLoop }); ``` @class run @namespace Ember @static @constructor @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} return value from invoking the passed function. */ Ember.run = function(target, method) { var loop, args = arguments; run.begin(); function tryable() { if (target || method) { return invoke(target, method, args, 2); } } return Ember.tryFinally(tryable, run.end); }; var run = Ember.run; /** Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to `Ember.run.end()`. This is an lower-level way to use a RunLoop instead of using `Ember.run()`. ```javascript Ember.run.begin(); // code to be execute within a RunLoop Ember.run.end(); ``` @method begin @return {void} */ Ember.run.begin = function() { run.currentRunLoop = new RunLoop(run.currentRunLoop); }; /** Ends a RunLoop. This must be called sometime after you call `Ember.run.begin()` to flush any deferred actions. This is a lower-level way to use a RunLoop instead of using `Ember.run()`. ```javascript Ember.run.begin(); // code to be execute within a RunLoop Ember.run.end(); ``` @method end @return {void} */ Ember.run.end = function() { Ember.assert('must have a current run loop', run.currentRunLoop); function tryable() { run.currentRunLoop.end(); } function finalizer() { run.currentRunLoop = run.currentRunLoop.prev(); } Ember.tryFinally(tryable, finalizer); }; /** Array of named queues. This array determines the order in which queues are flushed at the end of the RunLoop. You can define your own queues by simply adding the queue name to this array. Normally you should not need to inspect or modify this property. @property queues @type Array @default ['sync', 'actions', 'destroy', 'timers'] */ Ember.run.queues = ['sync', 'actions', 'destroy', 'timers']; /** Adds the passed target/method and any optional arguments to the named queue to be executed at the end of the RunLoop. If you have not already started a RunLoop when calling this method one will be started for you automatically. At the end of a RunLoop, any methods scheduled in this way will be invoked. Methods will be invoked in an order matching the named queues defined in the `run.queues` property. ```javascript Ember.run.schedule('timers', this, function(){ // this will be executed at the end of the RunLoop, when timers are run console.log("scheduled on timers queue"); }); Ember.run.schedule('sync', this, function(){ // this will be executed at the end of the RunLoop, when bindings are synced console.log("scheduled on sync queue"); }); // Note the functions will be run in order based on the run queues order. Output would be: // scheduled on sync queue // scheduled on timers queue ``` @method schedule @param {String} queue The name of the queue to schedule against. Default queues are 'sync' and 'actions' @param {Object} [target] target object to use as the context when invoking a method. @param {String|Function} method The method to invoke. If you pass a string it will be resolved on the target object at the time the scheduled item is invoked allowing you to change the target function. @param {Object} [arguments*] Optional arguments to be passed to the queued method. @return {void} */ Ember.run.schedule = function(queue, target, method) { var loop = run.autorun(); loop.schedule.apply(loop, arguments); }; var scheduledAutorun; function autorun() { scheduledAutorun = null; if (run.currentRunLoop) { run.end(); } } // Used by global test teardown Ember.run.hasScheduledTimers = function() { return !!(scheduledAutorun || scheduledLater || scheduledNext); }; // Used by global test teardown Ember.run.cancelTimers = function () { if (scheduledAutorun) { clearTimeout(scheduledAutorun); scheduledAutorun = null; } if (scheduledLater) { clearTimeout(scheduledLater); scheduledLater = null; } if (scheduledNext) { clearTimeout(scheduledNext); scheduledNext = null; } timers = {}; }; /** Begins a new RunLoop if necessary and schedules a timer to flush the RunLoop at a later time. This method is used by parts of Ember to ensure the RunLoop always finishes. You normally do not need to call this method directly. Instead use `Ember.run()` @method autorun @example Ember.run.autorun(); @return {Ember.RunLoop} the new current RunLoop */ Ember.run.autorun = function() { if (!run.currentRunLoop) { Ember.assert("You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in an Ember.run", !Ember.testing); run.begin(); if (!scheduledAutorun) { scheduledAutorun = setTimeout(autorun, 1); } } return run.currentRunLoop; }; /** Immediately flushes any events scheduled in the 'sync' queue. Bindings use this queue so this method is a useful way to immediately force all bindings in the application to sync. You should call this method anytime you need any changed state to propagate throughout the app immediately without repainting the UI. ```javascript Ember.run.sync(); ``` @method sync @return {void} */ Ember.run.sync = function() { run.autorun(); run.currentRunLoop.flush('sync'); }; // .......................................................... // TIMERS // var timers = {}; // active timers... var scheduledLater; function invokeLaterTimers() { scheduledLater = null; var now = (+ new Date()), earliest = -1; for (var key in timers) { if (!timers.hasOwnProperty(key)) { continue; } var timer = timers[key]; if (timer && timer.expires) { if (now >= timer.expires) { delete timers[key]; invoke(timer.target, timer.method, timer.args, 2); } else { if (earliest<0 || (timer.expires < earliest)) earliest=timer.expires; } } } // schedule next timeout to fire... if (earliest > 0) { scheduledLater = setTimeout(invokeLaterTimers, earliest-(+ new Date())); } } /** Invokes the passed target/method and optional arguments after a specified period if time. The last parameter of this method must always be a number of milliseconds. You should use this method whenever you need to run some action after a period of time instead of using `setTimeout()`. This method will ensure that items that expire during the same script execution cycle all execute together, which is often more efficient than using a real setTimeout. ```javascript Ember.run.later(myContext, function(){ // code here will execute within a RunLoop in about 500ms with this == myContext }, 500); ``` @method later @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @return {String} a string you can use to cancel the timer in {{#crossLink "Ember/run.cancel"}}{{/crossLink}} later. */ Ember.run.later = function(target, method) { var args, expires, timer, guid, wait; // setTimeout compatibility... if (arguments.length===2 && 'function' === typeof target) { wait = method; method = target; target = undefined; args = [target, method]; } else { args = slice.call(arguments); wait = args.pop(); } expires = (+ new Date()) + wait; timer = { target: target, method: method, expires: expires, args: args }; guid = Ember.guidFor(timer); timers[guid] = timer; run.once(timers, invokeLaterTimers); return guid; }; function invokeOnceTimer(guid, onceTimers) { if (onceTimers[this.tguid]) { delete onceTimers[this.tguid][this.mguid]; } if (timers[guid]) { invoke(this.target, this.method, this.args); } delete timers[guid]; } function scheduleOnce(queue, target, method, args) { var tguid = Ember.guidFor(target), mguid = Ember.guidFor(method), onceTimers = run.autorun().onceTimers, guid = onceTimers[tguid] && onceTimers[tguid][mguid], timer; if (guid && timers[guid]) { timers[guid].args = args; // replace args } else { timer = { target: target, method: method, args: args, tguid: tguid, mguid: mguid }; guid = Ember.guidFor(timer); timers[guid] = timer; if (!onceTimers[tguid]) { onceTimers[tguid] = {}; } onceTimers[tguid][mguid] = guid; // so it isn't scheduled more than once run.schedule(queue, timer, invokeOnceTimer, guid, onceTimers); } return guid; } /** Schedules an item to run one time during the current RunLoop. Calling this method with the same target/method combination will have no effect. Note that although you can pass optional arguments these will not be considered when looking for duplicates. New arguments will replace previous calls. ```javascript Ember.run(function(){ var doFoo = function() { foo(); } Ember.run.once(myContext, doFoo); Ember.run.once(myContext, doFoo); // doFoo will only be executed once at the end of the RunLoop }); ``` @method once @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} timer */ Ember.run.once = function(target, method) { return scheduleOnce('actions', target, method, slice.call(arguments, 2)); }; Ember.run.scheduleOnce = function(queue, target, method, args) { return scheduleOnce(queue, target, method, slice.call(arguments, 3)); }; var scheduledNext; function invokeNextTimers() { scheduledNext = null; for(var key in timers) { if (!timers.hasOwnProperty(key)) { continue; } var timer = timers[key]; if (timer.next) { delete timers[key]; invoke(timer.target, timer.method, timer.args, 2); } } } /** Schedules an item to run after control has been returned to the system. This is often equivalent to calling `setTimeout(function() {}, 1)`. ```javascript Ember.run.next(myContext, function(){ // code to be executed in the next RunLoop, which will be scheduled after the current one }); ``` @method next @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} timer */ Ember.run.next = function(target, method) { var guid, timer = { target: target, method: method, args: slice.call(arguments), next: true }; guid = Ember.guidFor(timer); timers[guid] = timer; if (!scheduledNext) { scheduledNext = setTimeout(invokeNextTimers, 1); } return guid; }; /** Cancels a scheduled item. Must be a value returned by `Ember.run.later()`, `Ember.run.once()`, or `Ember.run.next()`. ```javascript var runNext = Ember.run.next(myContext, function(){ // will not be executed }); Ember.run.cancel(runNext); var runLater = Ember.run.later(myContext, function(){ // will not be executed }, 500); Ember.run.cancel(runLater); var runOnce = Ember.run.once(myContext, function(){ // will not be executed }); Ember.run.cancel(runOnce); ``` @method cancel @param {Object} timer Timer object to cancel @return {void} */ Ember.run.cancel = function(timer) { delete timers[timer]; }; })(); (function() { // Ember.Logger // get, set, trySet // guidFor, isArray, meta // addObserver, removeObserver // Ember.run.schedule /** @module ember-metal */ // .......................................................... // CONSTANTS // /** Debug parameter you can turn on. This will log all bindings that fire to the console. This should be disabled in production code. Note that you can also enable this from the console or temporarily. @property LOG_BINDINGS @for Ember @type Boolean @default false */ Ember.LOG_BINDINGS = false || !!Ember.ENV.LOG_BINDINGS; var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isGlobalPath = Ember.isGlobalPath; function getWithGlobals(obj, path) { return get(isGlobalPath(path) ? Ember.lookup : obj, path); } // .......................................................... // BINDING // var Binding = function(toPath, fromPath) { this._direction = 'fwd'; this._from = fromPath; this._to = toPath; this._directionMap = Ember.Map.create(); }; /** @class Binding @namespace Ember */ Binding.prototype = { /** This copies the Binding so it can be connected to another object. @method copy @return {Ember.Binding} */ copy: function () { var copy = new Binding(this._to, this._from); if (this._oneWay) { copy._oneWay = true; } return copy; }, // .......................................................... // CONFIG // /** This will set `from` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method from @param {String} propertyPath the property path to connect to @return {Ember.Binding} `this` */ from: function(path) { this._from = path; return this; }, /** This will set the `to` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method to @param {String|Tuple} propertyPath A property path or tuple @return {Ember.Binding} `this` */ to: function(path) { this._to = path; return this; }, /** Configures the binding as one way. A one-way binding will relay changes on the `from` side to the `to` side, but not the other way around. This means that if you change the `to` side directly, the `from` side may have a different value. @method oneWay @return {Ember.Binding} `this` */ oneWay: function() { this._oneWay = true; return this; }, toString: function() { var oneWay = this._oneWay ? '[oneWay]' : ''; return "Ember.Binding<" + guidFor(this) + ">(" + this._from + " -> " + this._to + ")" + oneWay; }, // .......................................................... // CONNECT AND SYNC // /** Attempts to connect this binding instance so that it can receive and relay changes. This method will raise an exception if you have not set the from/to properties yet. @method connect @param {Object} obj The root object for this binding. @return {Ember.Binding} `this` */ connect: function(obj) { Ember.assert('Must pass a valid object to Ember.Binding.connect()', !!obj); var fromPath = this._from, toPath = this._to; Ember.trySet(obj, toPath, getWithGlobals(obj, fromPath)); // add an observer on the object to be notified when the binding should be updated Ember.addObserver(obj, fromPath, this, this.fromDidChange); // if the binding is a two-way binding, also set up an observer on the target if (!this._oneWay) { Ember.addObserver(obj, toPath, this, this.toDidChange); } this._readyToSync = true; return this; }, /** Disconnects the binding instance. Changes will no longer be relayed. You will not usually need to call this method. @method disconnect @param {Object} obj The root object you passed when connecting the binding. @return {Ember.Binding} `this` */ disconnect: function(obj) { Ember.assert('Must pass a valid object to Ember.Binding.disconnect()', !!obj); var twoWay = !this._oneWay; // remove an observer on the object so we're no longer notified of // changes that should update bindings. Ember.removeObserver(obj, this._from, this, this.fromDidChange); // if the binding is two-way, remove the observer from the target as well if (twoWay) { Ember.removeObserver(obj, this._to, this, this.toDidChange); } this._readyToSync = false; // disable scheduled syncs... return this; }, // .......................................................... // PRIVATE // /* called when the from side changes */ fromDidChange: function(target) { this._scheduleSync(target, 'fwd'); }, /* called when the to side changes */ toDidChange: function(target) { this._scheduleSync(target, 'back'); }, _scheduleSync: function(obj, dir) { var directionMap = this._directionMap; var existingDir = directionMap.get(obj); // if we haven't scheduled the binding yet, schedule it if (!existingDir) { Ember.run.schedule('sync', this, this._sync, obj); directionMap.set(obj, dir); } // If both a 'back' and 'fwd' sync have been scheduled on the same object, // default to a 'fwd' sync so that it remains deterministic. if (existingDir === 'back' && dir === 'fwd') { directionMap.set(obj, 'fwd'); } }, _sync: function(obj) { var log = Ember.LOG_BINDINGS; // don't synchronize destroyed objects or disconnected bindings if (obj.isDestroyed || !this._readyToSync) { return; } // get the direction of the binding for the object we are // synchronizing from var directionMap = this._directionMap; var direction = directionMap.get(obj); var fromPath = this._from, toPath = this._to; directionMap.remove(obj); // if we're synchronizing from the remote object... if (direction === 'fwd') { var fromValue = getWithGlobals(obj, this._from); if (log) { Ember.Logger.log(' ', this.toString(), '->', fromValue, obj); } if (this._oneWay) { Ember.trySet(obj, toPath, fromValue); } else { Ember._suspendObserver(obj, toPath, this, this.toDidChange, function () { Ember.trySet(obj, toPath, fromValue); }); } // if we're synchronizing *to* the remote object } else if (direction === 'back') { var toValue = get(obj, this._to); if (log) { Ember.Logger.log(' ', this.toString(), '<-', toValue, obj); } Ember._suspendObserver(obj, fromPath, this, this.fromDidChange, function () { Ember.trySet(Ember.isGlobalPath(fromPath) ? Ember.lookup : obj, fromPath, toValue); }); } } }; function mixinProperties(to, from) { for (var key in from) { if (from.hasOwnProperty(key)) { to[key] = from[key]; } } } mixinProperties(Binding, { /** See {{#crossLink "Ember.Binding/from"}}{{/crossLink}} @method from @static */ from: function() { var C = this, binding = new C(); return binding.from.apply(binding, arguments); }, /** See {{#crossLink "Ember.Binding/to"}}{{/crossLink}} @method to @static */ to: function() { var C = this, binding = new C(); return binding.to.apply(binding, arguments); }, /** Creates a new Binding instance and makes it apply in a single direction. A one-way binding will relay changes on the `from` side object (supplied as the `from` argument) the `to` side, but not the other way around. This means that if you change the "to" side directly, the "from" side may have a different value. See {{#crossLink "Binding/oneWay"}}{{/crossLink}} @method oneWay @param {String} from from path. @param {Boolean} [flag] (Optional) passing nothing here will make the binding `oneWay`. You can instead pass `false` to disable `oneWay`, making the binding two way again. */ oneWay: function(from, flag) { var C = this, binding = new C(null, from); return binding.oneWay(flag); } }); /** An `Ember.Binding` connects the properties of two objects so that whenever the value of one property changes, the other property will be changed also. ## Automatic Creation of Bindings with `/^*Binding/`-named Properties You do not usually create Binding objects directly but instead describe bindings in your class or object definition using automatic binding detection. Properties ending in a `Binding` suffix will be converted to `Ember.Binding` instances. The value of this property should be a string representing a path to another object or a custom binding instanced created using Binding helpers (see "Customizing Your Bindings"): ``` valueBinding: "MyApp.someController.title" ``` This will create a binding from `MyApp.someController.title` to the `value` property of your object instance automatically. Now the two values will be kept in sync. ## One Way Bindings One especially useful binding customization you can use is the `oneWay()` helper. This helper tells Ember that you are only interested in receiving changes on the object you are binding from. For example, if you are binding to a preference and you want to be notified if the preference has changed, but your object will not be changing the preference itself, you could do: ``` bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles") ``` This way if the value of `MyApp.preferencesController.bigTitles` changes the `bigTitles` property of your object will change also. However, if you change the value of your `bigTitles` property, it will not update the `preferencesController`. One way bindings are almost twice as fast to setup and twice as fast to execute because the binding only has to worry about changes to one side. You should consider using one way bindings anytime you have an object that may be created frequently and you do not intend to change a property; only to monitor it for changes. (such as in the example above). ## Adding Bindings Manually All of the examples above show you how to configure a custom binding, but the result of these customizations will be a binding template, not a fully active Binding instance. The binding will actually become active only when you instantiate the object the binding belongs to. It is useful however, to understand what actually happens when the binding is activated. For a binding to function it must have at least a `from` property and a `to` property. The `from` property path points to the object/key that you want to bind from while the `to` path points to the object/key you want to bind to. When you define a custom binding, you are usually describing the property you want to bind from (such as `MyApp.someController.value` in the examples above). When your object is created, it will automatically assign the value you want to bind `to` based on the name of your binding key. In the examples above, during init, Ember objects will effectively call something like this on your binding: ```javascript binding = Ember.Binding.from(this.valueBinding).to("value"); ``` This creates a new binding instance based on the template you provide, and sets the to path to the `value` property of the new object. Now that the binding is fully configured with a `from` and a `to`, it simply needs to be connected to become active. This is done through the `connect()` method: ```javascript binding.connect(this); ``` Note that when you connect a binding you pass the object you want it to be connected to. This object will be used as the root for both the from and to side of the binding when inspecting relative paths. This allows the binding to be automatically inherited by subclassed objects as well. Now that the binding is connected, it will observe both the from and to side and relay changes. If you ever needed to do so (you almost never will, but it is useful to understand this anyway), you could manually create an active binding by using the `Ember.bind()` helper method. (This is the same method used by to setup your bindings on objects): ```javascript Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value"); ``` Both of these code fragments have the same effect as doing the most friendly form of binding creation like so: ```javascript MyApp.anotherObject = Ember.Object.create({ valueBinding: "MyApp.someController.value", // OTHER CODE FOR THIS OBJECT... }); ``` Ember's built in binding creation method makes it easy to automatically create bindings for you. You should always use the highest-level APIs available, even if you understand how it works underneath. @class Binding @namespace Ember @since Ember 0.9 */ Ember.Binding = Binding; /** Global helper method to create a new binding. Just pass the root object along with a `to` and `from` path to create and connect the binding. @method bind @for Ember @param {Object} obj The root object of the transform. @param {String} to The path to the 'to' side of the binding. Must be relative to obj. @param {String} from The path to the 'from' side of the binding. Must be relative to obj or a global path. @return {Ember.Binding} binding instance */ Ember.bind = function(obj, to, from) { return new Ember.Binding(to, from).connect(obj); }; /** @method oneWay @for Ember @param {Object} obj The root object of the transform. @param {String} to The path to the 'to' side of the binding. Must be relative to obj. @param {String} from The path to the 'from' side of the binding. Must be relative to obj or a global path. @return {Ember.Binding} binding instance */ Ember.oneWay = function(obj, to, from) { return new Ember.Binding(to, from).oneWay().connect(obj); }; })(); (function() { /** @module ember-metal */ var Mixin, REQUIRED, Alias, a_map = Ember.ArrayPolyfills.map, a_indexOf = Ember.ArrayPolyfills.indexOf, a_forEach = Ember.ArrayPolyfills.forEach, a_slice = [].slice, EMPTY_META = {}, // dummy for non-writable meta o_create = Ember.create, defineProperty = Ember.defineProperty, guidFor = Ember.guidFor; function mixinsMeta(obj) { var m = Ember.meta(obj, true), ret = m.mixins; if (!ret) { ret = m.mixins = {}; } else if (!m.hasOwnProperty('mixins')) { ret = m.mixins = o_create(ret); } return ret; } function initMixin(mixin, args) { if (args && args.length > 0) { mixin.mixins = a_map.call(args, function(x) { if (x instanceof Mixin) { return x; } // Note: Manually setup a primitive mixin here. This is the only // way to actually get a primitive mixin. This way normal creation // of mixins will give you combined mixins... var mixin = new Mixin(); mixin.properties = x; return mixin; }); } return mixin; } function isMethod(obj) { return 'function' === typeof obj && obj.isMethod !== false && obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String; } var CONTINUE = {}; function mixinProperties(mixinsMeta, mixin) { var guid; if (mixin instanceof Mixin) { guid = guidFor(mixin); if (mixinsMeta[guid]) { return CONTINUE; } mixinsMeta[guid] = mixin; return mixin.properties; } else { return mixin; // apply anonymous mixin properties } } function concatenatedProperties(props, values, base) { var concats; // reset before adding each new mixin to pickup concats from previous concats = values.concatenatedProperties || base.concatenatedProperties; if (props.concatenatedProperties) { concats = concats ? concats.concat(props.concatenatedProperties) : props.concatenatedProperties; } return concats; } function giveDescriptorSuper(meta, key, property, values, descs) { var superProperty; // Computed properties override methods, and do not call super to them if (values[key] === undefined) { // Find the original descriptor in a parent mixin superProperty = descs[key]; } // If we didn't find the original descriptor in a parent mixin, find // it on the original object. superProperty = superProperty || meta.descs[key]; if (!superProperty || !(superProperty instanceof Ember.ComputedProperty)) { return property; } // Since multiple mixins may inherit from the same parent, we need // to clone the computed property so that other mixins do not receive // the wrapped version. property = o_create(property); property.func = Ember.wrap(property.func, superProperty.func); return property; } function giveMethodSuper(obj, key, method, values, descs) { var superMethod; // Methods overwrite computed properties, and do not call super to them. if (descs[key] === undefined) { // Find the original method in a parent mixin superMethod = values[key]; } // If we didn't find the original value in a parent mixin, find it in // the original object superMethod = superMethod || obj[key]; // Only wrap the new method if the original method was a function if ('function' !== typeof superMethod) { return method; } return Ember.wrap(method, superMethod); } function applyConcatenatedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; if (baseValue) { if ('function' === typeof baseValue.concat) { return baseValue.concat(value); } else { return Ember.makeArray(baseValue).concat(value); } } else { return Ember.makeArray(value); } } function addNormalizedProperty(base, key, value, meta, descs, values, concats) { if (value instanceof Ember.Descriptor) { if (value === REQUIRED && descs[key]) { return CONTINUE; } // Wrap descriptor function to implement // _super() if needed if (value.func) { value = giveDescriptorSuper(meta, key, value, values, descs); } descs[key] = value; values[key] = undefined; } else { // impl super if needed... if (isMethod(value)) { value = giveMethodSuper(base, key, value, values, descs); } else if ((concats && a_indexOf.call(concats, key) >= 0) || key === 'concatenatedProperties') { value = applyConcatenatedProperties(base, key, value, values); } descs[key] = undefined; values[key] = value; } } function mergeMixins(mixins, m, descs, values, base) { var mixin, props, key, concats, meta; function removeKeys(keyName) { delete descs[keyName]; delete values[keyName]; } for(var i=0, l=mixins.length; i<l; i++) { mixin = mixins[i]; Ember.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(mixin), typeof mixin === 'object' && mixin !== null && Object.prototype.toString.call(mixin) !== '[object Array]'); props = mixinProperties(m, mixin); if (props === CONTINUE) { continue; } if (props) { meta = Ember.meta(base); concats = concatenatedProperties(props, values, base); for (key in props) { if (!props.hasOwnProperty(key)) { continue; } addNormalizedProperty(base, key, props[key], meta, descs, values, concats); } // manually copy toString() because some JS engines do not enumerate it if (props.hasOwnProperty('toString')) { base.toString = props.toString; } } else if (mixin.mixins) { mergeMixins(mixin.mixins, m, descs, values, base); if (mixin._without) { a_forEach.call(mixin._without, removeKeys); } } } } function writableReq(obj) { var m = Ember.meta(obj), req = m.required; if (!req || !m.hasOwnProperty('required')) { req = m.required = req ? o_create(req) : {}; } return req; } var IS_BINDING = Ember.IS_BINDING = /^.+Binding$/; function detectBinding(obj, key, value, m) { if (IS_BINDING.test(key)) { var bindings = m.bindings; if (!bindings) { bindings = m.bindings = {}; } else if (!m.hasOwnProperty('bindings')) { bindings = m.bindings = o_create(m.bindings); } bindings[key] = value; } } function connectBindings(obj, m) { // TODO Mixin.apply(instance) should disconnect binding if exists var bindings = m.bindings, key, binding, to; if (bindings) { for (key in bindings) { binding = bindings[key]; if (binding) { to = key.slice(0, -7); // strip Binding off end if (binding instanceof Ember.Binding) { binding = binding.copy(); // copy prototypes' instance binding.to(to); } else { // binding is string path binding = new Ember.Binding(to, binding); } binding.connect(obj); obj[key] = binding; } } // mark as applied m.bindings = {}; } } function finishPartial(obj, m) { connectBindings(obj, m || Ember.meta(obj)); return obj; } function followAlias(obj, desc, m, descs, values) { var altKey = desc.methodName, value; if (descs[altKey] || values[altKey]) { value = values[altKey]; desc = descs[altKey]; } else if (m.descs[altKey]) { desc = m.descs[altKey]; value = undefined; } else { desc = undefined; value = obj[altKey]; } return { desc: desc, value: value }; } function updateObservers(obj, key, observer, observerKey, method) { if ('function' !== typeof observer) { return; } var paths = observer[observerKey]; if (paths) { for (var i=0, l=paths.length; i<l; i++) { Ember[method](obj, paths[i], null, key); } } } function replaceObservers(obj, key, observer) { var prevObserver = obj[key]; updateObservers(obj, key, prevObserver, '__ember_observesBefore__', 'removeBeforeObserver'); updateObservers(obj, key, prevObserver, '__ember_observes__', 'removeObserver'); updateObservers(obj, key, observer, '__ember_observesBefore__', 'addBeforeObserver'); updateObservers(obj, key, observer, '__ember_observes__', 'addObserver'); } function applyMixin(obj, mixins, partial) { var descs = {}, values = {}, m = Ember.meta(obj), key, value, desc; // Go through all mixins and hashes passed in, and: // // * Handle concatenated properties // * Set up _super wrapping if necessary // * Set up computed property descriptors // * Copying `toString` in broken browsers mergeMixins(mixins, mixinsMeta(obj), descs, values, obj); for(key in values) { if (key === 'contructor' || !values.hasOwnProperty(key)) { continue; } desc = descs[key]; value = values[key]; if (desc === REQUIRED) { continue; } while (desc && desc instanceof Alias) { var followed = followAlias(obj, desc, m, descs, values); desc = followed.desc; value = followed.value; } if (desc === undefined && value === undefined) { continue; } replaceObservers(obj, key, value); detectBinding(obj, key, value, m); defineProperty(obj, key, desc, value, m); } if (!partial) { // don't apply to prototype finishPartial(obj, m); } return obj; } /** @method mixin @for Ember @param obj @param mixins* @return obj */ Ember.mixin = function(obj) { var args = a_slice.call(arguments, 1); applyMixin(obj, args, false); return obj; }; /** The `Ember.Mixin` class allows you to create mixins, whose properties can be added to other classes. For instance, ```javascript App.Editable = Ember.Mixin.create({ edit: function() { console.log('starting to edit'); this.set('isEditing', true); }, isEditing: false }); // Mix mixins into classes by passing them as the first arguments to // .extend or .create. App.CommentView = Ember.View.extend(App.Editable, { template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}') }); commentView = App.CommentView.create(); commentView.edit(); // outputs 'starting to edit' ``` Note that Mixins are created with `Ember.Mixin.create`, not `Ember.Mixin.extend`. @class Mixin @namespace Ember */ Ember.Mixin = function() { return initMixin(this, arguments); }; Mixin = Ember.Mixin; Mixin._apply = applyMixin; Mixin.applyPartial = function(obj) { var args = a_slice.call(arguments, 1); return applyMixin(obj, args, true); }; Mixin.finishPartial = finishPartial; Ember.anyUnprocessedMixins = false; /** @method create @static @param arguments* */ Mixin.create = function() { Ember.anyUnprocessedMixins = true; var M = this; return initMixin(new M(), arguments); }; var MixinPrototype = Mixin.prototype; /** @method reopen @param arguments* */ MixinPrototype.reopen = function() { var mixin, tmp; if (this.properties) { mixin = Mixin.create(); mixin.properties = this.properties; delete this.properties; this.mixins = [mixin]; } else if (!this.mixins) { this.mixins = []; } var len = arguments.length, mixins = this.mixins, idx; for(idx=0; idx < len; idx++) { mixin = arguments[idx]; Ember.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(mixin), typeof mixin === 'object' && mixin !== null && Object.prototype.toString.call(mixin) !== '[object Array]'); if (mixin instanceof Mixin) { mixins.push(mixin); } else { tmp = Mixin.create(); tmp.properties = mixin; mixins.push(tmp); } } return this; }; /** @method apply @param obj @return applied object */ MixinPrototype.apply = function(obj) { return applyMixin(obj, [this], false); }; MixinPrototype.applyPartial = function(obj) { return applyMixin(obj, [this], true); }; function _detect(curMixin, targetMixin, seen) { var guid = guidFor(curMixin); if (seen[guid]) { return false; } seen[guid] = true; if (curMixin === targetMixin) { return true; } var mixins = curMixin.mixins, loc = mixins ? mixins.length : 0; while (--loc >= 0) { if (_detect(mixins[loc], targetMixin, seen)) { return true; } } return false; } /** @method detect @param obj @return {Boolean} */ MixinPrototype.detect = function(obj) { if (!obj) { return false; } if (obj instanceof Mixin) { return _detect(obj, this, {}); } var mixins = Ember.meta(obj, false).mixins; if (mixins) { return !!mixins[guidFor(this)]; } return false; }; MixinPrototype.without = function() { var ret = new Mixin(this); ret._without = a_slice.call(arguments); return ret; }; function _keys(ret, mixin, seen) { if (seen[guidFor(mixin)]) { return; } seen[guidFor(mixin)] = true; if (mixin.properties) { var props = mixin.properties; for (var key in props) { if (props.hasOwnProperty(key)) { ret[key] = true; } } } else if (mixin.mixins) { a_forEach.call(mixin.mixins, function(x) { _keys(ret, x, seen); }); } } MixinPrototype.keys = function() { var keys = {}, seen = {}, ret = []; _keys(keys, this, seen); for(var key in keys) { if (keys.hasOwnProperty(key)) { ret.push(key); } } return ret; }; // returns the mixins currently applied to the specified object // TODO: Make Ember.mixin Mixin.mixins = function(obj) { var mixins = Ember.meta(obj, false).mixins, ret = []; if (!mixins) { return ret; } for (var key in mixins) { var mixin = mixins[key]; // skip primitive mixins since these are always anonymous if (!mixin.properties) { ret.push(mixin); } } return ret; }; REQUIRED = new Ember.Descriptor(); REQUIRED.toString = function() { return '(Required Property)'; }; /** Denotes a required property for a mixin @method required @for Ember */ Ember.required = function() { return REQUIRED; }; Alias = function(methodName) { this.methodName = methodName; }; Alias.prototype = new Ember.Descriptor(); /** Makes a property or method available via an additional name. ```javascript App.PaintSample = Ember.Object.extend({ color: 'red', colour: Ember.alias('color'), name: function(){ return "Zed"; }, moniker: Ember.alias("name") }); var paintSample = App.PaintSample.create() paintSample.get('colour'); // 'red' paintSample.moniker(); // 'Zed' ``` @method alias @for Ember @param {String} methodName name of the method or property to alias @return {Ember.Descriptor} @deprecated Use `Ember.aliasMethod` or `Ember.computed.alias` instead */ Ember.alias = function(methodName) { return new Alias(methodName); }; Ember.deprecateFunc("Ember.alias is deprecated. Please use Ember.aliasMethod or Ember.computed.alias instead.", Ember.alias); /** Makes a method available via an additional name. ```javascript App.Person = Ember.Object.extend({ name: function(){ return 'Tomhuda Katzdale'; }, moniker: Ember.aliasMethod('name') }); var goodGuy = App.Person.create() ``` @method aliasMethod @for Ember @param {String} methodName name of the method to alias @return {Ember.Descriptor} */ Ember.aliasMethod = function(methodName) { return new Alias(methodName); }; // .......................................................... // OBSERVER HELPER // /** @method observer @for Ember @param {Function} func @param {String} propertyNames* @return func */ Ember.observer = function(func) { var paths = a_slice.call(arguments, 1); func.__ember_observes__ = paths; return func; }; // If observers ever become asynchronous, Ember.immediateObserver // must remain synchronous. /** @method immediateObserver @for Ember @param {Function} func @param {String} propertyNames* @return func */ Ember.immediateObserver = function() { for (var i=0, l=arguments.length; i<l; i++) { var arg = arguments[i]; Ember.assert("Immediate observers must observe internal properties only, not properties on other objects.", typeof arg !== "string" || arg.indexOf('.') === -1); } return Ember.observer.apply(this, arguments); }; /** @method beforeObserver @for Ember @param {Function} func @param {String} propertyNames* @return func */ Ember.beforeObserver = function(func) { var paths = a_slice.call(arguments, 1); func.__ember_observesBefore__ = paths; return func; }; })(); (function() { /** Ember Metal @module ember @submodule ember-metal */ })(); (function() { define("rsvp", [], function() { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var MutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var RSVP, async; if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { async = function(callback, binding) { process.nextTick(function() { callback.call(binding); }); }; } else if (MutationObserver) { var queue = []; var observer = new MutationObserver(function() { var toProcess = queue.slice(); queue = []; toProcess.forEach(function(tuple) { var callback = tuple[0], binding = tuple[1]; callback.call(binding); }); }); var element = document.createElement('div'); observer.observe(element, { attributes: true }); // Chrome Memory Leak: https://bugs.webkit.org/show_bug.cgi?id=93661 window.addEventListener('unload', function(){ observer.disconnect(); observer = null; }); async = function(callback, binding) { queue.push([callback, binding]); element.setAttribute('drainQueue', 'drainQueue'); }; } else { async = function(callback, binding) { setTimeout(function() { callback.call(binding); }, 1); }; } var Event = function(type, options) { this.type = type; for (var option in options) { if (!options.hasOwnProperty(option)) { continue; } this[option] = options[option]; } }; var indexOf = function(callbacks, callback) { for (var i=0, l=callbacks.length; i<l; i++) { if (callbacks[i][0] === callback) { return i; } } return -1; }; var callbacksFor = function(object) { var callbacks = object._promiseCallbacks; if (!callbacks) { callbacks = object._promiseCallbacks = {}; } return callbacks; }; var EventTarget = { mixin: function(object) { object.on = this.on; object.off = this.off; object.trigger = this.trigger; return object; }, on: function(eventNames, callback, binding) { var allCallbacks = callbacksFor(this), callbacks, eventName; eventNames = eventNames.split(/\s+/); binding = binding || this; while (eventName = eventNames.shift()) { callbacks = allCallbacks[eventName]; if (!callbacks) { callbacks = allCallbacks[eventName] = []; } if (indexOf(callbacks, callback) === -1) { callbacks.push([callback, binding]); } } }, off: function(eventNames, callback) { var allCallbacks = callbacksFor(this), callbacks, eventName, index; eventNames = eventNames.split(/\s+/); while (eventName = eventNames.shift()) { if (!callback) { allCallbacks[eventName] = []; continue; } callbacks = allCallbacks[eventName]; index = indexOf(callbacks, callback); if (index !== -1) { callbacks.splice(index, 1); } } }, trigger: function(eventName, options) { var allCallbacks = callbacksFor(this), callbacks, callbackTuple, callback, binding, event; if (callbacks = allCallbacks[eventName]) { for (var i=0, l=callbacks.length; i<l; i++) { callbackTuple = callbacks[i]; callback = callbackTuple[0]; binding = callbackTuple[1]; if (typeof options !== 'object') { options = { detail: options }; } event = new Event(eventName, options); callback.call(binding, event); } } } }; var Promise = function() { this.on('promise:resolved', function(event) { this.trigger('success', { detail: event.detail }); }, this); this.on('promise:failed', function(event) { this.trigger('error', { detail: event.detail }); }, this); }; var noop = function() {}; var invokeCallback = function(type, promise, callback, event) { var hasCallback = typeof callback === 'function', value, error, succeeded, failed; if (hasCallback) { try { value = callback(event.detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = event.detail; succeeded = true; } if (value && typeof value.then === 'function') { value.then(function(value) { promise.resolve(value); }, function(error) { promise.reject(error); }); } else if (hasCallback && succeeded) { promise.resolve(value); } else if (failed) { promise.reject(error); } else { promise[type](value); } }; Promise.prototype = { then: function(done, fail) { var thenPromise = new Promise(); if (this.isResolved) { RSVP.async(function() { invokeCallback('resolve', thenPromise, done, { detail: this.resolvedValue }); }, this); } if (this.isRejected) { RSVP.async(function() { invokeCallback('reject', thenPromise, fail, { detail: this.rejectedValue }); }, this); } this.on('promise:resolved', function(event) { invokeCallback('resolve', thenPromise, done, event); }); this.on('promise:failed', function(event) { invokeCallback('reject', thenPromise, fail, event); }); return thenPromise; }, resolve: function(value) { resolve(this, value); this.resolve = noop; this.reject = noop; }, reject: function(value) { reject(this, value); this.resolve = noop; this.reject = noop; } }; function resolve(promise, value) { RSVP.async(function() { promise.trigger('promise:resolved', { detail: value }); promise.isResolved = true; promise.resolvedValue = value; }); } function reject(promise, value) { RSVP.async(function() { promise.trigger('promise:failed', { detail: value }); promise.isRejected = true; promise.rejectedValue = value; }); } EventTarget.mixin(Promise.prototype); RSVP = { async: async, Promise: Promise, Event: Event, EventTarget: EventTarget }; return RSVP; }); })(); (function() { define("container", [], function() { var objectCreate = Object.create || function(parent) { function F() {} F.prototype = parent; return new F(); }; function InheritingDict(parent) { this.parent = parent; this.dict = {}; } InheritingDict.prototype = { get: function(key) { var dict = this.dict; if (dict.hasOwnProperty(key)) { return dict[key]; } if (this.parent) { return this.parent.get(key); } }, set: function(key, value) { this.dict[key] = value; }, has: function(key) { var dict = this.dict; if (dict.hasOwnProperty(key)) { return true; } if (this.parent) { return this.parent.has(key); } return false; }, eachLocal: function(callback, binding) { var dict = this.dict; for (var prop in dict) { if (dict.hasOwnProperty(prop)) { callback.call(binding, prop, dict[prop]); } } } }; function Container(parent) { this.parent = parent; this.children = []; this.resolver = parent && parent.resolver || function() {}; this.registry = new InheritingDict(parent && parent.registry); this.cache = new InheritingDict(parent && parent.cache); this.typeInjections = {}; this.injections = {}; this.options = {}; this.typeOptions = {}; } Container.prototype = { child: function() { var container = new Container(this); this.children.push(container); return container; }, set: function(object, key, value) { object[key] = value; }, register: function(type, name, factory, options) { this.registry.set(type + ":" + name, factory); this.options[type + ":" + name] = options || {}; }, resolve: function(fullName) { return this.resolver(fullName) || this.registry.get(fullName); }, lookup: function(fullName) { if (this.cache.has(fullName)) { return this.cache.get(fullName); } var value = instantiate(this, fullName); if (!value) { return; } if (isSingleton(this, fullName)) { this.cache.set(fullName, value); } return value; }, has: function(fullName) { if (this.cache.has(fullName)) { return true; } return !!factoryFor(this, fullName); }, optionsForType: function(type, options) { if (this.parent) { illegalChildOperation('optionsForType'); } this.typeOptions[type] = options; }, typeInjection: function(type, property, fullName) { if (this.parent) { illegalChildOperation('typeInjection'); } var injections = this.typeInjections[type] = this.typeInjections[type] || []; injections.push({ property: property, fullName: fullName }); }, injection: function(factoryName, property, injectionName) { if (this.parent) { illegalChildOperation('injection'); } var injections = this.injections[factoryName] = this.injections[factoryName] || []; injections.push({ property: property, fullName: injectionName }); }, destroy: function() { this.isDestroyed = true; for (var i=0, l=this.children.length; i<l; i++) { this.children[i].destroy(); } this.children = []; eachDestroyable(this, function(item) { item.isDestroying = true; }); eachDestroyable(this, function(item) { item.destroy(); }); delete this.parent; this.isDestroyed = true; }, reset: function() { for (var i=0, l=this.children.length; i<l; i++) { resetCache(this.children[i]); } resetCache(this); } }; function illegalChildOperation(operation) { throw new Error(operation + " is not currently supported on child containers"); } function isSingleton(container, fullName) { var singleton = option(container, fullName, 'singleton'); return singleton !== false; } function buildInjections(container, injections) { var hash = {}; if (!injections) { return hash; } var injection, lookup; for (var i=0, l=injections.length; i<l; i++) { injection = injections[i]; lookup = container.lookup(injection.fullName); hash[injection.property] = lookup; } return hash; } function option(container, fullName, optionName) { var options = container.options[fullName]; if (options && options[optionName] !== undefined) { return options[optionName]; } var type = fullName.split(":")[0]; options = container.typeOptions[type]; if (options) { return options[optionName]; } } function factoryFor(container, fullName) { return container.resolve(fullName); } function instantiate(container, fullName) { var factory = factoryFor(container, fullName); var splitName = fullName.split(":"), type = splitName[0], name = splitName[1], value; if (option(container, fullName, 'instantiate') === false) { return factory; } if (factory) { var injections = []; injections = injections.concat(container.typeInjections[type] || []); injections = injections.concat(container.injections[fullName] || []); var hash = buildInjections(container, injections); hash.container = container; value = factory.create(hash); return value; } } function eachDestroyable(container, callback) { container.cache.eachLocal(function(key, value) { if (option(container, key, 'instantiate') === false) { return; } callback(value); }); } function resetCache(container) { container.cache.eachLocal(function(key, value) { if (option(container, key, 'instantiate') === false) { return; } value.destroy(); }); container.cache.dict = {}; } return Container; }); })(); (function() { /*globals ENV */ /** @module ember @submodule ember-runtime */ var indexOf = Ember.EnumerableUtils.indexOf; // ........................................ // TYPING & ARRAY MESSAGING // var TYPE_MAP = {}; var t = "Boolean Number String Function Array Date RegExp Object".split(" "); Ember.ArrayPolyfills.forEach.call(t, function(name) { TYPE_MAP[ "[object " + name + "]" ] = name.toLowerCase(); }); var toString = Object.prototype.toString; /** Returns a consistent type for the passed item. Use this instead of the built-in `typeof` to get the type of an item. It will return the same result across all browsers and includes a bit more detail. Here is what will be returned: | Return Value | Meaning | |---------------|------------------------------------------------------| | 'string' | String primitive | | 'number' | Number primitive | | 'boolean' | Boolean primitive | | 'null' | Null value | | 'undefined' | Undefined value | | 'function' | A function | | 'array' | An instance of Array | | 'class' | A Ember class (created using Ember.Object.extend()) | | 'instance' | A Ember object instance | | 'error' | An instance of the Error object | | 'object' | A JavaScript object not inheriting from Ember.Object | Examples: ```javascript Ember.typeOf(); // 'undefined' Ember.typeOf(null); // 'null' Ember.typeOf(undefined); // 'undefined' Ember.typeOf('michael'); // 'string' Ember.typeOf(101); // 'number' Ember.typeOf(true); // 'boolean' Ember.typeOf(Ember.makeArray); // 'function' Ember.typeOf([1,2,90]); // 'array' Ember.typeOf(Ember.Object.extend()); // 'class' Ember.typeOf(Ember.Object.create()); // 'instance' Ember.typeOf(new Error('teamocil')); // 'error' // "normal" JavaScript object Ember.typeOf({a: 'b'}); // 'object' ``` @method typeOf @for Ember @param item {Object} the item to check @return {String} the type */ Ember.typeOf = function(item) { var ret; ret = (item === null || item === undefined) ? String(item) : TYPE_MAP[toString.call(item)] || 'object'; if (ret === 'function') { if (Ember.Object && Ember.Object.detect(item)) ret = 'class'; } else if (ret === 'object') { if (item instanceof Error) ret = 'error'; else if (Ember.Object && item instanceof Ember.Object) ret = 'instance'; else ret = 'object'; } return ret; }; /** Returns true if the passed value is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. ```javascript Ember.isNone(); // true Ember.isNone(null); // true Ember.isNone(undefined); // true Ember.isNone(''); // false Ember.isNone([]); // false Ember.isNone(function(){}); // false ``` @method isNone @for Ember @param {Object} obj Value to test @return {Boolean} */ Ember.isNone = function(obj) { return obj === null || obj === undefined; }; Ember.none = Ember.deprecateFunc("Ember.none is deprecated. Please use Ember.isNone instead.", Ember.isNone); /** Verifies that a value is `null` or an empty string, empty array, or empty function. Constrains the rules on `Ember.isNone` by returning false for empty string and empty arrays. ```javascript Ember.isEmpty(); // true Ember.isEmpty(null); // true Ember.isEmpty(undefined); // true Ember.isEmpty(''); // true Ember.isEmpty([]); // true Ember.isEmpty('Adam Hawkins'); // false Ember.isEmpty([0,1,2]); // false ``` @method isEmpty @for Ember @param {Object} obj Value to test @return {Boolean} */ Ember.isEmpty = function(obj) { return obj === null || obj === undefined || (obj.length === 0 && typeof obj !== 'function') || (typeof obj === 'object' && Ember.get(obj, 'length') === 0); }; Ember.empty = Ember.deprecateFunc("Ember.empty is deprecated. Please use Ember.isEmpty instead.", Ember.isEmpty) ; /** This will compare two javascript values of possibly different types. It will tell you which one is greater than the other by returning: - -1 if the first is smaller than the second, - 0 if both are equal, - 1 if the first is greater than the second. The order is calculated based on `Ember.ORDER_DEFINITION`, if types are different. In case they have the same type an appropriate comparison for this type is made. ```javascript Ember.compare('hello', 'hello'); // 0 Ember.compare('abc', 'dfg'); // -1 Ember.compare(2, 1); // 1 ```javascript @method compare @for Ember @param {Object} v First value to compare @param {Object} w Second value to compare @return {Number} -1 if v < w, 0 if v = w and 1 if v > w. */ Ember.compare = function compare(v, w) { if (v === w) { return 0; } var type1 = Ember.typeOf(v); var type2 = Ember.typeOf(w); var Comparable = Ember.Comparable; if (Comparable) { if (type1==='instance' && Comparable.detect(v.constructor)) { return v.constructor.compare(v, w); } if (type2 === 'instance' && Comparable.detect(w.constructor)) { return 1-w.constructor.compare(w, v); } } // If we haven't yet generated a reverse-mapping of Ember.ORDER_DEFINITION, // do so now. var mapping = Ember.ORDER_DEFINITION_MAPPING; if (!mapping) { var order = Ember.ORDER_DEFINITION; mapping = Ember.ORDER_DEFINITION_MAPPING = {}; var idx, len; for (idx = 0, len = order.length; idx < len; ++idx) { mapping[order[idx]] = idx; } // We no longer need Ember.ORDER_DEFINITION. delete Ember.ORDER_DEFINITION; } var type1Index = mapping[type1]; var type2Index = mapping[type2]; if (type1Index < type2Index) { return -1; } if (type1Index > type2Index) { return 1; } // types are equal - so we have to check values now switch (type1) { case 'boolean': case 'number': if (v < w) { return -1; } if (v > w) { return 1; } return 0; case 'string': var comp = v.localeCompare(w); if (comp < 0) { return -1; } if (comp > 0) { return 1; } return 0; case 'array': var vLen = v.length; var wLen = w.length; var l = Math.min(vLen, wLen); var r = 0; var i = 0; while (r === 0 && i < l) { r = compare(v[i],w[i]); i++; } if (r !== 0) { return r; } // all elements are equal now // shorter array should be ordered first if (vLen < wLen) { return -1; } if (vLen > wLen) { return 1; } // arrays are equal now return 0; case 'instance': if (Ember.Comparable && Ember.Comparable.detect(v)) { return v.compare(v, w); } return 0; case 'date': var vNum = v.getTime(); var wNum = w.getTime(); if (vNum < wNum) { return -1; } if (vNum > wNum) { return 1; } return 0; default: return 0; } }; function _copy(obj, deep, seen, copies) { var ret, loc, key; // primitive data types are immutable, just return them. if ('object' !== typeof obj || obj===null) return obj; // avoid cyclical loops if (deep && (loc=indexOf(seen, obj))>=0) return copies[loc]; Ember.assert('Cannot clone an Ember.Object that does not implement Ember.Copyable', !(obj instanceof Ember.Object) || (Ember.Copyable && Ember.Copyable.detect(obj))); // IMPORTANT: this specific test will detect a native array only. Any other // object will need to implement Copyable. if (Ember.typeOf(obj) === 'array') { ret = obj.slice(); if (deep) { loc = ret.length; while(--loc>=0) ret[loc] = _copy(ret[loc], deep, seen, copies); } } else if (Ember.Copyable && Ember.Copyable.detect(obj)) { ret = obj.copy(deep, seen, copies); } else { ret = {}; for(key in obj) { if (!obj.hasOwnProperty(key)) continue; // Prevents browsers that don't respect non-enumerability from // copying internal Ember properties if (key.substring(0,2) === '__') continue; ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key]; } } if (deep) { seen.push(obj); copies.push(ret); } return ret; } /** Creates a clone of the passed object. This function can take just about any type of object and create a clone of it, including primitive values (which are not actually cloned because they are immutable). If the passed object implements the `clone()` method, then this function will simply call that method and return the result. @method copy @for Ember @param {Object} object The object to clone @param {Boolean} deep If true, a deep copy of the object is made @return {Object} The cloned object */ Ember.copy = function(obj, deep) { // fast paths if ('object' !== typeof obj || obj===null) return obj; // can't copy primitives if (Ember.Copyable && Ember.Copyable.detect(obj)) return obj.copy(deep); return _copy(obj, deep, deep ? [] : null, deep ? [] : null); }; /** Convenience method to inspect an object. This method will attempt to convert the object into a useful string description. It is a pretty simple implementation. If you want something more robust, use something like JSDump: https://github.com/NV/jsDump @method inspect @for Ember @param {Object} obj The object you want to inspect. @return {String} A description of the object */ Ember.inspect = function(obj) { if (typeof obj !== 'object' || obj === null) { return obj + ''; } var v, ret = []; for(var key in obj) { if (obj.hasOwnProperty(key)) { v = obj[key]; if (v === 'toString') { continue; } // ignore useless items if (Ember.typeOf(v) === 'function') { v = "function() { ... }"; } ret.push(key + ": " + v); } } return "{" + ret.join(", ") + "}"; }; /** Compares two objects, returning true if they are logically equal. This is a deeper comparison than a simple triple equal. For sets it will compare the internal objects. For any other object that implements `isEqual()` it will respect that method. ```javascript Ember.isEqual('hello', 'hello'); // true Ember.isEqual(1, 2); // false Ember.isEqual([4,2], [4,2]); // false ``` @method isEqual @for Ember @param {Object} a first object to compare @param {Object} b second object to compare @return {Boolean} */ Ember.isEqual = function(a, b) { if (a && 'function'===typeof a.isEqual) return a.isEqual(b); return a === b; }; // Used by Ember.compare Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [ 'undefined', 'null', 'boolean', 'number', 'string', 'array', 'object', 'instance', 'function', 'class', 'date' ]; /** Returns all of the keys defined on an object or hash. This is useful when inspecting objects for debugging. On browsers that support it, this uses the native `Object.keys` implementation. @method keys @for Ember @param {Object} obj @return {Array} Array containing keys of obj */ Ember.keys = Object.keys; if (!Ember.keys) { Ember.keys = function(obj) { var ret = []; for(var key in obj) { if (obj.hasOwnProperty(key)) { ret.push(key); } } return ret; }; } // .......................................................... // ERROR // var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A subclass of the JavaScript Error object for use in Ember. @class Error @namespace Ember @extends Error @constructor */ Ember.Error = function() { var tmp = Error.prototype.constructor.apply(this, arguments); // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } }; Ember.Error.prototype = Ember.create(Error.prototype); })(); (function() { /** @module ember @submodule ember-runtime */ var STRING_DASHERIZE_REGEXP = (/[ _]/g); var STRING_DASHERIZE_CACHE = {}; var STRING_DECAMELIZE_REGEXP = (/([a-z])([A-Z])/g); var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g); var STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g); var STRING_UNDERSCORE_REGEXP_2 = (/\-|\s+/g); /** Defines the hash of localized strings for the current language. Used by the `Ember.String.loc()` helper. To localize, add string values to this hash. @property STRINGS @for Ember @type Hash */ Ember.STRINGS = {}; /** Defines string helper methods including string formatting and localization. Unless `Ember.EXTEND_PROTOTYPES.String` is `false` these methods will also be added to the `String.prototype` as well. @class String @namespace Ember @static */ Ember.String = { /** Apply formatting options to the string. This will look for occurrences of "%@" in your string and substitute them with the arguments you pass into this method. If you want to control the specific order of replacement, you can add a number after the key as well to indicate which argument you want to insert. Ordered insertions are most useful when building loc strings where values you need to insert may appear in different orders. ```javascript "Hello %@ %@".fmt('John', 'Doe'); // "Hello John Doe" "Hello %@2, %@1".fmt('John', 'Doe'); // "Hello Doe, John" ``` @method fmt @param {Object...} [args] @return {String} formatted string */ fmt: function(str, formats) { // first, replace any ORDERED replacements. var idx = 0; // the current index for non-numerical replacements return str.replace(/%@([0-9]+)?/g, function(s, argIndex) { argIndex = (argIndex) ? parseInt(argIndex,0) - 1 : idx++ ; s = formats[argIndex]; return ((s === null) ? '(null)' : (s === undefined) ? '' : s).toString(); }) ; }, /** Formats the passed string, but first looks up the string in the localized strings hash. This is a convenient way to localize text. See `Ember.String.fmt()` for more information on formatting. Note that it is traditional but not required to prefix localized string keys with an underscore or other character so you can easily identify localized strings. ```javascript Ember.STRINGS = { '_Hello World': 'Bonjour le monde', '_Hello %@ %@': 'Bonjour %@ %@' }; Ember.String.loc("_Hello World"); // 'Bonjour le monde'; Ember.String.loc("_Hello %@ %@", ["John", "Smith"]); // "Bonjour John Smith"; ``` @method loc @param {String} str The string to format @param {Array} formats Optional array of parameters to interpolate into string. @return {String} formatted string */ loc: function(str, formats) { str = Ember.STRINGS[str] || str; return Ember.String.fmt(str, formats) ; }, /** Splits a string into separate units separated by spaces, eliminating any empty strings in the process. This is a convenience method for split that is mostly useful when applied to the `String.prototype`. ```javascript Ember.String.w("alpha beta gamma").forEach(function(key) { console.log(key); }); // > alpha // > beta // > gamma ``` @method w @param {String} str The string to split @return {String} split string */ w: function(str) { return str.split(/\s+/); }, /** Converts a camelized string into all lower case separated by underscores. ```javascript 'innerHTML'.decamelize(); // 'inner_html' 'action_name'.decamelize(); // 'action_name' 'css-class-name'.decamelize(); // 'css-class-name' 'my favorite items'.decamelize(); // 'my favorite items' ``` @method decamelize @param {String} str The string to decamelize. @return {String} the decamelized string. */ decamelize: function(str) { return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase(); }, /** Replaces underscores or spaces with dashes. ```javascript 'innerHTML'.dasherize(); // 'inner-html' 'action_name'.dasherize(); // 'action-name' 'css-class-name'.dasherize(); // 'css-class-name' 'my favorite items'.dasherize(); // 'my-favorite-items' ``` @method dasherize @param {String} str The string to dasherize. @return {String} the dasherized string. */ dasherize: function(str) { var cache = STRING_DASHERIZE_CACHE, ret = cache[str]; if (ret) { return ret; } else { ret = Ember.String.decamelize(str).replace(STRING_DASHERIZE_REGEXP,'-'); cache[str] = ret; } return ret; }, /** Returns the lowerCaseCamel form of a string. ```javascript 'innerHTML'.camelize(); // 'innerHTML' 'action_name'.camelize(); // 'actionName' 'css-class-name'.camelize(); // 'cssClassName' 'my favorite items'.camelize(); // 'myFavoriteItems' ``` @method camelize @param {String} str The string to camelize. @return {String} the camelized string. */ camelize: function(str) { return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) { return chr ? chr.toUpperCase() : ''; }); }, /** Returns the UpperCamelCase form of a string. ```javascript 'innerHTML'.classify(); // 'InnerHTML' 'action_name'.classify(); // 'ActionName' 'css-class-name'.classify(); // 'CssClassName' 'my favorite items'.classify(); // 'MyFavoriteItems' ``` @method classify @param {String} str the string to classify @return {String} the classified string */ classify: function(str) { var parts = str.split("."), out = []; for (var i=0, l=parts.length; i<l; i++) { var camelized = Ember.String.camelize(parts[i]); out.push(camelized.charAt(0).toUpperCase() + camelized.substr(1)); } return out.join("."); }, /** More general than decamelize. Returns the lower\_case\_and\_underscored form of a string. ```javascript 'innerHTML'.underscore(); // 'inner_html' 'action_name'.underscore(); // 'action_name' 'css-class-name'.underscore(); // 'css_class_name' 'my favorite items'.underscore(); // 'my_favorite_items' ``` @method underscore @param {String} str The string to underscore. @return {String} the underscored string. */ underscore: function(str) { return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2'). replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase(); }, /** Returns the Capitalized form of a string 'innerHTML'.capitalize() => 'InnerHTML' 'action_name'.capitalize() => 'Action_name' 'css-class-name'.capitalize() => 'Css-class-name' 'my favorite items'.capitalize() => 'My favorite items' @method capitalize @param {String} str @return {String} */ capitalize: function(str) { return str.charAt(0).toUpperCase() + str.substr(1); } }; })(); (function() { /** @module ember @submodule ember-runtime */ var fmt = Ember.String.fmt, w = Ember.String.w, loc = Ember.String.loc, camelize = Ember.String.camelize, decamelize = Ember.String.decamelize, dasherize = Ember.String.dasherize, underscore = Ember.String.underscore, capitalize = Ember.String.capitalize, classify = Ember.String.classify; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/fmt"}}{{/crossLink}} @method fmt @for String */ String.prototype.fmt = function() { return fmt(this, arguments); }; /** See {{#crossLink "Ember.String/w"}}{{/crossLink}} @method w @for String */ String.prototype.w = function() { return w(this); }; /** See {{#crossLink "Ember.String/loc"}}{{/crossLink}} @method loc @for String */ String.prototype.loc = function() { return loc(this, arguments); }; /** See {{#crossLink "Ember.String/camelize"}}{{/crossLink}} @method camelize @for String */ String.prototype.camelize = function() { return camelize(this); }; /** See {{#crossLink "Ember.String/decamelize"}}{{/crossLink}} @method decamelize @for String */ String.prototype.decamelize = function() { return decamelize(this); }; /** See {{#crossLink "Ember.String/dasherize"}}{{/crossLink}} @method dasherize @for String */ String.prototype.dasherize = function() { return dasherize(this); }; /** See {{#crossLink "Ember.String/underscore"}}{{/crossLink}} @method underscore @for String */ String.prototype.underscore = function() { return underscore(this); }; /** See {{#crossLink "Ember.String/classify"}}{{/crossLink}} @method classify @for String */ String.prototype.classify = function() { return classify(this); }; /** See {{#crossLink "Ember.String/capitalize"}}{{/crossLink}} @method capitalize @for String */ String.prototype.capitalize = function() { return capitalize(this); }; } })(); (function() { /** @module ember @submodule ember-runtime */ var a_slice = Array.prototype.slice; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Function) { /** The `property` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is `true`, which is the default. Computed properties allow you to treat a function like a property: ```javascript MyApp.president = Ember.Object.create({ firstName: "Barack", lastName: "Obama", fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); // Call this flag to mark the function as a property }.property() }); MyApp.president.get('fullName'); // "Barack Obama" ``` Treating a function like a property is useful because they can work with bindings, just like any other property. Many computed properties have dependencies on other properties. For example, in the above example, the `fullName` property depends on `firstName` and `lastName` to determine its value. You can tell Ember about these dependencies like this: ```javascript MyApp.president = Ember.Object.create({ firstName: "Barack", lastName: "Obama", fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember.js that this computed property depends on firstName // and lastName }.property('firstName', 'lastName') }); ``` Make sure you list these dependencies so Ember knows when to update bindings that connect to a computed property. Changing a dependency will not immediately trigger an update of the computed property, but will instead clear the cache so that it is updated when the next `get` is called on the property. See {{#crossLink "Ember.ComputedProperty"}}{{/crossLink}}, {{#crossLink "Ember/computed"}}{{/crossLink}} @method property @for Function */ Function.prototype.property = function() { var ret = Ember.computed(this); return ret.property.apply(ret, arguments); }; /** The `observes` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. You can observe property changes simply by adding the `observes` call to the end of your method declarations in classes that you write. For example: ```javascript Ember.Object.create({ valueObserver: function() { // Executes whenever the "value" property changes }.observes('value') }); ``` See {{#crossLink "Ember.Observable/observes"}}{{/crossLink}} @method observes @for Function */ Function.prototype.observes = function() { this.__ember_observes__ = a_slice.call(arguments); return this; }; /** The `observesBefore` extension of Javascript's Function prototype is available when `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Function` is true, which is the default. You can get notified when a property changes is about to happen by by adding the `observesBefore` call to the end of your method declarations in classes that you write. For example: ```javascript Ember.Object.create({ valueObserver: function() { // Executes whenever the "value" property is about to change }.observesBefore('value') }); ``` See {{#crossLink "Ember.Observable/observesBefore"}}{{/crossLink}} @method observesBefore @for Function */ Function.prototype.observesBefore = function() { this.__ember_observesBefore__ = a_slice.call(arguments); return this; }; } })(); (function() { })(); (function() { /** @module ember @submodule ember-runtime */ // .......................................................... // HELPERS // var get = Ember.get, set = Ember.set; var a_slice = Array.prototype.slice; var a_indexOf = Ember.EnumerableUtils.indexOf; var contexts = []; function popCtx() { return contexts.length===0 ? {} : contexts.pop(); } function pushCtx(ctx) { contexts.push(ctx); return null; } function iter(key, value) { var valueProvided = arguments.length === 2; function i(item) { var cur = get(item, key); return valueProvided ? value===cur : !!cur; } return i ; } /** This mixin defines the common interface implemented by enumerable objects in Ember. Most of these methods follow the standard Array iteration API defined up to JavaScript 1.8 (excluding language-specific features that cannot be emulated in older versions of JavaScript). This mixin is applied automatically to the Array class on page load, so you can use any of these methods on simple arrays. If Array already implements one of these methods, the mixin will not override them. ## Writing Your Own Enumerable To make your own custom class enumerable, you need two items: 1. You must have a length property. This property should change whenever the number of items in your enumerable object changes. If you using this with an `Ember.Object` subclass, you should be sure to change the length property using `set().` 2. If you must implement `nextObject().` See documentation. Once you have these two methods implement, apply the `Ember.Enumerable` mixin to your class and you will be able to enumerate the contents of your object like any other collection. ## Using Ember Enumeration with Other Libraries Many other libraries provide some kind of iterator or enumeration like facility. This is often where the most common API conflicts occur. Ember's API is designed to be as friendly as possible with other libraries by implementing only methods that mostly correspond to the JavaScript 1.8 API. @class Enumerable @namespace Ember @extends Ember.Mixin @since Ember 0.9 */ Ember.Enumerable = Ember.Mixin.create( /** @scope Ember.Enumerable.prototype */ { // compatibility isEnumerable: true, /** Implement this method to make your class enumerable. This method will be call repeatedly during enumeration. The index value will always begin with 0 and increment monotonically. You don't have to rely on the index value to determine what object to return, but you should always check the value and start from the beginning when you see the requested index is 0. The `previousObject` is the object that was returned from the last call to `nextObject` for the current iteration. This is a useful way to manage iteration if you are tracing a linked list, for example. Finally the context parameter will always contain a hash you can use as a "scratchpad" to maintain any other state you need in order to iterate properly. The context object is reused and is not reset between iterations so make sure you setup the context with a fresh state whenever the index parameter is 0. Generally iterators will continue to call `nextObject` until the index reaches the your current length-1. If you run out of data before this time for some reason, you should simply return undefined. The default implementation of this method simply looks up the index. This works great on any Array-like objects. @method nextObject @param {Number} index the current index of the iteration @param {Object} previousObject the value returned by the last call to `nextObject`. @param {Object} context a context object you can use to maintain state. @return {Object} the next object in the iteration or undefined */ nextObject: Ember.required(Function), /** Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. If you override this method, you should implement it so that it will always return the same value each time it is called. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. ```javascript var arr = ["a", "b", "c"]; arr.firstObject(); // "a" var arr = []; arr.firstObject(); // undefined ``` @property firstObject @return {Object} the object or undefined */ firstObject: Ember.computed(function() { if (get(this, 'length')===0) return undefined ; // handle generic enumerables var context = popCtx(), ret; ret = this.nextObject(0, null, context); pushCtx(context); return ret ; }).property('[]'), /** Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. ```javascript var arr = ["a", "b", "c"]; arr.lastObject(); // "c" var arr = []; arr.lastObject(); // undefined ``` @property lastObject @return {Object} the last object or undefined */ lastObject: Ember.computed(function() { var len = get(this, 'length'); if (len===0) return undefined ; var context = popCtx(), idx=0, cur, last = null; do { last = cur; cur = this.nextObject(idx++, last, context); } while (cur !== undefined); pushCtx(context); return last; }).property('[]'), /** Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. ```javascript var arr = ["a", "b", "c"]; arr.contains("a"); // true arr.contains("z"); // false ``` @method contains @param {Object} obj The object to search for. @return {Boolean} `true` if object is found in enumerable. */ contains: function(obj) { return this.find(function(item) { return item===obj; }) !== undefined; }, /** Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method forEach @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Object} receiver */ forEach: function(callback, target) { if (typeof callback !== "function") throw new TypeError() ; var len = get(this, 'length'), last = null, context = popCtx(); if (target === undefined) target = null; for(var idx=0;idx<len;idx++) { var next = this.nextObject(idx, last, context) ; callback.call(target, next, idx, this); last = next ; } last = null ; context = pushCtx(context); return this ; }, /** Alias for `mapProperty` @method getEach @param {String} key name of the property @return {Array} The mapped array. */ getEach: function(key) { return this.mapProperty(key); }, /** Sets the value on the named property for each member. This is more efficient than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. @method setEach @param {String} key The key to set @param {Object} value The object to set @return {Object} receiver */ setEach: function(key, value) { return this.forEach(function(item) { set(item, key, value); }); }, /** Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the mapped value. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method map @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} The mapped array. */ map: function(callback, target) { var ret = []; this.forEach(function(x, idx, i) { ret[idx] = callback.call(target, x, idx,i); }); return ret ; }, /** Similar to map, this specialized function returns the value of the named property on all items in the enumeration. @method mapProperty @param {String} key name of the property @return {Array} The mapped array. */ mapProperty: function(key) { return this.map(function(next) { return get(next, key); }); }, /** Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method filter @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} A filtered array. */ filter: function(callback, target) { var ret = []; this.forEach(function(x, idx, i) { if (callback.call(target, x, idx, i)) ret.push(x); }); return ret ; }, /** Returns an array with all of the items in the enumeration where the passed function returns false for. This method is the inverse of filter(). The callback method you provide should have the following signature (all parameters are optional): function(item, index, enumerable); - *item* is the current item in the iteration. - *index* is the current index in the iteration - *enumerable* is the enumerable object itself. It should return the a falsey value to include the item in the results. Note that in addition to a callback, you can also pass an optional target object that will be set as "this" on the context. This is a good way to give your iterator function access to the current object. @method reject @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} A rejected array. */ reject: function(callback, target) { return this.filter(function() { return !(callback.apply(target, arguments)); }); }, /** Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. @method filterProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Array} filtered array */ filterProperty: function(key, value) { return this.filter(iter.apply(this, arguments)); }, /** Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. @method rejectProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Array} rejected array */ rejectProperty: function(key, value) { var exactValue = function(item) { return get(item, key) === value; }, hasValue = function(item) { return !!get(item, key); }, use = (arguments.length === 2 ? exactValue : hasValue); return this.reject(use); }, /** Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method find @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Object} Found item or `null`. */ find: function(callback, target) { var len = get(this, 'length') ; if (target === undefined) target = null; var last = null, next, found = false, ret ; var context = popCtx(); for(var idx=0;idx<len && !found;idx++) { next = this.nextObject(idx, last, context) ; if (found = callback.call(target, next, idx, this)) ret = next ; last = next ; } next = last = null ; context = pushCtx(context); return ret ; }, /** Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. This method works much like the more generic `find()` method. @method findProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Object} found item or `null` */ findProperty: function(key, value) { return this.find(iter.apply(this, arguments)); }, /** Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` or `false`. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. Example Usage: ```javascript if (people.every(isEngineer)) { Paychecks.addBigBonus(); } ``` @method every @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Boolean} */ every: function(callback, target) { return !this.find(function(x, idx, i) { return !callback.call(target, x, idx, i); }); }, /** Returns `true` if the passed property resolves to `true` for all items in the enumerable. This method is often simpler/faster than using a callback. @method everyProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Boolean} */ everyProperty: function(key, value) { return this.every(iter.apply(this, arguments)); }, /** Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. Usage Example: ```javascript if (people.some(isManager)) { Paychecks.addBiggerBonus(); } ``` @method some @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} A filtered array. */ some: function(callback, target) { return !!this.find(function(x, idx, i) { return !!callback.call(target, x, idx, i); }); }, /** Returns `true` if the passed property resolves to `true` for any item in the enumerable. This method is often simpler/faster than using a callback. @method someProperty @param {String} key the property to test @param {String} [value] optional value to test against. @return {Boolean} `true` */ someProperty: function(key, value) { return this.some(iter.apply(this, arguments)); }, /** This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(previousValue, item, index, enumerable); ``` - `previousValue` is the value returned by the last call to the iterator. - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. Return the new cumulative value. In addition to the callback you can also pass an `initialValue`. An error will be raised if you do not pass an initial value and the enumerator is empty. Note that unlike the other methods, this method does not allow you to pass a target object to set as this for the callback. It's part of the spec. Sorry. @method reduce @param {Function} callback The callback to execute @param {Object} initialValue Initial value for the reduce @param {String} reducerProperty internal use only. @return {Object} The reduced value. */ reduce: function(callback, initialValue, reducerProperty) { if (typeof callback !== "function") { throw new TypeError(); } var ret = initialValue; this.forEach(function(item, i) { ret = callback.call(null, ret, item, i, this, reducerProperty); }, this); return ret; }, /** Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. @method invoke @param {String} methodName the name of the method @param {Object...} args optional arguments to pass as well. @return {Array} return values from calling invoke. */ invoke: function(methodName) { var args, ret = []; if (arguments.length>1) args = a_slice.call(arguments, 1); this.forEach(function(x, idx) { var method = x && x[methodName]; if ('function' === typeof method) { ret[idx] = args ? method.apply(x, args) : method.call(x); } }, this); return ret; }, /** Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. @method toArray @return {Array} the enumerable as an array. */ toArray: function() { var ret = []; this.forEach(function(o, idx) { ret[idx] = o; }); return ret ; }, /** Returns a copy of the array with all null elements removed. ```javascript var arr = ["a", null, "c", null]; arr.compact(); // ["a", "c"] ``` @method compact @return {Array} the array without null elements. */ compact: function() { return this.without(null); }, /** Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type unless the receiver does not contain the value. ```javascript var arr = ["a", "b", "a", "c"]; arr.without("a"); // ["b", "c"] ``` @method without @param {Object} value @return {Ember.Enumerable} */ without: function(value) { if (!this.contains(value)) return this; // nothing to do var ret = [] ; this.forEach(function(k) { if (k !== value) ret[ret.length] = k; }) ; return ret ; }, /** Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. ```javascript var arr = ["a", "a", "b", "b"]; arr.uniq(); // ["a", "b"] ``` @method uniq @return {Ember.Enumerable} */ uniq: function() { var ret = []; this.forEach(function(k){ if (a_indexOf(ret, k)<0) ret.push(k); }); return ret; }, /** This property will trigger anytime the enumerable's content changes. You can observe this property to be notified of changes to the enumerables content. For plain enumerables, this property is read only. `Ember.Array` overrides this method. @property [] @type Ember.Array */ '[]': Ember.computed(function(key, value) { return this; }), // .......................................................... // ENUMERABLE OBSERVERS // /** Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. @method addEnumerableObserver @param target {Object} @param opts {Hash} */ addEnumerableObserver: function(target, opts) { var willChange = (opts && opts.willChange) || 'enumerableWillChange', didChange = (opts && opts.didChange) || 'enumerableDidChange'; var hasObservers = get(this, 'hasEnumerableObservers'); if (!hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers'); Ember.addListener(this, '@enumerable:before', target, willChange); Ember.addListener(this, '@enumerable:change', target, didChange); if (!hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers'); return this; }, /** Removes a registered enumerable observer. @method removeEnumerableObserver @param target {Object} @param [opts] {Hash} */ removeEnumerableObserver: function(target, opts) { var willChange = (opts && opts.willChange) || 'enumerableWillChange', didChange = (opts && opts.didChange) || 'enumerableDidChange'; var hasObservers = get(this, 'hasEnumerableObservers'); if (hasObservers) Ember.propertyWillChange(this, 'hasEnumerableObservers'); Ember.removeListener(this, '@enumerable:before', target, willChange); Ember.removeListener(this, '@enumerable:change', target, didChange); if (hasObservers) Ember.propertyDidChange(this, 'hasEnumerableObservers'); return this; }, /** Becomes true whenever the array currently has observers watching changes on the array. @property hasEnumerableObservers @type Boolean */ hasEnumerableObservers: Ember.computed(function() { return Ember.hasListeners(this, '@enumerable:change') || Ember.hasListeners(this, '@enumerable:before'); }), /** Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. @method enumerableContentWillChange @param {Ember.Enumerable|Number} removing An enumerable of the objects to be removed or the number of items to be removed. @param {Ember.Enumerable|Number} adding An enumerable of the objects to be added or the number of items to be added. @chainable */ enumerableContentWillChange: function(removing, adding) { var removeCnt, addCnt, hasDelta; if ('number' === typeof removing) removeCnt = removing; else if (removing) removeCnt = get(removing, 'length'); else removeCnt = removing = -1; if ('number' === typeof adding) addCnt = adding; else if (adding) addCnt = get(adding,'length'); else addCnt = adding = -1; hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; if (removing === -1) removing = null; if (adding === -1) adding = null; Ember.propertyWillChange(this, '[]'); if (hasDelta) Ember.propertyWillChange(this, 'length'); Ember.sendEvent(this, '@enumerable:before', [this, removing, adding]); return this; }, /** Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If your are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. @method enumerableContentDidChange @param {Number} [start] optional start offset for the content change. For unordered enumerables, you should always pass -1. @param {Ember.Enumerable|Number} removing An enumerable of the objects to be removed or the number of items to be removed. @param {Ember.Enumerable|Number} adding An enumerable of the objects to be added or the number of items to be added. @chainable */ enumerableContentDidChange: function(removing, adding) { var notify = this.propertyDidChange, removeCnt, addCnt, hasDelta; if ('number' === typeof removing) removeCnt = removing; else if (removing) removeCnt = get(removing, 'length'); else removeCnt = removing = -1; if ('number' === typeof adding) addCnt = adding; else if (adding) addCnt = get(adding, 'length'); else addCnt = adding = -1; hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; if (removing === -1) removing = null; if (adding === -1) adding = null; Ember.sendEvent(this, '@enumerable:change', [this, removing, adding]); if (hasDelta) Ember.propertyDidChange(this, 'length'); Ember.propertyDidChange(this, '[]'); return this ; } }) ; })(); (function() { /** @module ember @submodule ember-runtime */ // .......................................................... // HELPERS // var get = Ember.get, set = Ember.set, meta = Ember.meta, map = Ember.EnumerableUtils.map, cacheFor = Ember.cacheFor; function none(obj) { return obj===null || obj===undefined; } // .......................................................... // ARRAY // /** This module implements Observer-friendly Array-like behavior. This mixin is picked up by the Array class as well as other controllers, etc. that want to appear to be arrays. Unlike `Ember.Enumerable,` this mixin defines methods specifically for collections that provide index-ordered access to their contents. When you are designing code that needs to accept any kind of Array-like object, you should use these methods instead of Array primitives because these will properly notify observers of changes to the array. Although these methods are efficient, they do add a layer of indirection to your application so it is a good idea to use them only when you need the flexibility of using both true JavaScript arrays and "virtual" arrays such as controllers and collections. You can use the methods defined in this module to access and modify array contents in a KVO-friendly way. You can also be notified whenever the membership if an array changes by changing the syntax of the property to `.observes('*myProperty.[]')`. To support `Ember.Array` in your own class, you must override two primitives to use it: `replace()` and `objectAt()`. Note that the Ember.Array mixin also incorporates the `Ember.Enumerable` mixin. All `Ember.Array`-like objects are also enumerable. @class Array @namespace Ember @extends Ember.Mixin @uses Ember.Enumerable @since Ember 0.9.0 */ Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.prototype */ { // compatibility isSCArray: true, /** Your array must support the `length` property. Your replace methods should set this property whenever it changes. @property {Number} length */ length: Ember.required(), /** Returns the object at the given `index`. If the given `index` is negative or is greater or equal than the array length, returns `undefined`. This is one of the primitives you must implement to support `Ember.Array`. If your object supports retrieving the value of an array item using `get()` (i.e. `myArray.get(0)`), then you do not need to implement this method yourself. ```javascript var arr = ['a', 'b', 'c', 'd']; arr.objectAt(0); // "a" arr.objectAt(3); // "d" arr.objectAt(-1); // undefined arr.objectAt(4); // undefined arr.objectAt(5); // undefined ``` @method objectAt @param {Number} idx The index of the item to return. */ objectAt: function(idx) { if ((idx < 0) || (idx>=get(this, 'length'))) return undefined ; return get(this, idx); }, /** This returns the objects at the specified indexes, using `objectAt`. ```javascript var arr = ['a', 'b', 'c', 'd']; arr.objectsAt([0, 1, 2]); // ["a", "b", "c"] arr.objectsAt([2, 3, 4]); // ["c", "d", undefined] ``` @method objectsAt @param {Array} indexes An array of indexes of items to return. */ objectsAt: function(indexes) { var self = this; return map(indexes, function(idx){ return self.objectAt(idx); }); }, // overrides Ember.Enumerable version nextObject: function(idx) { return this.objectAt(idx); }, /** This is the handler for the special array content property. If you get this property, it will return this. If you set this property it a new array, it will replace the current content. This property overrides the default property defined in `Ember.Enumerable`. @property [] */ '[]': Ember.computed(function(key, value) { if (value !== undefined) this.replace(0, get(this, 'length'), value) ; return this ; }), firstObject: Ember.computed(function() { return this.objectAt(0); }), lastObject: Ember.computed(function() { return this.objectAt(get(this, 'length')-1); }), // optimized version from Enumerable contains: function(obj){ return this.indexOf(obj) >= 0; }, // Add any extra methods to Ember.Array that are native to the built-in Array. /** Returns a new array that is a slice of the receiver. This implementation uses the observable array methods to retrieve the objects for the new slice. ```javascript var arr = ['red', 'green', 'blue']; arr.slice(0); // ['red', 'green', 'blue'] arr.slice(0, 2); // ['red', 'green'] arr.slice(1, 100); // ['green', 'blue'] ``` @method slice @param beginIndex {Integer} (Optional) index to begin slicing from. @param endIndex {Integer} (Optional) index to end the slice at. @return {Array} New array with specified slice */ slice: function(beginIndex, endIndex) { var ret = []; var length = get(this, 'length') ; if (none(beginIndex)) beginIndex = 0 ; if (none(endIndex) || (endIndex > length)) endIndex = length ; while(beginIndex < endIndex) { ret[ret.length] = this.objectAt(beginIndex++) ; } return ret ; }, /** Returns the index of the given object's first occurrence. If no `startAt` argument is given, the starting location to search is 0. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. ```javascript var arr = ["a", "b", "c", "d", "a"]; arr.indexOf("a"); // 0 arr.indexOf("z"); // -1 arr.indexOf("a", 2); // 4 arr.indexOf("a", -1); // 4 arr.indexOf("b", 3); // -1 arr.indexOf("a", 100); // -1 ```javascript @method indexOf @param {Object} object the item to search for @param {Number} startAt optional starting location to search, default 0 @return {Number} index or -1 if not found */ indexOf: function(object, startAt) { var idx, len = get(this, 'length'); if (startAt === undefined) startAt = 0; if (startAt < 0) startAt += len; for(idx=startAt;idx<len;idx++) { if (this.objectAt(idx, true) === object) return idx ; } return -1; }, /** Returns the index of the given object's last occurrence. If no `startAt` argument is given, the search starts from the last position. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. ```javascript var arr = ["a", "b", "c", "d", "a"]; arr.lastIndexOf("a"); // 4 arr.lastIndexOf("z"); // -1 arr.lastIndexOf("a", 2); // 0 arr.lastIndexOf("a", -1); // 4 arr.lastIndexOf("b", 3); // 1 arr.lastIndexOf("a", 100); // 4 ``` @method lastIndexOf @param {Object} object the item to search for @param {Number} startAt optional starting location to search, default 0 @return {Number} index or -1 if not found */ lastIndexOf: function(object, startAt) { var idx, len = get(this, 'length'); if (startAt === undefined || startAt >= len) startAt = len-1; if (startAt < 0) startAt += len; for(idx=startAt;idx>=0;idx--) { if (this.objectAt(idx) === object) return idx ; } return -1; }, // .......................................................... // ARRAY OBSERVERS // /** Adds an array observer to the receiving array. The array observer object normally must implement two methods: * `arrayWillChange(start, removeCount, addCount)` - This method will be called just before the array is modified. * `arrayDidChange(start, removeCount, addCount)` - This method will be called just after the array is modified. Both callbacks will be passed the starting index of the change as well a a count of the items to be removed and added. You can use these callbacks to optionally inspect the array during the change, clear caches, or do any other bookkeeping necessary. In addition to passing a target, you can also include an options hash which you can use to override the method names that will be invoked on the target. @method addArrayObserver @param {Object} target The observer object. @param {Hash} opts Optional hash of configuration options including `willChange`, `didChange`, and a `context` option. @return {Ember.Array} receiver */ addArrayObserver: function(target, opts) { var willChange = (opts && opts.willChange) || 'arrayWillChange', didChange = (opts && opts.didChange) || 'arrayDidChange'; var hasObservers = get(this, 'hasArrayObservers'); if (!hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers'); Ember.addListener(this, '@array:before', target, willChange); Ember.addListener(this, '@array:change', target, didChange); if (!hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers'); return this; }, /** Removes an array observer from the object if the observer is current registered. Calling this method multiple times with the same object will have no effect. @method removeArrayObserver @param {Object} target The object observing the array. @return {Ember.Array} receiver */ removeArrayObserver: function(target, opts) { var willChange = (opts && opts.willChange) || 'arrayWillChange', didChange = (opts && opts.didChange) || 'arrayDidChange'; var hasObservers = get(this, 'hasArrayObservers'); if (hasObservers) Ember.propertyWillChange(this, 'hasArrayObservers'); Ember.removeListener(this, '@array:before', target, willChange); Ember.removeListener(this, '@array:change', target, didChange); if (hasObservers) Ember.propertyDidChange(this, 'hasArrayObservers'); return this; }, /** Becomes true whenever the array currently has observers watching changes on the array. @property Boolean */ hasArrayObservers: Ember.computed(function() { return Ember.hasListeners(this, '@array:change') || Ember.hasListeners(this, '@array:before'); }), /** If you are implementing an object that supports `Ember.Array`, call this method just before the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. @method arrayContentWillChange @param {Number} startIdx The starting index in the array that will change. @param {Number} removeAmt The number of items that will be removed. If you pass `null` assumes 0 @param {Number} addAmt The number of items that will be added If you pass `null` assumes 0. @return {Ember.Array} receiver */ arrayContentWillChange: function(startIdx, removeAmt, addAmt) { // if no args are passed assume everything changes if (startIdx===undefined) { startIdx = 0; removeAmt = addAmt = -1; } else { if (removeAmt === undefined) removeAmt=-1; if (addAmt === undefined) addAmt=-1; } // Make sure the @each proxy is set up if anyone is observing @each if (Ember.isWatching(this, '@each')) { get(this, '@each'); } Ember.sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]); var removing, lim; if (startIdx>=0 && removeAmt>=0 && get(this, 'hasEnumerableObservers')) { removing = []; lim = startIdx+removeAmt; for(var idx=startIdx;idx<lim;idx++) removing.push(this.objectAt(idx)); } else { removing = removeAmt; } this.enumerableContentWillChange(removing, addAmt); return this; }, arrayContentDidChange: function(startIdx, removeAmt, addAmt) { // if no args are passed assume everything changes if (startIdx===undefined) { startIdx = 0; removeAmt = addAmt = -1; } else { if (removeAmt === undefined) removeAmt=-1; if (addAmt === undefined) addAmt=-1; } var adding, lim; if (startIdx>=0 && addAmt>=0 && get(this, 'hasEnumerableObservers')) { adding = []; lim = startIdx+addAmt; for(var idx=startIdx;idx<lim;idx++) adding.push(this.objectAt(idx)); } else { adding = addAmt; } this.enumerableContentDidChange(removeAmt, adding); Ember.sendEvent(this, '@array:change', [this, startIdx, removeAmt, addAmt]); var length = get(this, 'length'), cachedFirst = cacheFor(this, 'firstObject'), cachedLast = cacheFor(this, 'lastObject'); if (this.objectAt(0) !== cachedFirst) { Ember.propertyWillChange(this, 'firstObject'); Ember.propertyDidChange(this, 'firstObject'); } if (this.objectAt(length-1) !== cachedLast) { Ember.propertyWillChange(this, 'lastObject'); Ember.propertyDidChange(this, 'lastObject'); } return this; }, // .......................................................... // ENUMERATED PROPERTIES // /** Returns a special object that can be used to observe individual properties on the array. Just get an equivalent property on this object and it will return an enumerable that maps automatically to the named key on the member objects. @property @each */ '@each': Ember.computed(function() { if (!this.__each) this.__each = new Ember.EachProxy(this); return this.__each; }) }) ; })(); (function() { /** @module ember @submodule ember-runtime */ /** Implements some standard methods for comparing objects. Add this mixin to any class you create that can compare its instances. You should implement the `compare()` method. @class Comparable @namespace Ember @extends Ember.Mixin @since Ember 0.9 */ Ember.Comparable = Ember.Mixin.create( /** @scope Ember.Comparable.prototype */{ /** walk like a duck. Indicates that the object can be compared. @property isComparable @type Boolean @default true */ isComparable: true, /** Override to return the result of the comparison of the two parameters. The compare method should return: - `-1` if `a < b` - `0` if `a == b` - `1` if `a > b` Default implementation raises an exception. @method compare @param a {Object} the first object to compare @param b {Object} the second object to compare @return {Integer} the result of the comparison */ compare: Ember.required(Function) }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; /** Implements some standard methods for copying an object. Add this mixin to any object you create that can create a copy of itself. This mixin is added automatically to the built-in array. You should generally implement the `copy()` method to return a copy of the receiver. Note that `frozenCopy()` will only work if you also implement `Ember.Freezable`. @class Copyable @namespace Ember @extends Ember.Mixin @since Ember 0.9 */ Ember.Copyable = Ember.Mixin.create( /** @scope Ember.Copyable.prototype */ { /** Override to return a copy of the receiver. Default implementation raises an exception. @method copy @param deep {Boolean} if `true`, a deep copy of the object should be made @return {Object} copy of receiver */ copy: Ember.required(Function), /** If the object implements `Ember.Freezable`, then this will return a new copy if the object is not frozen and the receiver if the object is frozen. Raises an exception if you try to call this method on a object that does not support freezing. You should use this method whenever you want a copy of a freezable object since a freezable object can simply return itself without actually consuming more memory. @method frozenCopy @return {Object} copy of receiver or receiver */ frozenCopy: function() { if (Ember.Freezable && Ember.Freezable.detect(this)) { return get(this, 'isFrozen') ? this : this.copy().freeze(); } else { throw new Error(Ember.String.fmt("%@ does not support freezing", [this])); } } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; /** The `Ember.Freezable` mixin implements some basic methods for marking an object as frozen. Once an object is frozen it should be read only. No changes may be made the internal state of the object. ## Enforcement To fully support freezing in your subclass, you must include this mixin and override any method that might alter any property on the object to instead raise an exception. You can check the state of an object by checking the `isFrozen` property. Although future versions of JavaScript may support language-level freezing object objects, that is not the case today. Even if an object is freezable, it is still technically possible to modify the object, even though it could break other parts of your application that do not expect a frozen object to change. It is, therefore, very important that you always respect the `isFrozen` property on all freezable objects. ## Example Usage The example below shows a simple object that implement the `Ember.Freezable` protocol. ```javascript Contact = Ember.Object.extend(Ember.Freezable, { firstName: null, lastName: null, // swaps the names swapNames: function() { if (this.get('isFrozen')) throw Ember.FROZEN_ERROR; var tmp = this.get('firstName'); this.set('firstName', this.get('lastName')); this.set('lastName', tmp); return this; } }); c = Context.create({ firstName: "John", lastName: "Doe" }); c.swapNames(); // returns c c.freeze(); c.swapNames(); // EXCEPTION ``` ## Copying Usually the `Ember.Freezable` protocol is implemented in cooperation with the `Ember.Copyable` protocol, which defines a `frozenCopy()` method that will return a frozen object, if the object implements this method as well. @class Freezable @namespace Ember @extends Ember.Mixin @since Ember 0.9 */ Ember.Freezable = Ember.Mixin.create( /** @scope Ember.Freezable.prototype */ { /** Set to `true` when the object is frozen. Use this property to detect whether your object is frozen or not. @property isFrozen @type Boolean */ isFrozen: false, /** Freezes the object. Once this method has been called the object should no longer allow any properties to be edited. @method freeze @return {Object} receiver */ freeze: function() { if (get(this, 'isFrozen')) return this; set(this, 'isFrozen', true); return this; } }); Ember.FROZEN_ERROR = "Frozen object cannot be modified."; })(); (function() { /** @module ember @submodule ember-runtime */ var forEach = Ember.EnumerableUtils.forEach; /** This mixin defines the API for modifying generic enumerables. These methods can be applied to an object regardless of whether it is ordered or unordered. Note that an Enumerable can change even if it does not implement this mixin. For example, a MappedEnumerable cannot be directly modified but if its underlying enumerable changes, it will change also. ## Adding Objects To add an object to an enumerable, use the `addObject()` method. This method will only add the object to the enumerable if the object is not already present and the object if of a type supported by the enumerable. ```javascript set.addObject(contact); ``` ## Removing Objects To remove an object form an enumerable, use the `removeObject()` method. This will only remove the object if it is already in the enumerable, otherwise this method has no effect. ```javascript set.removeObject(contact); ``` ## Implementing In Your Own Code If you are implementing an object and want to support this API, just include this mixin in your class and implement the required methods. In your unit tests, be sure to apply the Ember.MutableEnumerableTests to your object. @class MutableEnumerable @namespace Ember @extends Ember.Mixin @uses Ember.Enumerable */ Ember.MutableEnumerable = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.MutableEnumerable.prototype */ { /** __Required.__ You must implement this method to apply this mixin. Attempts to add the passed object to the receiver if the object is not already present in the collection. If the object is present, this method has no effect. If the passed object is of a type not supported by the receiver then this method should raise an exception. @method addObject @param {Object} object The object to add to the enumerable. @return {Object} the passed object */ addObject: Ember.required(Function), /** Adds each object in the passed enumerable to the receiver. @method addObjects @param {Ember.Enumerable} objects the objects to add. @return {Object} receiver */ addObjects: function(objects) { Ember.beginPropertyChanges(this); forEach(objects, function(obj) { this.addObject(obj); }, this); Ember.endPropertyChanges(this); return this; }, /** __Required.__ You must implement this method to apply this mixin. Attempts to remove the passed object from the receiver collection if the object is in present in the collection. If the object is not present, this method has no effect. If the passed object is of a type not supported by the receiver then this method should raise an exception. @method removeObject @param {Object} object The object to remove from the enumerable. @return {Object} the passed object */ removeObject: Ember.required(Function), /** Removes each objects in the passed enumerable from the receiver. @method removeObjects @param {Ember.Enumerable} objects the objects to remove @return {Object} receiver */ removeObjects: function(objects) { Ember.beginPropertyChanges(this); forEach(objects, function(obj) { this.removeObject(obj); }, this); Ember.endPropertyChanges(this); return this; } }); })(); (function() { /** @module ember @submodule ember-runtime */ // .......................................................... // CONSTANTS // var OUT_OF_RANGE_EXCEPTION = "Index out of range" ; var EMPTY = []; // .......................................................... // HELPERS // var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; /** This mixin defines the API for modifying array-like objects. These methods can be applied only to a collection that keeps its items in an ordered set. Note that an Array can change even if it does not implement this mixin. For example, one might implement a SparseArray that cannot be directly modified, but if its underlying enumerable changes, it will change also. @class MutableArray @namespace Ember @extends Ember.Mixin @uses Ember.Array @uses Ember.MutableEnumerable */ Ember.MutableArray = Ember.Mixin.create(Ember.Array, Ember.MutableEnumerable, /** @scope Ember.MutableArray.prototype */ { /** __Required.__ You must implement this method to apply this mixin. This is one of the primitives you must implement to support `Ember.Array`. You should replace amt objects started at idx with the objects in the passed array. You should also call `this.enumerableContentDidChange()` @method replace @param {Number} idx Starting index in the array to replace. If idx >= length, then append to the end of the array. @param {Number} amt Number of elements that should be removed from the array, starting at *idx*. @param {Array} objects An array of zero or more objects that should be inserted into the array at *idx* */ replace: Ember.required(), /** Remove all elements from self. This is useful if you want to reuse an existing array without having to recreate it. ```javascript var colors = ["red", "green", "blue"]; color.length(); // 3 colors.clear(); // [] colors.length(); // 0 ``` @method clear @return {Ember.Array} An empty Array. */ clear: function () { var len = get(this, 'length'); if (len === 0) return this; this.replace(0, len, EMPTY); return this; }, /** This will use the primitive `replace()` method to insert an object at the specified index. ```javascript var colors = ["red", "green", "blue"]; colors.insertAt(2, "yellow"); // ["red", "green", "yellow", "blue"] colors.insertAt(5, "orange"); // Error: Index out of range ```javascript @method insertAt @param {Number} idx index of insert the object at. @param {Object} object object to insert */ insertAt: function(idx, object) { if (idx > get(this, 'length')) throw new Error(OUT_OF_RANGE_EXCEPTION) ; this.replace(idx, 0, [object]) ; return this ; }, /** Remove an object at the specified index using the `replace()` primitive method. You can pass either a single index, or a start and a length. If you pass a start and length that is beyond the length this method will throw an `Ember.OUT_OF_RANGE_EXCEPTION` ```javascript var colors = ["red", "green", "blue", "yellow", "orange"]; colors.removeAt(0); // ["green", "blue", "yellow", "orange"] colors.removeAt(2, 2); // ["green", "blue"] colors.removeAt(4, 2); // Error: Index out of range ``` @method removeAt @param {Number} start index, start of range @param {Number} len length of passing range @return {Object} receiver */ removeAt: function(start, len) { if ('number' === typeof start) { if ((start < 0) || (start >= get(this, 'length'))) { throw new Error(OUT_OF_RANGE_EXCEPTION); } // fast case if (len === undefined) len = 1; this.replace(start, len, EMPTY); } return this ; }, /** Push the object onto the end of the array. Works just like `push()` but it is KVO-compliant. ```javascript var colors = ["red", "green", "blue"]; colors.pushObject("black"); // ["red", "green", "blue", "black"] colors.pushObject(["yellow", "orange"]); // ["red", "green", "blue", "black", ["yellow", "orange"]] ``` @method pushObject @param {anything} obj object to push */ pushObject: function(obj) { this.insertAt(get(this, 'length'), obj) ; return obj ; }, /** Add the objects in the passed numerable to the end of the array. Defers notifying observers of the change until all objects are added. ```javascript var colors = ["red", "green", "blue"]; colors.pushObjects("black"); // ["red", "green", "blue", "black"] colors.pushObjects(["yellow", "orange"]); // ["red", "green", "blue", "black", "yellow", "orange"] ``` @method pushObjects @param {Ember.Enumerable} objects the objects to add @return {Ember.Array} receiver */ pushObjects: function(objects) { this.replace(get(this, 'length'), 0, objects); return this; }, /** Pop object from array or nil if none are left. Works just like `pop()` but it is KVO-compliant. ```javascript var colors = ["red", "green", "blue"]; colors.popObject(); // "blue" console.log(colors); // ["red", "green"] ``` @method popObject @return object */ popObject: function() { var len = get(this, 'length') ; if (len === 0) return null ; var ret = this.objectAt(len-1) ; this.removeAt(len-1, 1) ; return ret ; }, /** Shift an object from start of array or nil if none are left. Works just like `shift()` but it is KVO-compliant. ```javascript var colors = ["red", "green", "blue"]; colors.shiftObject(); // "red" console.log(colors); // ["green", "blue"] ``` @method shiftObject @return object */ shiftObject: function() { if (get(this, 'length') === 0) return null ; var ret = this.objectAt(0) ; this.removeAt(0) ; return ret ; }, /** Unshift an object to start of array. Works just like `unshift()` but it is KVO-compliant. ```javascript var colors = ["red", "green", "blue"]; colors.unshiftObject("yellow"); // ["yellow", "red", "green", "blue"] colors.unshiftObject(["black", "white"]); // [["black", "white"], "yellow", "red", "green", "blue"] ``` @method unshiftObject @param {anything} obj object to unshift */ unshiftObject: function(obj) { this.insertAt(0, obj) ; return obj ; }, /** Adds the named objects to the beginning of the array. Defers notifying observers until all objects have been added. ```javascript var colors = ["red", "green", "blue"]; colors.unshiftObjects(["black", "white"]); // ["black", "white", "red", "green", "blue"] colors.unshiftObjects("yellow"); // Type Error: 'undefined' is not a function ``` @method unshiftObjects @param {Ember.Enumerable} objects the objects to add @return {Ember.Array} receiver */ unshiftObjects: function(objects) { this.replace(0, 0, objects); return this; }, /** Reverse objects in the array. Works just like `reverse()` but it is KVO-compliant. @method reverseObjects @return {Ember.Array} receiver */ reverseObjects: function() { var len = get(this, 'length'); if (len === 0) return this; var objects = this.toArray().reverse(); this.replace(0, len, objects); return this; }, /** Replace all the the receiver's content with content of the argument. If argument is an empty array receiver will be cleared. ```javascript var colors = ["red", "green", "blue"]; colors.setObjects(["black", "white"]); // ["black", "white"] colors.setObjects([]); // [] ``` @method setObjects @param {Ember.Array} objects array whose content will be used for replacing the content of the receiver @return {Ember.Array} receiver with the new content */ setObjects: function(objects) { if (objects.length === 0) return this.clear(); var len = get(this, 'length'); this.replace(0, len, objects); return this; }, // .......................................................... // IMPLEMENT Ember.MutableEnumerable // removeObject: function(obj) { var loc = get(this, 'length') || 0; while(--loc >= 0) { var curObject = this.objectAt(loc) ; if (curObject === obj) this.removeAt(loc) ; } return this ; }, addObject: function(obj) { if (!this.contains(obj)) this.pushObject(obj); return this ; } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, defineProperty = Ember.defineProperty; /** ## Overview This mixin provides properties and property observing functionality, core features of the Ember object model. Properties and observers allow one object to observe changes to a property on another object. This is one of the fundamental ways that models, controllers and views communicate with each other in an Ember application. Any object that has this mixin applied can be used in observer operations. That includes `Ember.Object` and most objects you will interact with as you write your Ember application. Note that you will not generally apply this mixin to classes yourself, but you will use the features provided by this module frequently, so it is important to understand how to use it. ## Using `get()` and `set()` Because of Ember's support for bindings and observers, you will always access properties using the get method, and set properties using the set method. This allows the observing objects to be notified and computed properties to be handled properly. More documentation about `get` and `set` are below. ## Observing Property Changes You typically observe property changes simply by adding the `observes` call to the end of your method declarations in classes that you write. For example: ```javascript Ember.Object.create({ valueObserver: function() { // Executes whenever the "value" property changes }.observes('value') }); ``` Although this is the most common way to add an observer, this capability is actually built into the `Ember.Object` class on top of two methods defined in this mixin: `addObserver` and `removeObserver`. You can use these two methods to add and remove observers yourself if you need to do so at runtime. To add an observer for a property, call: ```javascript object.addObserver('propertyKey', targetObject, targetAction) ``` This will call the `targetAction` method on the `targetObject` to be called whenever the value of the `propertyKey` changes. Note that if `propertyKey` is a computed property, the observer will be called when any of the property dependencies are changed, even if the resulting value of the computed property is unchanged. This is necessary because computed properties are not computed until `get` is called. @class Observable @namespace Ember @extends Ember.Mixin */ Ember.Observable = Ember.Mixin.create(/** @scope Ember.Observable.prototype */ { // compatibility isObserverable: true, /** Retrieves the value of a property from the object. This method is usually similar to using `object[keyName]` or `object.keyName`, however it supports both computed properties and the unknownProperty handler. Because `get` unifies the syntax for accessing all these kinds of properties, it can make many refactorings easier, such as replacing a simple property with a computed property, or vice versa. ### Computed Properties Computed properties are methods defined with the `property` modifier declared at the end, such as: ```javascript fullName: function() { return this.getEach('firstName', 'lastName').compact().join(' '); }.property('firstName', 'lastName') ``` When you call `get` on a computed property, the function will be called and the return value will be returned instead of the function itself. ### Unknown Properties Likewise, if you try to call `get` on a property whose value is `undefined`, the `unknownProperty()` method will be called on the object. If this method returns any value other than `undefined`, it will be returned instead. This allows you to implement "virtual" properties that are not defined upfront. @method get @param {String} key The property to retrieve @return {Object} The property value or undefined. */ get: function(keyName) { return get(this, keyName); }, /** To get multiple properties at once, call `getProperties` with a list of strings or an array: ```javascript record.getProperties('firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` is equivalent to: ```javascript record.getProperties(['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` @method getProperties @param {String...|Array} list of keys to get @return {Hash} */ getProperties: function() { var ret = {}; var propertyNames = arguments; if (arguments.length === 1 && Ember.typeOf(arguments[0]) === 'array') { propertyNames = arguments[0]; } for(var i = 0; i < propertyNames.length; i++) { ret[propertyNames[i]] = get(this, propertyNames[i]); } return ret; }, /** Sets the provided key or path to the value. This method is generally very similar to calling `object[key] = value` or `object.key = value`, except that it provides support for computed properties, the `unknownProperty()` method and property observers. ### Computed Properties If you try to set a value on a key that has a computed property handler defined (see the `get()` method for an example), then `set()` will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is composed of one or more member properties. ### Unknown Properties If you try to set a value on a key that is undefined in the target object, then the `unknownProperty()` handler will be called instead. This gives you an opportunity to implement complex "virtual" properties that are not predefined on the object. If `unknownProperty()` returns undefined, then `set()` will simply set the value on the object. ### Property Observers In addition to changing the property, `set()` will also register a property change with the object. Unless you have placed this call inside of a `beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers (i.e. observer methods declared on the same object), will be called immediately. Any "remote" observers (i.e. observer methods declared on another object) will be placed in a queue and called at a later time in a coalesced manner. ### Chaining In addition to property changes, `set()` returns the value of the object itself so you can do chaining like this: ```javascript record.set('firstName', 'Charles').set('lastName', 'Jolley'); ``` @method set @param {String} key The property to set @param {Object} value The value to set or `null`. @return {Ember.Observable} */ set: function(keyName, value) { set(this, keyName, value); return this; }, /** To set multiple properties at once, call `setProperties` with a Hash: ```javascript record.setProperties({ firstName: 'Charles', lastName: 'Jolley' }); ``` @method setProperties @param {Hash} hash the hash of keys and values to set @return {Ember.Observable} */ setProperties: function(hash) { return Ember.setProperties(this, hash); }, /** Begins a grouping of property changes. You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call this method at the beginning of the changes to begin deferring change notifications. When you are done making changes, call `endPropertyChanges()` to deliver the deferred change notifications and end deferring. @method beginPropertyChanges @return {Ember.Observable} */ beginPropertyChanges: function() { Ember.beginPropertyChanges(); return this; }, /** Ends a grouping of property changes. You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call `beginPropertyChanges()` at the beginning of the changes to defer change notifications. When you are done making changes, call this method to deliver the deferred change notifications and end deferring. @method endPropertyChanges @return {Ember.Observable} */ endPropertyChanges: function() { Ember.endPropertyChanges(); return this; }, /** Notify the observer system that a property is about to change. Sometimes you need to change a value directly or indirectly without actually calling `get()` or `set()` on it. In this case, you can use this method and `propertyDidChange()` instead. Calling these two methods together will notify all observers that the property has potentially changed value. Note that you must always call `propertyWillChange` and `propertyDidChange` as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like. @method propertyWillChange @param {String} key The property key that is about to change. @return {Ember.Observable} */ propertyWillChange: function(keyName){ Ember.propertyWillChange(this, keyName); return this; }, /** Notify the observer system that a property has just changed. Sometimes you need to change a value directly or indirectly without actually calling `get()` or `set()` on it. In this case, you can use this method and `propertyWillChange()` instead. Calling these two methods together will notify all observers that the property has potentially changed value. Note that you must always call `propertyWillChange` and `propertyDidChange` as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like. @method propertyDidChange @param {String} keyName The property key that has just changed. @return {Ember.Observable} */ propertyDidChange: function(keyName) { Ember.propertyDidChange(this, keyName); return this; }, /** Convenience method to call `propertyWillChange` and `propertyDidChange` in succession. @method notifyPropertyChange @param {String} keyName The property key to be notified about. @return {Ember.Observable} */ notifyPropertyChange: function(keyName) { this.propertyWillChange(keyName); this.propertyDidChange(keyName); return this; }, addBeforeObserver: function(key, target, method) { Ember.addBeforeObserver(this, key, target, method); }, /** Adds an observer on a property. This is the core method used to register an observer for a property. Once you call this method, anytime the key's value is set, your observer will be notified. Note that the observers are triggered anytime the value is set, regardless of whether it has actually changed. Your observer should be prepared to handle that. You can also pass an optional context parameter to this method. The context will be passed to your observer method whenever it is triggered. Note that if you add the same target/method pair on a key multiple times with different context parameters, your observer will only be called once with the last context you passed. ### Observer Methods Observer methods you pass should generally have the following signature if you do not pass a `context` parameter: ```javascript fooDidChange: function(sender, key, value, rev) { }; ``` The sender is the object that changed. The key is the property that changes. The value property is currently reserved and unused. The rev is the last property revision of the object when it changed, which you can use to detect if the key value has really changed or not. If you pass a `context` parameter, the context will be passed before the revision like so: ```javascript fooDidChange: function(sender, key, value, context, rev) { }; ``` Usually you will not need the value, context or revision parameters at the end. In this case, it is common to write observer methods that take only a sender and key value as parameters or, if you aren't interested in any of these values, to write an observer that has no parameters at all. @method addObserver @param {String} key The key to observer @param {Object} target The target object to invoke @param {String|Function} method The method to invoke. @return {Ember.Object} self */ addObserver: function(key, target, method) { Ember.addObserver(this, key, target, method); }, /** Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to `addObserver()` and your target will no longer receive notifications. @method removeObserver @param {String} key The key to observer @param {Object} target The target object to invoke @param {String|Function} method The method to invoke. @return {Ember.Observable} receiver */ removeObserver: function(key, target, method) { Ember.removeObserver(this, key, target, method); }, /** Returns `true` if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object. @method hasObserverFor @param {String} key Key to check @return {Boolean} */ hasObserverFor: function(key) { return Ember.hasListeners(this, key+':change'); }, /** @deprecated @method getPath @param {String} path The property path to retrieve @return {Object} The property value or undefined. */ getPath: function(path) { Ember.deprecate("getPath is deprecated since get now supports paths"); return this.get(path); }, /** @deprecated @method setPath @param {String} path The path to the property that will be set @param {Object} value The value to set or `null`. @return {Ember.Observable} */ setPath: function(path, value) { Ember.deprecate("setPath is deprecated since set now supports paths"); return this.set(path, value); }, /** Retrieves the value of a property, or a default value in the case that the property returns `undefined`. ```javascript person.getWithDefault('lastName', 'Doe'); ``` @method getWithDefault @param {String} keyName The name of the property to retrieve @param {Object} defaultValue The value to return if the property value is undefined @return {Object} The property value or the defaultValue. */ getWithDefault: function(keyName, defaultValue) { return Ember.getWithDefault(this, keyName, defaultValue); }, /** Set the value of a property to the current value plus some amount. ```javascript person.incrementProperty('age'); team.incrementProperty('score', 2); ``` @method incrementProperty @param {String} keyName The name of the property to increment @param {Object} increment The amount to increment by. Defaults to 1 @return {Object} The new property value */ incrementProperty: function(keyName, increment) { if (!increment) { increment = 1; } set(this, keyName, (get(this, keyName) || 0)+increment); return get(this, keyName); }, /** Set the value of a property to the current value minus some amount. ```javascript player.decrementProperty('lives'); orc.decrementProperty('health', 5); ``` @method decrementProperty @param {String} keyName The name of the property to decrement @param {Object} increment The amount to decrement by. Defaults to 1 @return {Object} The new property value */ decrementProperty: function(keyName, increment) { if (!increment) { increment = 1; } set(this, keyName, (get(this, keyName) || 0)-increment); return get(this, keyName); }, /** Set the value of a boolean property to the opposite of it's current value. ```javascript starship.toggleProperty('warpDriveEnaged'); ``` @method toggleProperty @param {String} keyName The name of the property to toggle @return {Object} The new property value */ toggleProperty: function(keyName) { set(this, keyName, !get(this, keyName)); return get(this, keyName); }, /** Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily. @method cacheFor @param {String} keyName @return {Object} The cached value of the computed property, if any */ cacheFor: function(keyName) { return Ember.cacheFor(this, keyName); }, // intended for debugging purposes observersForKey: function(keyName) { return Ember.observersFor(this, keyName); } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; /** @class TargetActionSupport @namespace Ember @extends Ember.Mixin */ Ember.TargetActionSupport = Ember.Mixin.create({ target: null, action: null, targetObject: Ember.computed(function() { var target = get(this, 'target'); if (Ember.typeOf(target) === "string") { var value = get(this, target); if (value === undefined) { value = get(Ember.lookup, target); } return value; } else { return target; } }).property('target'), triggerAction: function() { var action = get(this, 'action'), target = get(this, 'targetObject'); if (target && action) { var ret; if (typeof target.send === 'function') { ret = target.send(action, this); } else { if (typeof action === 'string') { action = target[action]; } ret = action.call(target, this); } if (ret !== false) ret = true; return ret; } else { return false; } } }); })(); (function() { /** @module ember @submodule ember-runtime */ /** This mixin allows for Ember objects to subscribe to and emit events. ```javascript App.Person = Ember.Object.extend(Ember.Evented, { greet: function() { // ... this.trigger('greet'); } }); var person = App.Person.create(); person.on('greet', function() { console.log('Our person has greeted'); }); person.greet(); // outputs: 'Our person has greeted' ``` @class Evented @namespace Ember @extends Ember.Mixin */ Ember.Evented = Ember.Mixin.create({ /** Subscribes to a named event with given function. ```javascript person.on('didLoad', function() { // fired once the person has loaded }); ``` An optional target can be passed in as the 2nd argument that will be set as the "this" for the callback. This is a good way to give your function access to the object triggering the event. When the target parameter is used the callback becomes the third argument. @method on @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute */ on: function(name, target, method) { Ember.addListener(this, name, target, method); }, /** Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use ``one`` when you only care about the first time an event has taken place. This function takes an optional 2nd argument that will become the "this" value for the callback. If this argument is passed then the 3rd argument becomes the function. @method one @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute */ one: function(name, target, method) { if (!method) { method = target; target = null; } Ember.addListener(this, name, target, method, true); }, /** Triggers a named event for the object. Any additional arguments will be passed as parameters to the functions that are subscribed to the event. ```javascript person.on('didEat', food) { console.log('person ate some ' + food); }); person.trigger('didEat', 'broccoli'); // outputs: person ate some broccoli ``` @method trigger @param {String} name The name of the event @param {Object...} args Optional arguments to pass on */ trigger: function(name) { var args = [], i, l; for (i = 1, l = arguments.length; i < l; i++) { args.push(arguments[i]); } Ember.sendEvent(this, name, args); }, fire: function(name) { Ember.deprecate("Ember.Evented#fire() has been deprecated in favor of trigger() for compatibility with jQuery. It will be removed in 1.0. Please update your code to call trigger() instead."); this.trigger.apply(this, arguments); }, /** Cancels subscription for give name, target, and method. @method off @param {String} name The name of the event @param {Object} target The target of the subscription @param {Function} method The function of the subscription */ off: function(name, target, method) { Ember.removeListener(this, name, target, method); }, /** Checks to see if object has any subscriptions for named event. @method has @param {String} name The name of the event @return {Boolean} does the object have a subscription for event */ has: function(name) { return Ember.hasListeners(this, name); } }); })(); (function() { var RSVP = requireModule("rsvp"); RSVP.async = function(callback, binding) { Ember.run.schedule('actions', binding, callback); }; /** @module ember @submodule ember-runtime */ var get = Ember.get, slice = Array.prototype.slice; /** @class Deferred @namespace Ember @extends Ember.Mixin */ Ember.DeferredMixin = Ember.Mixin.create({ /** Add handlers to be called when the Deferred object is resolved or rejected. @method then @param {Function} doneCallback a callback function to be called when done @param {Function} failCallback a callback function to be called when failed */ then: function(doneCallback, failCallback) { var promise = get(this, 'promise'); return promise.then.apply(promise, arguments); }, /** Resolve a Deferred object and call any `doneCallbacks` with the given args. @method resolve */ resolve: function(value) { get(this, 'promise').resolve(value); }, /** Reject a Deferred object and call any `failCallbacks` with the given args. @method reject */ reject: function(value) { get(this, 'promise').reject(value); }, promise: Ember.computed(function() { return new RSVP.Promise(); }) }); })(); (function() { })(); (function() { Ember.Container = requireModule('container'); Ember.Container.set = Ember.set; })(); (function() { /** @module ember @submodule ember-runtime */ // NOTE: this object should never be included directly. Instead use Ember. // Ember.Object. We only define this separately so that Ember.Set can depend on it var set = Ember.set, get = Ember.get, o_create = Ember.create, o_defineProperty = Ember.platform.defineProperty, a_slice = Array.prototype.slice, GUID_KEY = Ember.GUID_KEY, guidFor = Ember.guidFor, generateGuid = Ember.generateGuid, meta = Ember.meta, rewatch = Ember.rewatch, finishChains = Ember.finishChains, destroy = Ember.destroy, schedule = Ember.run.schedule, Mixin = Ember.Mixin, applyMixin = Mixin._apply, finishPartial = Mixin.finishPartial, reopen = Mixin.prototype.reopen, MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER, indexOf = Ember.EnumerableUtils.indexOf; var undefinedDescriptor = { configurable: true, writable: true, enumerable: false, value: undefined }; function makeCtor() { // Note: avoid accessing any properties on the object since it makes the // method a lot faster. This is glue code so we want it to be as fast as // possible. var wasApplied = false, initMixins, initProperties; var Class = function() { if (!wasApplied) { Class.proto(); // prepare prototype... } o_defineProperty(this, GUID_KEY, undefinedDescriptor); o_defineProperty(this, '_super', undefinedDescriptor); var m = meta(this); m.proto = this; if (initMixins) { // capture locally so we can clear the closed over variable var mixins = initMixins; initMixins = null; this.reopen.apply(this, mixins); } if (initProperties) { // capture locally so we can clear the closed over variable var props = initProperties; initProperties = null; var concatenatedProperties = this.concatenatedProperties; for (var i = 0, l = props.length; i < l; i++) { var properties = props[i]; for (var keyName in properties) { if (!properties.hasOwnProperty(keyName)) { continue; } var value = properties[keyName], IS_BINDING = Ember.IS_BINDING; if (IS_BINDING.test(keyName)) { var bindings = m.bindings; if (!bindings) { bindings = m.bindings = {}; } else if (!m.hasOwnProperty('bindings')) { bindings = m.bindings = o_create(m.bindings); } bindings[keyName] = value; } var desc = m.descs[keyName]; Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty)); Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1)); if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) { var baseValue = this[keyName]; if (baseValue) { if ('function' === typeof baseValue.concat) { value = baseValue.concat(value); } else { value = Ember.makeArray(baseValue).concat(value); } } else { value = Ember.makeArray(value); } } if (desc) { desc.set(this, keyName, value); } else { if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) { this.setUnknownProperty(keyName, value); } else if (MANDATORY_SETTER) { Ember.defineProperty(this, keyName, null, value); // setup mandatory setter } else { this[keyName] = value; } } } } } finishPartial(this, m); delete m.proto; finishChains(this); this.init.apply(this, arguments); }; Class.toString = Mixin.prototype.toString; Class.willReopen = function() { if (wasApplied) { Class.PrototypeMixin = Mixin.create(Class.PrototypeMixin); } wasApplied = false; }; Class._initMixins = function(args) { initMixins = args; }; Class._initProperties = function(args) { initProperties = args; }; Class.proto = function() { var superclass = Class.superclass; if (superclass) { superclass.proto(); } if (!wasApplied) { wasApplied = true; Class.PrototypeMixin.applyPartial(Class.prototype); rewatch(Class.prototype); } return this.prototype; }; return Class; } var CoreObject = makeCtor(); CoreObject.PrototypeMixin = Mixin.create({ reopen: function() { applyMixin(this, arguments, true); return this; }, isInstance: true, init: function() {}, /** Defines the properties that will be concatenated from the superclass (instead of overridden). By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the `classNames` property of `Ember.View`. Here is some sample code showing the difference between a concatenated property and a normal one: ```javascript App.BarView = Ember.View.extend({ someNonConcatenatedProperty: ['bar'], classNames: ['bar'] }); App.FooBarView = App.BarView.extend({ someNonConcatenatedProperty: ['foo'], classNames: ['foo'], }); var fooBarView = App.FooBarView.create(); fooBarView.get('someNonConcatenatedProperty'); // ['foo'] fooBarView.get('classNames'); // ['ember-view', 'bar', 'foo'] ``` This behavior extends to object creation as well. Continuing the above example: ```javascript var view = App.FooBarView.create({ someNonConcatenatedProperty: ['baz'], classNames: ['baz'] }) view.get('someNonConcatenatedProperty'); // ['baz'] view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ``` Adding a single property that is not an array will just add it in the array: ```javascript var view = App.FooBarView.create({ classNames: 'baz' }) view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ``` Using the `concatenatedProperties` property, we can tell to Ember that mix the content of the properties. In `Ember.View` the `classNameBindings` and `attributeBindings` properties are also concatenated, in addition to `classNames`. This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. @property concatenatedProperties @type Array @default null */ concatenatedProperties: null, /** @property isDestroyed @default false */ isDestroyed: false, /** @property isDestroying @default false */ isDestroying: false, /** Destroys an object by setting the `isDestroyed` flag and removing its metadata, which effectively destroys observers and bindings. If you try to set a property on a destroyed object, an exception will be raised. Note that destruction is scheduled for the end of the run loop and does not happen immediately. @method destroy @return {Ember.Object} receiver */ destroy: function() { if (this.isDestroying) { return; } this.isDestroying = true; if (this.willDestroy) { this.willDestroy(); } schedule('destroy', this, this._scheduledDestroy); return this; }, /** @private Invoked by the run loop to actually destroy the object. This is scheduled for execution by the `destroy` method. @method _scheduledDestroy */ _scheduledDestroy: function() { destroy(this); set(this, 'isDestroyed', true); if (this.didDestroy) { this.didDestroy(); } }, bind: function(to, from) { if (!(from instanceof Ember.Binding)) { from = Ember.Binding.from(from); } from.to(to).connect(this); return from; }, /** Returns a string representation which attempts to provide more information than Javascript's `toString` typically does, in a generic way for all Ember objects. App.Person = Em.Object.extend() person = App.Person.create() person.toString() //=> "<App.Person:ember1024>" If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass: Student = App.Person.extend() student = Student.create() student.toString() //=> "<(subclass of App.Person):ember1025>" If the method `toStringExtension` is defined, its return value will be included in the output. App.Teacher = App.Person.extend({ toStringExtension: function(){ return this.get('fullName'); } }); teacher = App.Teacher.create() teacher.toString(); // #=> "<App.Teacher:ember1026:Tom Dale>" @method toString @return {String} string representation */ toString: function toString() { var hasToStringExtension = typeof this.toStringExtension === 'function', extension = hasToStringExtension ? ":" + this.toStringExtension() : ''; var ret = '<'+this.constructor.toString()+':'+guidFor(this)+extension+'>'; this.toString = makeToString(ret); return ret; } }); function makeToString(ret) { return function() { return ret; }; } if (Ember.config.overridePrototypeMixin) { Ember.config.overridePrototypeMixin(CoreObject.PrototypeMixin); } CoreObject.__super__ = null; var ClassMixin = Mixin.create({ ClassMixin: Ember.required(), PrototypeMixin: Ember.required(), isClass: true, isMethod: false, extend: function() { var Class = makeCtor(), proto; Class.ClassMixin = Mixin.create(this.ClassMixin); Class.PrototypeMixin = Mixin.create(this.PrototypeMixin); Class.ClassMixin.ownerConstructor = Class; Class.PrototypeMixin.ownerConstructor = Class; reopen.apply(Class.PrototypeMixin, arguments); Class.superclass = this; Class.__super__ = this.prototype; proto = Class.prototype = o_create(this.prototype); proto.constructor = Class; generateGuid(proto, 'ember'); meta(proto).proto = proto; // this will disable observers on prototype Class.ClassMixin.apply(Class); return Class; }, createWithMixins: function() { var C = this; if (arguments.length>0) { this._initMixins(arguments); } return new C(); }, create: function() { var C = this; if (arguments.length>0) { this._initProperties(arguments); } return new C(); }, reopen: function() { this.willReopen(); reopen.apply(this.PrototypeMixin, arguments); return this; }, reopenClass: function() { reopen.apply(this.ClassMixin, arguments); applyMixin(this, arguments, false); return this; }, detect: function(obj) { if ('function' !== typeof obj) { return false; } while(obj) { if (obj===this) { return true; } obj = obj.superclass; } return false; }, detectInstance: function(obj) { return obj instanceof this; }, /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ```javascript person: function() { var personId = this.get('personId'); return App.Person.create({ id: personId }); }.property().meta({ type: App.Person }) ``` Once you've done this, you can retrieve the values saved to the computed property from your class like this: ```javascript MyClass.metaForProperty('person'); ``` This will return the original hash that was passed to `meta()`. @method metaForProperty @param key {String} property name */ metaForProperty: function(key) { var desc = meta(this.proto(), false).descs[key]; Ember.assert("metaForProperty() could not find a computed property with key '"+key+"'.", !!desc && desc instanceof Ember.ComputedProperty); return desc._meta || {}; }, /** Iterate over each computed property for the class, passing its name and any associated metadata (see `metaForProperty`) to the callback. @method eachComputedProperty @param {Function} callback @param {Object} binding */ eachComputedProperty: function(callback, binding) { var proto = this.proto(), descs = meta(proto).descs, empty = {}, property; for (var name in descs) { property = descs[name]; if (property instanceof Ember.ComputedProperty) { callback.call(binding || this, name, property._meta || empty); } } } }); if (Ember.config.overrideClassMixin) { Ember.config.overrideClassMixin(ClassMixin); } CoreObject.ClassMixin = ClassMixin; ClassMixin.apply(CoreObject); /** @class CoreObject @namespace Ember */ Ember.CoreObject = CoreObject; })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, none = Ember.isNone; /** An unordered collection of objects. A Set works a bit like an array except that its items are not ordered. You can create a set to efficiently test for membership for an object. You can also iterate through a set just like an array, even accessing objects by index, however there is no guarantee as to their order. All Sets are observable via the Enumerable Observer API - which works on any enumerable object including both Sets and Arrays. ## Creating a Set You can create a set like you would most objects using `new Ember.Set()`. Most new sets you create will be empty, but you can also initialize the set with some content by passing an array or other enumerable of objects to the constructor. Finally, you can pass in an existing set and the set will be copied. You can also create a copy of a set by calling `Ember.Set#copy()`. ```javascript // creates a new empty set var foundNames = new Ember.Set(); // creates a set with four names in it. var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P // creates a copy of the names set. var namesCopy = new Ember.Set(names); // same as above. var anotherNamesCopy = names.copy(); ``` ## Adding/Removing Objects You generally add or remove objects from a set using `add()` or `remove()`. You can add any type of object including primitives such as numbers, strings, and booleans. Unlike arrays, objects can only exist one time in a set. If you call `add()` on a set with the same object multiple times, the object will only be added once. Likewise, calling `remove()` with the same object multiple times will remove the object the first time and have no effect on future calls until you add the object to the set again. NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do so will be ignored. In addition to add/remove you can also call `push()`/`pop()`. Push behaves just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary object, remove it and return it. This is a good way to use a set as a job queue when you don't care which order the jobs are executed in. ## Testing for an Object To test for an object's presence in a set you simply call `Ember.Set#contains()`. ## Observing changes When using `Ember.Set`, you can observe the `"[]"` property to be alerted whenever the content changes. You can also add an enumerable observer to the set to be notified of specific objects that are added and removed from the set. See `Ember.Enumerable` for more information on enumerables. This is often unhelpful. If you are filtering sets of objects, for instance, it is very inefficient to re-filter all of the items each time the set changes. It would be better if you could just adjust the filtered set based on what was changed on the original set. The same issue applies to merging sets, as well. ## Other Methods `Ember.Set` primary implements other mixin APIs. For a complete reference on the methods you will use with `Ember.Set`, please consult these mixins. The most useful ones will be `Ember.Enumerable` and `Ember.MutableEnumerable` which implement most of the common iterator methods you are used to on Array. Note that you can also use the `Ember.Copyable` and `Ember.Freezable` APIs on `Ember.Set` as well. Once a set is frozen it can no longer be modified. The benefit of this is that when you call `frozenCopy()` on it, Ember will avoid making copies of the set. This allows you to write code that can know with certainty when the underlying set data will or will not be modified. @class Set @namespace Ember @extends Ember.CoreObject @uses Ember.MutableEnumerable @uses Ember.Copyable @uses Ember.Freezable @since Ember 0.9 */ Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable, /** @scope Ember.Set.prototype */ { // .......................................................... // IMPLEMENT ENUMERABLE APIS // /** This property will change as the number of objects in the set changes. @property length @type number @default 0 */ length: 0, /** Clears the set. This is useful if you want to reuse an existing set without having to recreate it. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.length; // 3 colors.clear(); colors.length; // 0 ``` @method clear @return {Ember.Set} An empty Set */ clear: function() { if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); } var len = get(this, 'length'); if (len === 0) { return this; } var guid; this.enumerableContentWillChange(len, 0); Ember.propertyWillChange(this, 'firstObject'); Ember.propertyWillChange(this, 'lastObject'); for (var i=0; i < len; i++){ guid = guidFor(this[i]); delete this[guid]; delete this[i]; } set(this, 'length', 0); Ember.propertyDidChange(this, 'firstObject'); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(len, 0); return this; }, /** Returns true if the passed object is also an enumerable that contains the same objects as the receiver. ```javascript var colors = ["red", "green", "blue"], same_colors = new Ember.Set(colors); same_colors.isEqual(colors); // true same_colors.isEqual(["purple", "brown"]); // false ``` @method isEqual @param {Ember.Set} obj the other object. @return {Boolean} */ isEqual: function(obj) { // fail fast if (!Ember.Enumerable.detect(obj)) return false; var loc = get(this, 'length'); if (get(obj, 'length') !== loc) return false; while(--loc >= 0) { if (!obj.contains(this[loc])) return false; } return true; }, /** Adds an object to the set. Only non-`null` objects can be added to a set and those can only be added once. If the object is already in the set or the passed value is null this method will have no effect. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.add("blue"); // ["blue"] colors.add("blue"); // ["blue"] colors.add("red"); // ["blue", "red"] colors.add(null); // ["blue", "red"] colors.add(undefined); // ["blue", "red"] ``` @method add @param {Object} obj The object to add. @return {Ember.Set} The set itself. */ add: Ember.aliasMethod('addObject'), /** Removes the object from the set if it is found. If you pass a `null` value or an object that is already not in the set, this method will have no effect. This is an alias for `Ember.MutableEnumerable.removeObject()`. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.remove("red"); // ["blue", "green"] colors.remove("purple"); // ["blue", "green"] colors.remove(null); // ["blue", "green"] ``` @method remove @param {Object} obj The object to remove @return {Ember.Set} The set itself. */ remove: Ember.aliasMethod('removeObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.pop(); // "blue" colors.pop(); // "green" colors.pop(); // null ``` @method pop @return {Object} The removed object from the set or null. */ pop: function() { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); var obj = this.length > 0 ? this[this.length-1] : null; this.remove(obj); return obj; }, /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.push("red"); // ["red"] colors.push("green"); // ["red", "green"] colors.push("blue"); // ["red", "green", "blue"] ``` @method push @return {Ember.Set} The set itself. */ push: Ember.aliasMethod('addObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. This is an alias for `Ember.Set.pop()`. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.shift(); // "blue" colors.shift(); // "green" colors.shift(); // null ``` @method shift @return {Object} The removed object from the set or null. */ shift: Ember.aliasMethod('pop'), /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias of `Ember.Set.push()` ```javascript var colors = new Ember.Set(); colors.unshift("red"); // ["red"] colors.unshift("green"); // ["red", "green"] colors.unshift("blue"); // ["red", "green", "blue"] ``` @method unshift @return {Ember.Set} The set itself. */ unshift: Ember.aliasMethod('push'), /** Adds each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.addObjects()` ```javascript var colors = new Ember.Set(); colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"] ``` @method addEach @param {Ember.Enumerable} objects the objects to add. @return {Ember.Set} The set itself. */ addEach: Ember.aliasMethod('addObjects'), /** Removes each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.removeObjects()` ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.removeEach(["red", "blue"]); // ["green"] ``` @method removeEach @param {Ember.Enumerable} objects the objects to remove. @return {Ember.Set} The set itself. */ removeEach: Ember.aliasMethod('removeObjects'), // .......................................................... // PRIVATE ENUMERABLE SUPPORT // init: function(items) { this._super(); if (items) this.addObjects(items); }, // implement Ember.Enumerable nextObject: function(idx) { return this[idx]; }, // more optimized version firstObject: Ember.computed(function() { return this.length > 0 ? this[0] : undefined; }), // more optimized version lastObject: Ember.computed(function() { return this.length > 0 ? this[this.length-1] : undefined; }), // implements Ember.MutableEnumerable addObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (none(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), added ; if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added added = [obj]; this.enumerableContentWillChange(null, added); Ember.propertyWillChange(this, 'lastObject'); len = get(this, 'length'); this[guid] = len; this[len] = obj; set(this, 'length', len+1); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(null, added); return this; }, // implements Ember.MutableEnumerable removeObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (none(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), isFirst = idx === 0, isLast = idx === len-1, last, removed; if (idx>=0 && idx<len && (this[idx] === obj)) { removed = [obj]; this.enumerableContentWillChange(removed, null); if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); } if (isLast) { Ember.propertyWillChange(this, 'lastObject'); } // swap items - basically move the item to the end so it can be removed if (idx < len-1) { last = this[len-1]; this[idx] = last; this[guidFor(last)] = idx; } delete this[guid]; delete this[len-1]; set(this, 'length', len-1); if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); } if (isLast) { Ember.propertyDidChange(this, 'lastObject'); } this.enumerableContentDidChange(removed, null); } return this; }, // optimized version contains: function(obj) { return this[guidFor(obj)]>=0; }, copy: function() { var C = this.constructor, ret = new C(), loc = get(this, 'length'); set(ret, 'length', loc); while(--loc>=0) { ret[loc] = this[loc]; ret[guidFor(this[loc])] = loc; } return ret; }, toString: function() { var len = this.length, idx, array = []; for(idx = 0; idx < len; idx++) { array[idx] = this[idx]; } return "Ember.Set<%@>".fmt(array.join(',')); } }); })(); (function() { /** @module ember @submodule ember-runtime */ /** `Ember.Object` is the main base class for all Ember objects. It is a subclass of `Ember.CoreObject` with the `Ember.Observable` mixin applied. For details, see the documentation for each of these. @class Object @namespace Ember @extends Ember.CoreObject @uses Ember.Observable */ Ember.Object = Ember.CoreObject.extend(Ember.Observable); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, indexOf = Ember.ArrayPolyfills.indexOf; /** A Namespace is an object usually used to contain other objects or methods such as an application or framework. Create a namespace anytime you want to define one of these new containers. # Example Usage ```javascript MyFramework = Ember.Namespace.create({ VERSION: '1.0.0' }); ``` @class Namespace @namespace Ember @extends Ember.Object */ var Namespace = Ember.Namespace = Ember.Object.extend({ isNamespace: true, init: function() { Ember.Namespace.NAMESPACES.push(this); Ember.Namespace.PROCESSED = false; }, toString: function() { var name = get(this, 'name'); if (name) { return name; } findNamespaces(); return this[Ember.GUID_KEY+'_name']; }, nameClasses: function() { processNamespace([this.toString()], this, {}); }, destroy: function() { var namespaces = Ember.Namespace.NAMESPACES; Ember.lookup[this.toString()] = undefined; namespaces.splice(indexOf.call(namespaces, this), 1); this._super(); } }); Namespace.reopenClass({ NAMESPACES: [Ember], PROCESSED: false, processAll: processAllNamespaces }); var hasOwnProp = ({}).hasOwnProperty, guidFor = Ember.guidFor; function processNamespace(paths, root, seen) { var idx = paths.length; // Loop over all of the keys in the namespace, looking for classes for(var key in root) { if (!hasOwnProp.call(root, key)) { continue; } var obj = root[key]; // If we are processing the `Ember` namespace, for example, the // `paths` will start with `["Ember"]`. Every iteration through // the loop will update the **second** element of this list with // the key, so processing `Ember.View` will make the Array // `['Ember', 'View']`. paths[idx] = key; // If we have found an unprocessed class if (obj && obj.toString === classToString) { // Replace the class' `toString` with the dot-separated path // and set its `NAME_KEY` obj.toString = makeToString(paths.join('.')); obj[NAME_KEY] = paths.join('.'); // Support nested namespaces } else if (obj && obj.isNamespace) { // Skip aliased namespaces if (seen[guidFor(obj)]) { continue; } seen[guidFor(obj)] = true; // Process the child namespace processNamespace(paths, obj, seen); } } paths.length = idx; // cut out last item } function findNamespaces() { var Namespace = Ember.Namespace, lookup = Ember.lookup, obj, isNamespace; if (Namespace.PROCESSED) { return; } for (var prop in lookup) { // These don't raise exceptions but can cause warnings if (prop === "parent" || prop === "top" || prop === "frameElement") { continue; } // get(window.globalStorage, 'isNamespace') would try to read the storage for domain isNamespace and cause exception in Firefox. // globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage if (prop === "globalStorage" && lookup.StorageList && lookup.globalStorage instanceof lookup.StorageList) { continue; } // Unfortunately, some versions of IE don't support window.hasOwnProperty if (lookup.hasOwnProperty && !lookup.hasOwnProperty(prop)) { continue; } // At times we are not allowed to access certain properties for security reasons. // There are also times where even if we can access them, we are not allowed to access their properties. try { obj = Ember.lookup[prop]; isNamespace = obj && obj.isNamespace; } catch (e) { continue; } if (isNamespace) { Ember.deprecate("Namespaces should not begin with lowercase.", /^[A-Z]/.test(prop)); obj[NAME_KEY] = prop; } } } var NAME_KEY = Ember.NAME_KEY = Ember.GUID_KEY + '_name'; function superClassString(mixin) { var superclass = mixin.superclass; if (superclass) { if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; } else { return superClassString(superclass); } } else { return; } } function classToString() { if (!Ember.BOOTED && !this[NAME_KEY]) { processAllNamespaces(); } var ret; if (this[NAME_KEY]) { ret = this[NAME_KEY]; } else { var str = superClassString(this); if (str) { ret = "(subclass of " + str + ")"; } else { ret = "(unknown mixin)"; } this.toString = makeToString(ret); } return ret; } function processAllNamespaces() { if (!Namespace.PROCESSED) { findNamespaces(); Namespace.PROCESSED = true; } if (Ember.anyUnprocessedMixins) { var namespaces = Namespace.NAMESPACES, namespace; for (var i=0, l=namespaces.length; i<l; i++) { namespace = namespaces[i]; processNamespace([namespace.toString()], namespace, {}); } Ember.anyUnprocessedMixins = false; } } function makeToString(ret) { return function() { return ret; }; } Ember.Mixin.prototype.toString = classToString; })(); (function() { /** @module ember @submodule ember-runtime */ /** Defines a namespace that will contain an executable application. This is very similar to a normal namespace except that it is expected to include at least a 'ready' function which can be run to initialize the application. Currently `Ember.Application` is very similar to `Ember.Namespace.` However, this class may be augmented by additional frameworks so it is important to use this instance when building new applications. # Example Usage ```javascript MyApp = Ember.Application.create({ VERSION: '1.0.0', store: Ember.Store.create().from(Ember.fixtures) }); MyApp.ready = function() { //..init code goes here... } ``` @class Application @namespace Ember @extends Ember.Namespace */ Ember.Application = Ember.Namespace.extend(); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; /** An ArrayProxy wraps any other object that implements `Ember.Array` and/or `Ember.MutableArray,` forwarding all requests. This makes it very useful for a number of binding use cases or other cases where being able to swap out the underlying array is useful. A simple example of usage: ```javascript var pets = ['dog', 'cat', 'fish']; var ap = Ember.ArrayProxy.create({ content: Ember.A(pets) }); ap.get('firstObject'); // 'dog' ap.set('content', ['amoeba', 'paramecium']); ap.get('firstObject'); // 'amoeba' ``` This class can also be useful as a layer to transform the contents of an array, as they are accessed. This can be done by overriding `objectAtContent`: ```javascript var pets = ['dog', 'cat', 'fish']; var ap = Ember.ArrayProxy.create({ content: Ember.A(pets), objectAtContent: function(idx) { return this.get('content').objectAt(idx).toUpperCase(); } }); ap.get('firstObject'); // . 'DOG' ``` @class ArrayProxy @namespace Ember @extends Ember.Object @uses Ember.MutableArray */ Ember.ArrayProxy = Ember.Object.extend(Ember.MutableArray, /** @scope Ember.ArrayProxy.prototype */ { /** The content array. Must be an object that implements `Ember.Array` and/or `Ember.MutableArray.` @property content @type Ember.Array */ content: null, /** The array that the proxy pretends to be. In the default `ArrayProxy` implementation, this and `content` are the same. Subclasses of `ArrayProxy` can override this property to provide things like sorting and filtering. @property arrangedContent */ arrangedContent: Ember.computed('content', function() { return get(this, 'content'); }), /** Should actually retrieve the object at the specified index from the content. You can override this method in subclasses to transform the content item to something new. This method will only be called if content is non-`null`. @method objectAtContent @param {Number} idx The index to retrieve. @return {Object} the value or undefined if none found */ objectAtContent: function(idx) { return get(this, 'arrangedContent').objectAt(idx); }, /** Should actually replace the specified objects on the content array. You can override this method in subclasses to transform the content item into something new. This method will only be called if content is non-`null`. @method replaceContent @param {Number} idx The starting index @param {Number} amt The number of items to remove from the content. @param {Array} objects Optional array of objects to insert or null if no objects. @return {void} */ replaceContent: function(idx, amt, objects) { get(this, 'content').replace(idx, amt, objects); }, /** @private Invoked when the content property is about to change. Notifies observers that the entire array content will change. @method _contentWillChange */ _contentWillChange: Ember.beforeObserver(function() { this._teardownContent(); }, 'content'), _teardownContent: function() { var content = get(this, 'content'); if (content) { content.removeArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); } }, contentArrayWillChange: Ember.K, contentArrayDidChange: Ember.K, /** @private Invoked when the content property changes. Notifies observers that the entire array content has changed. @method _contentDidChange */ _contentDidChange: Ember.observer(function() { var content = get(this, 'content'); Ember.assert("Can't set ArrayProxy's content to itself", content !== this); this._setupContent(); }, 'content'), _setupContent: function() { var content = get(this, 'content'); if (content) { content.addArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); } }, _arrangedContentWillChange: Ember.beforeObserver(function() { var arrangedContent = get(this, 'arrangedContent'), len = arrangedContent ? get(arrangedContent, 'length') : 0; this.arrangedContentArrayWillChange(this, 0, len, undefined); this.arrangedContentWillChange(this); this._teardownArrangedContent(arrangedContent); }, 'arrangedContent'), _arrangedContentDidChange: Ember.observer(function() { var arrangedContent = get(this, 'arrangedContent'), len = arrangedContent ? get(arrangedContent, 'length') : 0; Ember.assert("Can't set ArrayProxy's content to itself", arrangedContent !== this); this._setupArrangedContent(); this.arrangedContentDidChange(this); this.arrangedContentArrayDidChange(this, 0, undefined, len); }, 'arrangedContent'), _setupArrangedContent: function() { var arrangedContent = get(this, 'arrangedContent'); if (arrangedContent) { arrangedContent.addArrayObserver(this, { willChange: 'arrangedContentArrayWillChange', didChange: 'arrangedContentArrayDidChange' }); } }, _teardownArrangedContent: function() { var arrangedContent = get(this, 'arrangedContent'); if (arrangedContent) { arrangedContent.removeArrayObserver(this, { willChange: 'arrangedContentArrayWillChange', didChange: 'arrangedContentArrayDidChange' }); } }, arrangedContentWillChange: Ember.K, arrangedContentDidChange: Ember.K, objectAt: function(idx) { return get(this, 'content') && this.objectAtContent(idx); }, length: Ember.computed(function() { var arrangedContent = get(this, 'arrangedContent'); return arrangedContent ? get(arrangedContent, 'length') : 0; // No dependencies since Enumerable notifies length of change }), replace: function(idx, amt, objects) { Ember.assert('The content property of '+ this.constructor + ' should be set before modifying it', this.get('content')); if (get(this, 'content')) this.replaceContent(idx, amt, objects); return this; }, arrangedContentArrayWillChange: function(item, idx, removedCnt, addedCnt) { this.arrayContentWillChange(idx, removedCnt, addedCnt); }, arrangedContentArrayDidChange: function(item, idx, removedCnt, addedCnt) { this.arrayContentDidChange(idx, removedCnt, addedCnt); }, init: function() { this._super(); this._setupContent(); this._setupArrangedContent(); }, willDestroy: function() { this._teardownArrangedContent(); this._teardownContent(); } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt, addBeforeObserver = Ember.addBeforeObserver, addObserver = Ember.addObserver, removeBeforeObserver = Ember.removeBeforeObserver, removeObserver = Ember.removeObserver, propertyWillChange = Ember.propertyWillChange, propertyDidChange = Ember.propertyDidChange; function contentPropertyWillChange(content, contentKey) { var key = contentKey.slice(8); // remove "content." if (key in this) { return; } // if shadowed in proxy propertyWillChange(this, key); } function contentPropertyDidChange(content, contentKey) { var key = contentKey.slice(8); // remove "content." if (key in this) { return; } // if shadowed in proxy propertyDidChange(this, key); } /** `Ember.ObjectProxy` forwards all properties not defined by the proxy itself to a proxied `content` object. ```javascript object = Ember.Object.create({ name: 'Foo' }); proxy = Ember.ObjectProxy.create({ content: object }); // Access and change existing properties proxy.get('name') // 'Foo' proxy.set('name', 'Bar'); object.get('name') // 'Bar' // Create new 'description' property on `object` proxy.set('description', 'Foo is a whizboo baz'); object.get('description') // 'Foo is a whizboo baz' ``` While `content` is unset, setting a property to be delegated will throw an Error. ```javascript proxy = Ember.ObjectProxy.create({ content: null, flag: null }); proxy.set('flag', true); proxy.get('flag'); // true proxy.get('foo'); // undefined proxy.set('foo', 'data'); // throws Error ``` Delegated properties can be bound to and will change when content is updated. Computed properties on the proxy itself can depend on delegated properties. ```javascript ProxyWithComputedProperty = Ember.ObjectProxy.extend({ fullName: function () { var firstName = this.get('firstName'), lastName = this.get('lastName'); if (firstName && lastName) { return firstName + ' ' + lastName; } return firstName || lastName; }.property('firstName', 'lastName') }); proxy = ProxyWithComputedProperty.create(); proxy.get('fullName'); // undefined proxy.set('content', { firstName: 'Tom', lastName: 'Dale' }); // triggers property change for fullName on proxy proxy.get('fullName'); // 'Tom Dale' ``` @class ObjectProxy @namespace Ember @extends Ember.Object */ Ember.ObjectProxy = Ember.Object.extend( /** @scope Ember.ObjectProxy.prototype */ { /** The object whose properties will be forwarded. @property content @type Ember.Object @default null */ content: null, _contentDidChange: Ember.observer(function() { Ember.assert("Can't set ObjectProxy's content to itself", this.get('content') !== this); }, 'content'), willWatchProperty: function (key) { var contentKey = 'content.' + key; addBeforeObserver(this, contentKey, null, contentPropertyWillChange); addObserver(this, contentKey, null, contentPropertyDidChange); }, didUnwatchProperty: function (key) { var contentKey = 'content.' + key; removeBeforeObserver(this, contentKey, null, contentPropertyWillChange); removeObserver(this, contentKey, null, contentPropertyDidChange); }, unknownProperty: function (key) { var content = get(this, 'content'); if (content) { return get(content, key); } }, setUnknownProperty: function (key, value) { var content = get(this, 'content'); Ember.assert(fmt("Cannot delegate set('%@', %@) to the 'content' property of object proxy %@: its 'content' is undefined.", [key, value, this]), content); return set(content, key, value); } }); })(); (function() { /** @module ember @submodule ember-runtime */ var set = Ember.set, get = Ember.get, guidFor = Ember.guidFor; var forEach = Ember.EnumerableUtils.forEach; var EachArray = Ember.Object.extend(Ember.Array, { init: function(content, keyName, owner) { this._super(); this._keyName = keyName; this._owner = owner; this._content = content; }, objectAt: function(idx) { var item = this._content.objectAt(idx); return item && get(item, this._keyName); }, length: Ember.computed(function() { var content = this._content; return content ? get(content, 'length') : 0; }) }); var IS_OBSERVER = /^.+:(before|change)$/; function addObserverForContentKey(content, keyName, proxy, idx, loc) { var objects = proxy._objects, guid; if (!objects) objects = proxy._objects = {}; while(--loc>=idx) { var item = content.objectAt(loc); if (item) { Ember.addBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); Ember.addObserver(item, keyName, proxy, 'contentKeyDidChange'); // keep track of the indicies each item was found at so we can map // it back when the obj changes. guid = guidFor(item); if (!objects[guid]) objects[guid] = []; objects[guid].push(loc); } } } function removeObserverForContentKey(content, keyName, proxy, idx, loc) { var objects = proxy._objects; if (!objects) objects = proxy._objects = {}; var indicies, guid; while(--loc>=idx) { var item = content.objectAt(loc); if (item) { Ember.removeBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); Ember.removeObserver(item, keyName, proxy, 'contentKeyDidChange'); guid = guidFor(item); indicies = objects[guid]; indicies[indicies.indexOf(loc)] = null; } } } /** This is the object instance returned when you get the `@each` property on an array. It uses the unknownProperty handler to automatically create EachArray instances for property names. @private @class EachProxy @namespace Ember @extends Ember.Object */ Ember.EachProxy = Ember.Object.extend({ init: function(content) { this._super(); this._content = content; content.addArrayObserver(this); // in case someone is already observing some keys make sure they are // added forEach(Ember.watchedEvents(this), function(eventName) { this.didAddListener(eventName); }, this); }, /** You can directly access mapped properties by simply requesting them. The `unknownProperty` handler will generate an EachArray of each item. @method unknownProperty @param keyName {String} @param value {anything} */ unknownProperty: function(keyName, value) { var ret; ret = new EachArray(this._content, keyName, this); Ember.defineProperty(this, keyName, null, ret); this.beginObservingContentKey(keyName); return ret; }, // .......................................................... // ARRAY CHANGES // Invokes whenever the content array itself changes. arrayWillChange: function(content, idx, removedCnt, addedCnt) { var keys = this._keys, key, array, lim; lim = removedCnt>0 ? idx+removedCnt : -1; Ember.beginPropertyChanges(this); for(key in keys) { if (!keys.hasOwnProperty(key)) { continue; } if (lim>0) removeObserverForContentKey(content, key, this, idx, lim); Ember.propertyWillChange(this, key); } Ember.propertyWillChange(this._content, '@each'); Ember.endPropertyChanges(this); }, arrayDidChange: function(content, idx, removedCnt, addedCnt) { var keys = this._keys, key, array, lim; lim = addedCnt>0 ? idx+addedCnt : -1; Ember.beginPropertyChanges(this); for(key in keys) { if (!keys.hasOwnProperty(key)) { continue; } if (lim>0) addObserverForContentKey(content, key, this, idx, lim); Ember.propertyDidChange(this, key); } Ember.propertyDidChange(this._content, '@each'); Ember.endPropertyChanges(this); }, // .......................................................... // LISTEN FOR NEW OBSERVERS AND OTHER EVENT LISTENERS // Start monitoring keys based on who is listening... didAddListener: function(eventName) { if (IS_OBSERVER.test(eventName)) { this.beginObservingContentKey(eventName.slice(0, -7)); } }, didRemoveListener: function(eventName) { if (IS_OBSERVER.test(eventName)) { this.stopObservingContentKey(eventName.slice(0, -7)); } }, // .......................................................... // CONTENT KEY OBSERVING // Actual watch keys on the source content. beginObservingContentKey: function(keyName) { var keys = this._keys; if (!keys) keys = this._keys = {}; if (!keys[keyName]) { keys[keyName] = 1; var content = this._content, len = get(content, 'length'); addObserverForContentKey(content, keyName, this, 0, len); } else { keys[keyName]++; } }, stopObservingContentKey: function(keyName) { var keys = this._keys; if (keys && (keys[keyName]>0) && (--keys[keyName]<=0)) { var content = this._content, len = get(content, 'length'); removeObserverForContentKey(content, keyName, this, 0, len); } }, contentKeyWillChange: function(obj, keyName) { Ember.propertyWillChange(this, keyName); }, contentKeyDidChange: function(obj, keyName) { Ember.propertyDidChange(this, keyName); } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set; // Add Ember.Array to Array.prototype. Remove methods with native // implementations and supply some more optimized versions of generic methods // because they are so common. var NativeArray = Ember.Mixin.create(Ember.MutableArray, Ember.Observable, Ember.Copyable, { // because length is a built-in property we need to know to just get the // original property. get: function(key) { if (key==='length') return this.length; else if ('number' === typeof key) return this[key]; else return this._super(key); }, objectAt: function(idx) { return this[idx]; }, // primitive for array support. replace: function(idx, amt, objects) { if (this.isFrozen) throw Ember.FROZEN_ERROR ; // if we replaced exactly the same number of items, then pass only the // replaced range. Otherwise, pass the full remaining array length // since everything has shifted var len = objects ? get(objects, 'length') : 0; this.arrayContentWillChange(idx, amt, len); if (!objects || objects.length === 0) { this.splice(idx, amt) ; } else { var args = [idx, amt].concat(objects) ; this.splice.apply(this,args) ; } this.arrayContentDidChange(idx, amt, len); return this ; }, // If you ask for an unknown property, then try to collect the value // from member items. unknownProperty: function(key, value) { var ret;// = this.reducedProperty(key, value) ; if ((value !== undefined) && ret === undefined) { ret = this[key] = value; } return ret ; }, // If browser did not implement indexOf natively, then override with // specialized version indexOf: function(object, startAt) { var idx, len = this.length; if (startAt === undefined) startAt = 0; else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt); if (startAt < 0) startAt += len; for(idx=startAt;idx<len;idx++) { if (this[idx] === object) return idx ; } return -1; }, lastIndexOf: function(object, startAt) { var idx, len = this.length; if (startAt === undefined) startAt = len-1; else startAt = (startAt < 0) ? Math.ceil(startAt) : Math.floor(startAt); if (startAt < 0) startAt += len; for(idx=startAt;idx>=0;idx--) { if (this[idx] === object) return idx ; } return -1; }, copy: function(deep) { if (deep) { return this.map(function(item){ return Ember.copy(item, true); }); } return this.slice(); } }); // Remove any methods implemented natively so we don't override them var ignore = ['length']; Ember.EnumerableUtils.forEach(NativeArray.keys(), function(methodName) { if (Array.prototype[methodName]) ignore.push(methodName); }); if (ignore.length>0) { NativeArray = NativeArray.without.apply(NativeArray, ignore); } /** The NativeArray mixin contains the properties needed to to make the native Array support Ember.MutableArray and all of its dependent APIs. Unless you have `Ember.EXTEND_PROTOTYPES or `Ember.EXTEND_PROTOTYPES.Array` set to false, this will be applied automatically. Otherwise you can apply the mixin at anytime by calling `Ember.NativeArray.activate`. @class NativeArray @namespace Ember @extends Ember.Mixin @uses Ember.MutableArray @uses Ember.MutableEnumerable @uses Ember.Copyable @uses Ember.Freezable */ Ember.NativeArray = NativeArray; /** Creates an `Ember.NativeArray` from an Array like object. Does not modify the original object. @method A @for Ember @return {Ember.NativeArray} */ Ember.A = function(arr){ if (arr === undefined) { arr = []; } return Ember.Array.detect(arr) ? arr : Ember.NativeArray.apply(arr); }; /** Activates the mixin on the Array.prototype if not already applied. Calling this method more than once is safe. @method activate @for Ember.NativeArray @static @return {void} */ Ember.NativeArray.activate = function() { NativeArray.apply(Array.prototype); Ember.A = function(arr) { return arr || []; }; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Array) { Ember.NativeArray.activate(); } })(); (function() { var DeferredMixin = Ember.DeferredMixin, // mixins/deferred EmberObject = Ember.Object, // system/object get = Ember.get; var Deferred = Ember.Object.extend(DeferredMixin); Deferred.reopenClass({ promise: function(callback, binding) { var deferred = Deferred.create(); callback.call(binding, deferred); return get(deferred, 'promise'); } }); Ember.Deferred = Deferred; })(); (function() { /** @module ember @submodule ember-runtime */ var loadHooks = {}; var loaded = {}; /** @method onLoad @for Ember @param name {String} name of hook @param callback {Function} callback to be called */ Ember.onLoad = function(name, callback) { var object; loadHooks[name] = loadHooks[name] || Ember.A(); loadHooks[name].pushObject(callback); if (object = loaded[name]) { callback(object); } }; /** @method runLoadHooks @for Ember @param name {String} name of hook @param object {Object} object to pass to callbacks */ Ember.runLoadHooks = function(name, object) { var hooks; loaded[name] = object; if (hooks = loadHooks[name]) { loadHooks[name].forEach(function(callback) { callback(object); }); } }; })(); (function() { })(); (function() { var get = Ember.get; /** @module ember @submodule ember-runtime */ /** `Ember.ControllerMixin` provides a standard interface for all classes that compose Ember's controller layer: `Ember.Controller`, `Ember.ArrayController`, and `Ember.ObjectController`. Within an `Ember.Router`-managed application single shared instaces of every Controller object in your application's namespace will be added to the application's `Ember.Router` instance. See `Ember.Application#initialize` for additional information. ## Views By default a controller instance will be the rendering context for its associated `Ember.View.` This connection is made during calls to `Ember.ControllerMixin#connectOutlet`. Within the view's template, the `Ember.View` instance can be accessed through the controller with `{{view}}`. ## Target Forwarding By default a controller will target your application's `Ember.Router` instance. Calls to `{{action}}` within the template of a controller's view are forwarded to the router. See `Ember.Handlebars.helpers.action` for additional information. @class ControllerMixin @namespace Ember @extends Ember.Mixin */ Ember.ControllerMixin = Ember.Mixin.create({ /** The object to which events from the view should be sent. For example, when a Handlebars template uses the `{{action}}` helper, it will attempt to send the event to the view's controller's `target`. By default, a controller's `target` is set to the router after it is instantiated by `Ember.Application#initialize`. @property target @default null */ target: null, container: null, store: null, send: function(actionName) { var args = [].slice.call(arguments, 1), target; if (this[actionName]) { Ember.assert("The controller " + this + " does not have the action " + actionName, typeof this[actionName] === 'function'); this[actionName].apply(this, args); } else if(target = get(this, 'target')) { Ember.assert("The target for controller " + this + " (" + target + ") did not define a `send` method", typeof target.send === 'function'); target.send.apply(target, arguments); } } }); /** @class Controller @namespace Ember @extends Ember.Object @uses Ember.ControllerMixin */ Ember.Controller = Ember.Object.extend(Ember.ControllerMixin); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach; /** `Ember.SortableMixin` provides a standard interface for array proxies to specify a sort order and maintain this sorting when objects are added, removed, or updated without changing the implicit order of their underlying content array: ```javascript songs = [ {trackNumber: 4, title: 'Ob-La-Di, Ob-La-Da'}, {trackNumber: 2, title: 'Back in the U.S.S.R.'}, {trackNumber: 3, title: 'Glass Onion'}, ]; songsController = Ember.ArrayController.create({ content: songs, sortProperties: ['trackNumber'] }); songsController.get('firstObject'); // {trackNumber: 2, title: 'Back in the U.S.S.R.'} songsController.addObject({trackNumber: 1, title: 'Dear Prudence'}); songsController.get('firstObject'); // {trackNumber: 1, title: 'Dear Prudence'} ``` @class SortableMixin @namespace Ember @extends Ember.Mixin @uses Ember.MutableEnumerable */ Ember.SortableMixin = Ember.Mixin.create(Ember.MutableEnumerable, { sortProperties: null, sortAscending: true, orderBy: function(item1, item2) { var result = 0, sortProperties = get(this, 'sortProperties'), sortAscending = get(this, 'sortAscending'); Ember.assert("you need to define `sortProperties`", !!sortProperties); forEach(sortProperties, function(propertyName) { if (result === 0) { result = Ember.compare(get(item1, propertyName), get(item2, propertyName)); if ((result !== 0) && !sortAscending) { result = (-1) * result; } } }); return result; }, destroy: function() { var content = get(this, 'content'), sortProperties = get(this, 'sortProperties'); if (content && sortProperties) { forEach(content, function(item) { forEach(sortProperties, function(sortProperty) { Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); } return this._super(); }, isSorted: Ember.computed('sortProperties', function() { return !!get(this, 'sortProperties'); }), arrangedContent: Ember.computed('content', 'sortProperties.@each', function(key, value) { var content = get(this, 'content'), isSorted = get(this, 'isSorted'), sortProperties = get(this, 'sortProperties'), self = this; if (content && isSorted) { content = content.slice(); content.sort(function(item1, item2) { return self.orderBy(item1, item2); }); forEach(content, function(item) { forEach(sortProperties, function(sortProperty) { Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); return Ember.A(content); } return content; }), _contentWillChange: Ember.beforeObserver(function() { var content = get(this, 'content'), sortProperties = get(this, 'sortProperties'); if (content && sortProperties) { forEach(content, function(item) { forEach(sortProperties, function(sortProperty) { Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); } this._super(); }, 'content'), sortAscendingWillChange: Ember.beforeObserver(function() { this._lastSortAscending = get(this, 'sortAscending'); }, 'sortAscending'), sortAscendingDidChange: Ember.observer(function() { if (get(this, 'sortAscending') !== this._lastSortAscending) { var arrangedContent = get(this, 'arrangedContent'); arrangedContent.reverseObjects(); } }, 'sortAscending'), contentArrayWillChange: function(array, idx, removedCount, addedCount) { var isSorted = get(this, 'isSorted'); if (isSorted) { var arrangedContent = get(this, 'arrangedContent'); var removedObjects = array.slice(idx, idx+removedCount); var sortProperties = get(this, 'sortProperties'); forEach(removedObjects, function(item) { arrangedContent.removeObject(item); forEach(sortProperties, function(sortProperty) { Ember.removeObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); } return this._super(array, idx, removedCount, addedCount); }, contentArrayDidChange: function(array, idx, removedCount, addedCount) { var isSorted = get(this, 'isSorted'), sortProperties = get(this, 'sortProperties'); if (isSorted) { var addedObjects = array.slice(idx, idx+addedCount); var arrangedContent = get(this, 'arrangedContent'); forEach(addedObjects, function(item) { this.insertItemSorted(item); forEach(sortProperties, function(sortProperty) { Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange'); }, this); }, this); } return this._super(array, idx, removedCount, addedCount); }, insertItemSorted: function(item) { var arrangedContent = get(this, 'arrangedContent'); var length = get(arrangedContent, 'length'); var idx = this._binarySearch(item, 0, length); arrangedContent.insertAt(idx, item); }, contentItemSortPropertyDidChange: function(item) { var arrangedContent = get(this, 'arrangedContent'), oldIndex = arrangedContent.indexOf(item), leftItem = arrangedContent.objectAt(oldIndex - 1), rightItem = arrangedContent.objectAt(oldIndex + 1), leftResult = leftItem && this.orderBy(item, leftItem), rightResult = rightItem && this.orderBy(item, rightItem); if (leftResult < 0 || rightResult > 0) { arrangedContent.removeObject(item); this.insertItemSorted(item); } }, _binarySearch: function(item, low, high) { var mid, midItem, res, arrangedContent; if (low === high) { return low; } arrangedContent = get(this, 'arrangedContent'); mid = low + Math.floor((high - low) / 2); midItem = arrangedContent.objectAt(mid); res = this.orderBy(midItem, item); if (res < 0) { return this._binarySearch(item, mid+1, high); } else if (res > 0) { return this._binarySearch(item, low, mid); } return mid; } }); })(); (function() { /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, isGlobalPath = Ember.isGlobalPath, forEach = Ember.EnumerableUtils.forEach, replace = Ember.EnumerableUtils.replace; /** `Ember.ArrayController` provides a way for you to publish a collection of objects so that you can easily bind to the collection from a Handlebars `#each` helper, an `Ember.CollectionView`, or other controllers. The advantage of using an `ArrayController` is that you only have to set up your view bindings once; to change what's displayed, simply swap out the `content` property on the controller. For example, imagine you wanted to display a list of items fetched via an XHR request. Create an `Ember.ArrayController` and set its `content` property: ```javascript MyApp.listController = Ember.ArrayController.create(); $.get('people.json', function(data) { MyApp.listController.set('content', data); }); ``` Then, create a view that binds to your new controller: ```handlebars {{#each MyApp.listController}} {{firstName}} {{lastName}} {{/each}} ``` Although you are binding to the controller, the behavior of this controller is to pass through any methods or properties to the underlying array. This capability comes from `Ember.ArrayProxy`, which this class inherits from. Sometimes you want to display computed properties within the body of an `#each` helper that depend on the underlying items in `content`, but are not present on those items. To do this, set `itemController` to the name of a controller (probably an `ObjectController`) that will wrap each individual item. For example: ```handlebars {{#each post in controller}} <li>{{title}} ({{titleLength}} characters)</li> {{/each}} ``` ```javascript App.PostsController = Ember.ArrayController.extend({ itemController: 'post' }); App.PostController = Ember.ObjectController.extend({ // the `title` property will be proxied to the underlying post. titleLength: function() { return this.get('title').length; }.property('title') }); ``` In some cases it is helpful to return a different `itemController` depending on the particular item. Subclasses can do this by overriding `lookupItemController`. For example: ```javascript App.MyArrayController = Ember.ArrayController.extend({ lookupItemController: function( object ) { if (object.get('isSpecial')) { return "special"; // use App.SpecialController } else { return "regular"; // use App.RegularController } } }); ``` @class ArrayController @namespace Ember @extends Ember.ArrayProxy @uses Ember.SortableMixin @uses Ember.ControllerMixin */ Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin, Ember.SortableMixin, { /** The controller used to wrap items, if any. @property itemController @type String @default null */ itemController: null, /** Return the name of the controller to wrap items, or `null` if items should be returned directly. The default implementation simply returns the `itemController` property, but subclasses can override this method to return different controllers for different objects. For example: ```javascript App.MyArrayController = Ember.ArrayController.extend({ lookupItemController: function( object ) { if (object.get('isSpecial')) { return "special"; // use App.SpecialController } else { return "regular"; // use App.RegularController } } }); ``` @method @type String @default null */ lookupItemController: function(object) { return get(this, 'itemController'); }, objectAtContent: function(idx) { var length = get(this, 'length'), object = get(this,'arrangedContent').objectAt(idx), controllerClass = this.lookupItemController(object); if (controllerClass && idx < length) { return this.controllerAt(idx, object, controllerClass); } else { // When controllerClass is falsy we have not opted in to using item // controllers, so return the object directly. However, when // controllerClass is defined but the index is out of range, we want to // return the "out of range" value, whatever that might be. Rather than // make assumptions (e.g. guessing `null` or `undefined`) we defer this to // `arrangedContent`. return object; } }, arrangedContentDidChange: function() { this._super(); this._resetSubContainers(); }, arrayContentDidChange: function(idx, removedCnt, addedCnt) { var subContainers = get(this, 'subContainers'), subContainersToRemove = subContainers.slice(idx, idx+removedCnt); forEach(subContainersToRemove, function(subContainer) { if (subContainer) { subContainer.destroy(); } }); replace(subContainers, idx, removedCnt, new Array(addedCnt)); // The shadow array of subcontainers must be updated before we trigger // observers, otherwise observers will get the wrong subcontainer when // calling `objectAt` this._super(idx, removedCnt, addedCnt); }, init: function() { this._super(); this._resetSubContainers(); }, controllerAt: function(idx, object, controllerClass) { var container = get(this, 'container'), subContainers = get(this, 'subContainers'), subContainer = subContainers[idx], controller; if (!subContainer) { subContainer = subContainers[idx] = container.child(); } controller = subContainer.lookup("controller:" + controllerClass); if (!controller) { throw new Error('Could not resolve itemController: "' + controllerClass + '"'); } controller.set('target', this); controller.set('content', object); return controller; }, subContainers: null, _resetSubContainers: function() { var subContainers = get(this, 'subContainers'); if (subContainers) { forEach(subContainers, function(subContainer) { if (subContainer) { subContainer.destroy(); } }); } this.set('subContainers', Ember.A()); } }); })(); (function() { /** @module ember @submodule ember-runtime */ /** `Ember.ObjectController` is part of Ember's Controller layer. A single shared instance of each `Ember.ObjectController` subclass in your application's namespace will be created at application initialization and be stored on your application's `Ember.Router` instance. `Ember.ObjectController` derives its functionality from its superclass `Ember.ObjectProxy` and the `Ember.ControllerMixin` mixin. @class ObjectController @namespace Ember @extends Ember.ObjectProxy @uses Ember.ControllerMixin **/ Ember.ObjectController = Ember.ObjectProxy.extend(Ember.ControllerMixin); })(); (function() { })(); (function() { /** Ember Runtime @module ember @submodule ember-runtime @requires ember-metal */ })(); (function() { /** @module ember @submodule ember-views */ var jQuery = Ember.imports.jQuery; Ember.assert("Ember Views require jQuery 1.7 (>= 1.7.2), 1.8 or 1.9", jQuery && (jQuery().jquery.match(/^1\.(7(?!$)(?!\.[01])|8|9)(\.\d+)?(pre|rc\d?)?/) || Ember.ENV.FORCE_JQUERY)); /** Alias for jQuery @method $ @for Ember */ Ember.$ = jQuery; })(); (function() { /** @module ember @submodule ember-views */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents var dragEvents = Ember.String.w('dragstart drag dragenter dragleave dragover drop dragend'); // Copies the `dataTransfer` property from a browser event object onto the // jQuery event object for the specified events Ember.EnumerableUtils.forEach(dragEvents, function(eventName) { Ember.$.event.fixHooks[eventName] = { props: ['dataTransfer'] }; }); })(); (function() { /** @module ember @submodule ember-views */ /*** BEGIN METAMORPH HELPERS ***/ // Internet Explorer prior to 9 does not allow setting innerHTML if the first element // is a "zero-scope" element. This problem can be worked around by making // the first node an invisible text node. We, like Modernizr, use &shy; var needsShy = (function(){ var testEl = document.createElement('div'); testEl.innerHTML = "<div></div>"; testEl.firstChild.innerHTML = "<script></script>"; return testEl.firstChild.innerHTML === ''; })(); // IE 8 (and likely earlier) likes to move whitespace preceeding // a script tag to appear after it. This means that we can // accidentally remove whitespace when updating a morph. var movesWhitespace = (function() { var testEl = document.createElement('div'); testEl.innerHTML = "Test: <script type='text/x-placeholder'></script>Value"; return testEl.childNodes[0].nodeValue === 'Test:' && testEl.childNodes[2].nodeValue === ' Value'; })(); // Use this to find children by ID instead of using jQuery var findChildById = function(element, id) { if (element.getAttribute('id') === id) { return element; } var len = element.childNodes.length, idx, node, found; for (idx=0; idx<len; idx++) { node = element.childNodes[idx]; found = node.nodeType === 1 && findChildById(node, id); if (found) { return found; } } }; var setInnerHTMLWithoutFix = function(element, html) { if (needsShy) { html = '&shy;' + html; } var matches = []; if (movesWhitespace) { // Right now we only check for script tags with ids with the // goal of targeting morphs. html = html.replace(/(\s+)(<script id='([^']+)')/g, function(match, spaces, tag, id) { matches.push([id, spaces]); return tag; }); } element.innerHTML = html; // If we have to do any whitespace adjustments do them now if (matches.length > 0) { var len = matches.length, idx; for (idx=0; idx<len; idx++) { var script = findChildById(element, matches[idx][0]), node = document.createTextNode(matches[idx][1]); script.parentNode.insertBefore(node, script); } } if (needsShy) { var shyElement = element.firstChild; while (shyElement.nodeType === 1 && !shyElement.nodeName) { shyElement = shyElement.firstChild; } if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === "\u00AD") { shyElement.nodeValue = shyElement.nodeValue.slice(1); } } }; /*** END METAMORPH HELPERS */ var innerHTMLTags = {}; var canSetInnerHTML = function(tagName) { if (innerHTMLTags[tagName] !== undefined) { return innerHTMLTags[tagName]; } var canSet = true; // IE 8 and earlier don't allow us to do innerHTML on select if (tagName.toLowerCase() === 'select') { var el = document.createElement('select'); setInnerHTMLWithoutFix(el, '<option value="test">Test</option>'); canSet = el.options.length === 1; } innerHTMLTags[tagName] = canSet; return canSet; }; var setInnerHTML = function(element, html) { var tagName = element.tagName; if (canSetInnerHTML(tagName)) { setInnerHTMLWithoutFix(element, html); } else { Ember.assert("Can't set innerHTML on "+element.tagName+" in this browser", element.outerHTML); var startTag = element.outerHTML.match(new RegExp("<"+tagName+"([^>]*)>", 'i'))[0], endTag = '</'+tagName+'>'; var wrapper = document.createElement('div'); setInnerHTMLWithoutFix(wrapper, startTag + html + endTag); element = wrapper.firstChild; while (element.tagName !== tagName) { element = element.nextSibling; } } return element; }; function isSimpleClick(event) { var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey, secondaryClick = event.which > 1; // IE9 may return undefined return !modifier && !secondaryClick; } Ember.ViewUtils = { setInnerHTML: setInnerHTML, isSimpleClick: isSimpleClick }; })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set; var indexOf = Ember.ArrayPolyfills.indexOf; var ClassSet = function() { this.seen = {}; this.list = []; }; ClassSet.prototype = { add: function(string) { if (string in this.seen) { return; } this.seen[string] = true; this.list.push(string); }, toDOM: function() { return this.list.join(" "); } }; /** `Ember.RenderBuffer` gathers information regarding the a view and generates the final representation. `Ember.RenderBuffer` will generate HTML which can be pushed to the DOM. @class RenderBuffer @namespace Ember @constructor */ Ember.RenderBuffer = function(tagName) { return new Ember._RenderBuffer(tagName); }; Ember._RenderBuffer = function(tagName) { this.tagNames = [tagName || null]; this.buffer = []; }; Ember._RenderBuffer.prototype = /** @scope Ember.RenderBuffer.prototype */ { // The root view's element _element: null, /** @private An internal set used to de-dupe class names when `addClass()` is used. After each call to `addClass()`, the `classes` property will be updated. @property elementClasses @type Array @default [] */ elementClasses: null, /** Array of class names which will be applied in the class attribute. You can use `setClasses()` to set this property directly. If you use `addClass()`, it will be maintained for you. @property classes @type Array @default [] */ classes: null, /** The id in of the element, to be applied in the id attribute. You should not set this property yourself, rather, you should use the `id()` method of `Ember.RenderBuffer`. @property elementId @type String @default null */ elementId: null, /** A hash keyed on the name of the attribute and whose value will be applied to that attribute. For example, if you wanted to apply a `data-view="Foo.bar"` property to an element, you would set the elementAttributes hash to `{'data-view':'Foo.bar'}`. You should not maintain this hash yourself, rather, you should use the `attr()` method of `Ember.RenderBuffer`. @property elementAttributes @type Hash @default {} */ elementAttributes: null, /** The tagname of the element an instance of `Ember.RenderBuffer` represents. Usually, this gets set as the first parameter to `Ember.RenderBuffer`. For example, if you wanted to create a `p` tag, then you would call ```javascript Ember.RenderBuffer('p') ``` @property elementTag @type String @default null */ elementTag: null, /** A hash keyed on the name of the style attribute and whose value will be applied to that attribute. For example, if you wanted to apply a `background-color:black;` style to an element, you would set the elementStyle hash to `{'background-color':'black'}`. You should not maintain this hash yourself, rather, you should use the `style()` method of `Ember.RenderBuffer`. @property elementStyle @type Hash @default {} */ elementStyle: null, /** Nested `RenderBuffers` will set this to their parent `RenderBuffer` instance. @property parentBuffer @type Ember._RenderBuffer */ parentBuffer: null, /** Adds a string of HTML to the `RenderBuffer`. @method push @param {String} string HTML to push into the buffer @chainable */ push: function(string) { this.buffer.push(string); return this; }, /** Adds a class to the buffer, which will be rendered to the class attribute. @method addClass @param {String} className Class name to add to the buffer @chainable */ addClass: function(className) { // lazily create elementClasses var elementClasses = this.elementClasses = (this.elementClasses || new ClassSet()); this.elementClasses.add(className); this.classes = this.elementClasses.list; return this; }, setClasses: function(classNames) { this.classes = classNames; }, /** Sets the elementID to be used for the element. @method id @param {String} id @chainable */ id: function(id) { this.elementId = id; return this; }, // duck type attribute functionality like jQuery so a render buffer // can be used like a jQuery object in attribute binding scenarios. /** Adds an attribute which will be rendered to the element. @method attr @param {String} name The name of the attribute @param {String} value The value to add to the attribute @chainable @return {Ember.RenderBuffer|String} this or the current attribute value */ attr: function(name, value) { var attributes = this.elementAttributes = (this.elementAttributes || {}); if (arguments.length === 1) { return attributes[name]; } else { attributes[name] = value; } return this; }, /** Remove an attribute from the list of attributes to render. @method removeAttr @param {String} name The name of the attribute @chainable */ removeAttr: function(name) { var attributes = this.elementAttributes; if (attributes) { delete attributes[name]; } return this; }, /** Adds a style to the style attribute which will be rendered to the element. @method style @param {String} name Name of the style @param {String} value @chainable */ style: function(name, value) { var style = this.elementStyle = (this.elementStyle || {}); this.elementStyle[name] = value; return this; }, begin: function(tagName) { this.tagNames.push(tagName || null); return this; }, pushOpeningTag: function() { var tagName = this.currentTagName(); if (!tagName) { return; } if (!this._element && this.buffer.length === 0) { this._element = this.generateElement(); return; } var buffer = this.buffer, id = this.elementId, classes = this.classes, attrs = this.elementAttributes, style = this.elementStyle, prop; buffer.push('<' + tagName); if (id) { buffer.push(' id="' + this._escapeAttribute(id) + '"'); this.elementId = null; } if (classes) { buffer.push(' class="' + this._escapeAttribute(classes.join(' ')) + '"'); this.classes = null; } if (style) { buffer.push(' style="'); for (prop in style) { if (style.hasOwnProperty(prop)) { buffer.push(prop + ':' + this._escapeAttribute(style[prop]) + ';'); } } buffer.push('"'); this.elementStyle = null; } if (attrs) { for (prop in attrs) { if (attrs.hasOwnProperty(prop)) { buffer.push(' ' + prop + '="' + this._escapeAttribute(attrs[prop]) + '"'); } } this.elementAttributes = null; } buffer.push('>'); }, pushClosingTag: function() { var tagName = this.tagNames.pop(); if (tagName) { this.buffer.push('</' + tagName + '>'); } }, currentTagName: function() { return this.tagNames[this.tagNames.length-1]; }, generateElement: function() { var tagName = this.tagNames.pop(), // pop since we don't need to close element = document.createElement(tagName), $element = Ember.$(element), id = this.elementId, classes = this.classes, attrs = this.elementAttributes, style = this.elementStyle, styleBuffer = '', prop; if (id) { $element.attr('id', id); this.elementId = null; } if (classes) { $element.attr('class', classes.join(' ')); this.classes = null; } if (style) { for (prop in style) { if (style.hasOwnProperty(prop)) { styleBuffer += (prop + ':' + style[prop] + ';'); } } $element.attr('style', styleBuffer); this.elementStyle = null; } if (attrs) { for (prop in attrs) { if (attrs.hasOwnProperty(prop)) { $element.attr(prop, attrs[prop]); } } this.elementAttributes = null; } return element; }, /** @method element @return {DOMElement} The element corresponding to the generated HTML of this buffer */ element: function() { var html = this.innerString(); if (html) { this._element = Ember.ViewUtils.setInnerHTML(this._element, html); } return this._element; }, /** Generates the HTML content for this buffer. @method string @return {String} The generated HTML */ string: function() { if (this._element) { return this.element().outerHTML; } else { return this.innerString(); } }, innerString: function() { return this.buffer.join(''); }, _escapeAttribute: function(value) { // Stolen shamelessly from Handlebars var escape = { "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; var badChars = /&(?!\w+;)|[<>"'`]/g; var possible = /[&<>"'`]/; var escapeChar = function(chr) { return escape[chr] || "&amp;"; }; var string = value.toString(); if(!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } }; })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; /** `Ember.EventDispatcher` handles delegating browser events to their corresponding `Ember.Views.` For example, when you click on a view, `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets called. @class EventDispatcher @namespace Ember @private @extends Ember.Object */ Ember.EventDispatcher = Ember.Object.extend( /** @scope Ember.EventDispatcher.prototype */{ /** @private The root DOM element to which event listeners should be attached. Event listeners will be attached to the document unless this is overridden. Can be specified as a DOMElement or a selector string. The default body is a string since this may be evaluated before document.body exists in the DOM. @property rootElement @type DOMElement @default 'body' */ rootElement: 'body', /** @private Sets up event listeners for standard browser events. This will be called after the browser sends a `DOMContentReady` event. By default, it will set up all of the listeners on the document body. If you would like to register the listeners on a different element, set the event dispatcher's `root` property. @method setup @param addedEvents {Hash} */ setup: function(addedEvents) { var event, events = { touchstart : 'touchStart', touchmove : 'touchMove', touchend : 'touchEnd', touchcancel : 'touchCancel', keydown : 'keyDown', keyup : 'keyUp', keypress : 'keyPress', mousedown : 'mouseDown', mouseup : 'mouseUp', contextmenu : 'contextMenu', click : 'click', dblclick : 'doubleClick', mousemove : 'mouseMove', focusin : 'focusIn', focusout : 'focusOut', mouseenter : 'mouseEnter', mouseleave : 'mouseLeave', submit : 'submit', input : 'input', change : 'change', dragstart : 'dragStart', drag : 'drag', dragenter : 'dragEnter', dragleave : 'dragLeave', dragover : 'dragOver', drop : 'drop', dragend : 'dragEnd' }; Ember.$.extend(events, addedEvents || {}); var rootElement = Ember.$(get(this, 'rootElement')); Ember.assert(fmt('You cannot use the same root element (%@) multiple times in an Ember.Application', [rootElement.selector || rootElement[0].tagName]), !rootElement.is('.ember-application')); Ember.assert('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', !rootElement.closest('.ember-application').length); Ember.assert('You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application', !rootElement.find('.ember-application').length); rootElement.addClass('ember-application'); Ember.assert('Unable to add "ember-application" class to rootElement. Make sure you set rootElement to the body or an element in the body.', rootElement.is('.ember-application')); for (event in events) { if (events.hasOwnProperty(event)) { this.setupHandler(rootElement, event, events[event]); } } }, /** @private Registers an event listener on the document. If the given event is triggered, the provided event handler will be triggered on the target view. If the target view does not implement the event handler, or if the handler returns `false`, the parent view will be called. The event will continue to bubble to each successive parent view until it reaches the top. For example, to have the `mouseDown` method called on the target view when a `mousedown` event is received from the browser, do the following: ```javascript setupHandler('mousedown', 'mouseDown'); ``` @method setupHandler @param {Element} rootElement @param {String} event the browser-originated event to listen to @param {String} eventName the name of the method to call on the view */ setupHandler: function(rootElement, event, eventName) { var self = this; rootElement.delegate('.ember-view', event + '.ember', function(evt, triggeringManager) { return Ember.handleErrors(function() { var view = Ember.View.views[this.id], result = true, manager = null; manager = self._findNearestEventManager(view,eventName); if (manager && manager !== triggeringManager) { result = self._dispatchEvent(manager, evt, eventName, view); } else if (view) { result = self._bubbleEvent(view,evt,eventName); } else { evt.stopPropagation(); } return result; }, this); }); rootElement.delegate('[data-ember-action]', event + '.ember', function(evt) { return Ember.handleErrors(function() { var actionId = Ember.$(evt.currentTarget).attr('data-ember-action'), action = Ember.Handlebars.ActionHelper.registeredActions[actionId], handler = action.handler; if (action.eventName === eventName) { return handler(evt); } }, this); }); }, _findNearestEventManager: function(view, eventName) { var manager = null; while (view) { manager = get(view, 'eventManager'); if (manager && manager[eventName]) { break; } view = get(view, 'parentView'); } return manager; }, _dispatchEvent: function(object, evt, eventName, view) { var result = true; var handler = object[eventName]; if (Ember.typeOf(handler) === 'function') { result = handler.call(object, evt, view); // Do not preventDefault in eventManagers. evt.stopPropagation(); } else { result = this._bubbleEvent(view, evt, eventName); } return result; }, _bubbleEvent: function(view, evt, eventName) { return Ember.run(function() { return view.handleEvent(eventName, evt); }); }, destroy: function() { var rootElement = get(this, 'rootElement'); Ember.$(rootElement).undelegate('.ember').removeClass('ember-application'); return this._super(); } }); })(); (function() { /** @module ember @submodule ember-views */ // Add a new named queue for rendering views that happens // after bindings have synced, and a queue for scheduling actions // that that should occur after view rendering. var queues = Ember.run.queues; queues.splice(Ember.$.inArray('actions', queues)+1, 0, 'render', 'afterRender'); })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set; // Original class declaration and documentation in runtime/lib/controllers/controller.js // NOTE: It may be possible with YUIDoc to combine docs in two locations /** Additional methods for the ControllerMixin @class ControllerMixin @namespace Ember */ Ember.ControllerMixin.reopen({ target: null, namespace: null, view: null, container: null }); })(); (function() { })(); (function() { var states = {}; /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, addObserver = Ember.addObserver, removeObserver = Ember.removeObserver; var meta = Ember.meta, guidFor = Ember.guidFor, fmt = Ember.String.fmt; var a_slice = [].slice; var a_forEach = Ember.EnumerableUtils.forEach; var a_addObject = Ember.EnumerableUtils.addObject; var childViewsProperty = Ember.computed(function() { var childViews = this._childViews; var ret = Ember.A(); a_forEach(childViews, function(view) { if (view.isVirtual) { ret.pushObjects(get(view, 'childViews')); } else { ret.push(view); } }); return ret; }); Ember.warn("The VIEW_PRESERVES_CONTEXT flag has been removed and the functionality can no longer be disabled.", Ember.ENV.VIEW_PRESERVES_CONTEXT !== false); /** Global hash of shared templates. This will automatically be populated by the build tools so that you can store your Handlebars templates in separate files that get loaded into JavaScript at buildtime. @property TEMPLATES @for Ember @type Hash */ Ember.TEMPLATES = {}; Ember.CoreView = Ember.Object.extend(Ember.Evented, { isView: true, states: states, init: function() { this._super(); // Register the view for event handling. This hash is used by // Ember.EventDispatcher to dispatch incoming events. if (!this.isVirtual) Ember.View.views[this.elementId] = this; this.addBeforeObserver('elementId', function() { throw new Error("Changing a view's elementId after creation is not allowed"); }); this.transitionTo('preRender'); }, /** If the view is currently inserted into the DOM of a parent view, this property will point to the parent of the view. @property parentView @type Ember.View @default null */ parentView: Ember.computed(function() { var parent = this._parentView; if (parent && parent.isVirtual) { return get(parent, 'parentView'); } else { return parent; } }).property('_parentView'), state: null, _parentView: null, // return the current view, not including virtual views concreteView: Ember.computed(function() { if (!this.isVirtual) { return this; } else { return get(this, 'parentView'); } }).property('parentView').volatile(), instrumentName: 'core_view', instrumentDetails: function(hash) { hash.object = this.toString(); }, /** @private Invoked by the view system when this view needs to produce an HTML representation. This method will create a new render buffer, if needed, then apply any default attributes, such as class names and visibility. Finally, the `render()` method is invoked, which is responsible for doing the bulk of the rendering. You should not need to override this method; instead, implement the `template` property, or if you need more control, override the `render` method. @method renderToBuffer @param {Ember.RenderBuffer} buffer the render buffer. If no buffer is passed, a default buffer, using the current view's `tagName`, will be used. */ renderToBuffer: function(parentBuffer, bufferOperation) { var name = 'render.' + this.instrumentName, details = {}; this.instrumentDetails(details); return Ember.instrument(name, details, function() { return this._renderToBuffer(parentBuffer, bufferOperation); }, this); }, _renderToBuffer: function(parentBuffer, bufferOperation) { Ember.run.sync(); // If this is the top-most view, start a new buffer. Otherwise, // create a new buffer relative to the original using the // provided buffer operation (for example, `insertAfter` will // insert a new buffer after the "parent buffer"). var tagName = this.tagName; if (tagName === null || tagName === undefined) { tagName = 'div'; } var buffer = this.buffer = parentBuffer && parentBuffer.begin(tagName) || Ember.RenderBuffer(tagName); this.transitionTo('inBuffer', false); this.beforeRender(buffer); this.render(buffer); this.afterRender(buffer); return buffer; }, /** @private Override the default event firing from `Ember.Evented` to also call methods with the given name. @method trigger @param name {String} */ trigger: function(name) { this._super.apply(this, arguments); var method = this[name]; if (method) { var args = [], i, l; for (i = 1, l = arguments.length; i < l; i++) { args.push(arguments[i]); } return method.apply(this, args); } }, has: function(name) { return Ember.typeOf(this[name]) === 'function' || this._super(name); }, willDestroy: function() { var parent = this._parentView; // destroy the element -- this will avoid each child view destroying // the element over and over again... if (!this.removedFromDOM) { this.destroyElement(); } // remove from parent if found. Don't call removeFromParent, // as removeFromParent will try to remove the element from // the DOM again. if (parent) { parent.removeChild(this); } this.transitionTo('destroyed'); // next remove view from global hash if (!this.isVirtual) delete Ember.View.views[this.elementId]; }, clearRenderedChildren: Ember.K, triggerRecursively: Ember.K, invokeRecursively: Ember.K, transitionTo: Ember.K, destroyElement: Ember.K }); /** `Ember.View` is the class in Ember responsible for encapsulating templates of HTML content, combining templates with data to render as sections of a page's DOM, and registering and responding to user-initiated events. ## HTML Tag The default HTML tag name used for a view's DOM representation is `div`. This can be customized by setting the `tagName` property. The following view class: ```javascript ParagraphView = Ember.View.extend({ tagName: 'em' }); ``` Would result in instances with the following HTML: ```html <em id="ember1" class="ember-view"></em> ``` ## HTML `class` Attribute The HTML `class` attribute of a view's tag can be set by providing a `classNames` property that is set to an array of strings: ```javascript MyView = Ember.View.extend({ classNames: ['my-class', 'my-other-class'] }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view my-class my-other-class"></div> ``` `class` attribute values can also be set by providing a `classNameBindings` property set to an array of properties names for the view. The return value of these properties will be added as part of the value for the view's `class` attribute. These properties can be computed properties: ```javascript MyView = Ember.View.extend({ classNameBindings: ['propertyA', 'propertyB'], propertyA: 'from-a', propertyB: function(){ if(someLogic){ return 'from-b'; } }.property() }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view from-a from-b"></div> ``` If the value of a class name binding returns a boolean the property name itself will be used as the class name if the property is true. The class name will not be added if the value is `false` or `undefined`. ```javascript MyView = Ember.View.extend({ classNameBindings: ['hovered'], hovered: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view hovered"></div> ``` When using boolean class name bindings you can supply a string value other than the property name for use as the `class` HTML attribute by appending the preferred value after a ":" character when defining the binding: ```javascript MyView = Ember.View.extend({ classNameBindings: ['awesome:so-very-cool'], awesome: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view so-very-cool"></div> ``` Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format: ```javascript MyView = Ember.View.extend({ classNameBindings: ['isUrgent'], isUrgent: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view is-urgent"></div> ``` Class name bindings can also refer to object values that are found by traversing a path relative to the view itself: ```javascript MyView = Ember.View.extend({ classNameBindings: ['messages.empty'] messages: Ember.Object.create({ empty: true }) }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view empty"></div> ``` If you want to add a class name for a property which evaluates to true and and a different class name if it evaluates to false, you can pass a binding like this: ```javascript // Applies 'enabled' class when isEnabled is true and 'disabled' when isEnabled is false Ember.View.create({ classNameBindings: ['isEnabled:enabled:disabled'] isEnabled: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view enabled"></div> ``` When isEnabled is `false`, the resulting HTML reprensentation looks like this: ```html <div id="ember1" class="ember-view disabled"></div> ``` This syntax offers the convenience to add a class if a property is `false`: ```javascript // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false Ember.View.create({ classNameBindings: ['isEnabled::disabled'] isEnabled: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view"></div> ``` When the `isEnabled` property on the view is set to `false`, it will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view disabled"></div> ``` Updates to the the value of a class name binding will result in automatic update of the HTML `class` attribute in the view's rendered HTML representation. If the value becomes `false` or `undefined` the class name will be removed. Both `classNames` and `classNameBindings` are concatenated properties. See `Ember.Object` documentation for more information about concatenated properties. ## HTML Attributes The HTML attribute section of a view's tag can be set by providing an `attributeBindings` property set to an array of property names on the view. The return value of these properties will be used as the value of the view's HTML associated attribute: ```javascript AnchorView = Ember.View.extend({ tagName: 'a', attributeBindings: ['href'], href: 'http://google.com' }); ``` Will result in view instances with an HTML representation of: ```html <a id="ember1" class="ember-view" href="http://google.com"></a> ``` If the return value of an `attributeBindings` monitored property is a boolean the property will follow HTML's pattern of repeating the attribute's name as its value: ```javascript MyTextInput = Ember.View.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: true }); ``` Will result in view instances with an HTML representation of: ```html <input id="ember1" class="ember-view" disabled="disabled" /> ``` `attributeBindings` can refer to computed properties: ```javascript MyTextInput = Ember.View.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: function(){ if (someLogic) { return true; } else { return false; } }.property() }); ``` Updates to the the property of an attribute binding will result in automatic update of the HTML attribute in the view's rendered HTML representation. `attributeBindings` is a concatenated property. See `Ember.Object` documentation for more information about concatenated properties. ## Templates The HTML contents of a view's rendered representation are determined by its template. Templates can be any function that accepts an optional context parameter and returns a string of HTML that will be inserted within the view's tag. Most typically in Ember this function will be a compiled `Ember.Handlebars` template. ```javascript AView = Ember.View.extend({ template: Ember.Handlebars.compile('I am the template') }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view">I am the template</div> ``` Within an Ember application is more common to define a Handlebars templates as part of a page: ```html <script type='text/x-handlebars' data-template-name='some-template'> Hello </script> ``` And associate it by name using a view's `templateName` property: ```javascript AView = Ember.View.extend({ templateName: 'some-template' }); ``` Using a value for `templateName` that does not have a Handlebars template with a matching `data-template-name` attribute will throw an error. Assigning a value to both `template` and `templateName` properties will throw an error. For views classes that may have a template later defined (e.g. as the block portion of a `{{view}}` Handlebars helper call in another template or in a subclass), you can provide a `defaultTemplate` property set to compiled template function. If a template is not later provided for the view instance the `defaultTemplate` value will be used: ```javascript AView = Ember.View.extend({ defaultTemplate: Ember.Handlebars.compile('I was the default'), template: null, templateName: null }); ``` Will result in instances with an HTML representation of: ```html <div id="ember1" class="ember-view">I was the default</div> ``` If a `template` or `templateName` is provided it will take precedence over `defaultTemplate`: ```javascript AView = Ember.View.extend({ defaultTemplate: Ember.Handlebars.compile('I was the default') }); aView = AView.create({ template: Ember.Handlebars.compile('I was the template, not default') }); ``` Will result in the following HTML representation when rendered: ```html <div id="ember1" class="ember-view">I was the template, not default</div> ``` ## View Context The default context of the compiled template is the view's controller: ```javascript AView = Ember.View.extend({ template: Ember.Handlebars.compile('Hello {{excitedGreeting}}') }); aController = Ember.Object.create({ firstName: 'Barry', excitedGreeting: function(){ return this.get("content.firstName") + "!!!" }.property() }); aView = AView.create({ controller: aController, }); ``` Will result in an HTML representation of: ```html <div id="ember1" class="ember-view">Hello Barry!!!</div> ``` A context can also be explicitly supplied through the view's `context` property. If the view has neither `context` nor `controller` properties, the `parentView`'s context will be used. ## Layouts Views can have a secondary template that wraps their main template. Like primary templates, layouts can be any function that accepts an optional context parameter and returns a string of HTML that will be inserted inside view's tag. Views whose HTML element is self closing (e.g. `<input />`) cannot have a layout and this property will be ignored. Most typically in Ember a layout will be a compiled `Ember.Handlebars` template. A view's layout can be set directly with the `layout` property or reference an existing Handlebars template by name with the `layoutName` property. A template used as a layout must contain a single use of the Handlebars `{{yield}}` helper. The HTML contents of a view's rendered `template` will be inserted at this location: ```javascript AViewWithLayout = Ember.View.extend({ layout: Ember.Handlebars.compile("<div class='my-decorative-class'>{{yield}}</div>") template: Ember.Handlebars.compile("I got wrapped"), }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view"> <div class="my-decorative-class"> I got wrapped </div> </div> ``` See `Handlebars.helpers.yield` for more information. ## Responding to Browser Events Views can respond to user-initiated events in one of three ways: method implementation, through an event manager, and through `{{action}}` helper use in their template or layout. ### Method Implementation Views can respond to user-initiated events by implementing a method that matches the event name. A `jQuery.Event` object will be passed as the argument to this method. ```javascript AView = Ember.View.extend({ click: function(event){ // will be called when when an instance's // rendered element is clicked } }); ``` ### Event Managers Views can define an object as their `eventManager` property. This object can then implement methods that match the desired event names. Matching events that occur on the view's rendered HTML or the rendered HTML of any of its DOM descendants will trigger this method. A `jQuery.Event` object will be passed as the first argument to the method and an `Ember.View` object as the second. The `Ember.View` will be the view whose rendered HTML was interacted with. This may be the view with the `eventManager` property or one of its descendent views. ```javascript AView = Ember.View.extend({ eventManager: Ember.Object.create({ doubleClick: function(event, view){ // will be called when when an instance's // rendered element or any rendering // of this views's descendent // elements is clicked } }) }); ``` An event defined for an event manager takes precedence over events of the same name handled through methods on the view. ```javascript AView = Ember.View.extend({ mouseEnter: function(event){ // will never trigger. }, eventManager: Ember.Object.create({ mouseEnter: function(event, view){ // takes presedence over AView#mouseEnter } }) }); ``` Similarly a view's event manager will take precedence for events of any views rendered as a descendent. A method name that matches an event name will not be called if the view instance was rendered inside the HTML representation of a view that has an `eventManager` property defined that handles events of the name. Events not handled by the event manager will still trigger method calls on the descendent. ```javascript OuterView = Ember.View.extend({ template: Ember.Handlebars.compile("outer {{#view InnerView}}inner{{/view}} outer"), eventManager: Ember.Object.create({ mouseEnter: function(event, view){ // view might be instance of either // OutsideView or InnerView depending on // where on the page the user interaction occured } }) }); InnerView = Ember.View.extend({ click: function(event){ // will be called if rendered inside // an OuterView because OuterView's // eventManager doesn't handle click events }, mouseEnter: function(event){ // will never be called if rendered inside // an OuterView. } }); ``` ### Handlebars `{{action}}` Helper See `Handlebars.helpers.action`. ### Event Names Possible events names for any of the responding approaches described above are: Touch events: * `touchStart` * `touchMove` * `touchEnd` * `touchCancel` Keyboard events * `keyDown` * `keyUp` * `keyPress` Mouse events * `mouseDown` * `mouseUp` * `contextMenu` * `click` * `doubleClick` * `mouseMove` * `focusIn` * `focusOut` * `mouseEnter` * `mouseLeave` Form events: * `submit` * `change` * `focusIn` * `focusOut` * `input` HTML5 drag and drop events: * `dragStart` * `drag` * `dragEnter` * `dragLeave` * `drop` * `dragEnd` ## Handlebars `{{view}}` Helper Other `Ember.View` instances can be included as part of a view's template by using the `{{view}}` Handlebars helper. See `Handlebars.helpers.view` for additional information. @class View @namespace Ember @extends Ember.Object @uses Ember.Evented */ Ember.View = Ember.CoreView.extend( /** @scope Ember.View.prototype */ { concatenatedProperties: ['classNames', 'classNameBindings', 'attributeBindings'], /** @property isView @type Boolean @default true @final */ isView: true, // .......................................................... // TEMPLATE SUPPORT // /** The name of the template to lookup if no template is provided. `Ember.View` will look for a template with this name in this view's `templates` object. By default, this will be a global object shared in `Ember.TEMPLATES`. @property templateName @type String @default null */ templateName: null, /** The name of the layout to lookup if no layout is provided. `Ember.View` will look for a template with this name in this view's `templates` object. By default, this will be a global object shared in `Ember.TEMPLATES`. @property layoutName @type String @default null */ layoutName: null, /** The hash in which to look for `templateName`. @property templates @type Ember.Object @default Ember.TEMPLATES */ templates: Ember.TEMPLATES, /** The template used to render the view. This should be a function that accepts an optional context parameter and returns a string of HTML that will be inserted into the DOM relative to its parent view. In general, you should set the `templateName` property instead of setting the template yourself. @property template @type Function */ template: Ember.computed(function(key, value) { if (value !== undefined) { return value; } var templateName = get(this, 'templateName'), template = this.templateForName(templateName, 'template'); return template || get(this, 'defaultTemplate'); }).property('templateName'), container: Ember.computed(function() { var parentView = get(this, '_parentView'); if (parentView) { return get(parentView, 'container'); } return Ember.Container && Ember.Container.defaultContainer; }), /** The controller managing this view. If this property is set, it will be made available for use by the template. @property controller @type Object */ controller: Ember.computed(function(key) { var parentView = get(this, '_parentView'); return parentView ? get(parentView, 'controller') : null; }).property('_parentView'), /** A view may contain a layout. A layout is a regular template but supersedes the `template` property during rendering. It is the responsibility of the layout template to retrieve the `template` property from the view (or alternatively, call `Handlebars.helpers.yield`, `{{yield}}`) to render it in the correct location. This is useful for a view that has a shared wrapper, but which delegates the rendering of the contents of the wrapper to the `template` property on a subclass. @property layout @type Function */ layout: Ember.computed(function(key) { var layoutName = get(this, 'layoutName'), layout = this.templateForName(layoutName, 'layout'); return layout || get(this, 'defaultLayout'); }).property('layoutName'), templateForName: function(name, type) { if (!name) { return; } Ember.assert("templateNames are not allowed to contain periods: "+name, name.indexOf('.') === -1); var container = get(this, 'container'); if (container) { return container.lookup('template:' + name); } }, /** The object from which templates should access properties. This object will be passed to the template function each time the render method is called, but it is up to the individual function to decide what to do with it. By default, this will be the view's controller. @property context @type Object */ context: Ember.computed(function(key, value) { if (arguments.length === 2) { set(this, '_context', value); return value; } else { return get(this, '_context'); } }).volatile(), /** @private Private copy of the view's template context. This can be set directly by Handlebars without triggering the observer that causes the view to be re-rendered. The context of a view is looked up as follows: 1. Supplied context (usually by Handlebars) 2. Specified controller 3. `parentView`'s context (for a child of a ContainerView) The code in Handlebars that overrides the `_context` property first checks to see whether the view has a specified controller. This is something of a hack and should be revisited. @property _context */ _context: Ember.computed(function(key) { var parentView, controller; if (controller = get(this, 'controller')) { return controller; } parentView = this._parentView; if (parentView) { return get(parentView, '_context'); } return null; }), /** @private If a value that affects template rendering changes, the view should be re-rendered to reflect the new value. @method _displayPropertyDidChange */ _contextDidChange: Ember.observer(function() { this.rerender(); }, 'context'), /** If `false`, the view will appear hidden in DOM. @property isVisible @type Boolean @default null */ isVisible: true, /** @private Array of child views. You should never edit this array directly. Instead, use `appendChild` and `removeFromParent`. @property childViews @type Array @default [] */ childViews: childViewsProperty, _childViews: [], // When it's a virtual view, we need to notify the parent that their // childViews will change. _childViewsWillChange: Ember.beforeObserver(function() { if (this.isVirtual) { var parentView = get(this, 'parentView'); if (parentView) { Ember.propertyWillChange(parentView, 'childViews'); } } }, 'childViews'), // When it's a virtual view, we need to notify the parent that their // childViews did change. _childViewsDidChange: Ember.observer(function() { if (this.isVirtual) { var parentView = get(this, 'parentView'); if (parentView) { Ember.propertyDidChange(parentView, 'childViews'); } } }, 'childViews'), /** Return the nearest ancestor that is an instance of the provided class. @property nearestInstanceOf @param {Class} klass Subclass of Ember.View (or Ember.View itself) @return Ember.View @deprecated */ nearestInstanceOf: function(klass) { Ember.deprecate("nearestInstanceOf is deprecated and will be removed from future releases. Use nearestOfType."); var view = get(this, 'parentView'); while (view) { if(view instanceof klass) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor that is an instance of the provided class or mixin. @property nearestOfType @param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself), or an instance of Ember.Mixin. @return Ember.View */ nearestOfType: function(klass) { var view = get(this, 'parentView'), isOfType = klass instanceof Ember.Mixin ? function(view) { return klass.detect(view); } : function(view) { return klass.detect(view.constructor); }; while (view) { if( isOfType(view) ) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor that has a given property. @property nearestWithProperty @param {String} property A property name @return Ember.View */ nearestWithProperty: function(property) { var view = get(this, 'parentView'); while (view) { if (property in view) { return view; } view = get(view, 'parentView'); } }, /** Return the nearest ancestor whose parent is an instance of `klass`. @property nearestChildOf @param {Class} klass Subclass of Ember.View (or Ember.View itself) @return Ember.View */ nearestChildOf: function(klass) { var view = get(this, 'parentView'); while (view) { if(get(view, 'parentView') instanceof klass) { return view; } view = get(view, 'parentView'); } }, /** @private When the parent view changes, recursively invalidate `controller` @method _parentViewDidChange */ _parentViewDidChange: Ember.observer(function() { if (this.isDestroying) { return; } if (get(this, 'parentView.controller') && !get(this, 'controller')) { this.notifyPropertyChange('controller'); } }, '_parentView'), _controllerDidChange: Ember.observer(function() { if (this.isDestroying) { return; } this.rerender(); this.forEachChildView(function(view) { view.propertyDidChange('controller'); }); }, 'controller'), cloneKeywords: function() { var templateData = get(this, 'templateData'); var keywords = templateData ? Ember.copy(templateData.keywords) : {}; set(keywords, 'view', get(this, 'concreteView')); set(keywords, '_view', this); set(keywords, 'controller', get(this, 'controller')); return keywords; }, /** Called on your view when it should push strings of HTML into a `Ember.RenderBuffer`. Most users will want to override the `template` or `templateName` properties instead of this method. By default, `Ember.View` will look for a function in the `template` property and invoke it with the value of `context`. The value of `context` will be the view's controller unless you override it. @method render @param {Ember.RenderBuffer} buffer The render buffer */ render: function(buffer) { // If this view has a layout, it is the responsibility of the // the layout to render the view's template. Otherwise, render the template // directly. var template = get(this, 'layout') || get(this, 'template'); if (template) { var context = get(this, 'context'); var keywords = this.cloneKeywords(); var output; var data = { view: this, buffer: buffer, isRenderData: true, keywords: keywords, insideGroup: get(this, 'templateData.insideGroup') }; // Invoke the template with the provided template context, which // is the view's controller by default. A hash of data is also passed that provides // the template with access to the view and render buffer. Ember.assert('template must be a function. Did you mean to call Ember.Handlebars.compile("...") or specify templateName instead?', typeof template === 'function'); // The template should write directly to the render buffer instead // of returning a string. output = template(context, { data: data }); // If the template returned a string instead of writing to the buffer, // push the string onto the buffer. if (output !== undefined) { buffer.push(output); } } }, /** Renders the view again. This will work regardless of whether the view is already in the DOM or not. If the view is in the DOM, the rendering process will be deferred to give bindings a chance to synchronize. If children were added during the rendering process using `appendChild`, `rerender` will remove them, because they will be added again if needed by the next `render`. In general, if the display of your view changes, you should modify the DOM element directly instead of manually calling `rerender`, which can be slow. @method rerender */ rerender: function() { return this.currentState.rerender(this); }, clearRenderedChildren: function() { var lengthBefore = this.lengthBeforeRender, lengthAfter = this.lengthAfterRender; // If there were child views created during the last call to render(), // remove them under the assumption that they will be re-created when // we re-render. // VIEW-TODO: Unit test this path. var childViews = this._childViews; for (var i=lengthAfter-1; i>=lengthBefore; i--) { if (childViews[i]) { childViews[i].destroy(); } } }, /** @private Iterates over the view's `classNameBindings` array, inserts the value of the specified property into the `classNames` array, then creates an observer to update the view's element if the bound property ever changes in the future. @method _applyClassNameBindings */ _applyClassNameBindings: function(classBindings) { var classNames = this.classNames, elem, newClass, dasherizedClass; // Loop through all of the configured bindings. These will be either // property names ('isUrgent') or property paths relative to the view // ('content.isUrgent') a_forEach(classBindings, function(binding) { // Variable in which the old class value is saved. The observer function // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; // Extract just the property name from bindings like 'foo:bar' var parsedPath = Ember.View._parsePropertyPath(binding); // Set up an observer on the context. If the property changes, toggle the // class name. var observer = function() { // Get the current value of the property newClass = this._classStringForProperty(binding); elem = this.$(); // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); // Also remove from classNames so that if the view gets rerendered, // the class doesn't get added back to the DOM. classNames.removeObject(oldClass); } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if (newClass) { elem.addClass(newClass); oldClass = newClass; } else { oldClass = null; } }; // Get the class name for the property at its current value dasherizedClass = this._classStringForProperty(binding); if (dasherizedClass) { // Ensure that it gets into the classNames array // so it is displayed when we render. a_addObject(classNames, dasherizedClass); // Save a reference to the class name so we can remove it // if the observer fires. Remember that this variable has // been closed over by the observer. oldClass = dasherizedClass; } addObserver(this, parsedPath.path, observer); this.one('willClearRender', function() { removeObserver(this, parsedPath.path, observer); }); }, this); }, /** @private Iterates through the view's attribute bindings, sets up observers for each, then applies the current value of the attributes to the passed render buffer. @method _applyAttributeBindings @param {Ember.RenderBuffer} buffer */ _applyAttributeBindings: function(buffer, attributeBindings) { var attributeValue, elem, type; a_forEach(attributeBindings, function(binding) { var split = binding.split(':'), property = split[0], attributeName = split[1] || property; // Create an observer to add/remove/change the attribute if the // JavaScript property changes. var observer = function() { elem = this.$(); if (!elem) { return; } attributeValue = get(this, property); Ember.View.applyAttributeBindings(elem, attributeName, attributeValue); }; addObserver(this, property, observer); this.one('willClearRender', function() { removeObserver(this, property, observer); }); // Determine the current value and add it to the render buffer // if necessary. attributeValue = get(this, property); Ember.View.applyAttributeBindings(buffer, attributeName, attributeValue); }, this); }, /** @private Given a property name, returns a dasherized version of that property name if the property evaluates to a non-falsy value. For example, if the view has property `isUrgent` that evaluates to true, passing `isUrgent` to this method will return `"is-urgent"`. @method _classStringForProperty @param property */ _classStringForProperty: function(property) { var parsedPath = Ember.View._parsePropertyPath(property); var path = parsedPath.path; var val = get(this, path); if (val === undefined && Ember.isGlobalPath(path)) { val = get(Ember.lookup, path); } return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); }, // .......................................................... // ELEMENT SUPPORT // /** Returns the current DOM element for the view. @property element @type DOMElement */ element: Ember.computed(function(key, value) { if (value !== undefined) { return this.currentState.setElement(this, value); } else { return this.currentState.getElement(this); } }).property('_parentView'), /** Returns a jQuery object for this view's element. If you pass in a selector string, this method will return a jQuery object, using the current element as its buffer. For example, calling `view.$('li')` will return a jQuery object containing all of the `li` elements inside the DOM element of this view. @property $ @param {String} [selector] a jQuery-compatible selector string @return {jQuery} the CoreQuery object for the DOM node */ $: function(sel) { return this.currentState.$(this, sel); }, mutateChildViews: function(callback) { var childViews = this._childViews, idx = childViews.length, view; while(--idx >= 0) { view = childViews[idx]; callback.call(this, view, idx); } return this; }, forEachChildView: function(callback) { var childViews = this._childViews; if (!childViews) { return this; } var len = childViews.length, view, idx; for(idx = 0; idx < len; idx++) { view = childViews[idx]; callback.call(this, view); } return this; }, /** Appends the view's element to the specified parent element. If the view does not have an HTML representation yet, `createElement()` will be called automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the given element until all bindings have finished synchronizing. This is not typically a function that you will need to call directly when building your application. You might consider using `Ember.ContainerView` instead. If you do need to use `appendTo`, be sure that the target element you are providing is associated with an `Ember.Application` and does not have an ancestor element that is associated with an Ember view. @method appendTo @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object @return {Ember.View} receiver */ appendTo: function(target) { // Schedule the DOM element to be created and appended to the given // element after bindings have synchronized. this._insertElementLater(function() { Ember.assert("You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.", !Ember.$(target).is('.ember-view') && !Ember.$(target).parents().is('.ember-view')); this.$().appendTo(target); }); return this; }, /** Replaces the content of the specified parent element with this view's element. If the view does not have an HTML representation yet, `createElement()` will be called automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the given element until all bindings have finished synchronizing @method replaceIn @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object @return {Ember.View} received */ replaceIn: function(target) { Ember.assert("You cannot replace an existing Ember.View. Consider using Ember.ContainerView instead.", !Ember.$(target).is('.ember-view') && !Ember.$(target).parents().is('.ember-view')); this._insertElementLater(function() { Ember.$(target).empty(); this.$().appendTo(target); }); return this; }, /** @private Schedules a DOM operation to occur during the next render phase. This ensures that all bindings have finished synchronizing before the view is rendered. To use, pass a function that performs a DOM operation. Before your function is called, this view and all child views will receive the `willInsertElement` event. After your function is invoked, this view and all of its child views will receive the `didInsertElement` event. ```javascript view._insertElementLater(function() { this.createElement(); this.$().appendTo('body'); }); ``` @method _insertElementLater @param {Function} fn the function that inserts the element into the DOM */ _insertElementLater: function(fn) { this._scheduledInsert = Ember.run.scheduleOnce('render', this, '_insertElement', fn); }, _insertElement: function (fn) { this._scheduledInsert = null; this.currentState.insertElement(this, fn); }, /** Appends the view's element to the document body. If the view does not have an HTML representation yet, `createElement()` will be called automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the document body until all bindings have finished synchronizing. @method append @return {Ember.View} receiver */ append: function() { return this.appendTo(document.body); }, /** Removes the view's element from the element to which it is attached. @method remove @return {Ember.View} receiver */ remove: function() { // What we should really do here is wait until the end of the run loop // to determine if the element has been re-appended to a different // element. // In the interim, we will just re-render if that happens. It is more // important than elements get garbage collected. this.destroyElement(); this.invokeRecursively(function(view) { if (view.clearRenderedChildren) { view.clearRenderedChildren(); } }); }, elementId: null, /** Attempts to discover the element in the parent element. The default implementation looks for an element with an ID of `elementId` (or the view's guid if `elementId` is null). You can override this method to provide your own form of lookup. For example, if you want to discover your element using a CSS class name instead of an ID. @method findElementInParentElement @param {DOMElement} parentElement The parent's DOM element @return {DOMElement} The discovered element */ findElementInParentElement: function(parentElem) { var id = "#" + this.elementId; return Ember.$(id)[0] || Ember.$(id, parentElem)[0]; }, /** Creates a DOM representation of the view and all of its child views by recursively calling the `render()` method. After the element has been created, `didInsertElement` will be called on this view and all of its child views. @method createElement @return {Ember.View} receiver */ createElement: function() { if (get(this, 'element')) { return this; } var buffer = this.renderToBuffer(); set(this, 'element', buffer.element()); return this; }, /** Called when a view is going to insert an element into the DOM. @event willInsertElement */ willInsertElement: Ember.K, /** Called when the element of the view has been inserted into the DOM. Override this function to do any set up that requires an element in the document body. @event didInsertElement */ didInsertElement: Ember.K, /** Called when the view is about to rerender, but before anything has been torn down. This is a good opportunity to tear down any manual observers you have installed based on the DOM state @event willClearRender */ willClearRender: Ember.K, /** @private Run this callback on the current view and recursively on child views. @method invokeRecursively @param fn {Function} */ invokeRecursively: function(fn) { var childViews = [this], currentViews, view; while (childViews.length) { currentViews = childViews.slice(); childViews = []; for (var i=0, l=currentViews.length; i<l; i++) { view = currentViews[i]; fn.call(view, view); if (view._childViews) { childViews.push.apply(childViews, view._childViews); } } } }, triggerRecursively: function(eventName) { var childViews = [this], currentViews, view; while (childViews.length) { currentViews = childViews.slice(); childViews = []; for (var i=0, l=currentViews.length; i<l; i++) { view = currentViews[i]; if (view.trigger) { view.trigger(eventName); } if (view._childViews) { childViews.push.apply(childViews, view._childViews); } } } }, /** Destroys any existing element along with the element for any child views as well. If the view does not currently have a element, then this method will do nothing. If you implement `willDestroyElement()` on your view, then this method will be invoked on your view before your element is destroyed to give you a chance to clean up any event handlers, etc. If you write a `willDestroyElement()` handler, you can assume that your `didInsertElement()` handler was called earlier for the same element. Normally you will not call or override this method yourself, but you may want to implement the above callbacks when it is run. @method destroyElement @return {Ember.View} receiver */ destroyElement: function() { return this.currentState.destroyElement(this); }, /** Called when the element of the view is going to be destroyed. Override this function to do any teardown that requires an element, like removing event listeners. @event willDestroyElement */ willDestroyElement: function() {}, /** @private Triggers the `willDestroyElement` event (which invokes the `willDestroyElement()` method if it exists) on this view and all child views. Before triggering `willDestroyElement`, it first triggers the `willClearRender` event recursively. @method _notifyWillDestroyElement */ _notifyWillDestroyElement: function() { this.triggerRecursively('willClearRender'); this.triggerRecursively('willDestroyElement'); }, _elementWillChange: Ember.beforeObserver(function() { this.forEachChildView(function(view) { Ember.propertyWillChange(view, 'element'); }); }, 'element'), /** @private If this view's element changes, we need to invalidate the caches of our child views so that we do not retain references to DOM elements that are no longer needed. @method _elementDidChange */ _elementDidChange: Ember.observer(function() { this.forEachChildView(function(view) { Ember.propertyDidChange(view, 'element'); }); }, 'element'), /** Called when the parentView property has changed. @event parentViewDidChange */ parentViewDidChange: Ember.K, instrumentName: 'view', instrumentDetails: function(hash) { hash.template = get(this, 'templateName'); this._super(hash); }, _renderToBuffer: function(parentBuffer, bufferOperation) { this.lengthBeforeRender = this._childViews.length; var buffer = this._super(parentBuffer, bufferOperation); this.lengthAfterRender = this._childViews.length; return buffer; }, renderToBufferIfNeeded: function () { return this.currentState.renderToBufferIfNeeded(this, this); }, beforeRender: function(buffer) { this.applyAttributesToBuffer(buffer); buffer.pushOpeningTag(); }, afterRender: function(buffer) { buffer.pushClosingTag(); }, applyAttributesToBuffer: function(buffer) { // Creates observers for all registered class name and attribute bindings, // then adds them to the element. var classNameBindings = get(this, 'classNameBindings'); if (classNameBindings.length) { this._applyClassNameBindings(classNameBindings); } // Pass the render buffer so the method can apply attributes directly. // This isn't needed for class name bindings because they use the // existing classNames infrastructure. var attributeBindings = get(this, 'attributeBindings'); if (attributeBindings.length) { this._applyAttributeBindings(buffer, attributeBindings); } buffer.setClasses(this.classNames); buffer.id(this.elementId); var role = get(this, 'ariaRole'); if (role) { buffer.attr('role', role); } if (get(this, 'isVisible') === false) { buffer.style('display', 'none'); } }, // .......................................................... // STANDARD RENDER PROPERTIES // /** Tag name for the view's outer element. The tag name is only used when an element is first created. If you change the `tagName` for an element, you must destroy and recreate the view element. By default, the render buffer will use a `<div>` tag for views. @property tagName @type String @default null */ // We leave this null by default so we can tell the difference between // the default case and a user-specified tag. tagName: null, /** The WAI-ARIA role of the control represented by this view. For example, a button may have a role of type 'button', or a pane may have a role of type 'alertdialog'. This property is used by assistive software to help visually challenged users navigate rich web applications. The full list of valid WAI-ARIA roles is available at: http://www.w3.org/TR/wai-aria/roles#roles_categorization @property ariaRole @type String @default null */ ariaRole: null, /** Standard CSS class names to apply to the view's outer element. This property automatically inherits any class names defined by the view's superclasses as well. @property classNames @type Array @default ['ember-view'] */ classNames: ['ember-view'], /** A list of properties of the view to apply as class names. If the property is a string value, the value of that string will be applied as a class name. ```javascript // Applies the 'high' class to the view element Ember.View.create({ classNameBindings: ['priority'] priority: 'high' }); ``` If the value of the property is a Boolean, the name of that property is added as a dasherized class name. ```javascript // Applies the 'is-urgent' class to the view element Ember.View.create({ classNameBindings: ['isUrgent'] isUrgent: true }); ``` If you would prefer to use a custom value instead of the dasherized property name, you can pass a binding like this: ```javascript // Applies the 'urgent' class to the view element Ember.View.create({ classNameBindings: ['isUrgent:urgent'] isUrgent: true }); ``` This list of properties is inherited from the view's superclasses as well. @property classNameBindings @type Array @default [] */ classNameBindings: [], /** A list of properties of the view to apply as attributes. If the property is a string value, the value of that string will be applied as the attribute. ```javascript // Applies the type attribute to the element // with the value "button", like <div type="button"> Ember.View.create({ attributeBindings: ['type'], type: 'button' }); ``` If the value of the property is a Boolean, the name of that property is added as an attribute. ```javascript // Renders something like <div enabled="enabled"> Ember.View.create({ attributeBindings: ['enabled'], enabled: true }); ``` @property attributeBindings */ attributeBindings: [], // ....................................................... // CORE DISPLAY METHODS // /** @private Setup a view, but do not finish waking it up. - configure `childViews` - register the view with the global views hash, which is used for event dispatch @method init */ init: function() { this.elementId = this.elementId || guidFor(this); this._super(); // setup child views. be sure to clone the child views array first this._childViews = this._childViews.slice(); Ember.assert("Only arrays are allowed for 'classNameBindings'", Ember.typeOf(this.classNameBindings) === 'array'); this.classNameBindings = Ember.A(this.classNameBindings.slice()); Ember.assert("Only arrays are allowed for 'classNames'", Ember.typeOf(this.classNames) === 'array'); this.classNames = Ember.A(this.classNames.slice()); var viewController = get(this, 'viewController'); if (viewController) { viewController = get(viewController); if (viewController) { set(viewController, 'view', this); } } }, appendChild: function(view, options) { return this.currentState.appendChild(this, view, options); }, /** Removes the child view from the parent view. @method removeChild @param {Ember.View} view @return {Ember.View} receiver */ removeChild: function(view) { // If we're destroying, the entire subtree will be // freed, and the DOM will be handled separately, // so no need to mess with childViews. if (this.isDestroying) { return; } // update parent node set(view, '_parentView', null); // remove view from childViews array. var childViews = this._childViews; Ember.EnumerableUtils.removeObject(childViews, view); this.propertyDidChange('childViews'); // HUH?! what happened to will change? return this; }, /** Removes all children from the `parentView`. @method removeAllChildren @return {Ember.View} receiver */ removeAllChildren: function() { return this.mutateChildViews(function(view) { this.removeChild(view); }); }, destroyAllChildren: function() { return this.mutateChildViews(function(view) { view.destroy(); }); }, /** Removes the view from its `parentView`, if one is found. Otherwise does nothing. @method removeFromParent @return {Ember.View} receiver */ removeFromParent: function() { var parent = this._parentView; // Remove DOM element from parent this.remove(); if (parent) { parent.removeChild(this); } return this; }, /** You must call `destroy` on a view to destroy the view (and all of its child views). This will remove the view from any parent node, then make sure that the DOM element managed by the view can be released by the memory manager. @method willDestroy */ willDestroy: function() { // calling this._super() will nuke computed properties and observers, // so collect any information we need before calling super. var childViews = this._childViews, parent = this._parentView, childLen; // destroy the element -- this will avoid each child view destroying // the element over and over again... if (!this.removedFromDOM) { this.destroyElement(); } // remove from non-virtual parent view if viewName was specified if (this.viewName) { var nonVirtualParentView = get(this, 'parentView'); if (nonVirtualParentView) { set(nonVirtualParentView, this.viewName, null); } } // remove from parent if found. Don't call removeFromParent, // as removeFromParent will try to remove the element from // the DOM again. if (parent) { parent.removeChild(this); } this.transitionTo('destroyed'); childLen = childViews.length; for (var i=childLen-1; i>=0; i--) { childViews[i].removedFromDOM = true; childViews[i].destroy(); } // next remove view from global hash if (!this.isVirtual) delete Ember.View.views[get(this, 'elementId')]; }, /** Instantiates a view to be added to the childViews array during view initialization. You generally will not call this method directly unless you are overriding `createChildViews()`. Note that this method will automatically configure the correct settings on the new view instance to act as a child of the parent. @method createChildView @param {Class} viewClass @param {Hash} [attrs] Attributes to add @return {Ember.View} new instance */ createChildView: function(view, attrs) { if (view.isView && view._parentView === this) { return view; } if (Ember.CoreView.detect(view)) { attrs = attrs || {}; attrs._parentView = this; attrs.templateData = attrs.templateData || get(this, 'templateData'); view = view.create(attrs); // don't set the property on a virtual view, as they are invisible to // consumers of the view API if (view.viewName) { set(get(this, 'concreteView'), view.viewName, view); } } else { Ember.assert('You must pass instance or subclass of View', view.isView); if (attrs) { view.setProperties(attrs); } if (!get(view, 'templateData')) { set(view, 'templateData', get(this, 'templateData')); } set(view, '_parentView', this); } return view; }, becameVisible: Ember.K, becameHidden: Ember.K, /** @private When the view's `isVisible` property changes, toggle the visibility element of the actual DOM element. @method _isVisibleDidChange */ _isVisibleDidChange: Ember.observer(function() { var $el = this.$(); if (!$el) { return; } var isVisible = get(this, 'isVisible'); $el.toggle(isVisible); if (this._isAncestorHidden()) { return; } if (isVisible) { this._notifyBecameVisible(); } else { this._notifyBecameHidden(); } }, 'isVisible'), _notifyBecameVisible: function() { this.trigger('becameVisible'); this.forEachChildView(function(view) { var isVisible = get(view, 'isVisible'); if (isVisible || isVisible === null) { view._notifyBecameVisible(); } }); }, _notifyBecameHidden: function() { this.trigger('becameHidden'); this.forEachChildView(function(view) { var isVisible = get(view, 'isVisible'); if (isVisible || isVisible === null) { view._notifyBecameHidden(); } }); }, _isAncestorHidden: function() { var parent = get(this, 'parentView'); while (parent) { if (get(parent, 'isVisible') === false) { return true; } parent = get(parent, 'parentView'); } return false; }, clearBuffer: function() { this.invokeRecursively(function(view) { view.buffer = null; }); }, transitionTo: function(state, children) { this.currentState = this.states[state]; this.state = state; if (children !== false) { this.forEachChildView(function(view) { view.transitionTo(state); }); } }, // ....................................................... // EVENT HANDLING // /** @private Handle events from `Ember.EventDispatcher` @method handleEvent @param eventName {String} @param evt {Event} */ handleEvent: function(eventName, evt) { return this.currentState.handleEvent(this, eventName, evt); } }); /* Describe how the specified actions should behave in the various states that a view can exist in. Possible states: * preRender: when a view is first instantiated, and after its element was destroyed, it is in the preRender state * inBuffer: once a view has been rendered, but before it has been inserted into the DOM, it is in the inBuffer state * inDOM: once a view has been inserted into the DOM it is in the inDOM state. A view spends the vast majority of its existence in this state. * destroyed: once a view has been destroyed (using the destroy method), it is in this state. No further actions can be invoked on a destroyed view. */ // in the destroyed state, everything is illegal // before rendering has begun, all legal manipulations are noops. // inside the buffer, legal manipulations are done on the buffer // once the view has been inserted into the DOM, legal manipulations // are done on the DOM element. var DOMManager = { prepend: function(view, html) { view.$().prepend(html); }, after: function(view, html) { view.$().after(html); }, html: function(view, html) { view.$().html(html); }, replace: function(view) { var element = get(view, 'element'); set(view, 'element', null); view._insertElementLater(function() { Ember.$(element).replaceWith(get(view, 'element')); }); }, remove: function(view) { view.$().remove(); }, empty: function(view) { view.$().empty(); } }; Ember.View.reopen({ domManager: DOMManager }); Ember.View.reopenClass({ /** @private Parse a path and return an object which holds the parsed properties. For example a path like "content.isEnabled:enabled:disabled" wil return the following object: ```javascript { path: "content.isEnabled", className: "enabled", falsyClassName: "disabled", classNames: ":enabled:disabled" } ``` @method _parsePropertyPath @static */ _parsePropertyPath: function(path) { var split = path.split(':'), propertyPath = split[0], classNames = "", className, falsyClassName; // check if the property is defined as prop:class or prop:trueClass:falseClass if (split.length > 1) { className = split[1]; if (split.length === 3) { falsyClassName = split[2]; } classNames = ':' + className; if (falsyClassName) { classNames += ":" + falsyClassName; } } return { path: propertyPath, classNames: classNames, className: (className === '') ? undefined : className, falsyClassName: falsyClassName }; }, /** @private Get the class name for a given value, based on the path, optional `className` and optional `falsyClassName`. - if a `className` or `falsyClassName` has been specified: - if the value is truthy and `className` has been specified, `className` is returned - if the value is falsy and `falsyClassName` has been specified, `falsyClassName` is returned - otherwise `null` is returned - if the value is `true`, the dasherized last part of the supplied path is returned - if the value is not `false`, `undefined` or `null`, the `value` is returned - if none of the above rules apply, `null` is returned @method _classStringForValue @param path @param val @param className @param falsyClassName @static */ _classStringForValue: function(path, val, className, falsyClassName) { // When using the colon syntax, evaluate the truthiness or falsiness // of the value to determine which className to return if (className || falsyClassName) { if (className && !!val) { return className; } else if (falsyClassName && !val) { return falsyClassName; } else { return null; } // If value is a Boolean and true, return the dasherized property // name. } else if (val === true) { // Normalize property path to be suitable for use // as a class name. For exaple, content.foo.barBaz // becomes bar-baz. var parts = path.split('.'); return Ember.String.dasherize(parts[parts.length-1]); // If the value is not false, undefined, or null, return the current // value of the property. } else if (val !== false && val !== undefined && val !== null) { return val; // Nothing to display. Return null so that the old class is removed // but no new class is added. } else { return null; } } }); /** Global views hash @property views @static @type Hash */ Ember.View.views = {}; // If someone overrides the child views computed property when // defining their class, we want to be able to process the user's // supplied childViews and then restore the original computed property // at view initialization time. This happens in Ember.ContainerView's init // method. Ember.View.childViewsProperty = childViewsProperty; Ember.View.applyAttributeBindings = function(elem, name, value) { var type = Ember.typeOf(value); var currentValue = elem.attr(name); // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js if ((type === 'string' || (type === 'number' && !isNaN(value))) && value !== currentValue) { elem.attr(name, value); } else if (value && type === 'boolean') { elem.attr(name, name); } else if (!value) { elem.removeAttr(name); } }; Ember.View.states = states; })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set; Ember.View.states._default = { // appendChild is only legal while rendering the buffer. appendChild: function() { throw "You can't use appendChild outside of the rendering process"; }, $: function() { return undefined; }, getElement: function() { return null; }, // Handle events from `Ember.EventDispatcher` handleEvent: function() { return true; // continue event propagation }, destroyElement: function(view) { set(view, 'element', null); if (view._scheduledInsert) { Ember.run.cancel(view._scheduledInsert); view._scheduledInsert = null; } return view; }, renderToBufferIfNeeded: function () { return false; }, rerender: Ember.K }; })(); (function() { /** @module ember @submodule ember-views */ var preRender = Ember.View.states.preRender = Ember.create(Ember.View.states._default); Ember.merge(preRender, { // a view leaves the preRender state once its element has been // created (createElement). insertElement: function(view, fn) { view.createElement(); view.triggerRecursively('willInsertElement'); // after createElement, the view will be in the hasElement state. fn.call(view); view.transitionTo('inDOM'); view.triggerRecursively('didInsertElement'); }, renderToBufferIfNeeded: function(view) { return view.renderToBuffer(); }, empty: Ember.K, setElement: function(view, value) { if (value !== null) { view.transitionTo('hasElement'); } return value; } }); })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, meta = Ember.meta; var inBuffer = Ember.View.states.inBuffer = Ember.create(Ember.View.states._default); Ember.merge(inBuffer, { $: function(view, sel) { // if we don't have an element yet, someone calling this.$() is // trying to update an element that isn't in the DOM. Instead, // rerender the view to allow the render method to reflect the // changes. view.rerender(); return Ember.$(); }, // when a view is rendered in a buffer, rerendering it simply // replaces the existing buffer with a new one rerender: function(view) { throw new Ember.Error("Something you did caused a view to re-render after it rendered but before it was inserted into the DOM."); }, // when a view is rendered in a buffer, appending a child // view will render that view and append the resulting // buffer into its buffer. appendChild: function(view, childView, options) { var buffer = view.buffer; childView = view.createChildView(childView, options); view._childViews.push(childView); childView.renderToBuffer(buffer); view.propertyDidChange('childViews'); return childView; }, // when a view is rendered in a buffer, destroying the // element will simply destroy the buffer and put the // state back into the preRender state. destroyElement: function(view) { view.clearBuffer(); view._notifyWillDestroyElement(); view.transitionTo('preRender'); return view; }, empty: function() { Ember.assert("Emptying a view in the inBuffer state is not allowed and should not happen under normal circumstances. Most likely there is a bug in your application. This may be due to excessive property change notifications."); }, renderToBufferIfNeeded: function (view) { return view.buffer; }, // It should be impossible for a rendered view to be scheduled for // insertion. insertElement: function() { throw "You can't insert an element that has already been rendered"; }, setElement: function(view, value) { if (value === null) { view.transitionTo('preRender'); } else { view.clearBuffer(); view.transitionTo('hasElement'); } return value; } }); })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, meta = Ember.meta; var hasElement = Ember.View.states.hasElement = Ember.create(Ember.View.states._default); Ember.merge(hasElement, { $: function(view, sel) { var elem = get(view, 'element'); return sel ? Ember.$(sel, elem) : Ember.$(elem); }, getElement: function(view) { var parent = get(view, 'parentView'); if (parent) { parent = get(parent, 'element'); } if (parent) { return view.findElementInParentElement(parent); } return Ember.$("#" + get(view, 'elementId'))[0]; }, setElement: function(view, value) { if (value === null) { view.transitionTo('preRender'); } else { throw "You cannot set an element to a non-null value when the element is already in the DOM."; } return value; }, // once the view has been inserted into the DOM, rerendering is // deferred to allow bindings to synchronize. rerender: function(view) { view.triggerRecursively('willClearRender'); view.clearRenderedChildren(); view.domManager.replace(view); return view; }, // once the view is already in the DOM, destroying it removes it // from the DOM, nukes its element, and puts it back into the // preRender state if inDOM. destroyElement: function(view) { view._notifyWillDestroyElement(); view.domManager.remove(view); set(view, 'element', null); if (view._scheduledInsert) { Ember.run.cancel(view._scheduledInsert); view._scheduledInsert = null; } return view; }, empty: function(view) { var _childViews = view._childViews, len, idx; if (_childViews) { len = _childViews.length; for (idx = 0; idx < len; idx++) { _childViews[idx]._notifyWillDestroyElement(); } } view.domManager.empty(view); }, // Handle events from `Ember.EventDispatcher` handleEvent: function(view, eventName, evt) { if (view.has(eventName)) { // Handler should be able to re-dispatch events, so we don't // preventDefault or stopPropagation. return view.trigger(eventName, evt); } else { return true; // continue event propagation } } }); var inDOM = Ember.View.states.inDOM = Ember.create(hasElement); Ember.merge(inDOM, { insertElement: function(view, fn) { throw "You can't insert an element into the DOM that has already been inserted"; } }); })(); (function() { /** @module ember @submodule ember-views */ var destroyedError = "You can't call %@ on a destroyed view", fmt = Ember.String.fmt; var destroyed = Ember.View.states.destroyed = Ember.create(Ember.View.states._default); Ember.merge(destroyed, { appendChild: function() { throw fmt(destroyedError, ['appendChild']); }, rerender: function() { throw fmt(destroyedError, ['rerender']); }, destroyElement: function() { throw fmt(destroyedError, ['destroyElement']); }, empty: function() { throw fmt(destroyedError, ['empty']); }, setElement: function() { throw fmt(destroyedError, ["set('element', ...)"]); }, renderToBufferIfNeeded: function() { throw fmt(destroyedError, ["renderToBufferIfNeeded"]); }, // Since element insertion is scheduled, don't do anything if // the view has been destroyed between scheduling and execution insertElement: Ember.K }); })(); (function() { Ember.View.cloneStates = function(from) { var into = {}; into._default = {}; into.preRender = Ember.create(into._default); into.destroyed = Ember.create(into._default); into.inBuffer = Ember.create(into._default); into.hasElement = Ember.create(into._default); into.inDOM = Ember.create(into.hasElement); var viewState; for (var stateName in from) { if (!from.hasOwnProperty(stateName)) { continue; } Ember.merge(into[stateName], from[stateName]); } return into; }; })(); (function() { var states = Ember.View.cloneStates(Ember.View.states); /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, meta = Ember.meta; var forEach = Ember.EnumerableUtils.forEach; var childViewsProperty = Ember.computed(function() { return get(this, '_childViews'); }).property('_childViews'); /** A `ContainerView` is an `Ember.View` subclass that allows for manual or programatic management of a view's `childViews` array that will correctly update the `ContainerView` instance's rendered DOM representation. ## Setting Initial Child Views The initial array of child views can be set in one of two ways. You can provide a `childViews` property at creation time that contains instance of `Ember.View`: ```javascript aContainer = Ember.ContainerView.create({ childViews: [Ember.View.create(), Ember.View.create()] }); ``` You can also provide a list of property names whose values are instances of `Ember.View`: ```javascript aContainer = Ember.ContainerView.create({ childViews: ['aView', 'bView', 'cView'], aView: Ember.View.create(), bView: Ember.View.create(), cView: Ember.View.create() }); ``` The two strategies can be combined: ```javascript aContainer = Ember.ContainerView.create({ childViews: ['aView', Ember.View.create()], aView: Ember.View.create() }); ``` Each child view's rendering will be inserted into the container's rendered HTML in the same order as its position in the `childViews` property. ## Adding and Removing Child Views The views in a container's `childViews` array should be added and removed by manipulating the `childViews` property directly. To remove a view pass that view into a `removeObject` call on the container's `childViews` property. Given an empty `<body>` the following code ```javascript aContainer = Ember.ContainerView.create({ classNames: ['the-container'], childViews: ['aView', 'bView'], aView: Ember.View.create({ template: Ember.Handlebars.compile("A") }), bView: Ember.View.create({ template: Ember.Handlebars.compile("B") }) }); aContainer.appendTo('body'); ``` Results in the HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> <div class="ember-view">B</div> </div> ``` Removing a view ```javascript aContainer.get('childViews'); // [aContainer.aView, aContainer.bView] aContainer.get('childViews').removeObject(aContainer.get('bView')); aContainer.get('childViews'); // [aContainer.aView] ``` Will result in the following HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> </div> ``` Similarly, adding a child view is accomplished by adding `Ember.View` instances to the container's `childViews` property. Given an empty `<body>` the following code ```javascript aContainer = Ember.ContainerView.create({ classNames: ['the-container'], childViews: ['aView', 'bView'], aView: Ember.View.create({ template: Ember.Handlebars.compile("A") }), bView: Ember.View.create({ template: Ember.Handlebars.compile("B") }) }); aContainer.appendTo('body'); ``` Results in the HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> <div class="ember-view">B</div> </div> ``` Adding a view ```javascript AnotherViewClass = Ember.View.extend({ template: Ember.Handlebars.compile("Another view") }); aContainer.get('childViews'); // [aContainer.aView, aContainer.bView] aContainer.get('childViews').pushObject(AnotherViewClass.create()); aContainer.get('childViews'); // [aContainer.aView, aContainer.bView, <AnotherViewClass instance>] ``` Will result in the following HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> <div class="ember-view">B</div> <div class="ember-view">Another view</div> </div> ``` Direct manipulation of `childViews` presence or absence in the DOM via calls to `remove` or `removeFromParent` or calls to a container's `removeChild` may not behave correctly. Calling `remove()` on a child view will remove the view's HTML, but it will remain as part of its container's `childView`s property. Calling `removeChild()` on the container will remove the passed view instance from the container's `childView`s but keep its HTML within the container's rendered view. Calling `removeFromParent()` behaves as expected but should be avoided in favor of direct manipulation of a container's `childViews` property. ```javascript aContainer = Ember.ContainerView.create({ classNames: ['the-container'], childViews: ['aView', 'bView'], aView: Ember.View.create({ template: Ember.Handlebars.compile("A") }), bView: Ember.View.create({ template: Ember.Handlebars.compile("B") }) }); aContainer.appendTo('body'); ``` Results in the HTML ```html <div class="ember-view the-container"> <div class="ember-view">A</div> <div class="ember-view">B</div> </div> ``` Calling `aContainer.get('aView').removeFromParent()` will result in the following HTML ```html <div class="ember-view the-container"> <div class="ember-view">B</div> </div> ``` And the `Ember.View` instance stored in `aContainer.aView` will be removed from `aContainer`'s `childViews` array. ## Templates and Layout A `template`, `templateName`, `defaultTemplate`, `layout`, `layoutName` or `defaultLayout` property on a container view will not result in the template or layout being rendered. The HTML contents of a `Ember.ContainerView`'s DOM representation will only be the rendered HTML of its child views. ## Binding a View to Display If you would like to display a single view in your ContainerView, you can set its `currentView` property. When the `currentView` property is set to a view instance, it will be added to the ContainerView's `childViews` array. If the `currentView` property is later changed to a different view, the new view will replace the old view. If `currentView` is set to `null`, the last `currentView` will be removed. This functionality is useful for cases where you want to bind the display of a ContainerView to a controller or state manager. For example, you can bind the `currentView` of a container to a controller like this: ```javascript App.appController = Ember.Object.create({ view: Ember.View.create({ templateName: 'person_template' }) }); ``` ```handlebars {{view Ember.ContainerView currentViewBinding="App.appController.view"}} ``` @class ContainerView @namespace Ember @extends Ember.View */ Ember.ContainerView = Ember.View.extend({ states: states, init: function() { this._super(); var childViews = get(this, 'childViews'); Ember.defineProperty(this, 'childViews', childViewsProperty); var _childViews = this._childViews; forEach(childViews, function(viewName, idx) { var view; if ('string' === typeof viewName) { view = get(this, viewName); view = this.createChildView(view); set(this, viewName, view); } else { view = this.createChildView(viewName); } _childViews[idx] = view; }, this); var currentView = get(this, 'currentView'); if (currentView) _childViews.push(this.createChildView(currentView)); // Make the _childViews array observable Ember.A(_childViews); // Sets up an array observer on the child views array. This // observer will detect when child views are added or removed // and update the DOM to reflect the mutation. get(this, 'childViews').addArrayObserver(this, { willChange: 'childViewsWillChange', didChange: 'childViewsDidChange' }); }, /** @private Instructs each child view to render to the passed render buffer. @method render @param {Ember.RenderBuffer} buffer the buffer to render to */ render: function(buffer) { this.forEachChildView(function(view) { view.renderToBuffer(buffer); }); }, instrumentName: 'render.container', /** @private When the container view is destroyed, tear down the child views array observer. @method willDestroy */ willDestroy: function() { get(this, 'childViews').removeArrayObserver(this, { willChange: 'childViewsWillChange', didChange: 'childViewsDidChange' }); this._super(); }, /** @private When a child view is removed, destroy its element so that it is removed from the DOM. The array observer that triggers this action is set up in the `renderToBuffer` method. @method childViewsWillChange @param {Ember.Array} views the child views array before mutation @param {Number} start the start position of the mutation @param {Number} removed the number of child views removed **/ childViewsWillChange: function(views, start, removed) { if (removed === 0) { return; } var changedViews = views.slice(start, start+removed); this.initializeViews(changedViews, null, null); this.currentState.childViewsWillChange(this, views, start, removed); }, /** @private When a child view is added, make sure the DOM gets updated appropriately. If the view has already rendered an element, we tell the child view to create an element and insert it into the DOM. If the enclosing container view has already written to a buffer, but not yet converted that buffer into an element, we insert the string representation of the child into the appropriate place in the buffer. @method childViewsDidChange @param {Ember.Array} views the array of child views afte the mutation has occurred @param {Number} start the start position of the mutation @param {Number} removed the number of child views removed @param {Number} the number of child views added */ childViewsDidChange: function(views, start, removed, added) { var len = get(views, 'length'); // No new child views were added; bail out. if (added === 0) return; var changedViews = views.slice(start, start+added); this.initializeViews(changedViews, this, get(this, 'templateData')); // Let the current state handle the changes this.currentState.childViewsDidChange(this, views, start, added); }, initializeViews: function(views, parentView, templateData) { forEach(views, function(view) { set(view, '_parentView', parentView); if (!get(view, 'templateData')) { set(view, 'templateData', templateData); } }); }, currentView: null, _currentViewWillChange: Ember.beforeObserver(function() { var childViews = get(this, 'childViews'), currentView = get(this, 'currentView'); if (currentView) { currentView.destroy(); childViews.removeObject(currentView); } }, 'currentView'), _currentViewDidChange: Ember.observer(function() { var childViews = get(this, 'childViews'), currentView = get(this, 'currentView'); if (currentView) { childViews.pushObject(currentView); } }, 'currentView'), _ensureChildrenAreInDOM: function () { this.currentState.ensureChildrenAreInDOM(this); } }); Ember.merge(states._default, { childViewsWillChange: Ember.K, childViewsDidChange: Ember.K, ensureChildrenAreInDOM: Ember.K }); Ember.merge(states.inBuffer, { childViewsDidChange: function(parentView, views, start, added) { throw new Error('You cannot modify child views while in the inBuffer state'); } }); Ember.merge(states.hasElement, { childViewsWillChange: function(view, views, start, removed) { for (var i=start; i<start+removed; i++) { views[i].remove(); } }, childViewsDidChange: function(view, views, start, added) { Ember.run.scheduleOnce('render', view, '_ensureChildrenAreInDOM'); }, ensureChildrenAreInDOM: function(view) { var childViews = view.get('childViews'), i, len, childView, previous, buffer; for (i = 0, len = childViews.length; i < len; i++) { childView = childViews[i]; buffer = childView.renderToBufferIfNeeded(); if (buffer) { childView.triggerRecursively('willInsertElement'); if (previous) { previous.domManager.after(previous, buffer.string()); } else { view.domManager.prepend(view, buffer.string()); } childView.transitionTo('inDOM'); childView.propertyDidChange('element'); childView.triggerRecursively('didInsertElement'); } previous = childView; } } }); })(); (function() { /** @module ember @submodule ember-views */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; /** `Ember.CollectionView` is an `Ember.View` descendent responsible for managing a collection (an array or array-like object) by maintaing a child view object and associated DOM representation for each item in the array and ensuring that child views and their associated rendered HTML are updated when items in the array are added, removed, or replaced. ## Setting content The managed collection of objects is referenced as the `Ember.CollectionView` instance's `content` property. ```javascript someItemsView = Ember.CollectionView.create({ content: ['A', 'B','C'] }) ``` The view for each item in the collection will have its `content` property set to the item. ## Specifying itemViewClass By default the view class for each item in the managed collection will be an instance of `Ember.View`. You can supply a different class by setting the `CollectionView`'s `itemViewClass` property. Given an empty `<body>` and the following code: ```javascript someItemsView = Ember.CollectionView.create({ classNames: ['a-collection'], content: ['A','B','C'], itemViewClass: Ember.View.extend({ template: Ember.Handlebars.compile("the letter: {{view.content}}") }) }); someItemsView.appendTo('body'); ``` Will result in the following HTML structure ```html <div class="ember-view a-collection"> <div class="ember-view">the letter: A</div> <div class="ember-view">the letter: B</div> <div class="ember-view">the letter: C</div> </div> ``` ## Automatic matching of parent/child tagNames Setting the `tagName` property of a `CollectionView` to any of "ul", "ol", "table", "thead", "tbody", "tfoot", "tr", or "select" will result in the item views receiving an appropriately matched `tagName` property. Given an empty `<body>` and the following code: ```javascript anUndorderedListView = Ember.CollectionView.create({ tagName: 'ul', content: ['A','B','C'], itemViewClass: Ember.View.extend({ template: Ember.Handlebars.compile("the letter: {{view.content}}") }) }); anUndorderedListView.appendTo('body'); ``` Will result in the following HTML structure ```html <ul class="ember-view a-collection"> <li class="ember-view">the letter: A</li> <li class="ember-view">the letter: B</li> <li class="ember-view">the letter: C</li> </ul> ``` Additional `tagName` pairs can be provided by adding to `Ember.CollectionView.CONTAINER_MAP ` ```javascript Ember.CollectionView.CONTAINER_MAP['article'] = 'section' ``` ## Programatic creation of child views For cases where additional customization beyond the use of a single `itemViewClass` or `tagName` matching is required CollectionView's `createChildView` method can be overidden: ```javascript CustomCollectionView = Ember.CollectionView.extend({ createChildView: function(viewClass, attrs) { if (attrs.content.kind == 'album') { viewClass = App.AlbumView; } else { viewClass = App.SongView; } this._super(viewClass, attrs); } }); ``` ## Empty View You can provide an `Ember.View` subclass to the `Ember.CollectionView` instance as its `emptyView` property. If the `content` property of a `CollectionView` is set to `null` or an empty array, an instance of this view will be the `CollectionView`s only child. ```javascript aListWithNothing = Ember.CollectionView.create({ classNames: ['nothing'] content: null, emptyView: Ember.View.extend({ template: Ember.Handlebars.compile("The collection is empty") }) }); aListWithNothing.appendTo('body'); ``` Will result in the following HTML structure ```html <div class="ember-view nothing"> <div class="ember-view"> The collection is empty </div> </div> ``` ## Adding and Removing items The `childViews` property of a `CollectionView` should not be directly manipulated. Instead, add, remove, replace items from its `content` property. This will trigger appropriate changes to its rendered HTML. ## Use in templates via the `{{collection}}` `Ember.Handlebars` helper `Ember.Handlebars` provides a helper specifically for adding `CollectionView`s to templates. See `Ember.Handlebars.collection` for more details @class CollectionView @namespace Ember @extends Ember.ContainerView @since Ember 0.9 */ Ember.CollectionView = Ember.ContainerView.extend( /** @scope Ember.CollectionView.prototype */ { /** A list of items to be displayed by the `Ember.CollectionView`. @property content @type Ember.Array @default null */ content: null, /** @private This provides metadata about what kind of empty view class this collection would like if it is being instantiated from another system (like Handlebars) @property emptyViewClass */ emptyViewClass: Ember.View, /** An optional view to display if content is set to an empty array. @property emptyView @type Ember.View @default null */ emptyView: null, /** @property itemViewClass @type Ember.View @default Ember.View */ itemViewClass: Ember.View, init: function() { var ret = this._super(); this._contentDidChange(); return ret; }, _contentWillChange: Ember.beforeObserver(function() { var content = this.get('content'); if (content) { content.removeArrayObserver(this); } var len = content ? get(content, 'length') : 0; this.arrayWillChange(content, 0, len); }, 'content'), /** @private Check to make sure that the content has changed, and if so, update the children directly. This is always scheduled asynchronously, to allow the element to be created before bindings have synchronized and vice versa. @method _contentDidChange */ _contentDidChange: Ember.observer(function() { var content = get(this, 'content'); if (content) { Ember.assert(fmt("an Ember.CollectionView's content must implement Ember.Array. You passed %@", [content]), Ember.Array.detect(content)); content.addArrayObserver(this); } var len = content ? get(content, 'length') : 0; this.arrayDidChange(content, 0, null, len); }, 'content'), willDestroy: function() { var content = get(this, 'content'); if (content) { content.removeArrayObserver(this); } this._super(); }, arrayWillChange: function(content, start, removedCount) { // If the contents were empty before and this template collection has an // empty view remove it now. var emptyView = get(this, 'emptyView'); if (emptyView && emptyView instanceof Ember.View) { emptyView.removeFromParent(); } // Loop through child views that correspond with the removed items. // Note that we loop from the end of the array to the beginning because // we are mutating it as we go. var childViews = get(this, 'childViews'), childView, idx, len; len = get(childViews, 'length'); var removingAll = removedCount === len; if (removingAll) { this.currentState.empty(this); } for (idx = start + removedCount - 1; idx >= start; idx--) { childView = childViews[idx]; if (removingAll) { childView.removedFromDOM = true; } childView.destroy(); } }, /** Called when a mutation to the underlying content array occurs. This method will replay that mutation against the views that compose the `Ember.CollectionView`, ensuring that the view reflects the model. This array observer is added in `contentDidChange`. @method arrayDidChange @param {Array} addedObjects the objects that were added to the content @param {Array} removedObjects the objects that were removed from the content @param {Number} changeIndex the index at which the changes occurred */ arrayDidChange: function(content, start, removed, added) { var itemViewClass = get(this, 'itemViewClass'), childViews = get(this, 'childViews'), addedViews = [], view, item, idx, len, itemTagName; if ('string' === typeof itemViewClass) { itemViewClass = get(itemViewClass); } Ember.assert(fmt("itemViewClass must be a subclass of Ember.View, not %@", [itemViewClass]), Ember.View.detect(itemViewClass)); len = content ? get(content, 'length') : 0; if (len) { for (idx = start; idx < start+added; idx++) { item = content.objectAt(idx); view = this.createChildView(itemViewClass, { content: item, contentIndex: idx }); addedViews.push(view); } } else { var emptyView = get(this, 'emptyView'); if (!emptyView) { return; } emptyView = this.createChildView(emptyView); addedViews.push(emptyView); set(this, 'emptyView', emptyView); } childViews.replace(start, 0, addedViews); }, createChildView: function(view, attrs) { view = this._super(view, attrs); var itemTagName = get(view, 'tagName'); var tagName = (itemTagName === null || itemTagName === undefined) ? Ember.CollectionView.CONTAINER_MAP[get(this, 'tagName')] : itemTagName; set(view, 'tagName', tagName); return view; } }); /** A map of parent tags to their default child tags. You can add additional parent tags if you want collection views that use a particular parent tag to default to a child tag. @property CONTAINER_MAP @type Hash @static @final */ Ember.CollectionView.CONTAINER_MAP = { ul: 'li', ol: 'li', table: 'tr', thead: 'tr', tbody: 'tr', tfoot: 'tr', tr: 'td', select: 'option' }; })(); (function() { })(); (function() { /*globals jQuery*/ /** Ember Views @module ember @submodule ember-views @requires ember-runtime @main ember-views */ })(); (function() { define("metamorph", [], function() { "use strict"; // ========================================================================== // Project: metamorph // Copyright: ©2011 My Company Inc. All rights reserved. // ========================================================================== var K = function(){}, guid = 0, document = window.document, // Feature-detect the W3C range API, the extended check is for IE9 which only partially supports ranges supportsRange = ('createRange' in document) && (typeof Range !== 'undefined') && Range.prototype.createContextualFragment, // Internet Explorer prior to 9 does not allow setting innerHTML if the first element // is a "zero-scope" element. This problem can be worked around by making // the first node an invisible text node. We, like Modernizr, use &shy; needsShy = (function(){ var testEl = document.createElement('div'); testEl.innerHTML = "<div></div>"; testEl.firstChild.innerHTML = "<script></script>"; return testEl.firstChild.innerHTML === ''; })(), // IE 8 (and likely earlier) likes to move whitespace preceeding // a script tag to appear after it. This means that we can // accidentally remove whitespace when updating a morph. movesWhitespace = (function() { var testEl = document.createElement('div'); testEl.innerHTML = "Test: <script type='text/x-placeholder'></script>Value"; return testEl.childNodes[0].nodeValue === 'Test:' && testEl.childNodes[2].nodeValue === ' Value'; })(); // Constructor that supports either Metamorph('foo') or new // Metamorph('foo'); // // Takes a string of HTML as the argument. var Metamorph = function(html) { var self; if (this instanceof Metamorph) { self = this; } else { self = new K(); } self.innerHTML = html; var myGuid = 'metamorph-'+(guid++); self.start = myGuid + '-start'; self.end = myGuid + '-end'; return self; }; K.prototype = Metamorph.prototype; var rangeFor, htmlFunc, removeFunc, outerHTMLFunc, appendToFunc, afterFunc, prependFunc, startTagFunc, endTagFunc; outerHTMLFunc = function() { return this.startTag() + this.innerHTML + this.endTag(); }; startTagFunc = function() { /* * We replace chevron by its hex code in order to prevent escaping problems. * Check this thread for more explaination: * http://stackoverflow.com/questions/8231048/why-use-x3c-instead-of-when-generating-html-from-javascript */ return "<script id='" + this.start + "' type='text/x-placeholder'>\x3C/script>"; }; endTagFunc = function() { /* * We replace chevron by its hex code in order to prevent escaping problems. * Check this thread for more explaination: * http://stackoverflow.com/questions/8231048/why-use-x3c-instead-of-when-generating-html-from-javascript */ return "<script id='" + this.end + "' type='text/x-placeholder'>\x3C/script>"; }; // If we have the W3C range API, this process is relatively straight forward. if (supportsRange) { // Get a range for the current morph. Optionally include the starting and // ending placeholders. rangeFor = function(morph, outerToo) { var range = document.createRange(); var before = document.getElementById(morph.start); var after = document.getElementById(morph.end); if (outerToo) { range.setStartBefore(before); range.setEndAfter(after); } else { range.setStartAfter(before); range.setEndBefore(after); } return range; }; htmlFunc = function(html, outerToo) { // get a range for the current metamorph object var range = rangeFor(this, outerToo); // delete the contents of the range, which will be the // nodes between the starting and ending placeholder. range.deleteContents(); // create a new document fragment for the HTML var fragment = range.createContextualFragment(html); // insert the fragment into the range range.insertNode(fragment); }; removeFunc = function() { // get a range for the current metamorph object including // the starting and ending placeholders. var range = rangeFor(this, true); // delete the entire range. range.deleteContents(); }; appendToFunc = function(node) { var range = document.createRange(); range.setStart(node); range.collapse(false); var frag = range.createContextualFragment(this.outerHTML()); node.appendChild(frag); }; afterFunc = function(html) { var range = document.createRange(); var after = document.getElementById(this.end); range.setStartAfter(after); range.setEndAfter(after); var fragment = range.createContextualFragment(html); range.insertNode(fragment); }; prependFunc = function(html) { var range = document.createRange(); var start = document.getElementById(this.start); range.setStartAfter(start); range.setEndAfter(start); var fragment = range.createContextualFragment(html); range.insertNode(fragment); }; } else { /** * This code is mostly taken from jQuery, with one exception. In jQuery's case, we * have some HTML and we need to figure out how to convert it into some nodes. * * In this case, jQuery needs to scan the HTML looking for an opening tag and use * that as the key for the wrap map. In our case, we know the parent node, and * can use its type as the key for the wrap map. **/ var wrapMap = { select: [ 1, "<select multiple='multiple'>", "</select>" ], fieldset: [ 1, "<fieldset>", "</fieldset>" ], table: [ 1, "<table>", "</table>" ], tbody: [ 2, "<table><tbody>", "</tbody></table>" ], tr: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], colgroup: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], map: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; var findChildById = function(element, id) { if (element.getAttribute('id') === id) { return element; } var len = element.childNodes.length, idx, node, found; for (idx=0; idx<len; idx++) { node = element.childNodes[idx]; found = node.nodeType === 1 && findChildById(node, id); if (found) { return found; } } }; var setInnerHTML = function(element, html) { var matches = []; if (movesWhitespace) { // Right now we only check for script tags with ids with the // goal of targeting morphs. html = html.replace(/(\s+)(<script id='([^']+)')/g, function(match, spaces, tag, id) { matches.push([id, spaces]); return tag; }); } element.innerHTML = html; // If we have to do any whitespace adjustments do them now if (matches.length > 0) { var len = matches.length, idx; for (idx=0; idx<len; idx++) { var script = findChildById(element, matches[idx][0]), node = document.createTextNode(matches[idx][1]); script.parentNode.insertBefore(node, script); } } }; /** * Given a parent node and some HTML, generate a set of nodes. Return the first * node, which will allow us to traverse the rest using nextSibling. * * We need to do this because innerHTML in IE does not really parse the nodes. **/ var firstNodeFor = function(parentNode, html) { var arr = wrapMap[parentNode.tagName.toLowerCase()] || wrapMap._default; var depth = arr[0], start = arr[1], end = arr[2]; if (needsShy) { html = '&shy;'+html; } var element = document.createElement('div'); setInnerHTML(element, start + html + end); for (var i=0; i<=depth; i++) { element = element.firstChild; } // Look for &shy; to remove it. if (needsShy) { var shyElement = element; // Sometimes we get nameless elements with the shy inside while (shyElement.nodeType === 1 && !shyElement.nodeName) { shyElement = shyElement.firstChild; } // At this point it's the actual unicode character. if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === "\u00AD") { shyElement.nodeValue = shyElement.nodeValue.slice(1); } } return element; }; /** * In some cases, Internet Explorer can create an anonymous node in * the hierarchy with no tagName. You can create this scenario via: * * div = document.createElement("div"); * div.innerHTML = "<table>&shy<script></script><tr><td>hi</td></tr></table>"; * div.firstChild.firstChild.tagName //=> "" * * If our script markers are inside such a node, we need to find that * node and use *it* as the marker. **/ var realNode = function(start) { while (start.parentNode.tagName === "") { start = start.parentNode; } return start; }; /** * When automatically adding a tbody, Internet Explorer inserts the * tbody immediately before the first <tr>. Other browsers create it * before the first node, no matter what. * * This means the the following code: * * div = document.createElement("div"); * div.innerHTML = "<table><script id='first'></script><tr><td>hi</td></tr><script id='last'></script></table> * * Generates the following DOM in IE: * * + div * + table * - script id='first' * + tbody * + tr * + td * - "hi" * - script id='last' * * Which means that the two script tags, even though they were * inserted at the same point in the hierarchy in the original * HTML, now have different parents. * * This code reparents the first script tag by making it the tbody's * first child. **/ var fixParentage = function(start, end) { if (start.parentNode !== end.parentNode) { end.parentNode.insertBefore(start, end.parentNode.firstChild); } }; htmlFunc = function(html, outerToo) { // get the real starting node. see realNode for details. var start = realNode(document.getElementById(this.start)); var end = document.getElementById(this.end); var parentNode = end.parentNode; var node, nextSibling, last; // make sure that the start and end nodes share the same // parent. If not, fix it. fixParentage(start, end); // remove all of the nodes after the starting placeholder and // before the ending placeholder. node = start.nextSibling; while (node) { nextSibling = node.nextSibling; last = node === end; // if this is the last node, and we want to remove it as well, // set the `end` node to the next sibling. This is because // for the rest of the function, we insert the new nodes // before the end (note that insertBefore(node, null) is // the same as appendChild(node)). // // if we do not want to remove it, just break. if (last) { if (outerToo) { end = node.nextSibling; } else { break; } } node.parentNode.removeChild(node); // if this is the last node and we didn't break before // (because we wanted to remove the outer nodes), break // now. if (last) { break; } node = nextSibling; } // get the first node for the HTML string, even in cases like // tables and lists where a simple innerHTML on a div would // swallow some of the content. node = firstNodeFor(start.parentNode, html); // copy the nodes for the HTML between the starting and ending // placeholder. while (node) { nextSibling = node.nextSibling; parentNode.insertBefore(node, end); node = nextSibling; } }; // remove the nodes in the DOM representing this metamorph. // // this includes the starting and ending placeholders. removeFunc = function() { var start = realNode(document.getElementById(this.start)); var end = document.getElementById(this.end); this.html(''); start.parentNode.removeChild(start); end.parentNode.removeChild(end); }; appendToFunc = function(parentNode) { var node = firstNodeFor(parentNode, this.outerHTML()); var nextSibling; while (node) { nextSibling = node.nextSibling; parentNode.appendChild(node); node = nextSibling; } }; afterFunc = function(html) { // get the real starting node. see realNode for details. var end = document.getElementById(this.end); var insertBefore = end.nextSibling; var parentNode = end.parentNode; var nextSibling; var node; // get the first node for the HTML string, even in cases like // tables and lists where a simple innerHTML on a div would // swallow some of the content. node = firstNodeFor(parentNode, html); // copy the nodes for the HTML between the starting and ending // placeholder. while (node) { nextSibling = node.nextSibling; parentNode.insertBefore(node, insertBefore); node = nextSibling; } }; prependFunc = function(html) { var start = document.getElementById(this.start); var parentNode = start.parentNode; var nextSibling; var node; node = firstNodeFor(parentNode, html); var insertBefore = start.nextSibling; while (node) { nextSibling = node.nextSibling; parentNode.insertBefore(node, insertBefore); node = nextSibling; } }; } Metamorph.prototype.html = function(html) { this.checkRemoved(); if (html === undefined) { return this.innerHTML; } htmlFunc.call(this, html); this.innerHTML = html; }; Metamorph.prototype.replaceWith = function(html) { this.checkRemoved(); htmlFunc.call(this, html, true); }; Metamorph.prototype.remove = removeFunc; Metamorph.prototype.outerHTML = outerHTMLFunc; Metamorph.prototype.appendTo = appendToFunc; Metamorph.prototype.after = afterFunc; Metamorph.prototype.prepend = prependFunc; Metamorph.prototype.startTag = startTagFunc; Metamorph.prototype.endTag = endTagFunc; Metamorph.prototype.isRemoved = function() { var before = document.getElementById(this.start); var after = document.getElementById(this.end); return !before || !after; }; Metamorph.prototype.checkRemoved = function() { if (this.isRemoved()) { throw new Error("Cannot perform operations on a Metamorph that is not in the DOM."); } }; return Metamorph; }); })(); (function() { /** @module ember @submodule ember-handlebars */ // Eliminate dependency on any Ember to simplify precompilation workflow var objectCreate = Object.create || function(parent) { function F() {} F.prototype = parent; return new F(); }; var Handlebars = this.Handlebars || Ember.imports.Handlebars; Ember.assert("Ember Handlebars requires Handlebars 1.0.beta.5 or greater", Handlebars && Handlebars.VERSION.match(/^1\.0\.beta\.[56789]$|^1\.0\.rc\.[123456789]+/)); /** Prepares the Handlebars templating library for use inside Ember's view system. The `Ember.Handlebars` object is the standard Handlebars library, extended to use Ember's `get()` method instead of direct property access, which allows computed properties to be used inside templates. To create an `Ember.Handlebars` template, call `Ember.Handlebars.compile()`. This will return a function that can be used by `Ember.View` for rendering. @class Handlebars @namespace Ember */ Ember.Handlebars = objectCreate(Handlebars); /** @class helpers @namespace Ember.Handlebars */ Ember.Handlebars.helpers = objectCreate(Handlebars.helpers); /** Override the the opcode compiler and JavaScript compiler for Handlebars. @class Compiler @namespace Ember.Handlebars @private @constructor */ Ember.Handlebars.Compiler = function() {}; // Handlebars.Compiler doesn't exist in runtime-only if (Handlebars.Compiler) { Ember.Handlebars.Compiler.prototype = objectCreate(Handlebars.Compiler.prototype); } Ember.Handlebars.Compiler.prototype.compiler = Ember.Handlebars.Compiler; /** @class JavaScriptCompiler @namespace Ember.Handlebars @private @constructor */ Ember.Handlebars.JavaScriptCompiler = function() {}; // Handlebars.JavaScriptCompiler doesn't exist in runtime-only if (Handlebars.JavaScriptCompiler) { Ember.Handlebars.JavaScriptCompiler.prototype = objectCreate(Handlebars.JavaScriptCompiler.prototype); Ember.Handlebars.JavaScriptCompiler.prototype.compiler = Ember.Handlebars.JavaScriptCompiler; } Ember.Handlebars.JavaScriptCompiler.prototype.namespace = "Ember.Handlebars"; Ember.Handlebars.JavaScriptCompiler.prototype.initializeBuffer = function() { return "''"; }; /** @private Override the default buffer for Ember Handlebars. By default, Handlebars creates an empty String at the beginning of each invocation and appends to it. Ember's Handlebars overrides this to append to a single shared buffer. @method appendToBuffer @param string {String} */ Ember.Handlebars.JavaScriptCompiler.prototype.appendToBuffer = function(string) { return "data.buffer.push("+string+");"; }; /** @private Rewrite simple mustaches from `{{foo}}` to `{{bind "foo"}}`. This means that all simple mustaches in Ember's Handlebars will also set up an observer to keep the DOM up to date when the underlying property changes. @method mustache @for Ember.Handlebars.Compiler @param mustache */ Ember.Handlebars.Compiler.prototype.mustache = function(mustache) { if (mustache.params.length || mustache.hash) { return Handlebars.Compiler.prototype.mustache.call(this, mustache); } else { var id = new Handlebars.AST.IdNode(['_triageMustache']); // Update the mustache node to include a hash value indicating whether the original node // was escaped. This will allow us to properly escape values when the underlying value // changes and we need to re-render the value. if(!mustache.escaped) { mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]); mustache.hash.pairs.push(["unescaped", new Handlebars.AST.StringNode("true")]); } mustache = new Handlebars.AST.MustacheNode([id].concat([mustache.id]), mustache.hash, !mustache.escaped); return Handlebars.Compiler.prototype.mustache.call(this, mustache); } }; /** Used for precompilation of Ember Handlebars templates. This will not be used during normal app execution. @method precompile @for Ember.Handlebars @static @param {String} string The template to precompile */ Ember.Handlebars.precompile = function(string) { var ast = Handlebars.parse(string); var options = { knownHelpers: { action: true, unbound: true, bindAttr: true, template: true, view: true, _triageMustache: true }, data: true, stringParams: true }; var environment = new Ember.Handlebars.Compiler().compile(ast, options); return new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); }; // We don't support this for Handlebars runtime-only if (Handlebars.compile) { /** The entry point for Ember Handlebars. This replaces the default `Handlebars.compile` and turns on template-local data and String parameters. @method compile @for Ember.Handlebars @static @param {String} string The template to compile @return {Function} */ Ember.Handlebars.compile = function(string) { var ast = Handlebars.parse(string); var options = { data: true, stringParams: true }; var environment = new Ember.Handlebars.Compiler().compile(ast, options); var templateSpec = new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); return Ember.Handlebars.template(templateSpec); }; } })(); (function() { /** @private If a path starts with a reserved keyword, returns the root that should be used. @method normalizePath @for Ember @param root {Object} @param path {String} @param data {Hash} */ var normalizePath = Ember.Handlebars.normalizePath = function(root, path, data) { var keywords = (data && data.keywords) || {}, keyword, isKeyword; // Get the first segment of the path. For example, if the // path is "foo.bar.baz", returns "foo". keyword = path.split('.', 1)[0]; // Test to see if the first path is a keyword that has been // passed along in the view's data hash. If so, we will treat // that object as the new root. if (keywords.hasOwnProperty(keyword)) { // Look up the value in the template's data hash. root = keywords[keyword]; isKeyword = true; // Handle cases where the entire path is the reserved // word. In that case, return the object itself. if (path === keyword) { path = ''; } else { // Strip the keyword from the path and look up // the remainder from the newly found root. path = path.substr(keyword.length+1); } } return { root: root, path: path, isKeyword: isKeyword }; }; /** Lookup both on root and on window. If the path starts with a keyword, the corresponding object will be looked up in the template's data hash and used to resolve the path. @method get @for Ember.Handlebars @param {Object} root The object to look up the property on @param {String} path The path to be lookedup @param {Object} options The template's option hash */ Ember.Handlebars.get = function(root, path, options) { var data = options && options.data, normalizedPath = normalizePath(root, path, data), value; // In cases where the path begins with a keyword, change the // root to the value represented by that keyword, and ensure // the path is relative to it. root = normalizedPath.root; path = normalizedPath.path; value = Ember.get(root, path); // If the path starts with a capital letter, look it up on Ember.lookup, // which defaults to the `window` object in browsers. if (value === undefined && root !== Ember.lookup && Ember.isGlobalPath(path)) { value = Ember.get(Ember.lookup, path); } return value; }; Ember.Handlebars.getPath = Ember.deprecateFunc('`Ember.Handlebars.getPath` has been changed to `Ember.Handlebars.get` for consistency.', Ember.Handlebars.get); /** @private Registers a helper in Handlebars that will be called if no property with the given name can be found on the current context object, and no helper with that name is registered. This throws an exception with a more helpful error message so the user can track down where the problem is happening. @method helperMissing @for Ember.Handlebars.helpers @param {String} path @param {Hash} options */ Ember.Handlebars.registerHelper('helperMissing', function(path, options) { var error, view = ""; error = "%@ Handlebars error: Could not find property '%@' on object %@."; if (options.data){ view = options.data.view; } throw new Ember.Error(Ember.String.fmt(error, [view, path, this])); }); /** Register a bound handlebars helper. Bound helpers behave similarly to regular handlebars helpers, with the added ability to re-render when the underlying data changes. ## Simple example ```javascript Ember.Handlebars.registerBoundHelper('capitalize', function(value) { return value.toUpperCase(); }); ``` The above bound helper can be used inside of templates as follows: ```handlebars {{capitalize name}} ``` In this case, when the `name` property of the template's context changes, the rendered value of the helper will update to reflect this change. ## Example with options Like normal handlebars helpers, bound helpers have access to the options passed into the helper call. ```javascript Ember.Handlebars.registerBoundHelper('repeat', function(value, options) { var count = options.hash.count; var a = []; while(a.length < count){ a.push(value); } return a.join(''); }); ``` This helper could be used in a template as follows: ```handlebars {{repeat text count=3}} ``` ## Example with extra dependencies The `Ember.Handlebars.registerBoundHelper` method takes a variable length third parameter which indicates extra dependencies on the passed in value. This allows the handlebars helper to update when these dependencies change. ```javascript Ember.Handlebars.registerBoundHelper('capitalizeName', function(value) { return value.get('name').toUpperCase(); }, 'name'); ``` @method registerBoundHelper @for Ember.Handlebars @param {String} name @param {Function} function @param {String} dependentKeys* */ Ember.Handlebars.registerBoundHelper = function(name, fn) { var dependentKeys = Array.prototype.slice.call(arguments, 2); Ember.Handlebars.registerHelper(name, function(property, options) { var data = options.data, view = data.view, currentContext = (options.contexts && options.contexts[0]) || this, pathRoot, path, normalized, observer, loc; normalized = Ember.Handlebars.normalizePath(currentContext, property, data); pathRoot = normalized.root; path = normalized.path; var bindView = new Ember._SimpleHandlebarsView( path, pathRoot, !options.hash.unescaped, options.data ); bindView.normalizedValue = function() { var value = Ember._SimpleHandlebarsView.prototype.normalizedValue.call(bindView); return fn.call(view, value, options); }; view.appendChild(bindView); observer = function() { Ember.run.scheduleOnce('render', bindView, 'rerender'); }; Ember.addObserver(pathRoot, path, observer); loc = 0; while(loc < dependentKeys.length) { Ember.addObserver(pathRoot, path + '.' + dependentKeys[loc], observer); loc += 1; } view.one('willClearRender', function() { Ember.removeObserver(pathRoot, path, observer); loc = 0; while(loc < dependentKeys.length) { Ember.removeObserver(pathRoot, path + '.' + dependentKeys[loc], observer); loc += 1; } }); }); }; /** @private Overrides Handlebars.template so that we can distinguish user-created, top-level templates from inner contexts. @method template @for Ember.Handlebars @param {String} template spec */ Ember.Handlebars.template = function(spec){ var t = Handlebars.template(spec); t.isTop = true; return t; }; })(); (function() { /** @method htmlSafe @for Ember.String @static */ Ember.String.htmlSafe = function(str) { return new Handlebars.SafeString(str); }; var htmlSafe = Ember.String.htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/htmlSafe"}}{{/crossLink}} @method htmlSafe @for String */ String.prototype.htmlSafe = function() { return htmlSafe(this); }; } })(); (function() { Ember.Handlebars.resolvePaths = function(options) { var ret = [], contexts = options.contexts, roots = options.roots, data = options.data; for (var i=0, l=contexts.length; i<l; i++) { ret.push( Ember.Handlebars.get(roots[i], contexts[i], { data: data }) ); } return ret; }; })(); (function() { /*jshint newcap:false*/ /** @module ember @submodule ember-handlebars */ var set = Ember.set, get = Ember.get; var Metamorph = requireModule('metamorph'); // DOMManager should just abstract dom manipulation between jquery and metamorph var DOMManager = { remove: function(view) { view.morph.remove(); }, prepend: function(view, html) { view.morph.prepend(html); }, after: function(view, html) { view.morph.after(html); }, html: function(view, html) { view.morph.html(html); }, // This is messed up. replace: function(view) { var morph = view.morph; view.transitionTo('preRender'); Ember.run.schedule('render', this, function() { if (get(view, 'isDestroyed')) { return; } view.clearRenderedChildren(); var buffer = view.renderToBuffer(); view.invokeRecursively(function(view) { view.propertyDidChange('element'); }); view.triggerRecursively('willInsertElement'); morph.replaceWith(buffer.string()); view.transitionTo('inDOM'); view.triggerRecursively('didInsertElement'); }); }, empty: function(view) { view.morph.html(""); } }; // The `morph` and `outerHTML` properties are internal only // and not observable. /** @class _Metamorph @namespace Ember @extends Ember.Mixin @private */ Ember._Metamorph = Ember.Mixin.create({ isVirtual: true, tagName: '', instrumentName: 'render.metamorph', init: function() { this._super(); this.morph = Metamorph(); }, beforeRender: function(buffer) { buffer.push(this.morph.startTag()); buffer.pushOpeningTag(); }, afterRender: function(buffer) { buffer.pushClosingTag(); buffer.push(this.morph.endTag()); }, createElement: function() { var buffer = this.renderToBuffer(); this.outerHTML = buffer.string(); this.clearBuffer(); }, domManager: DOMManager }); /** @class _MetamorphView @namespace Ember @extends Ember.View @uses Ember._Metamorph @private */ Ember._MetamorphView = Ember.View.extend(Ember._Metamorph); /** @class _SimpleMetamorphView @namespace Ember @extends Ember.View @uses Ember._Metamorph @private */ Ember._SimpleMetamorphView = Ember.CoreView.extend(Ember._Metamorph); })(); (function() { /*globals Handlebars */ /*jshint newcap:false*/ /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set, handlebarsGet = Ember.Handlebars.get; var Metamorph = requireModule('metamorph'); function SimpleHandlebarsView(path, pathRoot, isEscaped, templateData) { this.path = path; this.pathRoot = pathRoot; this.isEscaped = isEscaped; this.templateData = templateData; this.morph = Metamorph(); this.state = 'preRender'; this.updateId = null; } Ember._SimpleHandlebarsView = SimpleHandlebarsView; SimpleHandlebarsView.prototype = { isVirtual: true, isView: true, destroy: function () { if (this.updateId) { Ember.run.cancel(this.updateId); this.updateId = null; } this.morph = null; }, propertyDidChange: Ember.K, normalizedValue: function() { var path = this.path, pathRoot = this.pathRoot, result, templateData; // Use the pathRoot as the result if no path is provided. This // happens if the path is `this`, which gets normalized into // a `pathRoot` of the current Handlebars context and a path // of `''`. if (path === '') { result = pathRoot; } else { templateData = this.templateData; result = handlebarsGet(pathRoot, path, { data: templateData }); } return result; }, renderToBuffer: function(buffer) { var string = ''; string += this.morph.startTag(); string += this.render(); string += this.morph.endTag(); buffer.push(string); }, render: function() { // If not invoked via a triple-mustache ({{{foo}}}), escape // the content of the template. var escape = this.isEscaped; var result = this.normalizedValue(); if (result === null || result === undefined) { result = ""; } else if (!(result instanceof Handlebars.SafeString)) { result = String(result); } if (escape) { result = Handlebars.Utils.escapeExpression(result); } return result; }, rerender: function() { switch(this.state) { case 'preRender': case 'destroyed': break; case 'inBuffer': throw new Ember.Error("Something you did tried to replace an {{expression}} before it was inserted into the DOM."); case 'hasElement': case 'inDOM': this.updateId = Ember.run.scheduleOnce('render', this, 'update'); break; } return this; }, update: function () { this.updateId = null; this.morph.html(this.render()); }, transitionTo: function(state) { this.state = state; } }; var states = Ember.View.cloneStates(Ember.View.states), merge = Ember.merge; merge(states._default, { rerenderIfNeeded: Ember.K }); merge(states.inDOM, { rerenderIfNeeded: function(view) { if (get(view, 'normalizedValue') !== view._lastNormalizedValue) { view.rerender(); } } }); /** `Ember._HandlebarsBoundView` is a private view created by the Handlebars `{{bind}}` helpers that is used to keep track of bound properties. Every time a property is bound using a `{{mustache}}`, an anonymous subclass of `Ember._HandlebarsBoundView` is created with the appropriate sub-template and context set up. When the associated property changes, just the template for this view will re-render. @class _HandlebarsBoundView @namespace Ember @extends Ember._MetamorphView @private */ Ember._HandlebarsBoundView = Ember._MetamorphView.extend({ instrumentName: 'render.boundHandlebars', states: states, /** The function used to determine if the `displayTemplate` or `inverseTemplate` should be rendered. This should be a function that takes a value and returns a Boolean. @property shouldDisplayFunc @type Function @default null */ shouldDisplayFunc: null, /** Whether the template rendered by this view gets passed the context object of its parent template, or gets passed the value of retrieving `path` from the `pathRoot`. For example, this is true when using the `{{#if}}` helper, because the template inside the helper should look up properties relative to the same object as outside the block. This would be `false` when used with `{{#with foo}}` because the template should receive the object found by evaluating `foo`. @property preserveContext @type Boolean @default false */ preserveContext: false, /** If `preserveContext` is true, this is the object that will be used to render the template. @property previousContext @type Object */ previousContext: null, /** The template to render when `shouldDisplayFunc` evaluates to `true`. @property displayTemplate @type Function @default null */ displayTemplate: null, /** The template to render when `shouldDisplayFunc` evaluates to `false`. @property inverseTemplate @type Function @default null */ inverseTemplate: null, /** The path to look up on `pathRoot` that is passed to `shouldDisplayFunc` to determine which template to render. In addition, if `preserveContext` is `false,` the object at this path will be passed to the template when rendering. @property path @type String @default null */ path: null, /** The object from which the `path` will be looked up. Sometimes this is the same as the `previousContext`, but in cases where this view has been generated for paths that start with a keyword such as `view` or `controller`, the path root will be that resolved object. @property pathRoot @type Object */ pathRoot: null, normalizedValue: Ember.computed(function() { var path = get(this, 'path'), pathRoot = get(this, 'pathRoot'), valueNormalizer = get(this, 'valueNormalizerFunc'), result, templateData; // Use the pathRoot as the result if no path is provided. This // happens if the path is `this`, which gets normalized into // a `pathRoot` of the current Handlebars context and a path // of `''`. if (path === '') { result = pathRoot; } else { templateData = get(this, 'templateData'); result = handlebarsGet(pathRoot, path, { data: templateData }); } return valueNormalizer ? valueNormalizer(result) : result; }).property('path', 'pathRoot', 'valueNormalizerFunc').volatile(), rerenderIfNeeded: function() { this.currentState.rerenderIfNeeded(this); }, /** Determines which template to invoke, sets up the correct state based on that logic, then invokes the default `Ember.View` `render` implementation. This method will first look up the `path` key on `pathRoot`, then pass that value to the `shouldDisplayFunc` function. If that returns `true,` the `displayTemplate` function will be rendered to DOM. Otherwise, `inverseTemplate`, if specified, will be rendered. For example, if this `Ember._HandlebarsBoundView` represented the `{{#with foo}}` helper, it would look up the `foo` property of its context, and `shouldDisplayFunc` would always return true. The object found by looking up `foo` would be passed to `displayTemplate`. @method render @param {Ember.RenderBuffer} buffer */ render: function(buffer) { // If not invoked via a triple-mustache ({{{foo}}}), escape // the content of the template. var escape = get(this, 'isEscaped'); var shouldDisplay = get(this, 'shouldDisplayFunc'), preserveContext = get(this, 'preserveContext'), context = get(this, 'previousContext'); var inverseTemplate = get(this, 'inverseTemplate'), displayTemplate = get(this, 'displayTemplate'); var result = get(this, 'normalizedValue'); this._lastNormalizedValue = result; // First, test the conditional to see if we should // render the template or not. if (shouldDisplay(result)) { set(this, 'template', displayTemplate); // If we are preserving the context (for example, if this // is an #if block, call the template with the same object. if (preserveContext) { set(this, '_context', context); } else { // Otherwise, determine if this is a block bind or not. // If so, pass the specified object to the template if (displayTemplate) { set(this, '_context', result); } else { // This is not a bind block, just push the result of the // expression to the render context and return. if (result === null || result === undefined) { result = ""; } else if (!(result instanceof Handlebars.SafeString)) { result = String(result); } if (escape) { result = Handlebars.Utils.escapeExpression(result); } buffer.push(result); return; } } } else if (inverseTemplate) { set(this, 'template', inverseTemplate); if (preserveContext) { set(this, '_context', context); } else { set(this, '_context', result); } } else { set(this, 'template', function() { return ''; }); } return this._super(buffer); } }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; var handlebarsGet = Ember.Handlebars.get, normalizePath = Ember.Handlebars.normalizePath; var forEach = Ember.ArrayPolyfills.forEach; var EmberHandlebars = Ember.Handlebars, helpers = EmberHandlebars.helpers; // Binds a property into the DOM. This will create a hook in DOM that the // KVO system will look for and update if the property changes. function bind(property, options, preserveContext, shouldDisplay, valueNormalizer) { var data = options.data, fn = options.fn, inverse = options.inverse, view = data.view, currentContext = this, pathRoot, path, normalized, observer; normalized = normalizePath(currentContext, property, data); pathRoot = normalized.root; path = normalized.path; // Set up observers for observable objects if ('object' === typeof this) { if (data.insideGroup) { observer = function() { Ember.run.once(view, 'rerender'); }; var template, context, result = handlebarsGet(pathRoot, path, options); result = valueNormalizer(result); context = preserveContext ? currentContext : result; if (shouldDisplay(result)) { template = fn; } else if (inverse) { template = inverse; } template(context, { data: options.data }); } else { // Create the view that will wrap the output of this template/property // and add it to the nearest view's childViews array. // See the documentation of Ember._HandlebarsBoundView for more. var bindView = view.createChildView(Ember._HandlebarsBoundView, { preserveContext: preserveContext, shouldDisplayFunc: shouldDisplay, valueNormalizerFunc: valueNormalizer, displayTemplate: fn, inverseTemplate: inverse, path: path, pathRoot: pathRoot, previousContext: currentContext, isEscaped: !options.hash.unescaped, templateData: options.data }); view.appendChild(bindView); observer = function() { Ember.run.scheduleOnce('render', bindView, 'rerenderIfNeeded'); }; } // Observes the given property on the context and // tells the Ember._HandlebarsBoundView to re-render. If property // is an empty string, we are printing the current context // object ({{this}}) so updating it is not our responsibility. if (path !== '') { Ember.addObserver(pathRoot, path, observer); view.one('willClearRender', function() { Ember.removeObserver(pathRoot, path, observer); }); } } else { // The object is not observable, so just render it out and // be done with it. data.buffer.push(handlebarsGet(pathRoot, path, options)); } } function simpleBind(property, options) { var data = options.data, view = data.view, currentContext = this, pathRoot, path, normalized, observer; normalized = normalizePath(currentContext, property, data); pathRoot = normalized.root; path = normalized.path; // Set up observers for observable objects if ('object' === typeof this) { if (data.insideGroup) { observer = function() { Ember.run.once(view, 'rerender'); }; var result = handlebarsGet(pathRoot, path, options); if (result === null || result === undefined) { result = ""; } data.buffer.push(result); } else { var bindView = new Ember._SimpleHandlebarsView( path, pathRoot, !options.hash.unescaped, options.data ); bindView._parentView = view; view.appendChild(bindView); observer = function() { Ember.run.scheduleOnce('render', bindView, 'rerender'); }; } // Observes the given property on the context and // tells the Ember._HandlebarsBoundView to re-render. If property // is an empty string, we are printing the current context // object ({{this}}) so updating it is not our responsibility. if (path !== '') { Ember.addObserver(pathRoot, path, observer); view.one('willClearRender', function() { Ember.removeObserver(pathRoot, path, observer); }); } } else { // The object is not observable, so just render it out and // be done with it. data.buffer.push(handlebarsGet(pathRoot, path, options)); } } /** @private '_triageMustache' is used internally select between a binding and helper for the given context. Until this point, it would be hard to determine if the mustache is a property reference or a regular helper reference. This triage helper resolves that. This would not be typically invoked by directly. @method _triageMustache @for Ember.Handlebars.helpers @param {String} property Property/helperID to triage @param {Function} fn Context to provide for rendering @return {String} HTML string */ EmberHandlebars.registerHelper('_triageMustache', function(property, fn) { Ember.assert("You cannot pass more than one argument to the _triageMustache helper", arguments.length <= 2); if (helpers[property]) { return helpers[property].call(this, fn); } else { return helpers.bind.apply(this, arguments); } }); /** @private `bind` can be used to display a value, then update that value if it changes. For example, if you wanted to print the `title` property of `content`: ```handlebars {{bind "content.title"}} ``` This will return the `title` property as a string, then create a new observer at the specified path. If it changes, it will update the value in DOM. Note that if you need to support IE7 and IE8 you must modify the model objects properties using `Ember.get()` and `Ember.set()` for this to work as it relies on Ember's KVO system. For all other browsers this will be handled for you automatically. @method bind @for Ember.Handlebars.helpers @param {String} property Property to bind @param {Function} fn Context to provide for rendering @return {String} HTML string */ EmberHandlebars.registerHelper('bind', function(property, options) { Ember.assert("You cannot pass more than one argument to the bind helper", arguments.length <= 2); var context = (options.contexts && options.contexts[0]) || this; if (!options.fn) { return simpleBind.call(context, property, options); } return bind.call(context, property, options, false, function(result) { return !Ember.isNone(result); }); }); /** @private Use the `boundIf` helper to create a conditional that re-evaluates whenever the truthiness of the bound value changes. ```handlebars {{#boundIf "content.shouldDisplayTitle"}} {{content.title}} {{/boundIf}} ``` @method boundIf @for Ember.Handlebars.helpers @param {String} property Property to bind @param {Function} fn Context to provide for rendering @return {String} HTML string */ EmberHandlebars.registerHelper('boundIf', function(property, fn) { var context = (fn.contexts && fn.contexts[0]) || this; var func = function(result) { if (Ember.typeOf(result) === 'array') { return get(result, 'length') !== 0; } else { return !!result; } }; return bind.call(context, property, fn, true, func, func); }); /** @method with @for Ember.Handlebars.helpers @param {Function} context @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('with', function(context, options) { if (arguments.length === 4) { var keywordName, path, rootPath, normalized; Ember.assert("If you pass more than one argument to the with helper, it must be in the form #with foo as bar", arguments[1] === "as"); options = arguments[3]; keywordName = arguments[2]; path = arguments[0]; Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop); if (Ember.isGlobalPath(path)) { Ember.bind(options.data.keywords, keywordName, path); } else { normalized = normalizePath(this, path, options.data); path = normalized.path; rootPath = normalized.root; // This is a workaround for the fact that you cannot bind separate objects // together. When we implement that functionality, we should use it here. var contextKey = Ember.$.expando + Ember.guidFor(rootPath); options.data.keywords[contextKey] = rootPath; // if the path is '' ("this"), just bind directly to the current context var contextPath = path ? contextKey + '.' + path : contextKey; Ember.bind(options.data.keywords, keywordName, contextPath); } return bind.call(this, path, options, true, function(result) { return !Ember.isNone(result); }); } else { Ember.assert("You must pass exactly one argument to the with helper", arguments.length === 2); Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop); return helpers.bind.call(options.contexts[0], context, options); } }); /** See `boundIf` @method if @for Ember.Handlebars.helpers @param {Function} context @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('if', function(context, options) { Ember.assert("You must pass exactly one argument to the if helper", arguments.length === 2); Ember.assert("You must pass a block to the if helper", options.fn && options.fn !== Handlebars.VM.noop); return helpers.boundIf.call(options.contexts[0], context, options); }); /** @method unless @for Ember.Handlebars.helpers @param {Function} context @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('unless', function(context, options) { Ember.assert("You must pass exactly one argument to the unless helper", arguments.length === 2); Ember.assert("You must pass a block to the unless helper", options.fn && options.fn !== Handlebars.VM.noop); var fn = options.fn, inverse = options.inverse; options.fn = inverse; options.inverse = fn; return helpers.boundIf.call(options.contexts[0], context, options); }); /** `bindAttr` allows you to create a binding between DOM element attributes and Ember objects. For example: ```handlebars <img {{bindAttr src="imageUrl" alt="imageTitle"}}> ``` The above handlebars template will fill the `<img>`'s `src` attribute will the value of the property referenced with `"imageUrl"` and its `alt` attribute with the value of the property referenced with `"imageTitle"`. If the rendering context of this template is the following object: ```javascript { imageUrl: 'http://lolcats.info/haz-a-funny', imageTitle: 'A humorous image of a cat' } ``` The resulting HTML output will be: ```html <img src="http://lolcats.info/haz-a-funny" alt="A humorous image of a cat"> ``` `bindAttr` cannot redeclare existing DOM element attributes. The use of `src` in the following `bindAttr` example will be ignored and the hard coded value of `src="/failwhale.gif"` will take precedence: ```handlebars <img src="/failwhale.gif" {{bindAttr src="imageUrl" alt="imageTitle"}}> ``` ### `bindAttr` and the `class` attribute `bindAttr` supports a special syntax for handling a number of cases unique to the `class` DOM element attribute. The `class` attribute combines multiple discreet values into a single attribute as a space-delimited list of strings. Each string can be: * a string return value of an object's property. * a boolean return value of an object's property * a hard-coded value A string return value works identically to other uses of `bindAttr`. The return value of the property will become the value of the attribute. For example, the following view and template: ```javascript AView = Ember.View.extend({ someProperty: function(){ return "aValue"; }.property() }) ``` ```handlebars <img {{bindAttr class="view.someProperty}}> ``` Result in the following rendered output: ```html <img class="aValue"> ``` A boolean return value will insert a specified class name if the property returns `true` and remove the class name if the property returns `false`. A class name is provided via the syntax `somePropertyName:class-name-if-true`. ```javascript AView = Ember.View.extend({ someBool: true }) ``` ```handlebars <img {{bindAttr class="view.someBool:class-name-if-true"}}> ``` Result in the following rendered output: ```html <img class="class-name-if-true"> ``` An additional section of the binding can be provided if you want to replace the existing class instead of removing it when the boolean value changes: ```handlebars <img {{bindAttr class="view.someBool:class-name-if-true:class-name-if-false"}}> ``` A hard-coded value can be used by prepending `:` to the desired class name: `:class-name-to-always-apply`. ```handlebars <img {{bindAttr class=":class-name-to-always-apply"}}> ``` Results in the following rendered output: ```html <img class=":class-name-to-always-apply"> ``` All three strategies - string return value, boolean return value, and hard-coded value – can be combined in a single declaration: ```handlebars <img {{bindAttr class=":class-name-to-always-apply view.someBool:class-name-if-true view.someProperty"}}> ``` @method bindAttr @for Ember.Handlebars.helpers @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('bindAttr', function(options) { var attrs = options.hash; Ember.assert("You must specify at least one hash argument to bindAttr", !!Ember.keys(attrs).length); var view = options.data.view; var ret = []; var ctx = this; // Generate a unique id for this element. This will be added as a // data attribute to the element so it can be looked up when // the bound property changes. var dataId = ++Ember.uuid; // Handle classes differently, as we can bind multiple classes var classBindings = attrs['class']; if (classBindings !== null && classBindings !== undefined) { var classResults = EmberHandlebars.bindClasses(this, classBindings, view, dataId, options); ret.push('class="' + Handlebars.Utils.escapeExpression(classResults.join(' ')) + '"'); delete attrs['class']; } var attrKeys = Ember.keys(attrs); // For each attribute passed, create an observer and emit the // current value of the property as an attribute. forEach.call(attrKeys, function(attr) { var path = attrs[attr], pathRoot, normalized; Ember.assert(fmt("You must provide a String for a bound attribute, not %@", [path]), typeof path === 'string'); normalized = normalizePath(ctx, path, options.data); pathRoot = normalized.root; path = normalized.path; var value = (path === 'this') ? pathRoot : handlebarsGet(pathRoot, path, options), type = Ember.typeOf(value); Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), value === null || value === undefined || type === 'number' || type === 'string' || type === 'boolean'); var observer, invoker; observer = function observer() { var result = handlebarsGet(pathRoot, path, options); Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), result === null || result === undefined || typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean'); var elem = view.$("[data-bindattr-" + dataId + "='" + dataId + "']"); // If we aren't able to find the element, it means the element // to which we were bound has been removed from the view. // In that case, we can assume the template has been re-rendered // and we need to clean up the observer. if (!elem || elem.length === 0) { Ember.removeObserver(pathRoot, path, invoker); return; } Ember.View.applyAttributeBindings(elem, attr, result); }; invoker = function() { Ember.run.scheduleOnce('render', observer); }; // Add an observer to the view for when the property changes. // When the observer fires, find the element using the // unique data id and update the attribute to the new value. if (path !== 'this') { Ember.addObserver(pathRoot, path, invoker); view.one('willClearRender', function() { Ember.removeObserver(pathRoot, path, invoker); }); } // if this changes, also change the logic in ember-views/lib/views/view.js if ((type === 'string' || (type === 'number' && !isNaN(value)))) { ret.push(attr + '="' + Handlebars.Utils.escapeExpression(value) + '"'); } else if (value && type === 'boolean') { // The developer controls the attr name, so it should always be safe ret.push(attr + '="' + attr + '"'); } }, this); // Add the unique identifier // NOTE: We use all lower-case since Firefox has problems with mixed case in SVG ret.push('data-bindattr-' + dataId + '="' + dataId + '"'); return new EmberHandlebars.SafeString(ret.join(' ')); }); /** @private Helper that, given a space-separated string of property paths and a context, returns an array of class names. Calling this method also has the side effect of setting up observers at those property paths, such that if they change, the correct class name will be reapplied to the DOM element. For example, if you pass the string "fooBar", it will first look up the "fooBar" value of the context. If that value is true, it will add the "foo-bar" class to the current element (i.e., the dasherized form of "fooBar"). If the value is a string, it will add that string as the class. Otherwise, it will not add any new class name. @method bindClasses @for Ember.Handlebars @param {Ember.Object} context The context from which to lookup properties @param {String} classBindings A string, space-separated, of class bindings to use @param {Ember.View} view The view in which observers should look for the element to update @param {Srting} bindAttrId Optional bindAttr id used to lookup elements @return {Array} An array of class names to add */ EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, options) { var ret = [], newClass, value, elem; // Helper method to retrieve the property from the context and // determine which class string to return, based on whether it is // a Boolean or not. var classStringForPath = function(root, parsedPath, options) { var val, path = parsedPath.path; if (path === 'this') { val = root; } else if (path === '') { val = true; } else { val = handlebarsGet(root, path, options); } return Ember.View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); }; // For each property passed, loop through and setup // an observer. forEach.call(classBindings.split(' '), function(binding) { // Variable in which the old class value is saved. The observer function // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; var observer, invoker; var parsedPath = Ember.View._parsePropertyPath(binding), path = parsedPath.path, pathRoot = context, normalized; if (path !== '' && path !== 'this') { normalized = normalizePath(context, path, options.data); pathRoot = normalized.root; path = normalized.path; } // Set up an observer on the context. If the property changes, toggle the // class name. observer = function() { // Get the current value of the property newClass = classStringForPath(pathRoot, parsedPath, options); elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$(); // If we can't find the element anymore, a parent template has been // re-rendered and we've been nuked. Remove the observer. if (!elem || elem.length === 0) { Ember.removeObserver(pathRoot, path, invoker); } else { // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if (newClass) { elem.addClass(newClass); oldClass = newClass; } else { oldClass = null; } } }; invoker = function() { Ember.run.scheduleOnce('render', observer); }; if (path !== '' && path !== 'this') { Ember.addObserver(pathRoot, path, invoker); view.one('willClearRender', function() { Ember.removeObserver(pathRoot, path, invoker); }); } // We've already setup the observer; now we just need to figure out the // correct behavior right now on the first pass through. value = classStringForPath(pathRoot, parsedPath, options); if (value) { ret.push(value); // Make sure we save the current value so that it can be removed if the // observer fires. oldClass = value; } }); return ret; }; })(); (function() { /*globals Handlebars */ // TODO: Don't require the entire module /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; var PARENT_VIEW_PATH = /^parentView\./; var EmberHandlebars = Ember.Handlebars; EmberHandlebars.ViewHelper = Ember.Object.create({ propertiesFromHTMLOptions: function(options, thisContext) { var hash = options.hash, data = options.data; var extensions = {}, classes = hash['class'], dup = false; if (hash.id) { extensions.elementId = hash.id; dup = true; } if (classes) { classes = classes.split(' '); extensions.classNames = classes; dup = true; } if (hash.classBinding) { extensions.classNameBindings = hash.classBinding.split(' '); dup = true; } if (hash.classNameBindings) { if (extensions.classNameBindings === undefined) extensions.classNameBindings = []; extensions.classNameBindings = extensions.classNameBindings.concat(hash.classNameBindings.split(' ')); dup = true; } if (hash.attributeBindings) { Ember.assert("Setting 'attributeBindings' via Handlebars is not allowed. Please subclass Ember.View and set it there instead."); extensions.attributeBindings = null; dup = true; } if (dup) { hash = Ember.$.extend({}, hash); delete hash.id; delete hash['class']; delete hash.classBinding; } // Set the proper context for all bindings passed to the helper. This applies to regular attribute bindings // as well as class name bindings. If the bindings are local, make them relative to the current context // instead of the view. var path; // Evaluate the context of regular attribute bindings: for (var prop in hash) { if (!hash.hasOwnProperty(prop)) { continue; } // Test if the property ends in "Binding" if (Ember.IS_BINDING.test(prop) && typeof hash[prop] === 'string') { path = this.contextualizeBindingPath(hash[prop], data); if (path) { hash[prop] = path; } } } // Evaluate the context of class name bindings: if (extensions.classNameBindings) { for (var b in extensions.classNameBindings) { var full = extensions.classNameBindings[b]; if (typeof full === 'string') { // Contextualize the path of classNameBinding so this: // // classNameBinding="isGreen:green" // // is converted to this: // // classNameBinding="_parentView.context.isGreen:green" var parsedPath = Ember.View._parsePropertyPath(full); path = this.contextualizeBindingPath(parsedPath.path, data); if (path) { extensions.classNameBindings[b] = path + parsedPath.classNames; } } } } return Ember.$.extend(hash, extensions); }, // Transform bindings from the current context to a context that can be evaluated within the view. // Returns null if the path shouldn't be changed. // // TODO: consider the addition of a prefix that would allow this method to return `path`. contextualizeBindingPath: function(path, data) { var normalized = Ember.Handlebars.normalizePath(null, path, data); if (normalized.isKeyword) { return 'templateData.keywords.' + path; } else if (Ember.isGlobalPath(path)) { return null; } else if (path === 'this') { return '_parentView.context'; } else { return '_parentView.context.' + path; } }, helper: function(thisContext, path, options) { var inverse = options.inverse, data = options.data, view = data.view, fn = options.fn, hash = options.hash, newView; if ('string' === typeof path) { newView = EmberHandlebars.get(thisContext, path, options); Ember.assert("Unable to find view at path '" + path + "'", !!newView); } else { newView = path; } Ember.assert(Ember.String.fmt('You must pass a view to the #view helper, not %@ (%@)', [path, newView]), Ember.View.detect(newView) || Ember.View.detectInstance(newView)); var viewOptions = this.propertiesFromHTMLOptions(options, thisContext); var currentView = data.view; viewOptions.templateData = options.data; var newViewProto = newView.proto ? newView.proto() : newView; if (fn) { Ember.assert("You cannot provide a template block if you also specified a templateName", !get(viewOptions, 'templateName') && !get(newViewProto, 'templateName')); viewOptions.template = fn; } // We only want to override the `_context` computed property if there is // no specified controller. See View#_context for more information. if (!newViewProto.controller && !newViewProto.controllerBinding && !viewOptions.controller && !viewOptions.controllerBinding) { viewOptions._context = thisContext; } currentView.appendChild(newView, viewOptions); } }); /** `{{view}}` inserts a new instance of `Ember.View` into a template passing its options to the `Ember.View`'s `create` method and using the supplied block as the view's own template. An empty `<body>` and the following template: ```handlebars A span: {{#view tagName="span"}} hello. {{/view}} ``` Will result in HTML structure: ```html <body> <!-- Note: the handlebars template script also results in a rendered Ember.View which is the outer <div> here --> <div class="ember-view"> A span: <span id="ember1" class="ember-view"> Hello. </span> </div> </body> ``` ### `parentView` setting The `parentView` property of the new `Ember.View` instance created through `{{view}}` will be set to the `Ember.View` instance of the template where `{{view}}` was called. ```javascript aView = Ember.View.create({ template: Ember.Handlebars.compile("{{#view}} my parent: {{parentView.elementId}} {{/view}}") }); aView.appendTo('body'); ``` Will result in HTML structure: ```html <div id="ember1" class="ember-view"> <div id="ember2" class="ember-view"> my parent: ember1 </div> </div> ``` ### Setting CSS id and class attributes The HTML `id` attribute can be set on the `{{view}}`'s resulting element with the `id` option. This option will _not_ be passed to `Ember.View.create`. ```handlebars {{#view tagName="span" id="a-custom-id"}} hello. {{/view}} ``` Results in the following HTML structure: ```html <div class="ember-view"> <span id="a-custom-id" class="ember-view"> hello. </span> </div> ``` The HTML `class` attribute can be set on the `{{view}}`'s resulting element with the `class` or `classNameBindings` options. The `class` option will directly set the CSS `class` attribute and will not be passed to `Ember.View.create`. `classNameBindings` will be passed to `create` and use `Ember.View`'s class name binding functionality: ```handlebars {{#view tagName="span" class="a-custom-class"}} hello. {{/view}} ``` Results in the following HTML structure: ```html <div class="ember-view"> <span id="ember2" class="ember-view a-custom-class"> hello. </span> </div> ``` ### Supplying a different view class `{{view}}` can take an optional first argument before its supplied options to specify a path to a custom view class. ```handlebars {{#view "MyApp.CustomView"}} hello. {{/view}} ``` The first argument can also be a relative path. Ember will search for the view class starting at the `Ember.View` of the template where `{{view}}` was used as the root object: ```javascript MyApp = Ember.Application.create({}); MyApp.OuterView = Ember.View.extend({ innerViewClass: Ember.View.extend({ classNames: ['a-custom-view-class-as-property'] }), template: Ember.Handlebars.compile('{{#view "innerViewClass"}} hi {{/view}}') }); MyApp.OuterView.create().appendTo('body'); ``` Will result in the following HTML: ```html <div id="ember1" class="ember-view"> <div id="ember2" class="ember-view a-custom-view-class-as-property"> hi </div> </div> ``` ### Blockless use If you supply a custom `Ember.View` subclass that specifies its own template or provide a `templateName` option to `{{view}}` it can be used without supplying a block. Attempts to use both a `templateName` option and supply a block will throw an error. ```handlebars {{view "MyApp.ViewWithATemplateDefined"}} ``` ### `viewName` property You can supply a `viewName` option to `{{view}}`. The `Ember.View` instance will be referenced as a property of its parent view by this name. ```javascript aView = Ember.View.create({ template: Ember.Handlebars.compile('{{#view viewName="aChildByName"}} hi {{/view}}') }); aView.appendTo('body'); aView.get('aChildByName') // the instance of Ember.View created by {{view}} helper ``` @method view @for Ember.Handlebars.helpers @param {String} path @param {Hash} options @return {String} HTML string */ EmberHandlebars.registerHelper('view', function(path, options) { Ember.assert("The view helper only takes a single argument", arguments.length <= 2); // If no path is provided, treat path param as options. if (path && path.data && path.data.isRenderData) { options = path; path = "Ember.View"; } return EmberHandlebars.ViewHelper.helper(this, path, options); }); })(); (function() { /*globals Handlebars */ // TODO: Don't require all of this module /** @module ember @submodule ember-handlebars */ var get = Ember.get, handlebarsGet = Ember.Handlebars.get, fmt = Ember.String.fmt; /** `{{collection}}` is a `Ember.Handlebars` helper for adding instances of `Ember.CollectionView` to a template. See `Ember.CollectionView` for additional information on how a `CollectionView` functions. `{{collection}}`'s primary use is as a block helper with a `contentBinding` option pointing towards an `Ember.Array`-compatible object. An `Ember.View` instance will be created for each item in its `content` property. Each view will have its own `content` property set to the appropriate item in the collection. The provided block will be applied as the template for each item's view. Given an empty `<body>` the following template: ```handlebars {{#collection contentBinding="App.items"}} Hi {{view.content.name}} {{/collection}} ``` And the following application code ```javascript App = Ember.Application.create() App.items = [ Ember.Object.create({name: 'Dave'}), Ember.Object.create({name: 'Mary'}), Ember.Object.create({name: 'Sara'}) ] ``` Will result in the HTML structure below ```html <div class="ember-view"> <div class="ember-view">Hi Dave</div> <div class="ember-view">Hi Mary</div> <div class="ember-view">Hi Sara</div> </div> ``` ### Blockless Use If you provide an `itemViewClass` option that has its own `template` you can omit the block. The following template: ```handlebars {{collection contentBinding="App.items" itemViewClass="App.AnItemView"}} ``` And application code ```javascript App = Ember.Application.create(); App.items = [ Ember.Object.create({name: 'Dave'}), Ember.Object.create({name: 'Mary'}), Ember.Object.create({name: 'Sara'}) ]; App.AnItemView = Ember.View.extend({ template: Ember.Handlebars.compile("Greetings {{view.content.name}}") }); ``` Will result in the HTML structure below ```html <div class="ember-view"> <div class="ember-view">Greetings Dave</div> <div class="ember-view">Greetings Mary</div> <div class="ember-view">Greetings Sara</div> </div> ``` ### Specifying a CollectionView subclass By default the `{{collection}}` helper will create an instance of `Ember.CollectionView`. You can supply a `Ember.CollectionView` subclass to the helper by passing it as the first argument: ```handlebars {{#collection App.MyCustomCollectionClass contentBinding="App.items"}} Hi {{view.content.name}} {{/collection}} ``` ### Forwarded `item.*`-named Options As with the `{{view}}`, helper options passed to the `{{collection}}` will be set on the resulting `Ember.CollectionView` as properties. Additionally, options prefixed with `item` will be applied to the views rendered for each item (note the camelcasing): ```handlebars {{#collection contentBinding="App.items" itemTagName="p" itemClassNames="greeting"}} Howdy {{view.content.name}} {{/collection}} ``` Will result in the following HTML structure: ```html <div class="ember-view"> <p class="ember-view greeting">Howdy Dave</p> <p class="ember-view greeting">Howdy Mary</p> <p class="ember-view greeting">Howdy Sara</p> </div> ``` @method collection @for Ember.Handlebars.helpers @param {String} path @param {Hash} options @return {String} HTML string @deprecated Use `{{each}}` helper instead. */ Ember.Handlebars.registerHelper('collection', function(path, options) { Ember.deprecate("Using the {{collection}} helper without specifying a class has been deprecated as the {{each}} helper now supports the same functionality.", path !== 'collection'); // If no path is provided, treat path param as options. if (path && path.data && path.data.isRenderData) { options = path; path = undefined; Ember.assert("You cannot pass more than one argument to the collection helper", arguments.length === 1); } else { Ember.assert("You cannot pass more than one argument to the collection helper", arguments.length === 2); } var fn = options.fn; var data = options.data; var inverse = options.inverse; var view = options.data.view; // If passed a path string, convert that into an object. // Otherwise, just default to the standard class. var collectionClass; collectionClass = path ? handlebarsGet(this, path, options) : Ember.CollectionView; Ember.assert(fmt("%@ #collection: Could not find collection class %@", [data.view, path]), !!collectionClass); var hash = options.hash, itemHash = {}, match; // Extract item view class if provided else default to the standard class var itemViewClass, itemViewPath = hash.itemViewClass; var collectionPrototype = collectionClass.proto(); delete hash.itemViewClass; itemViewClass = itemViewPath ? handlebarsGet(collectionPrototype, itemViewPath, options) : collectionPrototype.itemViewClass; Ember.assert(fmt("%@ #collection: Could not find itemViewClass %@", [data.view, itemViewPath]), !!itemViewClass); // Go through options passed to the {{collection}} helper and extract options // that configure item views instead of the collection itself. for (var prop in hash) { if (hash.hasOwnProperty(prop)) { match = prop.match(/^item(.)(.*)$/); if(match) { // Convert itemShouldFoo -> shouldFoo itemHash[match[1].toLowerCase() + match[2]] = hash[prop]; // Delete from hash as this will end up getting passed to the // {{view}} helper method. delete hash[prop]; } } } var tagName = hash.tagName || collectionPrototype.tagName; if (fn) { itemHash.template = fn; delete options.fn; } var emptyViewClass; if (inverse && inverse !== Handlebars.VM.noop) { emptyViewClass = get(collectionPrototype, 'emptyViewClass'); emptyViewClass = emptyViewClass.extend({ template: inverse, tagName: itemHash.tagName }); } else if (hash.emptyViewClass) { emptyViewClass = handlebarsGet(this, hash.emptyViewClass, options); } hash.emptyView = emptyViewClass; if (hash.eachHelper === 'each') { itemHash._context = Ember.computed(function() { return get(this, 'content'); }).property('content'); delete hash.eachHelper; } var viewString = view.toString(); var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this); hash.itemViewClass = itemViewClass.extend(viewOptions); return Ember.Handlebars.helpers.view.call(this, collectionClass, options); }); })(); (function() { /*globals Handlebars */ /** @module ember @submodule ember-handlebars */ var handlebarsGet = Ember.Handlebars.get; /** `unbound` allows you to output a property without binding. *Important:* The output will not be updated if the property changes. Use with caution. ```handlebars <div>{{unbound somePropertyThatDoesntChange}}</div> ``` @method unbound @for Ember.Handlebars.helpers @param {String} property @return {String} HTML string */ Ember.Handlebars.registerHelper('unbound', function(property, fn) { var context = (fn.contexts && fn.contexts[0]) || this; return handlebarsGet(context, property, fn); }); })(); (function() { /*jshint debug:true*/ /** @module ember @submodule ember-handlebars */ var handlebarsGet = Ember.Handlebars.get, normalizePath = Ember.Handlebars.normalizePath; /** `log` allows you to output the value of a value in the current rendering context. ```handlebars {{log myVariable}} ``` @method log @for Ember.Handlebars.helpers @param {String} property */ Ember.Handlebars.registerHelper('log', function(property, options) { var context = (options.contexts && options.contexts[0]) || this, normalized = normalizePath(context, property, options.data), pathRoot = normalized.root, path = normalized.path, value = (path === 'this') ? pathRoot : handlebarsGet(pathRoot, path, options); Ember.Logger.log(value); }); /** Execute the `debugger` statement in the current context. ```handlebars {{debugger}} ``` @method debugger @for Ember.Handlebars.helpers @param {String} property */ Ember.Handlebars.registerHelper('debugger', function() { debugger; }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; Ember.Handlebars.EachView = Ember.CollectionView.extend(Ember._Metamorph, { itemViewClass: Ember._MetamorphView, emptyViewClass: Ember._MetamorphView, createChildView: function(view, attrs) { view = this._super(view, attrs); // At the moment, if a container view subclass wants // to insert keywords, it is responsible for cloning // the keywords hash. This will be fixed momentarily. var keyword = get(this, 'keyword'); if (keyword) { var data = get(view, 'templateData'); data = Ember.copy(data); data.keywords = view.cloneKeywords(); set(view, 'templateData', data); var content = get(view, 'content'); // In this case, we do not bind, because the `content` of // a #each item cannot change. data.keywords[keyword] = content; } return view; } }); var GroupedEach = Ember.Handlebars.GroupedEach = function(context, path, options) { var self = this, normalized = Ember.Handlebars.normalizePath(context, path, options.data); this.context = context; this.path = path; this.options = options; this.template = options.fn; this.containingView = options.data.view; this.normalizedRoot = normalized.root; this.normalizedPath = normalized.path; this.content = this.lookupContent(); this.addContentObservers(); this.addArrayObservers(); this.containingView.on('willClearRender', function() { self.destroy(); }); }; GroupedEach.prototype = { contentWillChange: function() { this.removeArrayObservers(); }, contentDidChange: function() { this.content = this.lookupContent(); this.addArrayObservers(); this.rerenderContainingView(); }, contentArrayWillChange: Ember.K, contentArrayDidChange: function() { this.rerenderContainingView(); }, lookupContent: function() { return Ember.Handlebars.get(this.normalizedRoot, this.normalizedPath, this.options); }, addArrayObservers: function() { this.content.addArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); }, removeArrayObservers: function() { this.content.removeArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); }, addContentObservers: function() { Ember.addBeforeObserver(this.normalizedRoot, this.normalizedPath, this, this.contentWillChange); Ember.addObserver(this.normalizedRoot, this.normalizedPath, this, this.contentDidChange); }, removeContentObservers: function() { Ember.removeBeforeObserver(this.normalizedRoot, this.normalizedPath, this.contentWillChange); Ember.removeObserver(this.normalizedRoot, this.normalizedPath, this.contentDidChange); }, render: function() { var content = this.content, contentLength = get(content, 'length'), data = this.options.data, template = this.template; data.insideEach = true; for (var i = 0; i < contentLength; i++) { template(content.objectAt(i), { data: data }); } }, rerenderContainingView: function() { Ember.run.scheduleOnce('render', this.containingView, 'rerender'); }, destroy: function() { this.removeContentObservers(); this.removeArrayObservers(); } }; /** The `{{#each}}` helper loops over elements in a collection, rendering its block once for each item: ```javascript Developers = [{name: 'Yehuda'},{name: 'Tom'}, {name: 'Paul'}]; ``` ```handlebars {{#each Developers}} {{name}} {{/each}} ``` `{{each}}` supports an alternative syntax with element naming: ```handlebars {{#each person in Developers}} {{person.name}} {{/each}} ``` When looping over objects that do not have properties, `{{this}}` can be used to render the object: ```javascript DeveloperNames = ['Yehuda', 'Tom', 'Paul'] ``` ```handlebars {{#each DeveloperNames}} {{this}} {{/each}} ``` ### Blockless Use If you provide an `itemViewClass` option that has its own `template` you can omit the block in a similar way to how it can be done with the collection helper. The following template: ```handlebars {{#view App.MyView }} {{each view.items itemViewClass="App.AnItemView"}} {{/view}} ``` And application code ```javascript App = Ember.Application.create({ MyView: Ember.View.extend({ items: [ Ember.Object.create({name: 'Dave'}), Ember.Object.create({name: 'Mary'}), Ember.Object.create({name: 'Sara'}) ] }) }); App.AnItemView = Ember.View.extend({ template: Ember.Handlebars.compile("Greetings {{name}}") }); App.initialize(); ``` Will result in the HTML structure below ```html <div class="ember-view"> <div class="ember-view">Greetings Dave</div> <div class="ember-view">Greetings Mary</div> <div class="ember-view">Greetings Sara</div> </div> ``` @method each @for Ember.Handlebars.helpers @param [name] {String} name for item (used with `in`) @param path {String} path */ Ember.Handlebars.registerHelper('each', function(path, options) { if (arguments.length === 4) { Ember.assert("If you pass more than one argument to the each helper, it must be in the form #each foo in bar", arguments[1] === "in"); var keywordName = arguments[0]; options = arguments[3]; path = arguments[2]; if (path === '') { path = "this"; } options.hash.keyword = keywordName; } else { options.hash.eachHelper = 'each'; } options.hash.contentBinding = path; // Set up emptyView as a metamorph with no tag //options.hash.emptyViewClass = Ember._MetamorphView; if (options.data.insideGroup && !options.hash.groupedRows && !options.hash.itemViewClass) { new Ember.Handlebars.GroupedEach(this, path, options).render(); } else { return Ember.Handlebars.helpers.collection.call(this, 'Ember.Handlebars.EachView', options); } }); })(); (function() { /** @module ember @submodule ember-handlebars */ /** `template` allows you to render a template from inside another template. This allows you to re-use the same template in multiple places. For example: ```html <script type="text/x-handlebars" data-template-name="logged_in_user"> {{#with loggedInUser}} Last Login: {{lastLogin}} User Info: {{template "user_info"}} {{/with}} </script> ``` ```html <script type="text/x-handlebars" data-template-name="user_info"> Name: <em>{{name}}</em> Karma: <em>{{karma}}</em> </script> ``` This helper looks for templates in the global `Ember.TEMPLATES` hash. If you add `<script>` tags to your page with the `data-template-name` attribute set, they will be compiled and placed in this hash automatically. You can also manually register templates by adding them to the hash: ```javascript Ember.TEMPLATES["my_cool_template"] = Ember.Handlebars.compile('<b>{{user}}</b>'); ``` @method template @for Ember.Handlebars.helpers @param {String} templateName the template to render */ Ember.Handlebars.registerHelper('template', function(name, options) { var template = Ember.TEMPLATES[name]; Ember.assert("Unable to find template with name '"+name+"'.", !!template); Ember.TEMPLATES[name](this, { data: options.data }); }); Ember.Handlebars.registerHelper('partial', function(name, options) { var nameParts = name.split("/"), lastPart = nameParts[nameParts.length - 1]; nameParts[nameParts.length - 1] = "_" + lastPart; var underscoredName = nameParts.join("/"); var template = Ember.TEMPLATES[underscoredName], deprecatedTemplate = Ember.TEMPLATES[name]; Ember.deprecate("You tried to render the partial " + name + ", which should be at '" + underscoredName + "', but Ember found '" + name + "'. Please use a leading underscore in your partials", template); Ember.assert("Unable to find partial with name '"+name+"'.", template || deprecatedTemplate); template = template || deprecatedTemplate; template(this, { data: options.data }); }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** When used in a Handlebars template that is assigned to an `Ember.View` instance's `layout` property Ember will render the layout template first, inserting the view's own rendered output at the `{{yield}}` location. An empty `<body>` and the following application code: ```javascript AView = Ember.View.extend({ classNames: ['a-view-with-layout'], layout: Ember.Handlebars.compile('<div class="wrapper">{{yield}}</div>'), template: Ember.Handlebars.compile('<span>I am wrapped</span>') }); aView = AView.create(); aView.appendTo('body'); ``` Will result in the following HTML output: ```html <body> <div class='ember-view a-view-with-layout'> <div class="wrapper"> <span>I am wrapped</span> </div> </div> </body> ``` The `yield` helper cannot be used outside of a template assigned to an `Ember.View`'s `layout` property and will throw an error if attempted. ```javascript BView = Ember.View.extend({ classNames: ['a-view-with-layout'], template: Ember.Handlebars.compile('{{yield}}') }); bView = BView.create(); bView.appendTo('body'); // throws // Uncaught Error: assertion failed: You called yield in a template that was not a layout ``` @method yield @for Ember.Handlebars.helpers @param {Hash} options @return {String} HTML string */ Ember.Handlebars.registerHelper('yield', function(options) { var view = options.data.view, template; while (view && !get(view, 'layout')) { view = get(view, 'parentView'); } Ember.assert("You called yield in a template that was not a layout", !!view); template = get(view, 'template'); if (template) { template(this, options); } }); })(); (function() { })(); (function() { })(); (function() { /** @module ember @submodule ember-handlebars */ var set = Ember.set, get = Ember.get; /** The `Ember.Checkbox` view class renders a checkbox [input](https://developer.mozilla.org/en/HTML/Element/Input) element. It allows for binding an Ember property (`checked`) to the status of the checkbox. Example: ```handlebars {{view Ember.Checkbox checkedBinding="receiveEmail"}} ``` You can add a `label` tag yourself in the template where the `Ember.Checkbox` is being used. ```html <label> {{view Ember.Checkbox classNames="applicaton-specific-checkbox"}} Some Title </label> ``` The `checked` attribute of an `Ember.Checkbox` object should always be set through the Ember object or by interacting with its rendered element representation via the mouse, keyboard, or touch. Updating the value of the checkbox via jQuery will result in the checked value of the object and its element losing synchronization. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See `Ember.View`'s layout section for more information. @class Checkbox @namespace Ember @extends Ember.View */ Ember.Checkbox = Ember.View.extend({ classNames: ['ember-checkbox'], tagName: 'input', attributeBindings: ['type', 'checked', 'disabled', 'tabindex'], type: "checkbox", checked: false, disabled: false, init: function() { this._super(); this.on("change", this, this._updateElementValue); }, _updateElementValue: function() { set(this, 'checked', this.$().prop('checked')); } }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** Shared mixin used by `Ember.TextField` and `Ember.TextArea`. @class TextSupport @namespace Ember @extends Ember.Mixin @private */ Ember.TextSupport = Ember.Mixin.create({ value: "", attributeBindings: ['placeholder', 'disabled', 'maxlength', 'tabindex'], placeholder: null, disabled: false, maxlength: null, insertNewline: Ember.K, cancel: Ember.K, init: function() { this._super(); this.on("focusOut", this, this._elementValueDidChange); this.on("change", this, this._elementValueDidChange); this.on("paste", this, this._elementValueDidChange); this.on("cut", this, this._elementValueDidChange); this.on("input", this, this._elementValueDidChange); this.on("keyUp", this, this.interpretKeyEvents); }, interpretKeyEvents: function(event) { var map = Ember.TextSupport.KEY_EVENTS; var method = map[event.keyCode]; this._elementValueDidChange(); if (method) { return this[method](event); } }, _elementValueDidChange: function() { set(this, 'value', this.$().val()); } }); Ember.TextSupport.KEY_EVENTS = { 13: 'insertNewline', 27: 'cancel' }; })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** The `Ember.TextField` view class renders a text [input](https://developer.mozilla.org/en/HTML/Element/Input) element. It allows for binding Ember properties to the text field contents (`value`), live-updating as the user inputs text. Example: ```handlebars {{view Ember.TextField valueBinding="firstName"}} ``` ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See `Ember.View`'s layout section for more information. ## HTML Attributes By default `Ember.TextField` provides support for `type`, `value`, `size`, `placeholder`, `disabled`, `maxlength` and `tabindex` attributes on a test field. If you need to support more attributes have a look at the `attributeBindings` property in `Ember.View`'s HTML Attributes section. To globally add support for additional attributes you can reopen `Ember.TextField` or `Ember.TextSupport`. ```javascript Ember.TextSupport.reopen({ attributeBindings: ["required"] }) ``` @class TextField @namespace Ember @extends Ember.View @uses Ember.TextSupport */ Ember.TextField = Ember.View.extend(Ember.TextSupport, /** @scope Ember.TextField.prototype */ { classNames: ['ember-text-field'], tagName: "input", attributeBindings: ['type', 'value', 'size'], /** The `value` attribute of the input element. As the user inputs text, this property is updated live. @property value @type String @default "" */ value: "", /** The `type` attribute of the input element. @property type @type String @default "text" */ type: "text", /** The `size` of the text field in characters. @property size @type String @default null */ size: null, /** The action to be sent when the user presses the return key. This is similar to the `{{action}}` helper, but is fired when the user presses the return key when editing a text field, and sends the value of the field as the context. @property action @type String @default null */ action: null, insertNewline: function() { var controller = get(this, 'controller'), action = get(this, 'action'); if (action) { controller.send(action, get(this, 'value')); } return false; } }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** @class Button @namespace Ember @extends Ember.View @uses Ember.TargetActionSupport @deprecated */ Ember.Button = Ember.View.extend(Ember.TargetActionSupport, { classNames: ['ember-button'], classNameBindings: ['isActive'], tagName: 'button', propagateEvents: false, attributeBindings: ['type', 'disabled', 'href', 'tabindex'], /** @private Overrides `TargetActionSupport`'s `targetObject` computed property to use Handlebars-specific path resolution. @property targetObject */ targetObject: Ember.computed(function() { var target = get(this, 'target'), root = get(this, 'context'), data = get(this, 'templateData'); if (typeof target !== 'string') { return target; } return Ember.Handlebars.get(root, target, { data: data }); }).property('target'), // Defaults to 'button' if tagName is 'input' or 'button' type: Ember.computed(function(key) { var tagName = this.tagName; if (tagName === 'input' || tagName === 'button') { return 'button'; } }), disabled: false, // Allow 'a' tags to act like buttons href: Ember.computed(function() { return this.tagName === 'a' ? '#' : null; }), mouseDown: function() { if (!get(this, 'disabled')) { set(this, 'isActive', true); this._mouseDown = true; this._mouseEntered = true; } return get(this, 'propagateEvents'); }, mouseLeave: function() { if (this._mouseDown) { set(this, 'isActive', false); this._mouseEntered = false; } }, mouseEnter: function() { if (this._mouseDown) { set(this, 'isActive', true); this._mouseEntered = true; } }, mouseUp: function(event) { if (get(this, 'isActive')) { // Actually invoke the button's target and action. // This method comes from the Ember.TargetActionSupport mixin. this.triggerAction(); set(this, 'isActive', false); } this._mouseDown = false; this._mouseEntered = false; return get(this, 'propagateEvents'); }, keyDown: function(event) { // Handle space or enter if (event.keyCode === 13 || event.keyCode === 32) { this.mouseDown(); } }, keyUp: function(event) { // Handle space or enter if (event.keyCode === 13 || event.keyCode === 32) { this.mouseUp(); } }, // TODO: Handle proper touch behavior. Including should make inactive when // finger moves more than 20x outside of the edge of the button (vs mouse // which goes inactive as soon as mouse goes out of edges.) touchStart: function(touch) { return this.mouseDown(touch); }, touchEnd: function(touch) { return this.mouseUp(touch); }, init: function() { Ember.deprecate("Ember.Button is deprecated and will be removed from future releases. Consider using the `{{action}}` helper."); this._super(); } }); })(); (function() { /** @module ember @submodule ember-handlebars */ var get = Ember.get, set = Ember.set; /** The `Ember.TextArea` view class renders a [textarea](https://developer.mozilla.org/en/HTML/Element/textarea) element. It allows for binding Ember properties to the text area contents (`value`), live-updating as the user inputs text. ## Layout and LayoutName properties Because HTML `textarea` elements do not contain inner HTML the `layout` and `layoutName` properties will not be applied. See `Ember.View`'s layout section for more information. ## HTML Attributes By default `Ember.TextArea` provides support for `rows`, `cols`, `placeholder`, `disabled`, `maxlength` and `tabindex` attributes on a textarea. If you need to support more attributes have a look at the `attributeBindings` property in `Ember.View`'s HTML Attributes section. To globally add support for additional attributes you can reopen `Ember.TextArea` or `Ember.TextSupport`. ```javascript Ember.TextSupport.reopen({ attributeBindings: ["required"] }) ``` @class TextArea @namespace Ember @extends Ember.View @uses Ember.TextSupport */ Ember.TextArea = Ember.View.extend(Ember.TextSupport, { classNames: ['ember-text-area'], tagName: "textarea", attributeBindings: ['rows', 'cols'], rows: null, cols: null, _updateElementValue: Ember.observer(function() { // We do this check so cursor position doesn't get affected in IE var value = get(this, 'value'), $el = this.$(); if ($el && value !== $el.val()) { $el.val(value); } }, 'value'), init: function() { this._super(); this.on("didInsertElement", this, this._updateElementValue); } }); })(); (function() { /*jshint eqeqeq:false */ /** @module ember @submodule ember-handlebars */ var set = Ember.set, get = Ember.get, indexOf = Ember.EnumerableUtils.indexOf, indexesOf = Ember.EnumerableUtils.indexesOf, replace = Ember.EnumerableUtils.replace, isArray = Ember.isArray, precompileTemplate = Ember.Handlebars.compile; /** The `Ember.Select` view class renders a [select](https://developer.mozilla.org/en/HTML/Element/select) HTML element, allowing the user to choose from a list of options. The text and `value` property of each `<option>` element within the `<select>` element are populated from the objects in the `Element.Select`'s `content` property. The underlying data object of the selected `<option>` is stored in the `Element.Select`'s `value` property. ### `content` as an array of Strings The simplest version of an `Ember.Select` takes an array of strings as its `content` property. The string will be used as both the `value` property and the inner text of each `<option>` element inside the rendered `<select>`. Example: ```javascript App.names = ["Yehuda", "Tom"]; ``` ```handlebars {{view Ember.Select contentBinding="App.names"}} ``` Would result in the following HTML: ```html <select class="ember-select"> <option value="Yehuda">Yehuda</option> <option value="Tom">Tom</option> </select> ``` You can control which `<option>` is selected through the `Ember.Select`'s `value` property directly or as a binding: ```javascript App.names = Ember.Object.create({ selected: 'Tom', content: ["Yehuda", "Tom"] }); ``` ```handlebars {{view Ember.Select contentBinding="App.names.content" valueBinding="App.names.selected" }} ``` Would result in the following HTML with the `<option>` for 'Tom' selected: ```html <select class="ember-select"> <option value="Yehuda">Yehuda</option> <option value="Tom" selected="selected">Tom</option> </select> ``` A user interacting with the rendered `<select>` to choose "Yehuda" would update the value of `App.names.selected` to "Yehuda". ### `content` as an Array of Objects An `Ember.Select` can also take an array of JavaScript or Ember objects as its `content` property. When using objects you need to tell the `Ember.Select` which property should be accessed on each object to supply the `value` attribute of the `<option>` and which property should be used to supply the element text. The `optionValuePath` option is used to specify the path on each object to the desired property for the `value` attribute. The `optionLabelPath` specifies the path on each object to the desired property for the element's text. Both paths must reference each object itself as `content`: ```javascript App.programmers = [ Ember.Object.create({firstName: "Yehuda", id: 1}), Ember.Object.create({firstName: "Tom", id: 2}) ]; ``` ```handlebars {{view Ember.Select contentBinding="App.programmers" optionValuePath="content.id" optionLabelPath="content.firstName"}} ``` Would result in the following HTML: ```html <select class="ember-select"> <option value>Please Select</option> <option value="1">Yehuda</option> <option value="2">Tom</option> </select> ``` The `value` attribute of the selected `<option>` within an `Ember.Select` can be bound to a property on another object by providing a `valueBinding` option: ```javascript App.programmers = [ Ember.Object.create({firstName: "Yehuda", id: 1}), Ember.Object.create({firstName: "Tom", id: 2}) ]; App.currentProgrammer = Ember.Object.create({ id: 2 }); ``` ```handlebars {{view Ember.Select contentBinding="App.programmers" optionValuePath="content.id" optionLabelPath="content.firstName" valueBinding="App.currentProgrammer.id"}} ``` Would result in the following HTML with a selected option: ```html <select class="ember-select"> <option value>Please Select</option> <option value="1">Yehuda</option> <option value="2" selected="selected">Tom</option> </select> ``` Interacting with the rendered element by selecting the first option ('Yehuda') will update the `id` value of `App.currentProgrammer` to match the `value` property of the newly selected `<option>`. Alternatively, you can control selection through the underlying objects used to render each object providing a `selectionBinding`. When the selected `<option>` is changed, the property path provided to `selectionBinding` will be updated to match the content object of the rendered `<option>` element: ```javascript App.controller = Ember.Object.create({ selectedPerson: null, content: [ Ember.Object.create({firstName: "Yehuda", id: 1}), Ember.Object.create({firstName: "Tom", id: 2}) ] }); ``` ```handlebars {{view Ember.Select contentBinding="App.controller.content" optionValuePath="content.id" optionLabelPath="content.firstName" selectionBinding="App.controller.selectedPerson"}} ``` Would result in the following HTML with a selected option: ```html <select class="ember-select"> <option value>Please Select</option> <option value="1">Yehuda</option> <option value="2" selected="selected">Tom</option> </select> ``` Interacting with the rendered element by selecting the first option ('Yehuda') will update the `selectedPerson` value of `App.controller` to match the content object of the newly selected `<option>`. In this case it is the first object in the `App.content.content` ### Supplying a Prompt A `null` value for the `Ember.Select`'s `value` or `selection` property results in there being no `<option>` with a `selected` attribute: ```javascript App.controller = Ember.Object.create({ selected: null, content: [ "Yehuda", "Tom" ] }); ``` ``` handlebars {{view Ember.Select contentBinding="App.controller.content" valueBinding="App.controller.selected" }} ``` Would result in the following HTML: ```html <select class="ember-select"> <option value="Yehuda">Yehuda</option> <option value="Tom">Tom</option> </select> ``` Although `App.controller.selected` is `null` and no `<option>` has a `selected` attribute the rendered HTML will display the first item as though it were selected. You can supply a string value for the `Ember.Select` to display when there is no selection with the `prompt` option: ```javascript App.controller = Ember.Object.create({ selected: null, content: [ "Yehuda", "Tom" ] }); ``` ```handlebars {{view Ember.Select contentBinding="App.controller.content" valueBinding="App.controller.selected" prompt="Please select a name" }} ``` Would result in the following HTML: ```html <select class="ember-select"> <option>Please select a name</option> <option value="Yehuda">Yehuda</option> <option value="Tom">Tom</option> </select> ``` @class Select @namespace Ember @extends Ember.View */ Ember.Select = Ember.View.extend( /** @scope Ember.Select.prototype */ { tagName: 'select', classNames: ['ember-select'], defaultTemplate: Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) { helpers = helpers || Ember.Handlebars.helpers; data = data || {}; var buffer = '', stack1, escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = '', stack1; data.buffer.push("<option value=\"\">"); stack1 = helpers._triageMustache.call(depth0, "view.prompt", {hash:{},contexts:[depth0],data:data}); data.buffer.push(escapeExpression(stack1) + "</option>"); return buffer;} function program3(depth0,data) { var stack1; stack1 = {}; stack1['contentBinding'] = "this"; stack1 = helpers.view.call(depth0, "Ember.SelectOption", {hash:stack1,contexts:[depth0],data:data}); data.buffer.push(escapeExpression(stack1));} stack1 = helpers['if'].call(depth0, "view.prompt", {hash:{},inverse:self.noop,fn:self.program(1, program1, data),contexts:[depth0],data:data}); if(stack1 || stack1 === 0) { data.buffer.push(stack1); } stack1 = helpers.each.call(depth0, "view.content", {hash:{},inverse:self.noop,fn:self.program(3, program3, data),contexts:[depth0],data:data}); if(stack1 || stack1 === 0) { data.buffer.push(stack1); } return buffer; }), attributeBindings: ['multiple', 'disabled', 'tabindex'], /** The `multiple` attribute of the select element. Indicates whether multiple options can be selected. @property multiple @type Boolean @default false */ multiple: false, disabled: false, /** The list of options. If `optionLabelPath` and `optionValuePath` are not overridden, this should be a list of strings, which will serve simultaneously as labels and values. Otherwise, this should be a list of objects. For instance: ```javascript Ember.Select.create({ content: Ember.A([ { id: 1, firstName: 'Yehuda' }, { id: 2, firstName: 'Tom' } ]), optionLabelPath: 'content.firstName', optionValuePath: 'content.id' }); ``` @property content @type Array @default null */ content: null, /** When `multiple` is `false`, the element of `content` that is currently selected, if any. When `multiple` is `true`, an array of such elements. @property selection @type Object or Array @default null */ selection: null, /** In single selection mode (when `multiple` is `false`), value can be used to get the current selection's value or set the selection by it's value. It is not currently supported in multiple selection mode. @property value @type String @default null */ value: Ember.computed(function(key, value) { if (arguments.length === 2) { return value; } var valuePath = get(this, 'optionValuePath').replace(/^content\.?/, ''); return valuePath ? get(this, 'selection.' + valuePath) : get(this, 'selection'); }).property('selection'), /** If given, a top-most dummy option will be rendered to serve as a user prompt. @property prompt @type String @default null */ prompt: null, /** The path of the option labels. See `content`. @property optionLabelPath @type String @default 'content' */ optionLabelPath: 'content', /** The path of the option values. See `content`. @property optionValuePath @type String @default 'content' */ optionValuePath: 'content', _change: function() { if (get(this, 'multiple')) { this._changeMultiple(); } else { this._changeSingle(); } }, selectionDidChange: Ember.observer(function() { var selection = get(this, 'selection'); if (get(this, 'multiple')) { if (!isArray(selection)) { set(this, 'selection', Ember.A([selection])); return; } this._selectionDidChangeMultiple(); } else { this._selectionDidChangeSingle(); } }, 'selection.@each'), valueDidChange: Ember.observer(function() { var content = get(this, 'content'), value = get(this, 'value'), valuePath = get(this, 'optionValuePath').replace(/^content\.?/, ''), selectedValue = (valuePath ? get(this, 'selection.' + valuePath) : get(this, 'selection')), selection; if (value !== selectedValue) { selection = content.find(function(obj) { return value === (valuePath ? get(obj, valuePath) : obj); }); this.set('selection', selection); } }, 'value'), _triggerChange: function() { var selection = get(this, 'selection'); var value = get(this, 'value'); if (selection) { this.selectionDidChange(); } if (value) { this.valueDidChange(); } this._change(); }, _changeSingle: function() { var selectedIndex = this.$()[0].selectedIndex, content = get(this, 'content'), prompt = get(this, 'prompt'); if (!get(content, 'length')) { return; } if (prompt && selectedIndex === 0) { set(this, 'selection', null); return; } if (prompt) { selectedIndex -= 1; } set(this, 'selection', content.objectAt(selectedIndex)); }, _changeMultiple: function() { var options = this.$('option:selected'), prompt = get(this, 'prompt'), offset = prompt ? 1 : 0, content = get(this, 'content'), selection = get(this, 'selection'); if (!content){ return; } if (options) { var selectedIndexes = options.map(function(){ return this.index - offset; }).toArray(); var newSelection = content.objectsAt(selectedIndexes); if (isArray(selection)) { replace(selection, 0, get(selection, 'length'), newSelection); } else { set(this, 'selection', newSelection); } } }, _selectionDidChangeSingle: function() { var el = this.get('element'); if (!el) { return; } var content = get(this, 'content'), selection = get(this, 'selection'), selectionIndex = content ? indexOf(content, selection) : -1, prompt = get(this, 'prompt'); if (prompt) { selectionIndex += 1; } if (el) { el.selectedIndex = selectionIndex; } }, _selectionDidChangeMultiple: function() { var content = get(this, 'content'), selection = get(this, 'selection'), selectedIndexes = content ? indexesOf(content, selection) : [-1], prompt = get(this, 'prompt'), offset = prompt ? 1 : 0, options = this.$('option'), adjusted; if (options) { options.each(function() { adjusted = this.index > -1 ? this.index - offset : -1; this.selected = indexOf(selectedIndexes, adjusted) > -1; }); } }, init: function() { this._super(); this.on("didInsertElement", this, this._triggerChange); this.on("change", this, this._change); } }); Ember.SelectOption = Ember.View.extend({ tagName: 'option', attributeBindings: ['value', 'selected'], defaultTemplate: function(context, options) { options = { data: options.data, hash: {} }; Ember.Handlebars.helpers.bind.call(context, "view.label", options); }, init: function() { this.labelPathDidChange(); this.valuePathDidChange(); this._super(); }, selected: Ember.computed(function() { var content = get(this, 'content'), selection = get(this, 'parentView.selection'); if (get(this, 'parentView.multiple')) { return selection && indexOf(selection, content.valueOf()) > -1; } else { // Primitives get passed through bindings as objects... since // `new Number(4) !== 4`, we use `==` below return content == selection; } }).property('content', 'parentView.selection').volatile(), labelPathDidChange: Ember.observer(function() { var labelPath = get(this, 'parentView.optionLabelPath'); if (!labelPath) { return; } Ember.defineProperty(this, 'label', Ember.computed(function() { return get(this, labelPath); }).property(labelPath)); }, 'parentView.optionLabelPath'), valuePathDidChange: Ember.observer(function() { var valuePath = get(this, 'parentView.optionValuePath'); if (!valuePath) { return; } Ember.defineProperty(this, 'value', Ember.computed(function() { return get(this, valuePath); }).property(valuePath)); }, 'parentView.optionValuePath') }); })(); (function() { })(); (function() { /*globals Handlebars */ /** @module ember @submodule ember-handlebars */ /** @private Find templates stored in the head tag as script tags and make them available to `Ember.CoreView` in the global `Ember.TEMPLATES` object. This will be run as as jQuery DOM-ready callback. Script tags with `text/x-handlebars` will be compiled with Ember's Handlebars and are suitable for use as a view's template. Those with type `text/x-raw-handlebars` will be compiled with regular Handlebars and are suitable for use in views' computed properties. @method bootstrap @for Ember.Handlebars @static @param ctx */ Ember.Handlebars.bootstrap = function(ctx) { var selectors = 'script[type="text/x-handlebars"], script[type="text/x-raw-handlebars"]'; Ember.$(selectors, ctx) .each(function() { // Get a reference to the script tag var script = Ember.$(this), type = script.attr('type'); var compile = (script.attr('type') === 'text/x-raw-handlebars') ? Ember.$.proxy(Handlebars.compile, Handlebars) : Ember.$.proxy(Ember.Handlebars.compile, Ember.Handlebars), // Get the name of the script, used by Ember.View's templateName property. // First look for data-template-name attribute, then fall back to its // id if no name is found. templateName = script.attr('data-template-name') || script.attr('id') || 'application', template = compile(script.html()); // For templates which have a name, we save them and then remove them from the DOM Ember.TEMPLATES[templateName] = template; // Remove script tag from DOM script.remove(); }); }; function bootstrap() { Ember.Handlebars.bootstrap( Ember.$(document) ); } /* We tie this to application.load to ensure that we've at least attempted to bootstrap at the point that the application is loaded. We also tie this to document ready since we're guaranteed that all the inline templates are present at this point. There's no harm to running this twice, since we remove the templates from the DOM after processing. */ Ember.onLoad('application', bootstrap); })(); (function() { /** Ember Handlebars @module ember @submodule ember-handlebars @requires ember-views */ Ember.runLoadHooks('Ember.Handlebars', Ember.Handlebars); })(); (function() { define("route-recognizer", [], function() { "use strict"; var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat function StaticSegment(string) { this.string = string; } StaticSegment.prototype = { eachChar: function(callback) { var string = this.string, char; for (var i=0, l=string.length; i<l; i++) { char = string.charAt(i); callback({ validChars: char }); } }, regex: function() { return this.string.replace(escapeRegex, '\\$1'); }, generate: function() { return this.string; } }; function DynamicSegment(name) { this.name = name; } DynamicSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "/", repeat: true }); }, regex: function() { return "([^/]+)"; }, generate: function(params) { return params[this.name]; } }; function StarSegment(name) { this.name = name; } StarSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "", repeat: true }); }, regex: function() { return "(.+)"; }, generate: function(params) { return params[this.name]; } }; function EpsilonSegment() {} EpsilonSegment.prototype = { eachChar: function() {}, regex: function() { return ""; }, generate: function() { return ""; } }; function parse(route, names, types) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.charAt(0) === "/") { route = route.substr(1); } var segments = route.split("/"), results = []; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i], match; if (match = segment.match(/^:([^\/]+)$/)) { results.push(new DynamicSegment(match[1])); names.push(match[1]); types.dynamics++; } else if (match = segment.match(/^\*([^\/]+)$/)) { results.push(new StarSegment(match[1])); names.push(match[1]); types.stars++; } else if(segment === "") { results.push(new EpsilonSegment()); } else { results.push(new StaticSegment(segment)); types.statics++; } } return results; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. function State(charSpec) { this.charSpec = charSpec; this.nextStates = []; } State.prototype = { get: function(charSpec) { var nextStates = this.nextStates; for (var i=0, l=nextStates.length; i<l; i++) { var child = nextStates[i]; var isEqual = child.charSpec.validChars === charSpec.validChars; isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } }, put: function(charSpec) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(charSpec)) { return state; } // Make a new state for the character spec state = new State(charSpec); // Insert the new state as a child of the current state this.nextStates.push(state); // If this character specification repeats, insert the new state as a child // of itself. Note that this will not trigger an infinite loop because each // transition during recognition consumes a character. if (charSpec.repeat) { state.nextStates.push(state); } // Return the new state return state; }, // Find a list of child states matching the next character match: function(char) { // DEBUG "Processing `" + char + "`:" var nextStates = this.nextStates, child, charSpec, chars; // DEBUG " " + debugState(this) var returned = []; for (var i=0, l=nextStates.length; i<l; i++) { child = nextStates[i]; charSpec = child.charSpec; if (typeof (chars = charSpec.validChars) !== 'undefined') { if (chars.indexOf(char) !== -1) { returned.push(child); } } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { if (chars.indexOf(char) === -1) { returned.push(child); } } } return returned; } /** IF DEBUG , debug: function() { var charSpec = this.charSpec, debug = "[", chars = charSpec.validChars || charSpec.invalidChars; if (charSpec.invalidChars) { debug += "^"; } debug += chars; debug += "]"; if (charSpec.repeat) { debug += "+"; } return debug; } END IF **/ }; /** IF DEBUG function debug(log) { console.log(log); } function debugState(state) { return state.nextStates.map(function(n) { if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; } return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; }).join(", ") } END IF **/ // This is a somewhat naive strategy, but should work in a lot of cases // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id function sortSolutions(states) { return states.sort(function(a, b) { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return a.types.statics - b.types.statics; } return 0; }); } function recognizeChar(states, char) { var nextStates = []; for (var i=0, l=states.length; i<l; i++) { var state = states[i]; nextStates = nextStates.concat(state.match(char)); } return nextStates; } function findHandler(state, path) { var handlers = state.handlers, regex = state.regex; var captures = path.match(regex), currentCapture = 1; var result = []; for (var i=0, l=handlers.length; i<l; i++) { var handler = handlers[i], names = handler.names, params = {}; for (var j=0, m=names.length; j<m; j++) { params[names[j]] = captures[currentCapture++]; } result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); } return result; } function addSegment(currentState, segment) { segment.eachChar(function(char) { var state; currentState = currentState.put(char); }); return currentState; } // The main interface var RouteRecognizer = function() { this.rootState = new State(); this.names = {}; }; RouteRecognizer.prototype = { add: function(routes, options) { var currentState = this.rootState, regex = "^", types = { statics: 0, dynamics: 0, stars: 0 }, handlers = [], allSegments = [], name; var isEmpty = true; for (var i=0, l=routes.length; i<l; i++) { var route = routes[i], names = []; var segments = parse(route.path, names, types); allSegments = allSegments.concat(segments); for (var j=0, m=segments.length; j<m; j++) { var segment = segments[j]; if (segment instanceof EpsilonSegment) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put({ validChars: "/" }); regex += "/"; // Add a representation of the segment to the NFA and regex currentState = addSegment(currentState, segment); regex += segment.regex(); } handlers.push({ handler: route.handler, names: names }); } if (isEmpty) { currentState = currentState.put({ validChars: "/" }); regex += "/"; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + "$"); currentState.types = types; if (name = options && options.as) { this.names[name] = { segments: allSegments, handlers: handlers }; } }, handlersFor: function(name) { var route = this.names[name], result = []; if (!route) { throw new Error("There is no route named " + name); } for (var i=0, l=route.handlers.length; i<l; i++) { result.push(route.handlers[i]); } return result; }, hasRoute: function(name) { return !!this.names[name]; }, generate: function(name, params) { var route = this.names[name], output = ""; if (!route) { throw new Error("There is no route named " + name); } var segments = route.segments; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } output += "/"; output += segment.generate(params); } if (output.charAt(0) !== '/') { output = '/' + output; } return output; }, recognize: function(path) { var states = [ this.rootState ], i, l; // DEBUG GROUP path var pathLen = path.length; if (path.charAt(0) !== "/") { path = "/" + path; } if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); } for (i=0, l=path.length; i<l; i++) { states = recognizeChar(states, path.charAt(i)); if (!states.length) { break; } } // END DEBUG GROUP var solutions = []; for (i=0, l=states.length; i<l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { return findHandler(state, path); } } }; function Target(path, matcher, delegate) { this.path = path; this.matcher = matcher; this.delegate = delegate; } Target.prototype = { to: function(target, callback) { var delegate = this.delegate; if (delegate && delegate.willAddRoute) { target = delegate.willAddRoute(this.matcher.target, target); } this.matcher.add(this.path, target); if (callback) { if (callback.length === 0) { throw new Error("You must have an argument in the function passed to `to`"); } this.matcher.addChild(this.path, target, callback, this.delegate); } } }; function Matcher(target) { this.routes = {}; this.children = {}; this.target = target; } Matcher.prototype = { add: function(path, handler) { this.routes[path] = handler; }, addChild: function(path, target, callback, delegate) { var matcher = new Matcher(target); this.children[path] = matcher; var match = generateMatch(path, matcher, delegate); if (delegate && delegate.contextEntered) { delegate.contextEntered(target, match); } callback(match); } }; function generateMatch(startingPath, matcher, delegate) { return function(path, nestedCallback) { var fullPath = startingPath + path; if (nestedCallback) { nestedCallback(generateMatch(fullPath, matcher, delegate)); } else { return new Target(startingPath + path, matcher, delegate); } }; } function addRoute(routeArray, path, handler) { var len = 0; for (var i=0, l=routeArray.length; i<l; i++) { len += routeArray[i].path.length; } path = path.substr(len); routeArray.push({ path: path, handler: handler }); } function eachRoute(baseRoute, matcher, callback, binding) { var routes = matcher.routes; for (var path in routes) { if (routes.hasOwnProperty(path)) { var routeArray = baseRoute.slice(); addRoute(routeArray, path, routes[path]); if (matcher.children[path]) { eachRoute(routeArray, matcher.children[path], callback, binding); } else { callback.call(binding, routeArray); } } } } RouteRecognizer.prototype.map = function(callback, addRouteCallback) { var matcher = new Matcher(); callback(generateMatch("", matcher, this.delegate)); eachRoute([], matcher, function(route) { if (addRouteCallback) { addRouteCallback(this, route); } else { this.add(route); } }, this); }; return RouteRecognizer; }); })(); (function() { define("router", ["route-recognizer"], function(RouteRecognizer) { "use strict"; /** @private This file references several internal structures: ## `RecognizedHandler` * `{String} handler`: A handler name * `{Object} params`: A hash of recognized parameters ## `UnresolvedHandlerInfo` * `{Boolean} isDynamic`: whether a handler has any dynamic segments * `{String} name`: the name of a handler * `{Object} context`: the active context for the handler ## `HandlerInfo` * `{Boolean} isDynamic`: whether a handler has any dynamic segments * `{String} name`: the original unresolved handler name * `{Object} handler`: a handler object * `{Object} context`: the active context for the handler */ function Router() { this.recognizer = new RouteRecognizer(); } Router.prototype = { /** The main entry point into the router. The API is essentially the same as the `map` method in `route-recognizer`. This method extracts the String handler at the last `.to()` call and uses it as the name of the whole route. @param {Function} callback */ map: function(callback) { this.recognizer.delegate = this.delegate; this.recognizer.map(callback, function(recognizer, route) { var lastHandler = route[route.length - 1].handler; var args = [route, { as: lastHandler }]; recognizer.add.apply(recognizer, args); }); }, hasRoute: function(route) { return this.recognizer.hasRoute(route); }, /** The entry point for handling a change to the URL (usually via the back and forward button). Returns an Array of handlers and the parameters associated with those parameters. @param {String} url a URL to process @return {Array} an Array of `[handler, parameter]` tuples */ handleURL: function(url) { var results = this.recognizer.recognize(url), objects = []; if (!results) { throw new Error("No route matched the URL '" + url + "'"); } collectObjects(this, results, 0, []); }, /** Hook point for updating the URL. @param {String} url a URL to update to */ updateURL: function() { throw "updateURL is not implemented"; }, /** Hook point for replacing the current URL, i.e. with replaceState By default this behaves the same as `updateURL` @param {String} url a URL to update to */ replaceURL: function(url) { this.updateURL(url); }, /** Transition into the specified named route. If necessary, trigger the exit callback on any handlers that are no longer represented by the target route. @param {String} name the name of the route */ transitionTo: function(name) { var args = Array.prototype.slice.call(arguments, 1); doTransition(this, name, this.updateURL, args); }, /** Identical to `transitionTo` except that the current URL will be replaced if possible. This method is intended primarily for use with `replaceState`. @param {String} name the name of the route */ replaceWith: function(name) { var args = Array.prototype.slice.call(arguments, 1); doTransition(this, name, this.replaceURL, args); }, /** @private This method takes a handler name and a list of contexts and returns a serialized parameter hash suitable to pass to `recognizer.generate()`. @param {String} handlerName @param {Array[Object]} contexts @return {Object} a serialized parameter hash */ paramsForHandler: function(handlerName, callback) { var output = this._paramsForHandler(handlerName, [].slice.call(arguments, 1)); return output.params; }, /** Take a named route and context objects and generate a URL. @param {String} name the name of the route to generate a URL for @param {...Object} objects a list of objects to serialize @return {String} a URL */ generate: function(handlerName) { var params = this.paramsForHandler.apply(this, arguments); return this.recognizer.generate(handlerName, params); }, /** @private Used internally by `generate` and `transitionTo`. */ _paramsForHandler: function(handlerName, objects, doUpdate) { var handlers = this.recognizer.handlersFor(handlerName), params = {}, toSetup = [], startIdx = handlers.length, objectsToMatch = objects.length, object, objectChanged, handlerObj, handler, names, i, len; // Find out which handler to start matching at for (i=handlers.length-1; i>=0 && objectsToMatch>0; i--) { if (handlers[i].names.length) { objectsToMatch--; startIdx = i; } } if (objectsToMatch > 0) { throw "More objects were passed than dynamic segments"; } // Connect the objects to the routes for (i=0, len=handlers.length; i<len; i++) { handlerObj = handlers[i]; handler = this.getHandler(handlerObj.handler); names = handlerObj.names; objectChanged = false; // If it's a dynamic segment if (names.length) { // If we have objects, use them if (i >= startIdx) { object = objects.shift(); objectChanged = true; // Otherwise use existing context } else { object = handler.context; } // Serialize to generate params if (handler.serialize) { merge(params, handler.serialize(object, names)); } // If it's not a dynamic segment and we're updating } else if (doUpdate) { // If we've passed the match point we need to deserialize again // or if we never had a context if (i > startIdx || !handler.hasOwnProperty('context')) { if (handler.deserialize) { object = handler.deserialize({}); objectChanged = true; } // Otherwise use existing context } else { object = handler.context; } } // Make sure that we update the context here so it's available to // subsequent deserialize calls if (doUpdate && objectChanged) { // TODO: It's a bit awkward to set the context twice, see if we can DRY things up setContext(handler, object); } toSetup.push({ isDynamic: !!handlerObj.names.length, handler: handlerObj.handler, name: handlerObj.name, context: object }); } return { params: params, toSetup: toSetup }; }, isActive: function(handlerName) { var contexts = [].slice.call(arguments, 1); var currentHandlerInfos = this.currentHandlerInfos, found = false, names, object, handlerInfo, handlerObj; for (var i=currentHandlerInfos.length-1; i>=0; i--) { handlerInfo = currentHandlerInfos[i]; if (handlerInfo.name === handlerName) { found = true; } if (found) { if (contexts.length === 0) { break; } if (handlerInfo.isDynamic) { object = contexts.pop(); if (handlerInfo.context !== object) { return false; } } } } return contexts.length === 0 && found; }, trigger: function(name) { var args = [].slice.call(arguments); trigger(this, args); } }; function merge(hash, other) { for (var prop in other) { if (other.hasOwnProperty(prop)) { hash[prop] = other[prop]; } } } function isCurrent(currentHandlerInfos, handlerName) { return currentHandlerInfos[currentHandlerInfos.length - 1].name === handlerName; } /** @private This function is called the first time the `collectObjects` function encounters a promise while converting URL parameters into objects. It triggers the `enter` and `setup` methods on the `loading` handler. @param {Router} router */ function loading(router) { if (!router.isLoading) { router.isLoading = true; var handler = router.getHandler('loading'); if (handler) { if (handler.enter) { handler.enter(); } if (handler.setup) { handler.setup(); } } } } /** @private This function is called if a promise was previously encountered once all promises are resolved. It triggers the `exit` method on the `loading` handler. @param {Router} router */ function loaded(router) { router.isLoading = false; var handler = router.getHandler('loading'); if (handler && handler.exit) { handler.exit(); } } /** @private This function is called if any encountered promise is rejected. It triggers the `exit` method on the `loading` handler, the `enter` method on the `failure` handler, and the `setup` method on the `failure` handler with the `error`. @param {Router} router @param {Object} error the reason for the promise rejection, to pass into the failure handler's `setup` method. */ function failure(router, error) { loaded(router); var handler = router.getHandler('failure'); if (handler && handler.setup) { handler.setup(error); } } /** @private */ function doTransition(router, name, method, args) { var output = router._paramsForHandler(name, args, true); var params = output.params, toSetup = output.toSetup; var url = router.recognizer.generate(name, params); method.call(router, url); setupContexts(router, toSetup); } /** @private This function is called after a URL change has been handled by `router.handleURL`. Takes an Array of `RecognizedHandler`s, and converts the raw params hashes into deserialized objects by calling deserialize on the handlers. This process builds up an Array of `HandlerInfo`s. It then calls `setupContexts` with the Array. If the `deserialize` method on a handler returns a promise (i.e. has a method called `then`), this function will pause building up the `HandlerInfo` Array until the promise is resolved. It will use the resolved value as the context of `HandlerInfo`. */ function collectObjects(router, results, index, objects) { if (results.length === index) { loaded(router); setupContexts(router, objects); return; } var result = results[index]; var handler = router.getHandler(result.handler); var object = handler.deserialize && handler.deserialize(result.params); if (object && typeof object.then === 'function') { loading(router); // The chained `then` means that we can also catch errors that happen in `proceed` object.then(proceed).then(null, function(error) { failure(router, error); }); } else { proceed(object); } function proceed(value) { if (handler.context !== object) { setContext(handler, object); } var updatedObjects = objects.concat([{ context: value, handler: result.handler, isDynamic: result.isDynamic }]); collectObjects(router, results, index + 1, updatedObjects); } } /** @private Takes an Array of `UnresolvedHandlerInfo`s, resolves the handler names into handlers, and then figures out what to do with each of the handlers. For example, consider the following tree of handlers. Each handler is followed by the URL segment it handles. ``` |~index ("/") | |~posts ("/posts") | | |-showPost ("/:id") | | |-newPost ("/new") | | |-editPost ("/edit") | |~about ("/about/:id") ``` Consider the following transitions: 1. A URL transition to `/posts/1`. 1. Triggers the `deserialize` callback on the `index`, `posts`, and `showPost` handlers 2. Triggers the `enter` callback on the same 3. Triggers the `setup` callback on the same 2. A direct transition to `newPost` 1. Triggers the `exit` callback on `showPost` 2. Triggers the `enter` callback on `newPost` 3. Triggers the `setup` callback on `newPost` 3. A direct transition to `about` with a specified context object 1. Triggers the `exit` callback on `newPost` and `posts` 2. Triggers the `serialize` callback on `about` 3. Triggers the `enter` callback on `about` 4. Triggers the `setup` callback on `about` @param {Router} router @param {Array[UnresolvedHandlerInfo]} handlerInfos */ function setupContexts(router, handlerInfos) { resolveHandlers(router, handlerInfos); var partition = partitionHandlers(router.currentHandlerInfos || [], handlerInfos); router.currentHandlerInfos = handlerInfos; eachHandler(partition.exited, function(handler, context) { delete handler.context; if (handler.exit) { handler.exit(); } }); eachHandler(partition.updatedContext, function(handler, context) { setContext(handler, context); if (handler.setup) { handler.setup(context); } }); eachHandler(partition.entered, function(handler, context) { if (handler.enter) { handler.enter(); } setContext(handler, context); if (handler.setup) { handler.setup(context); } }); if (router.didTransition) { router.didTransition(handlerInfos); } } /** @private Iterates over an array of `HandlerInfo`s, passing the handler and context into the callback. @param {Array[HandlerInfo]} handlerInfos @param {Function(Object, Object)} callback */ function eachHandler(handlerInfos, callback) { for (var i=0, l=handlerInfos.length; i<l; i++) { var handlerInfo = handlerInfos[i], handler = handlerInfo.handler, context = handlerInfo.context; callback(handler, context); } } /** @private Updates the `handler` field in each element in an Array of `UnresolvedHandlerInfo`s from a handler name to a resolved handler. When done, the Array will contain `HandlerInfo` structures. @param {Router} router @param {Array[UnresolvedHandlerInfo]} handlerInfos */ function resolveHandlers(router, handlerInfos) { var handlerInfo; for (var i=0, l=handlerInfos.length; i<l; i++) { handlerInfo = handlerInfos[i]; handlerInfo.name = handlerInfo.handler; handlerInfo.handler = router.getHandler(handlerInfo.handler); } } /** @private This function is called when transitioning from one URL to another to determine which handlers are not longer active, which handlers are newly active, and which handlers remain active but have their context changed. Take a list of old handlers and new handlers and partition them into four buckets: * unchanged: the handler was active in both the old and new URL, and its context remains the same * updated context: the handler was active in both the old and new URL, but its context changed. The handler's `setup` method, if any, will be called with the new context. * exited: the handler was active in the old URL, but is no longer active. * entered: the handler was not active in the old URL, but is now active. The PartitionedHandlers structure has three fields: * `updatedContext`: a list of `HandlerInfo` objects that represent handlers that remain active but have a changed context * `entered`: a list of `HandlerInfo` objects that represent handlers that are newly active * `exited`: a list of `HandlerInfo` objects that are no longer active. @param {Array[HandlerInfo]} oldHandlers a list of the handler information for the previous URL (or `[]` if this is the first handled transition) @param {Array[HandlerInfo]} newHandlers a list of the handler information for the new URL @return {Partition} */ function partitionHandlers(oldHandlers, newHandlers) { var handlers = { updatedContext: [], exited: [], entered: [] }; var handlerChanged, contextChanged, i, l; for (i=0, l=newHandlers.length; i<l; i++) { var oldHandler = oldHandlers[i], newHandler = newHandlers[i]; if (!oldHandler || oldHandler.handler !== newHandler.handler) { handlerChanged = true; } if (handlerChanged) { handlers.entered.push(newHandler); if (oldHandler) { handlers.exited.unshift(oldHandler); } } else if (contextChanged || oldHandler.context !== newHandler.context) { contextChanged = true; handlers.updatedContext.push(newHandler); } } for (i=newHandlers.length, l=oldHandlers.length; i<l; i++) { handlers.exited.unshift(oldHandlers[i]); } return handlers; } function trigger(router, args) { var currentHandlerInfos = router.currentHandlerInfos; if (!currentHandlerInfos) { throw new Error("Could not trigger event. There are no active handlers"); } var name = args.shift(); for (var i=currentHandlerInfos.length-1; i>=0; i--) { var handlerInfo = currentHandlerInfos[i], handler = handlerInfo.handler; if (handler.events && handler.events[name]) { handler.events[name].apply(handler, args); break; } } } function setContext(handler, context) { handler.context = context; if (handler.contextDidChange) { handler.contextDidChange(); } } return Router; }); })(); (function() { /** @module ember @submodule ember-routing */ function DSL(name) { this.parent = name; this.matches = []; } DSL.prototype = { resource: function(name, options, callback) { if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } if (arguments.length === 1) { options = {}; } if (typeof options.path !== 'string') { options.path = "/" + name; } if (callback) { var dsl = new DSL(name); callback.call(dsl); this.push(options.path, name, dsl.generate()); } else { this.push(options.path, name); } }, push: function(url, name, callback) { if (url === "" || url === "/") { this.explicitIndex = true; } this.matches.push([url, name, callback]); }, route: function(name, options) { Ember.assert("You must use `this.resource` to nest", typeof options !== 'function'); options = options || {}; if (typeof options.path !== 'string') { options.path = "/" + name; } if (this.parent && this.parent !== 'application') { name = this.parent + "." + name; } this.push(options.path, name); }, generate: function() { var dslMatches = this.matches; if (!this.explicitIndex) { this.route("index", { path: "/" }); } return function(match) { for (var i=0, l=dslMatches.length; i<l; i++) { var dslMatch = dslMatches[i]; match(dslMatch[0]).to(dslMatch[1], dslMatch[2]); } }; } }; DSL.map = function(callback) { var dsl = new DSL(); callback.call(dsl); return dsl; }; Ember.RouterDSL = DSL; })(); (function() { /** @module ember @submodule ember-routing */ Ember.controllerFor = function(container, controllerName, context) { return container.lookup('controller:' + controllerName) || Ember.generateController(container, controllerName, context); }; Ember.generateController = function(container, controllerName, context) { var controller; if (context && Ember.isArray(context)) { controller = Ember.ArrayController.extend({ content: context }); } else if (context) { controller = Ember.ObjectController.extend({ content: context }); } else { controller = Ember.Controller.extend(); } controller.toString = function() { return "(generated " + controllerName + " controller)"; }; container.register('controller', controllerName, controller); return container.lookup('controller:' + controllerName); }; })(); (function() { /** @module ember @submodule ember-routing */ var Router = requireModule("router"); var get = Ember.get, set = Ember.set, classify = Ember.String.classify; var DefaultView = Ember.View.extend(Ember._Metamorph); function setupLocation(router) { var location = get(router, 'location'), rootURL = get(router, 'rootURL'); if ('string' === typeof location) { location = set(router, 'location', Ember.Location.create({ implementation: location })); if (typeof rootURL === 'string') { set(location, 'rootURL', rootURL); } } } Ember.Router = Ember.Object.extend({ location: 'hash', init: function() { this.router = this.constructor.router; this._activeViews = {}; setupLocation(this); }, startRouting: function() { this.router = this.router || this.constructor.map(Ember.K); var router = this.router, location = get(this, 'location'), container = this.container, self = this; setupRouter(this, router, location); container.register('view', 'default', DefaultView); container.register('view', 'toplevel', Ember.View.extend()); router.handleURL(location.getURL()); location.onUpdateURL(function(url) { router.handleURL(url); }); }, didTransition: function(infos) { // Don't do any further action here if we redirected if (infos[infos.length-1].handler.transitioned) { return; } var appController = this.container.lookup('controller:application'), path = routePath(infos); set(appController, 'currentPath', path); this.notifyPropertyChange('url'); if (get(this, 'namespace').LOG_TRANSITIONS) { Ember.Logger.log("Transitioned into '" + path + "'"); } }, handleURL: function(url) { this.router.handleURL(url); this.notifyPropertyChange('url'); }, transitionTo: function(passedName) { var args = [].slice.call(arguments), name; if (!this.router.hasRoute(passedName)) { name = args[0] = passedName + '.index'; } else { name = passedName; } Ember.assert("The route " + passedName + " was not found", this.router.hasRoute(name)); this.router.transitionTo.apply(this.router, args); this.notifyPropertyChange('url'); }, replaceWith: function() { this.router.replaceWith.apply(this.router, arguments); this.notifyPropertyChange('url'); }, generate: function() { var url = this.router.generate.apply(this.router, arguments); return this.location.formatURL(url); }, isActive: function(routeName) { var router = this.router; return router.isActive.apply(router, arguments); }, send: function(name, context) { if (Ember.$ && context instanceof Ember.$.Event) { context = context.context; } this.router.trigger(name, context); }, hasRoute: function(route) { return this.router.hasRoute(route); }, _lookupActiveView: function(templateName) { var active = this._activeViews[templateName]; return active && active[0]; }, _connectActiveView: function(templateName, view) { var existing = this._activeViews[templateName]; if (existing) { existing[0].off('willDestroyElement', this, existing[1]); } var disconnect = function() { delete this._activeViews[templateName]; }; this._activeViews[templateName] = [view, disconnect]; view.one('willDestroyElement', this, disconnect); } }); Ember.Router.reopenClass({ defaultFailureHandler: { setup: function(error) { Ember.Logger.error('Error while loading route:', error); // Using setTimeout allows us to escape from the Promise's try/catch block setTimeout(function() { throw error; }); } } }); function getHandlerFunction(router) { var seen = {}, container = router.container; return function(name) { var handler = container.lookup('route:' + name); if (seen[name]) { return handler; } seen[name] = true; if (!handler) { if (name === 'loading') { return {}; } if (name === 'failure') { return router.constructor.defaultFailureHandler; } container.register('route', name, Ember.Route.extend()); handler = container.lookup('route:' + name); } handler.routeName = name; return handler; }; } function handlerIsActive(router, handlerName) { var handler = router.container.lookup('route:' + handlerName), currentHandlerInfos = router.router.currentHandlerInfos, handlerInfo; for (var i=0, l=currentHandlerInfos.length; i<l; i++) { handlerInfo = currentHandlerInfos[i]; if (handlerInfo.handler === handler) { return true; } } return false; } function routePath(handlerInfos) { var path = []; for (var i=1, l=handlerInfos.length; i<l; i++) { var name = handlerInfos[i].name, nameParts = name.split("."); path.push(nameParts[nameParts.length - 1]); } return path.join("."); } function setupRouter(emberRouter, router, location) { var lastURL; router.getHandler = getHandlerFunction(emberRouter); var doUpdateURL = function() { location.setURL(lastURL); }; router.updateURL = function(path) { lastURL = path; Ember.run.once(doUpdateURL); }; if (location.replaceURL) { var doReplaceURL = function() { location.replaceURL(lastURL); }; router.replaceURL = function(path) { lastURL = path; Ember.run.once(doReplaceURL); }; } router.didTransition = function(infos) { emberRouter.didTransition(infos); }; } Ember.Router.reopenClass({ map: function(callback) { var router = this.router = new Router(); var dsl = Ember.RouterDSL.map(function() { this.resource('application', { path: "/" }, function() { callback.call(this); }); }); router.map(dsl.generate()); return router; } }); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set, classify = Ember.String.classify, decamelize = Ember.String.decamelize; Ember.Route = Ember.Object.extend({ exit: function() { teardownView(this); }, /** Transition into another route. Optionally supply a model for the route in question. The model will be serialized into the URL using the `serialize` hook. @method transitionTo @param {String} name the name of the route @param {...Object} models the */ transitionTo: function() { this.transitioned = true; return this.router.transitionTo.apply(this.router, arguments); }, /** Transition into another route while replacing the current URL if possible. Identical to `transitionTo` in all other respects. @method replaceWith @param {String} name the name of the route @param {...Object} models the */ replaceWith: function() { this.transitioned = true; return this.router.replaceWith.apply(this.router, arguments); }, send: function() { return this.router.send.apply(this.router, arguments); }, /** @private This hook is the entry point for router.js @method setup */ setup: function(context) { this.transitioned = false; this.redirect(context); if (this.transitioned) { return; } var controller = this.controllerFor(this.routeName, context); if (controller) { set(controller, 'model', context); } if (this.setupControllers) { Ember.deprecate("Ember.Route.setupControllers is deprecated. Please use Ember.Route.setupController(controller, model) instead."); this.setupControllers(controller, context); } else { this.setupController(controller, context); } if (this.renderTemplates) { Ember.deprecate("Ember.Route.renderTemplates is deprecated. Please use Ember.Route.renderTemplate(controller, model) instead."); this.renderTemplates(context); } else { this.renderTemplate(controller, context); } }, /** A hook you can implement to optionally redirect to another route. If you call `this.transitionTo` from inside of this hook, this route will not be entered in favor of the other hook. @method redirect @param {Object} model the model for this route */ redirect: Ember.K, /** @private The hook called by `router.js` to convert parameters into the context for this handler. The public Ember hook is `model`. @method deserialize */ deserialize: function(params) { var model = this.model(params); return this.currentModel = model; }, /** @private Called when the context is changed by router.js. */ contextDidChange: function() { this.currentModel = this.context; }, /** A hook you can implement to convert the URL into the model for this route. ```js App.Route.map(function(match) { match("/posts/:post_id").to("post"); }); ``` The model for the `post` route is `App.Post.find(params.post_id)`. By default, if your route has a dynamic segment ending in `_id`: * The model class is determined from the segment (`post_id`'s class is `App.Post`) * The find method is called on the model class with the value of the dynamic segment. @method model @param {Object} params the parameters extracted from the URL */ model: function(params) { var match, name, value; for (var prop in params) { if (match = prop.match(/^(.*)_id$/)) { name = match[1]; value = params[prop]; } } if (!name) { return; } var className = classify(name), namespace = this.router.namespace, modelClass = namespace[className]; Ember.assert("You used the dynamic segment " + name + "_id in your router, but " + namespace + "." + className + " did not exist and you did not override your state's `model` hook.", modelClass); return modelClass.find(value); }, /** A hook you can implement to convert the route's model into parameters for the URL. ```js App.Route.map(function(match) { match("/posts/:post_id").to("post"); }); App.PostRoute = Ember.Route.extend({ model: function(params) { // the server returns `{ id: 12 }` return jQuery.getJSON("/posts/" + params.post_id); }, serialize: function(model) { // this will make the URL `/posts/12` return { post_id: model.id }; } }); ``` The default `serialize` method inserts the model's `id` into the route's dynamic segment (in this case, `:post_id`). This method is called when `transitionTo` is called with a context in order to populate the URL. @method serialize @param {Object} model the route's model @param {Array} params an Array of parameter names for the current route (in the example, `['post_id']`. @return {Object} the serialized parameters */ serialize: function(model, params) { if (params.length !== 1) { return; } var name = params[0], object = {}; object[name] = get(model, 'id'); return object; }, /** A hook you can use to setup the controller for the current route. This method is called with the controller for the current route and the model supplied by the `model` hook. ```js App.Route.map(function(match) { match("/posts/:post_id").to("post"); }); ``` For the `post` route, the controller is `App.PostController`. By default, the `setupController` hook sets the `content` property of the controller to the `model`. If no explicit controller is defined, the route will automatically create an appropriate controller for the model: * if the model is an `Ember.Array` (including record arrays from Ember Data), the controller is an `Ember.ArrayController`. * otherwise, the controller is an `Ember.ObjectController`. This means that your template will get a proxy for the model as its context, and you can act as though the model itself was the context. @method setupController */ setupController: Ember.K, /** Returns the controller for a particular route. ```js App.PostRoute = Ember.Route.extend({ setupController: function(controller, post) { this._super(controller, post); this.controllerFor('posts').set('currentPost', post); } }); ``` By default, the controller for `post` is the shared instance of `App.PostController`. @method controllerFor @param {String} name the name of the route @param {Object} model the model associated with the route (optional) @return {Ember.Controller} */ controllerFor: function(name, model) { var container = this.router.container, controller = container.lookup('controller:' + name); if (!controller) { model = model || this.modelFor(name); Ember.assert("You are trying to look up a controller that you did not define, and for which Ember does not know the model.\n\nThis is not a controller for a route, so you must explicitly define the controller ("+this.router.namespace.toString() + "." + Ember.String.capitalize(Ember.String.camelize(name))+"Controller) or pass a model as the second parameter to `controllerFor`, so that Ember knows which type of controller to create for you.", model || this.container.lookup('route:' + name)); controller = Ember.generateController(container, name, model); } return controller; }, /** Returns the current model for a given route. This is the object returned by the `model` hook of the route in question. @method modelFor @param {String} name the name of the route @return {Object} the model object */ modelFor: function(name) { var route = this.container.lookup('route:' + name); return route && route.currentModel; }, /** A hook you can use to render the template for the current route. This method is called with the controller for the current route and the model supplied by the `model` hook. By default, it renders the route's template, configured with the controller for the route. This method can be overridden to set up and render additional or alternative templates. @method renderTemplate @param {Object} controller the route's controller @param {Object} model the route's model */ renderTemplate: function(controller, model) { this.render(); }, /** Renders a template into an outlet. This method has a number of defaults, based on the name of the route specified in the router. For example: ```js App.Router.map(function(match) { match("/").to("index"); match("/posts/:post_id").to("post"); }); App.PostRoute = App.Route.extend({ renderTemplate: function() { this.render(); } }); ``` The name of the `PostRoute`, as defined by the router, is `post`. By default, render will: * render the `post` template * with the `post` view (`PostView`) for event handling, if one exists * and the `post` controller (`PostController`), if one exists * into the `main` outlet of the `application` template You can override this behavior: ```js App.PostRoute = App.Route.extend({ renderTemplate: function() { this.render('myPost', { // the template to render into: 'index', // the template to render into outlet: 'detail', // the name of the outlet in that template controller: 'blogPost' // the controller to use for the template }); } }); ``` Remember that the controller's `content` will be the route's model. In this case, the default model will be `App.Post.find(params.post_id)`. @method render @param {String} name the name of the template to render @param {Object} options the options */ render: function(name, options) { if (typeof name === 'object' && !options) { options = name; name = this.routeName; } name = name ? name.replace(/\//g, '.') : this.routeName; var container = this.container, view = container.lookup('view:' + name), template = container.lookup('template:' + name); if (!view && !template) { return; } this.lastRenderedTemplate = name; options = normalizeOptions(this, name, template, options); view = setupView(view, container, options); appendView(this, view, options); } }); function parentRoute(route) { var handlerInfos = route.router.router.currentHandlerInfos; var parent, current; for (var i=0, l=handlerInfos.length; i<l; i++) { current = handlerInfos[i].handler; if (current === route) { return parent; } parent = current; } } function parentTemplate(route) { var parent = parentRoute(route), template; if (!parent) { return; } if (template = parent.lastRenderedTemplate) { return template; } else { return parentTemplate(parent); } } function normalizeOptions(route, name, template, options) { options = options || {}; options.into = options.into ? options.into.replace(/\//g, '.') : parentTemplate(route); options.outlet = options.outlet || 'main'; options.name = name; options.template = template; var controller = options.controller, namedController; if (options.controller) { controller = options.controller; } else if (namedController = route.container.lookup('controller:' + name)) { controller = namedController; } else { controller = route.routeName; } if (typeof controller === 'string') { controller = route.container.lookup('controller:' + controller); } options.controller = controller; return options; } function setupView(view, container, options) { var defaultView = options.into ? 'view:default' : 'view:toplevel'; view = view || container.lookup(defaultView); if (!get(view, 'templateName')) { set(view, 'template', options.template); } set(view, 'renderedName', options.name); set(view, 'controller', options.controller); return view; } function appendView(route, view, options) { if (options.into) { var parentView = route.router._lookupActiveView(options.into); route.teardownView = teardownOutlet(parentView, options.outlet); parentView.connectOutlet(options.outlet, view); } else { var rootElement = get(route, 'router.namespace.rootElement'); route.router._connectActiveView(options.name, view); route.teardownView = teardownTopLevel(view); view.appendTo(rootElement); } } function teardownTopLevel(view) { return function() { view.remove(); }; } function teardownOutlet(parentView, outlet) { return function() { parentView.disconnectOutlet(outlet); }; } function teardownView(route) { if (route.teardownView) { route.teardownView(); } delete route.teardownView; delete route.lastRenderedTemplate; } })(); (function() { })(); (function() { var get = Ember.get, set = Ember.set; Ember.onLoad('Ember.Handlebars', function(Handlebars) { var resolvePaths = Ember.Handlebars.resolvePaths, isSimpleClick = Ember.ViewUtils.isSimpleClick; function fullRouteName(router, name) { if (!router.hasRoute(name)) { name = name + '.index'; } return name; } function resolvedPaths(linkView) { return resolvePaths(linkView.parameters); } function args(linkView, router, route) { var passedRouteName = route || linkView.namedRoute, routeName; routeName = fullRouteName(router, passedRouteName); Ember.assert("The route " + passedRouteName + " was not found", router.hasRoute(routeName)); var ret = [ routeName ]; return ret.concat(resolvePaths(linkView.parameters)); } var LinkView = Ember.View.extend({ tagName: 'a', namedRoute: null, currentWhen: null, title: null, activeClass: 'active', replace: false, attributeBindings: ['href', 'title'], classNameBindings: 'active', active: Ember.computed(function() { var router = this.get('router'), params = resolvedPaths(this), currentWithIndex = this.currentWhen + '.index', isActive = router.isActive.apply(router, [this.currentWhen].concat(params)) || router.isActive.apply(router, [currentWithIndex].concat(params)); if (isActive) { return get(this, 'activeClass'); } }).property('namedRoute', 'router.url'), router: Ember.computed(function() { return this.get('controller').container.lookup('router:main'); }), click: function(event) { if (!isSimpleClick(event)) { return true; } event.preventDefault(); if (this.bubbles === false) { event.stopPropagation(); } var router = this.get('router'); if (this.get('replace')) { router.replaceWith.apply(router, args(this, router)); } else { router.transitionTo.apply(router, args(this, router)); } }, href: Ember.computed(function() { var router = this.get('router'); return router.generate.apply(router, args(this, router)); }) }); LinkView.toString = function() { return "LinkView"; }; Ember.Handlebars.registerHelper('linkTo', function(name) { var options = [].slice.call(arguments, -1)[0]; var contexts = [].slice.call(arguments, 1, -1); var hash = options.hash; hash.namedRoute = name; hash.currentWhen = hash.currentWhen || name; hash.parameters = { data: options.data, contexts: contexts, roots: options.contexts }; return Ember.Handlebars.helpers.view.call(this, LinkView, options); }); }); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; Ember.onLoad('Ember.Handlebars', function(Handlebars) { /** @module ember @submodule ember-handlebars */ Handlebars.OutletView = Ember.ContainerView.extend(Ember._Metamorph); /** The `outlet` helper allows you to specify that the current view's controller will fill in the view for a given area. ``` handlebars {{outlet}} ``` By default, when the the current controller's `view` property changes, the outlet will replace its current view with the new view. You can set the `view` property directly, but it's normally best to use `connectOutlet`. ``` javascript # Instantiate App.PostsView and assign to `view`, so as to render into outlet. controller.connectOutlet('posts'); ``` You can also specify a particular name other than `view`: ``` handlebars {{outlet masterView}} {{outlet detailView}} ``` Then, you can control several outlets from a single controller. ``` javascript # Instantiate App.PostsView and assign to controller.masterView. controller.connectOutlet('masterView', 'posts'); # Also, instantiate App.PostInfoView and assign to controller.detailView. controller.connectOutlet('detailView', 'postInfo'); ``` @method outlet @for Ember.Handlebars.helpers @param {String} property the property on the controller that holds the view for this outlet */ Handlebars.registerHelper('outlet', function(property, options) { var outletSource; if (property && property.data && property.data.isRenderData) { options = property; property = 'main'; } outletSource = options.data.view; while (!(outletSource.get('template.isTop'))){ outletSource = outletSource.get('_parentView'); } options.data.view.set('outletSource', outletSource); options.hash.currentViewBinding = '_view.outletSource._outlets.' + property; return Handlebars.helpers.view.call(this, Handlebars.OutletView, options); }); Ember.View.reopen({ init: function() { set(this, '_outlets', {}); this._super(); }, connectOutlet: function(outletName, view) { var outlets = get(this, '_outlets'), container = get(this, 'container'), router = container && container.lookup('router:main'), oldView = get(outlets, outletName), renderedName = get(view, 'renderedName'); set(outlets, outletName, view); if (router) { if (oldView) { router._disconnectActiveView(oldView); } if (renderedName) { router._connectActiveView(renderedName, view); } } }, disconnectOutlet: function(outletName) { var outlets = get(this, '_outlets'), container = get(this, 'container'), router = container && container.lookup('router:main'), view = get(outlets, outletName); set(outlets, outletName, null); if (router && view) { router._disconnectActiveView(view); } } }); }); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; Ember.onLoad('Ember.Handlebars', function(Handlebars) { Ember.Handlebars.registerHelper('render', function(name, context, options) { Ember.assert("You must pass a template to render", arguments.length >= 2); var container, router, controller, view; if (arguments.length === 2) { options = context; context = undefined; } if (typeof context === 'string') { context = Ember.Handlebars.get(options.contexts[1], context, options); } name = name.replace(/\//g, '.'); container = options.data.keywords.controller.container; router = container.lookup('router:main'); Ember.assert("This view is already rendered", !router || !router._lookupActiveView(name)); view = container.lookup('view:' + name) || container.lookup('view:default'); if (controller = options.hash.controller) { controller = container.lookup('controller:' + controller); } else { controller = Ember.controllerFor(container, name, context); } if (controller && context) { controller.set('model', context); } controller.set('target', options.data.keywords.controller); options.hash.viewName = Ember.String.camelize(name); options.hash.template = container.lookup('template:' + name); options.hash.controller = controller; if (router) { router._connectActiveView(name, view); } Ember.Handlebars.helpers.view.call(this, view, options); }); }); })(); (function() { /** @module ember @submodule ember-routing */ Ember.onLoad('Ember.Handlebars', function(Handlebars) { var resolvePaths = Ember.Handlebars.resolvePaths, isSimpleClick = Ember.ViewUtils.isSimpleClick; var EmberHandlebars = Ember.Handlebars, handlebarsGet = EmberHandlebars.get, SafeString = EmberHandlebars.SafeString, get = Ember.get, a_slice = Array.prototype.slice; function args(options, actionName) { var ret = []; if (actionName) { ret.push(actionName); } return ret.concat(resolvePaths(options.parameters)); } var ActionHelper = EmberHandlebars.ActionHelper = { registeredActions: {} }; ActionHelper.registerAction = function(actionName, options) { var actionId = (++Ember.uuid).toString(); ActionHelper.registeredActions[actionId] = { eventName: options.eventName, handler: function(event) { if (!isSimpleClick(event)) { return true; } event.preventDefault(); if (options.bubbles === false) { event.stopPropagation(); } var view = options.view, contexts = options.contexts, target = options.target; if (target.send) { return target.send.apply(target, args(options, actionName)); } else { Ember.assert("The action '" + actionName + "' did not exist on " + target, typeof target[actionName] === 'function'); return target[actionName].apply(target, args(options)); } } }; options.view.on('willClearRender', function() { delete ActionHelper.registeredActions[actionId]; }); return actionId; }; /** The `{{action}}` helper registers an HTML element within a template for DOM event handling and forwards that interaction to the view's controller or supplied `target` option (see 'Specifying a Target'). If the view's controller does not implement the event, the event is sent to the current route, and it bubbles up the route hierarchy from there. User interaction with that element will invoke the supplied action name on the appropriate target. Given the following Handlebars template on the page ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> <div {{action anActionName}}> click me </div> </script> ``` And application code ```javascript AController = Ember.Controller.extend({ anActionName: function() {} }); AView = Ember.View.extend({ controller: AController.create(), templateName: 'a-template' }); aView = AView.create(); aView.appendTo('body'); ``` Will results in the following rendered HTML ```html <div class="ember-view"> <div data-ember-action="1"> click me </div> </div> ``` Clicking "click me" will trigger the `anActionName` method of the `AController`. In this case, no additional parameters will be passed. If you provide additional parameters to the helper: ```handlebars <button {{action 'edit' post}}>Edit</button> ``` Those parameters will be passed along as arguments to the JavaScript function implementing the action. ### Event Propagation Events triggered through the action helper will automatically have `.preventDefault()` called on them. You do not need to do so in your event handlers. To also disable bubbling, pass `bubbles=false` to the helper: ```handlebars <button {{action 'edit' post bubbles=false}}>Edit</button> ``` If you need the default handler to trigger you should either register your own event handler, or use event methods on your view class. See `Ember.View` 'Responding to Browser Events' for more information. ### Specifying DOM event type By default the `{{action}}` helper registers for DOM `click` events. You can supply an `on` option to the helper to specify a different DOM event name: ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> <div {{action anActionName on="doubleClick"}}> click me </div> </script> ``` See `Ember.View` 'Responding to Browser Events' for a list of acceptable DOM event names. NOTE: Because `{{action}}` depends on Ember's event dispatch system it will only function if an `Ember.EventDispatcher` instance is available. An `Ember.EventDispatcher` instance will be created when a new `Ember.Application` is created. Having an instance of `Ember.Application` will satisfy this requirement. ### Specifying a Target There are several possible target objects for `{{action}}` helpers: In a typical Ember application, where views are managed through use of the `{{outlet}}` helper, actions will bubble to the current controller, then to the current route, and then up the route hierarchy. Alternatively, a `target` option can be provided to the helper to change which object will receive the method call. This option must be a path path to an object, accessible in the current context: ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> <div {{action anActionName target="MyApplication.someObject"}}> click me </div> </script> ``` Clicking "click me" in the rendered HTML of the above template will trigger the `anActionName` method of the object at `MyApplication.someObject`. If an action's target does not implement a method that matches the supplied action name an error will be thrown. ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> <div {{action aMethodNameThatIsMissing}}> click me </div> </script> ``` With the following application code ```javascript AView = Ember.View.extend({ templateName; 'a-template', // note: no method 'aMethodNameThatIsMissing' anActionName: function(event) {} }); aView = AView.create(); aView.appendTo('body'); ``` Will throw `Uncaught TypeError: Cannot call method 'call' of undefined` when "click me" is clicked. ### Additional Parameters You may specify additional parameters to the `{{action}}` helper. These parameters are passed along as the arguments to the JavaScript function implementing the action. ```handlebars <script type="text/x-handlebars" data-template-name='a-template'> {{#each person in people}} <div {{action edit person}}> click me </div> {{/each}} </script> ``` Clicking "click me" will trigger the `edit` method on the current view's controller with the current person as a parameter. @method action @for Ember.Handlebars.helpers @param {String} actionName @param {Object...} contexts @param {Hash} options */ EmberHandlebars.registerHelper('action', function(actionName) { var options = arguments[arguments.length - 1], contexts = a_slice.call(arguments, 1, -1); var hash = options.hash, view = options.data.view, target, controller, link; // create a hash to pass along to registerAction var action = { eventName: hash.on || "click" }; action.parameters = { data: options.data, contexts: contexts, roots: options.contexts }; action.view = view = get(view, 'concreteView'); if (hash.target) { target = handlebarsGet(this, hash.target, options); } else if (controller = options.data.keywords.controller) { target = controller; } action.target = target; action.bubbles = hash.bubbles; var actionId = ActionHelper.registerAction(actionName, action); return new SafeString('data-ember-action="' + actionId + '"'); }); }); })(); (function() { })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; var ControllersProxy = Ember.Object.extend({ controller: null, unknownProperty: function(controllerName) { var controller = get(this, 'controller'), needs = get(controller, 'needs'), dependency; for (var i=0, l=needs.length; i<l; i++) { dependency = needs[i]; if (dependency === controllerName) { return controller.controllerFor(controllerName); } } } }); Ember.ControllerMixin.reopen({ concatenatedProperties: ['needs'], needs: [], init: function() { this._super.apply(this, arguments); // Structure asserts to still do verification but not string concat in production if(!verifyDependencies(this)) { Ember.assert("Missing dependencies", false); } }, transitionToRoute: function() { var target = get(this, 'target'); return target.transitionTo.apply(target, arguments); }, // TODO: Deprecate this, see https://github.com/emberjs/ember.js/issues/1785 transitionTo: function() { return this.transitionToRoute.apply(this, arguments); }, replaceRoute: function() { var target = get(this, 'target'); return target.replaceWith.apply(target, arguments); }, // TODO: Deprecate this, see https://github.com/emberjs/ember.js/issues/1785 replaceWith: function() { return this.replaceRoute.apply(this, arguments); }, controllerFor: function(controllerName) { var container = get(this, 'container'); return container.lookup('controller:' + controllerName); }, model: Ember.computed(function(key, value) { if (arguments.length > 1) { return set(this, 'content', value); } else { return get(this, 'content'); } }).property('content'), controllers: Ember.computed(function() { return ControllersProxy.create({ controller: this }); }) }); function verifyDependencies(controller) { var needs = get(controller, 'needs'), container = get(controller, 'container'), dependency, satisfied = true; for (var i=0, l=needs.length; i<l; i++) { dependency = needs[i]; if (dependency.indexOf(':') === -1) { dependency = "controller:" + dependency; } if (!container.has(dependency)) { satisfied = false; Ember.assert(controller + " needs " + dependency + " but it does not exist", false); } } return satisfied; } })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; Ember.View.reopen({ init: function() { set(this, '_outlets', {}); this._super(); }, connectOutlet: function(outletName, view) { var outlets = get(this, '_outlets'), container = get(this, 'container'), router = container && container.lookup('router:main'), renderedName = get(view, 'renderedName'); set(outlets, outletName, view); if (router && renderedName) { router._connectActiveView(renderedName, view); } }, disconnectOutlet: function(outletName) { var outlets = get(this, '_outlets'); set(outlets, outletName, null); } }); })(); (function() { })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; /* This file implements the `location` API used by Ember's router. That API is: getURL: returns the current URL setURL(path): sets the current URL replaceURL(path): replace the current URL (optional) onUpdateURL(callback): triggers the callback when the URL changes formatURL(url): formats `url` to be placed into `href` attribute Calling setURL or replaceURL will not trigger onUpdateURL callbacks. TODO: This should perhaps be moved so that it's visible in the doc output. */ /** Ember.Location returns an instance of the correct implementation of the `location` API. You can pass it a `implementation` ('hash', 'history', 'none') to force a particular implementation. @class Location @namespace Ember @static */ Ember.Location = { create: function(options) { var implementation = options && options.implementation; Ember.assert("Ember.Location.create: you must specify a 'implementation' option", !!implementation); var implementationClass = this.implementations[implementation]; Ember.assert("Ember.Location.create: " + implementation + " is not a valid implementation", !!implementationClass); return implementationClass.create.apply(implementationClass, arguments); }, registerImplementation: function(name, implementation) { this.implementations[name] = implementation; }, implementations: {} }; })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; /** Ember.NoneLocation does not interact with the browser. It is useful for testing, or when you need to manage state with your Router, but temporarily don't want it to muck with the URL (for example when you embed your application in a larger page). @class NoneLocation @namespace Ember @extends Ember.Object */ Ember.NoneLocation = Ember.Object.extend({ path: '', getURL: function() { return get(this, 'path'); }, setURL: function(path) { set(this, 'path', path); }, onUpdateURL: function(callback) { // We are not wired up to the browser, so we'll never trigger the callback. }, formatURL: function(url) { // The return value is not overly meaningful, but we do not want to throw // errors when test code renders templates containing {{action href=true}} // helpers. return url; } }); Ember.Location.registerImplementation('none', Ember.NoneLocation); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; /** Ember.HashLocation implements the location API using the browser's hash. At present, it relies on a hashchange event existing in the browser. @class HashLocation @namespace Ember @extends Ember.Object */ Ember.HashLocation = Ember.Object.extend({ init: function() { set(this, 'location', get(this, 'location') || window.location); }, /** @private Returns the current `location.hash`, minus the '#' at the front. @method getURL */ getURL: function() { return get(this, 'location').hash.substr(1); }, /** @private Set the `location.hash` and remembers what was set. This prevents `onUpdateURL` callbacks from triggering when the hash was set by `HashLocation`. @method setURL @param path {String} */ setURL: function(path) { get(this, 'location').hash = path; set(this, 'lastSetURL', path); }, /** @private Register a callback to be invoked when the hash changes. These callbacks will execute when the user presses the back or forward button, but not after `setURL` is invoked. @method onUpdateURL @param callback {Function} */ onUpdateURL: function(callback) { var self = this; var guid = Ember.guidFor(this); Ember.$(window).bind('hashchange.ember-location-'+guid, function() { var path = location.hash.substr(1); if (get(self, 'lastSetURL') === path) { return; } set(self, 'lastSetURL', null); callback(location.hash.substr(1)); }); }, /** @private Given a URL, formats it to be placed into the page as part of an element's `href` attribute. This is used, for example, when using the {{action}} helper to generate a URL based on an event. @method formatURL @param url {String} */ formatURL: function(url) { return '#'+url; }, willDestroy: function() { var guid = Ember.guidFor(this); Ember.$(window).unbind('hashchange.ember-location-'+guid); } }); Ember.Location.registerImplementation('hash', Ember.HashLocation); })(); (function() { /** @module ember @submodule ember-routing */ var get = Ember.get, set = Ember.set; var popstateReady = false; /** Ember.HistoryLocation implements the location API using the browser's history.pushState API. @class HistoryLocation @namespace Ember @extends Ember.Object */ Ember.HistoryLocation = Ember.Object.extend({ init: function() { set(this, 'location', get(this, 'location') || window.location); this.initState(); }, /** @private Used to set state on first call to setURL @method initState */ initState: function() { this.replaceState(get(this, 'location').pathname); set(this, 'history', window.history); }, /** Will be pre-pended to path upon state change @property rootURL @default '/' */ rootURL: '/', /** @private Returns the current `location.pathname`. @method getURL */ getURL: function() { return get(this, 'location').pathname; }, /** @private Uses `history.pushState` to update the url without a page reload. @method setURL @param path {String} */ setURL: function(path) { path = this.formatURL(path); if (this.getState() && this.getState().path !== path) { popstateReady = true; this.pushState(path); } }, /** @private Uses `history.replaceState` to update the url without a page reload or history modification. @method replaceURL @param path {String} */ replaceURL: function(path) { path = this.formatURL(path); if (this.getState() && this.getState().path !== path) { popstateReady = true; this.replaceState(path); } }, /** @private Get the current `history.state` @method getState */ getState: function() { return get(this, 'history').state; }, /** @private Pushes a new state @method pushState @param path {String} */ pushState: function(path) { window.history.pushState({ path: path }, null, path); }, /** @private Replaces the current state @method replaceState @param path {String} */ replaceState: function(path) { window.history.replaceState({ path: path }, null, path); }, /** @private Register a callback to be invoked whenever the browser history changes, including using forward and back buttons. @method onUpdateURL @param callback {Function} */ onUpdateURL: function(callback) { var guid = Ember.guidFor(this); Ember.$(window).bind('popstate.ember-location-'+guid, function(e) { if(!popstateReady) { return; } callback(location.pathname); }); }, /** @private Used when using `{{action}}` helper. The url is always appended to the rootURL. @method formatURL @param url {String} */ formatURL: function(url) { var rootURL = get(this, 'rootURL'); if (url !== '') { rootURL = rootURL.replace(/\/$/, ''); } return rootURL + url; }, willDestroy: function() { var guid = Ember.guidFor(this); Ember.$(window).unbind('popstate.ember-location-'+guid); } }); Ember.Location.registerImplementation('history', Ember.HistoryLocation); })(); (function() { })(); (function() { /** Ember Routing @module ember @submodule ember-routing @requires ember-states @requires ember-views */ })(); (function() { function visit(vertex, fn, visited, path) { var name = vertex.name, vertices = vertex.incoming, names = vertex.incomingNames, len = names.length, i; if (!visited) { visited = {}; } if (!path) { path = []; } if (visited.hasOwnProperty(name)) { return; } path.push(name); visited[name] = true; for (i = 0; i < len; i++) { visit(vertices[names[i]], fn, visited, path); } fn(vertex, path); path.pop(); } function DAG() { this.names = []; this.vertices = {}; } DAG.prototype.add = function(name) { if (!name) { return; } if (this.vertices.hasOwnProperty(name)) { return this.vertices[name]; } var vertex = { name: name, incoming: {}, incomingNames: [], hasOutgoing: false, value: null }; this.vertices[name] = vertex; this.names.push(name); return vertex; }; DAG.prototype.map = function(name, value) { this.add(name).value = value; }; DAG.prototype.addEdge = function(fromName, toName) { if (!fromName || !toName || fromName === toName) { return; } var from = this.add(fromName), to = this.add(toName); if (to.incoming.hasOwnProperty(fromName)) { return; } function checkCycle(vertex, path) { if (vertex.name === toName) { throw new Error("cycle detected: " + toName + " <- " + path.join(" <- ")); } } visit(from, checkCycle); from.hasOutgoing = true; to.incoming[fromName] = from; to.incomingNames.push(fromName); }; DAG.prototype.topsort = function(fn) { var visited = {}, vertices = this.vertices, names = this.names, len = names.length, i, vertex; for (i = 0; i < len; i++) { vertex = vertices[names[i]]; if (!vertex.hasOutgoing) { visit(vertex, fn, visited); } } }; DAG.prototype.addEdges = function(name, value, before, after) { var i; this.map(name, value); if (before) { if (typeof before === 'string') { this.addEdge(name, before); } else { for (i = 0; i < before.length; i++) { this.addEdge(name, before[i]); } } } if (after) { if (typeof after === 'string') { this.addEdge(after, name); } else { for (i = 0; i < after.length; i++) { this.addEdge(after[i], name); } } } }; Ember.DAG = DAG; })(); (function() { /** @module ember @submodule ember-application */ var get = Ember.get, set = Ember.set, classify = Ember.String.classify, decamelize = Ember.String.decamelize; /** An instance of `Ember.Application` is the starting point for every Ember application. It helps to instantiate, initialize and coordinate the many objects that make up your app. Each Ember app has one and only one `Ember.Application` object. In fact, the very first thing you should do in your application is create the instance: ```javascript window.App = Ember.Application.create(); ``` Typically, the application object is the only global variable. All other classes in your app should be properties on the `Ember.Application` instance, which highlights its first role: a global namespace. For example, if you define a view class, it might look like this: ```javascript App.MyView = Ember.View.extend(); ``` By default, calling `Ember.Application.create()` will automatically initialize your application by calling the `Ember.Application.initialize()` method. If you need to delay initialization, you can call your app's `deferReadiness()` method. When you are ready for your app to be initialized, call its `advanceReadiness()` method. Because `Ember.Application` inherits from `Ember.Namespace`, any classes you create will have useful string representations when calling `toString()`. See the `Ember.Namespace` documentation for more information. While you can think of your `Ember.Application` as a container that holds the other classes in your application, there are several other responsibilities going on under-the-hood that you may want to understand. ### Event Delegation Ember uses a technique called _event delegation_. This allows the framework to set up a global, shared event listener instead of requiring each view to do it manually. For example, instead of each view registering its own `mousedown` listener on its associated element, Ember sets up a `mousedown` listener on the `body`. If a `mousedown` event occurs, Ember will look at the target of the event and start walking up the DOM node tree, finding corresponding views and invoking their `mouseDown` method as it goes. `Ember.Application` has a number of default events that it listens for, as well as a mapping from lowercase events to camel-cased view method names. For example, the `keypress` event causes the `keyPress` method on the view to be called, the `dblclick` event causes `doubleClick` to be called, and so on. If there is a browser event that Ember does not listen for by default, you can specify custom events and their corresponding view method names by setting the application's `customEvents` property: ```javascript App = Ember.Application.create({ customEvents: { // add support for the loadedmetadata media // player event 'loadedmetadata': "loadedMetadata" } }); ``` By default, the application sets up these event listeners on the document body. However, in cases where you are embedding an Ember application inside an existing page, you may want it to set up the listeners on an element inside the body. For example, if only events inside a DOM element with the ID of `ember-app` should be delegated, set your application's `rootElement` property: ```javascript window.App = Ember.Application.create({ rootElement: '#ember-app' }); ``` The `rootElement` can be either a DOM element or a jQuery-compatible selector string. Note that *views appended to the DOM outside the root element will not receive events.* If you specify a custom root element, make sure you only append views inside it! To learn more about the advantages of event delegation and the Ember view layer, and a list of the event listeners that are setup by default, visit the [Ember View Layer guide](http://emberjs.com/guides/view_layer#toc_event-delegation). ### Dependency Injection One thing you may have noticed while using Ember is that you define *classes*, not *instances*. When your application loads, all of the instances are created for you. Creating these instances is the responsibility of `Ember.Application`. When the `Ember.Application` initializes, it will look for an `Ember.Router` class defined on the applications's `Router` property, like this: ```javascript App.Router = Ember.Router.extend({ // ... }); ``` If found, the router is instantiated and saved on the application's `router` property (note the lowercase 'r'). While you should *not* reference this router instance directly from your application code, having access to `App.router` from the console can be useful during debugging. After the router is created, the application loops through all of the registered _injections_ and invokes them once for each property on the `Ember.Application` object. An injection is a function that is responsible for instantiating objects from classes defined on the application. By default, the only injection registered instantiates controllers and makes them available on the router. For example, if you define a controller class: ```javascript App.MyController = Ember.Controller.extend({ // ... }); ``` Your router will receive an instance of `App.MyController` saved on its `myController` property. Libraries on top of Ember can register additional injections. For example, if your application is using Ember Data, it registers an injection that instantiates `DS.Store`: ```javascript Ember.Application.registerInjection({ name: 'store', before: 'controllers', injection: function(app, router, property) { if (property === 'Store') { set(router, 'store', app[property].create()); } } }); ``` ### Routing In addition to creating your application's router, `Ember.Application` is also responsible for telling the router when to start routing. By default, the router will begin trying to translate the current URL into application state once the browser emits the `DOMContentReady` event. If you need to defer routing, you can call the application's `deferReadiness()` method. Once routing can begin, call the `advanceReadiness()` method. If there is any setup required before routing begins, you can implement a `ready()` method on your app that will be invoked immediately before routing begins: ```javascript window.App = Ember.Application.create({ ready: function() { this.set('router.enableLogging', true); } }); To begin routing, you must have at a minimum a top-level controller and view. You define these as `App.ApplicationController` and `App.ApplicationView`, respectively. Your application will not work if you do not define these two mandatory classes. For example: ```javascript App.ApplicationView = Ember.View.extend({ templateName: 'application' }); App.ApplicationController = Ember.Controller.extend(); ``` @class Application @namespace Ember @extends Ember.Namespace */ var Application = Ember.Application = Ember.Namespace.extend( /** @scope Ember.Application.prototype */{ /** The root DOM element of the Application. This can be specified as an element or a [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). This is the element that will be passed to the Application's, `eventDispatcher`, which sets up the listeners for event delegation. Every view in your application should be a child of the element you specify here. @property rootElement @type DOMElement @default 'body' */ rootElement: 'body', /** The `Ember.EventDispatcher` responsible for delegating events to this application's views. The event dispatcher is created by the application at initialization time and sets up event listeners on the DOM element described by the application's `rootElement` property. See the documentation for `Ember.EventDispatcher` for more information. @property eventDispatcher @type Ember.EventDispatcher @default null */ eventDispatcher: null, /** The DOM events for which the event dispatcher should listen. By default, the application's `Ember.EventDispatcher` listens for a set of standard DOM events, such as `mousedown` and `keyup`, and delegates them to your application's `Ember.View` instances. If you would like additional events to be delegated to your views, set your `Ember.Application`'s `customEvents` property to a hash containing the DOM event name as the key and the corresponding view method name as the value. For example: ```javascript App = Ember.Application.create({ customEvents: { // add support for the loadedmetadata media // player event 'loadedmetadata': "loadedMetadata" } }); ``` @property customEvents @type Object @default null */ customEvents: null, isInitialized: false, // Start off the number of deferrals at 1. This will be // decremented by the Application's own `initialize` method. _readinessDeferrals: 1, init: function() { if (!this.$) { this.$ = Ember.$; } this.__container__ = this.buildContainer(); this.Router = this.Router || this.defaultRouter(); if (this.Router) { this.Router.namespace = this; } this._super(); this.deferUntilDOMReady(); this.scheduleInitialize(); }, /** @private Build the container for the current application. Also register a default application view in case the application itself does not. @method buildContainer @return {Ember.Container} the configured container */ buildContainer: function() { var container = this.__container__ = Application.buildContainer(this); return container; }, /** @private If the application has not opted out of routing and has not explicitly defined a router, supply a default router for the application author to configure. This allows application developers to do: ```javascript App = Ember.Application.create(); App.Router.map(function(match) { match("/").to("index"); }); ``` @method defaultRouter @return {Ember.Router} the default router */ defaultRouter: function() { // Create a default App.Router if one was not supplied to make // it possible to do App.Router.map(...) without explicitly // creating a router first. if (this.router === undefined) { return Ember.Router.extend(); } }, /** @private Defer Ember readiness until DOM readiness. By default, Ember will wait for both DOM readiness and application initialization, as well as any deferrals registered by initializers. @method deferUntilDOMReady */ deferUntilDOMReady: function() { this.deferReadiness(); var self = this; this.$().ready(function() { self.advanceReadiness(); }); }, /** @private Automatically initialize the application once the DOM has become ready. The initialization itself is deferred using Ember.run.once, which ensures that application loading finishes before booting. If you are asynchronously loading code, you should call `deferReadiness()` to defer booting, and then call `advanceReadiness()` once all of your code has finished loading. @method scheduleInitialize */ scheduleInitialize: function() { var self = this; this.$().ready(function() { if (self.isDestroyed || self.isInitialized) return; Ember.run.once(self, 'initialize'); }); }, /** Use this to defer readiness until some condition is true. Example: ```javascript App = Ember.Application.create(); App.deferReadiness(); jQuery.getJSON("/auth-token", function(token) { App.token = token; App.advanceReadiness(); }); ``` This allows you to perform asynchronous setup logic and defer booting your application until the setup has finished. However, if the setup requires a loading UI, it might be better to use the router for this purpose. @method deferReadiness */ deferReadiness: function() { Ember.assert("You cannot defer readiness since the `ready()` hook has already been called.", this._readinessDeferrals > 0); this._readinessDeferrals++; }, /** @method advanceReadiness @see {Ember.Application#deferReadiness} */ advanceReadiness: function() { this._readinessDeferrals--; if (this._readinessDeferrals === 0) { Ember.run.once(this, this.didBecomeReady); } }, register: function() { var container = this.__container__; return container.register.apply(container, arguments); }, /** @private Initialize the application. This happens automatically. Run any injections and run the application load hook. These hooks may choose to defer readiness. For example, an authentication hook might want to defer readiness until the auth token has been retrieved. @method initialize */ initialize: function() { Ember.assert("Application initialize may only be called once", !this.isInitialized); Ember.assert("Cannot initialize a destroyed application", !this.isDestroyed); this.isInitialized = true; // At this point, the App.Router must already be assigned this.__container__.register('router', 'main', this.Router); // Run any injections and run the application load hook. These hooks may // choose to defer readiness. For example, an authentication hook might want // to defer readiness until the auth token has been retrieved. this.runInitializers(); Ember.runLoadHooks('application', this); // At this point, any injections or load hooks that would have wanted // to defer readiness have fired. In general, advancing readiness here // will proceed to didBecomeReady. this.advanceReadiness(); return this; }, /** @private @method runInitializers */ runInitializers: function() { var initializers = get(this.constructor, 'initializers'), container = this.__container__, graph = new Ember.DAG(), namespace = this, properties, i, initializer; for (i=0; i<initializers.length; i++) { initializer = initializers[i]; graph.addEdges(initializer.name, initializer.initialize, initializer.before, initializer.after); } graph.topsort(function (vertex) { var initializer = vertex.value; initializer(container, namespace); }); }, /** @private @method didBecomeReady */ didBecomeReady: function() { this.setupEventDispatcher(); this.ready(); // user hook this.startRouting(); if (!Ember.testing) { // Eagerly name all classes that are already loaded Ember.Namespace.processAll(); Ember.BOOTED = true; } }, /** @private Setup up the event dispatcher to receive events on the application's `rootElement` with any registered `customEvents`. @method setupEventDispatcher */ setupEventDispatcher: function() { var eventDispatcher = this.createEventDispatcher(), customEvents = get(this, 'customEvents'); eventDispatcher.setup(customEvents); }, /** @private Create an event dispatcher for the application's `rootElement`. @method createEventDispatcher */ createEventDispatcher: function() { var rootElement = get(this, 'rootElement'), eventDispatcher = Ember.EventDispatcher.create({ rootElement: rootElement }); set(this, 'eventDispatcher', eventDispatcher); return eventDispatcher; }, /** @private If the application has a router, use it to route to the current URL, and trigger a new call to `route` whenever the URL changes. @method startRouting @property router {Ember.Router} */ startRouting: function() { var router = this.__container__.lookup('router:main'); if (!router) { return; } router.startRouting(); }, /** Called when the Application has become ready. The call will be delayed until the DOM has become ready. @event ready */ ready: Ember.K, willDestroy: function() { Ember.BOOTED = false; var eventDispatcher = get(this, 'eventDispatcher'); if (eventDispatcher) { eventDispatcher.destroy(); } this.__container__.destroy(); }, initializer: function(options) { this.constructor.initializer(options); } }); Ember.Application.reopenClass({ concatenatedProperties: ['initializers'], initializers: Ember.A(), initializer: function(initializer) { var initializers = get(this, 'initializers'); Ember.assert("The initializer '" + initializer.name + "' has already been registered", !initializers.findProperty('name', initializers.name)); Ember.assert("An injection cannot be registered with both a before and an after", !(initializer.before && initializer.after)); Ember.assert("An injection cannot be registered without an injection function", Ember.canInvoke(initializer, 'initialize')); initializers.push(initializer); }, /** @private This creates a container with the default Ember naming conventions. It also configures the container: * registered views are created every time they are looked up (they are not singletons) * registered templates are not factories; the registered value is returned directly. * the router receives the application as its `namespace` property * all controllers receive the router as their `target` and `controllers` properties * all controllers receive the application as their `namespace` property * the application view receives the application controller as its `controller` property * the application view receives the application template as its `defaultTemplate` property @method buildContainer @static @param {Ember.Application} namespace the application to build the container for. @return {Ember.Container} the built container */ buildContainer: function(namespace) { var container = new Ember.Container(); Ember.Container.defaultContainer = container; container.set = Ember.set; container.resolver = resolverFor(namespace); container.optionsForType('view', { singleton: false }); container.optionsForType('template', { instantiate: false }); container.register('application', 'main', namespace, { instantiate: false }); container.injection('router:main', 'namespace', 'application:main'); container.typeInjection('controller', 'target', 'router:main'); container.typeInjection('controller', 'namespace', 'application:main'); container.typeInjection('route', 'router', 'router:main'); return container; } }); /** @private This function defines the default lookup rules for container lookups: * templates are looked up on `Ember.TEMPLATES` * other names are looked up on the application after classifying the name. For example, `controller:post` looks up `App.PostController` by default. * if the default lookup fails, look for registered classes on the container This allows the application to register default injections in the container that could be overridden by the normal naming convention. @param {Ember.Namespace} namespace the namespace to look for classes @return {any} the resolved value for a given lookup */ function resolverFor(namespace) { return function(fullName) { var nameParts = fullName.split(":"), type = nameParts[0], name = nameParts[1]; if (type === 'template') { var templateName = name.replace(/\./g, '/'); if (Ember.TEMPLATES[templateName]) { return Ember.TEMPLATES[templateName]; } templateName = decamelize(templateName); if (Ember.TEMPLATES[templateName]) { return Ember.TEMPLATES[templateName]; } } if (type === 'controller' || type === 'route' || type === 'view') { name = name.replace(/\./g, '_'); } var className = classify(name) + classify(type); var factory = get(namespace, className); if (factory) { return factory; } }; } Ember.runLoadHooks('Ember.Application', Ember.Application); })(); (function() { })(); (function() { /** Ember Application @module ember @submodule ember-application @requires ember-views, ember-states, ember-routing */ })(); (function() { var get = Ember.get, set = Ember.set; /** @module ember @submodule ember-states */ /** @class State @namespace Ember @extends Ember.Object @uses Ember.Evented */ Ember.State = Ember.Object.extend(Ember.Evented, /** @scope Ember.State.prototype */{ isState: true, /** A reference to the parent state. @property parentState @type Ember.State */ parentState: null, start: null, /** The name of this state. @property name @type String */ name: null, /** The full path to this state. @property path @type String */ path: Ember.computed(function() { var parentPath = get(this, 'parentState.path'), path = get(this, 'name'); if (parentPath) { path = parentPath + '.' + path; } return path; }), /** @private Override the default event firing from `Ember.Evented` to also call methods with the given name. @method trigger @param name */ trigger: function(name) { if (this[name]) { this[name].apply(this, [].slice.call(arguments, 1)); } this._super.apply(this, arguments); }, init: function() { var states = get(this, 'states'), foundStates; set(this, 'childStates', Ember.A()); set(this, 'eventTransitions', get(this, 'eventTransitions') || {}); var name, value, transitionTarget; // As a convenience, loop over the properties // of this state and look for any that are other // Ember.State instances or classes, and move them // to the `states` hash. This avoids having to // create an explicit separate hash. if (!states) { states = {}; for (name in this) { if (name === "constructor") { continue; } if (value = this[name]) { if (transitionTarget = value.transitionTarget) { this.eventTransitions[name] = transitionTarget; } this.setupChild(states, name, value); } } set(this, 'states', states); } else { for (name in states) { this.setupChild(states, name, states[name]); } } set(this, 'pathsCache', {}); set(this, 'pathsCacheNoContext', {}); }, setupChild: function(states, name, value) { if (!value) { return false; } if (value.isState) { set(value, 'name', name); } else if (Ember.State.detect(value)) { value = value.create({ name: name }); } if (value.isState) { set(value, 'parentState', this); get(this, 'childStates').pushObject(value); states[name] = value; return value; } }, lookupEventTransition: function(name) { var path, state = this; while(state && !path) { path = state.eventTransitions[name]; state = state.get('parentState'); } return path; }, /** A Boolean value indicating whether the state is a leaf state in the state hierarchy. This is `false` if the state has child states; otherwise it is true. @property isLeaf @type Boolean */ isLeaf: Ember.computed(function() { return !get(this, 'childStates').length; }), /** A boolean value indicating whether the state takes a context. By default we assume all states take contexts. @property hasContext @default true */ hasContext: true, /** This is the default transition event. @event setup @param {Ember.StateManager} manager @param context @see Ember.StateManager#transitionEvent */ setup: Ember.K, /** This event fires when the state is entered. @event enter @param {Ember.StateManager} manager */ enter: Ember.K, /** This event fires when the state is exited. @event exit @param {Ember.StateManager} manager */ exit: Ember.K }); Ember.State.reopenClass({ /** Creates an action function for transitioning to the named state while preserving context. The following example StateManagers are equivalent: ```javascript aManager = Ember.StateManager.create({ stateOne: Ember.State.create({ changeToStateTwo: Ember.State.transitionTo('stateTwo') }), stateTwo: Ember.State.create({}) }) bManager = Ember.StateManager.create({ stateOne: Ember.State.create({ changeToStateTwo: function(manager, context){ manager.transitionTo('stateTwo', context) } }), stateTwo: Ember.State.create({}) }) ``` @method transitionTo @static @param {String} target */ transitionTo: function(target) { var transitionFunction = function(stateManager, contextOrEvent) { var contexts = [], transitionArgs, Event = Ember.$ && Ember.$.Event; if (contextOrEvent && (Event && contextOrEvent instanceof Event)) { if (contextOrEvent.hasOwnProperty('contexts')) { contexts = contextOrEvent.contexts.slice(); } } else { contexts = [].slice.call(arguments, 1); } contexts.unshift(target); stateManager.transitionTo.apply(stateManager, contexts); }; transitionFunction.transitionTarget = target; return transitionFunction; } }); })(); (function() { /** @module ember @submodule ember-states */ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt; var arrayForEach = Ember.ArrayPolyfills.forEach; /** A Transition takes the enter, exit and resolve states and normalizes them: * takes any passed in contexts into consideration * adds in `initialState`s @class Transition @private */ var Transition = function(raw) { this.enterStates = raw.enterStates.slice(); this.exitStates = raw.exitStates.slice(); this.resolveState = raw.resolveState; this.finalState = raw.enterStates[raw.enterStates.length - 1] || raw.resolveState; }; Transition.prototype = { /** Normalize the passed in enter, exit and resolve states. This process also adds `finalState` and `contexts` to the Transition object. @method normalize @param {Ember.StateManager} manager the state manager running the transition @param {Array} contexts a list of contexts passed into `transitionTo` */ normalize: function(manager, contexts) { this.matchContextsToStates(contexts); this.addInitialStates(); this.removeUnchangedContexts(manager); return this; }, /** Match each of the contexts passed to `transitionTo` to a state. This process may also require adding additional enter and exit states if there are more contexts than enter states. @method matchContextsToStates @param {Array} contexts a list of contexts passed into `transitionTo` */ matchContextsToStates: function(contexts) { var stateIdx = this.enterStates.length - 1, matchedContexts = [], state, context; // Next, we will match the passed in contexts to the states they // represent. // // First, assign a context to each enter state in reverse order. If // any contexts are left, add a parent state to the list of states // to enter and exit, and assign a context to the parent state. // // If there are still contexts left when the state manager is // reached, raise an exception. // // This allows the following: // // |- root // | |- post // | | |- comments // | |- about (* current state) // // For `transitionTo('post.comments', post, post.get('comments')`, // the first context (`post`) will be assigned to `root.post`, and // the second context (`post.get('comments')`) will be assigned // to `root.post.comments`. // // For the following: // // |- root // | |- post // | | |- index (* current state) // | | |- comments // // For `transitionTo('post.comments', otherPost, otherPost.get('comments')`, // the `<root.post>` state will be added to the list of enter and exit // states because its context has changed. while (contexts.length > 0) { if (stateIdx >= 0) { state = this.enterStates[stateIdx--]; } else { if (this.enterStates.length) { state = get(this.enterStates[0], 'parentState'); if (!state) { throw "Cannot match all contexts to states"; } } else { // If re-entering the current state with a context, the resolve // state will be the current state. state = this.resolveState; } this.enterStates.unshift(state); this.exitStates.unshift(state); } // in routers, only states with dynamic segments have a context if (get(state, 'hasContext')) { context = contexts.pop(); } else { context = null; } matchedContexts.unshift(context); } this.contexts = matchedContexts; }, /** Add any `initialState`s to the list of enter states. @method addInitialStates */ addInitialStates: function() { var finalState = this.finalState, initialState; while(true) { initialState = get(finalState, 'initialState') || 'start'; finalState = get(finalState, 'states.' + initialState); if (!finalState) { break; } this.finalState = finalState; this.enterStates.push(finalState); this.contexts.push(undefined); } }, /** Remove any states that were added because the number of contexts exceeded the number of explicit enter states, but the context has not changed since the last time the state was entered. @method removeUnchangedContexts @param {Ember.StateManager} manager passed in to look up the last context for a states */ removeUnchangedContexts: function(manager) { // Start from the beginning of the enter states. If the state was added // to the list during the context matching phase, make sure the context // has actually changed since the last time the state was entered. while (this.enterStates.length > 0) { if (this.enterStates[0] !== this.exitStates[0]) { break; } if (this.enterStates.length === this.contexts.length) { if (manager.getStateMeta(this.enterStates[0], 'context') !== this.contexts[0]) { break; } this.contexts.shift(); } this.resolveState = this.enterStates.shift(); this.exitStates.shift(); } } }; var sendRecursively = function(event, currentState, isUnhandledPass) { var log = this.enableLogging, eventName = isUnhandledPass ? 'unhandledEvent' : event, action = currentState[eventName], contexts, sendRecursiveArguments, actionArguments; contexts = [].slice.call(arguments, 3); // Test to see if the action is a method that // can be invoked. Don't blindly check just for // existence, because it is possible the state // manager has a child state of the given name, // and we should still raise an exception in that // case. if (typeof action === 'function') { if (log) { if (isUnhandledPass) { Ember.Logger.log(fmt("STATEMANAGER: Unhandled event '%@' being sent to state %@.", [event, get(currentState, 'path')])); } else { Ember.Logger.log(fmt("STATEMANAGER: Sending event '%@' to state %@.", [event, get(currentState, 'path')])); } } actionArguments = contexts; if (isUnhandledPass) { actionArguments.unshift(event); } actionArguments.unshift(this); return action.apply(currentState, actionArguments); } else { var parentState = get(currentState, 'parentState'); if (parentState) { sendRecursiveArguments = contexts; sendRecursiveArguments.unshift(event, parentState, isUnhandledPass); return sendRecursively.apply(this, sendRecursiveArguments); } else if (!isUnhandledPass) { return sendEvent.call(this, event, contexts, true); } } }; var sendEvent = function(eventName, sendRecursiveArguments, isUnhandledPass) { sendRecursiveArguments.unshift(eventName, get(this, 'currentState'), isUnhandledPass); return sendRecursively.apply(this, sendRecursiveArguments); }; /** StateManager is part of Ember's implementation of a finite state machine. A StateManager instance manages a number of properties that are instances of `Ember.State`, tracks the current active state, and triggers callbacks when states have changed. ## Defining States The states of StateManager can be declared in one of two ways. First, you can define a `states` property that contains all the states: ```javascript managerA = Ember.StateManager.create({ states: { stateOne: Ember.State.create(), stateTwo: Ember.State.create() } }) managerA.get('states') // { // stateOne: Ember.State.create(), // stateTwo: Ember.State.create() // } ``` You can also add instances of `Ember.State` (or an `Ember.State` subclass) directly as properties of a StateManager. These states will be collected into the `states` property for you. ```javascript managerA = Ember.StateManager.create({ stateOne: Ember.State.create(), stateTwo: Ember.State.create() }) managerA.get('states') // { // stateOne: Ember.State.create(), // stateTwo: Ember.State.create() // } ``` ## The Initial State When created a StateManager instance will immediately enter into the state defined as its `start` property or the state referenced by name in its `initialState` property: ```javascript managerA = Ember.StateManager.create({ start: Ember.State.create({}) }) managerA.get('currentState.name') // 'start' managerB = Ember.StateManager.create({ initialState: 'beginHere', beginHere: Ember.State.create({}) }) managerB.get('currentState.name') // 'beginHere' ``` Because it is a property you may also provide a computed function if you wish to derive an `initialState` programmatically: ```javascript managerC = Ember.StateManager.create({ initialState: function(){ if (someLogic) { return 'active'; } else { return 'passive'; } }.property(), active: Ember.State.create({}), passive: Ember.State.create({}) }) ``` ## Moving Between States A StateManager can have any number of `Ember.State` objects as properties and can have a single one of these states as its current state. Calling `transitionTo` transitions between states: ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({}), poweredUp: Ember.State.create({}) }) robotManager.get('currentState.name') // 'poweredDown' robotManager.transitionTo('poweredUp') robotManager.get('currentState.name') // 'poweredUp' ``` Before transitioning into a new state the existing `currentState` will have its `exit` method called with the StateManager instance as its first argument and an object representing the transition as its second argument. After transitioning into a new state the new `currentState` will have its `enter` method called with the StateManager instance as its first argument and an object representing the transition as its second argument. ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({ exit: function(stateManager){ console.log("exiting the poweredDown state") } }), poweredUp: Ember.State.create({ enter: function(stateManager){ console.log("entering the poweredUp state. Destroy all humans.") } }) }) robotManager.get('currentState.name') // 'poweredDown' robotManager.transitionTo('poweredUp') // will log // 'exiting the poweredDown state' // 'entering the poweredUp state. Destroy all humans.' ``` Once a StateManager is already in a state, subsequent attempts to enter that state will not trigger enter or exit method calls. Attempts to transition into a state that the manager does not have will result in no changes in the StateManager's current state: ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({ exit: function(stateManager){ console.log("exiting the poweredDown state") } }), poweredUp: Ember.State.create({ enter: function(stateManager){ console.log("entering the poweredUp state. Destroy all humans.") } }) }) robotManager.get('currentState.name') // 'poweredDown' robotManager.transitionTo('poweredUp') // will log // 'exiting the poweredDown state' // 'entering the poweredUp state. Destroy all humans.' robotManager.transitionTo('poweredUp') // no logging, no state change robotManager.transitionTo('someUnknownState') // silently fails robotManager.get('currentState.name') // 'poweredUp' ``` Each state property may itself contain properties that are instances of `Ember.State`. The StateManager can transition to specific sub-states in a series of transitionTo method calls or via a single transitionTo with the full path to the specific state. The StateManager will also keep track of the full path to its currentState ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({ charging: Ember.State.create(), charged: Ember.State.create() }), poweredUp: Ember.State.create({ mobile: Ember.State.create(), stationary: Ember.State.create() }) }) robotManager.get('currentState.name') // 'poweredDown' robotManager.transitionTo('poweredUp') robotManager.get('currentState.name') // 'poweredUp' robotManager.transitionTo('mobile') robotManager.get('currentState.name') // 'mobile' // transition via a state path robotManager.transitionTo('poweredDown.charging') robotManager.get('currentState.name') // 'charging' robotManager.get('currentState.path') // 'poweredDown.charging' ``` Enter transition methods will be called for each state and nested child state in their hierarchical order. Exit methods will be called for each state and its nested states in reverse hierarchical order. Exit transitions for a parent state are not called when entering into one of its child states, only when transitioning to a new section of possible states in the hierarchy. ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown', poweredDown: Ember.State.create({ enter: function(){}, exit: function(){ console.log("exited poweredDown state") }, charging: Ember.State.create({ enter: function(){}, exit: function(){} }), charged: Ember.State.create({ enter: function(){ console.log("entered charged state") }, exit: function(){ console.log("exited charged state") } }) }), poweredUp: Ember.State.create({ enter: function(){ console.log("entered poweredUp state") }, exit: function(){}, mobile: Ember.State.create({ enter: function(){ console.log("entered mobile state") }, exit: function(){} }), stationary: Ember.State.create({ enter: function(){}, exit: function(){} }) }) }) robotManager.get('currentState.path') // 'poweredDown' robotManager.transitionTo('charged') // logs 'entered charged state' // but does *not* log 'exited poweredDown state' robotManager.get('currentState.name') // 'charged robotManager.transitionTo('poweredUp.mobile') // logs // 'exited charged state' // 'exited poweredDown state' // 'entered poweredUp state' // 'entered mobile state' ``` During development you can set a StateManager's `enableLogging` property to `true` to receive console messages of state transitions. ```javascript robotManager = Ember.StateManager.create({ enableLogging: true }) ``` ## Managing currentState with Actions To control which transitions are possible for a given state, and appropriately handle external events, the StateManager can receive and route action messages to its states via the `send` method. Calling to `send` with an action name will begin searching for a method with the same name starting at the current state and moving up through the parent states in a state hierarchy until an appropriate method is found or the StateManager instance itself is reached. If an appropriately named method is found it will be called with the state manager as the first argument and an optional `context` object as the second argument. ```javascript managerA = Ember.StateManager.create({ initialState: 'stateOne.substateOne.subsubstateOne', stateOne: Ember.State.create({ substateOne: Ember.State.create({ anAction: function(manager, context){ console.log("an action was called") }, subsubstateOne: Ember.State.create({}) }) }) }) managerA.get('currentState.name') // 'subsubstateOne' managerA.send('anAction') // 'stateOne.substateOne.subsubstateOne' has no anAction method // so the 'anAction' method of 'stateOne.substateOne' is called // and logs "an action was called" // with managerA as the first argument // and no second argument someObject = {} managerA.send('anAction', someObject) // the 'anAction' method of 'stateOne.substateOne' is called again // with managerA as the first argument and // someObject as the second argument. ``` If the StateManager attempts to send an action but does not find an appropriately named method in the current state or while moving upwards through the state hierarchy, it will repeat the process looking for a `unhandledEvent` method. If an `unhandledEvent` method is found, it will be called with the original event name as the second argument. If an `unhandledEvent` method is not found, the StateManager will throw a new Ember.Error. ```javascript managerB = Ember.StateManager.create({ initialState: 'stateOne.substateOne.subsubstateOne', stateOne: Ember.State.create({ substateOne: Ember.State.create({ subsubstateOne: Ember.State.create({}), unhandledEvent: function(manager, eventName, context) { console.log("got an unhandledEvent with name " + eventName); } }) }) }) managerB.get('currentState.name') // 'subsubstateOne' managerB.send('anAction') // neither `stateOne.substateOne.subsubstateOne` nor any of it's // parent states have a handler for `anAction`. `subsubstateOne` // also does not have a `unhandledEvent` method, but its parent // state, `substateOne`, does, and it gets fired. It will log // "got an unhandledEvent with name anAction" ``` Action detection only moves upwards through the state hierarchy from the current state. It does not search in other portions of the hierarchy. ```javascript managerC = Ember.StateManager.create({ initialState: 'stateOne.substateOne.subsubstateOne', stateOne: Ember.State.create({ substateOne: Ember.State.create({ subsubstateOne: Ember.State.create({}) }) }), stateTwo: Ember.State.create({ anAction: function(manager, context){ // will not be called below because it is // not a parent of the current state } }) }) managerC.get('currentState.name') // 'subsubstateOne' managerC.send('anAction') // Error: <Ember.StateManager:ember132> could not // respond to event anAction in state stateOne.substateOne.subsubstateOne. ``` Inside of an action method the given state should delegate `transitionTo` calls on its StateManager. ```javascript robotManager = Ember.StateManager.create({ initialState: 'poweredDown.charging', poweredDown: Ember.State.create({ charging: Ember.State.create({ chargeComplete: function(manager, context){ manager.transitionTo('charged') } }), charged: Ember.State.create({ boot: function(manager, context){ manager.transitionTo('poweredUp') } }) }), poweredUp: Ember.State.create({ beginExtermination: function(manager, context){ manager.transitionTo('rampaging') }, rampaging: Ember.State.create() }) }) robotManager.get('currentState.name') // 'charging' robotManager.send('boot') // throws error, no boot action // in current hierarchy robotManager.get('currentState.name') // remains 'charging' robotManager.send('beginExtermination') // throws error, no beginExtermination // action in current hierarchy robotManager.get('currentState.name') // remains 'charging' robotManager.send('chargeComplete') robotManager.get('currentState.name') // 'charged' robotManager.send('boot') robotManager.get('currentState.name') // 'poweredUp' robotManager.send('beginExtermination', allHumans) robotManager.get('currentState.name') // 'rampaging' ``` Transition actions can also be created using the `transitionTo` method of the `Ember.State` class. The following example StateManagers are equivalent: ```javascript aManager = Ember.StateManager.create({ stateOne: Ember.State.create({ changeToStateTwo: Ember.State.transitionTo('stateTwo') }), stateTwo: Ember.State.create({}) }) bManager = Ember.StateManager.create({ stateOne: Ember.State.create({ changeToStateTwo: function(manager, context){ manager.transitionTo('stateTwo', context) } }), stateTwo: Ember.State.create({}) }) ``` @class StateManager @namespace Ember @extends Ember.State **/ Ember.StateManager = Ember.State.extend({ /** @private When creating a new statemanager, look for a default state to transition into. This state can either be named `start`, or can be specified using the `initialState` property. @method init */ init: function() { this._super(); set(this, 'stateMeta', Ember.Map.create()); var initialState = get(this, 'initialState'); if (!initialState && get(this, 'states.start')) { initialState = 'start'; } if (initialState) { this.transitionTo(initialState); Ember.assert('Failed to transition to initial state "' + initialState + '"', !!get(this, 'currentState')); } }, stateMetaFor: function(state) { var meta = get(this, 'stateMeta'), stateMeta = meta.get(state); if (!stateMeta) { stateMeta = {}; meta.set(state, stateMeta); } return stateMeta; }, setStateMeta: function(state, key, value) { return set(this.stateMetaFor(state), key, value); }, getStateMeta: function(state, key) { return get(this.stateMetaFor(state), key); }, /** The current state from among the manager's possible states. This property should not be set directly. Use `transitionTo` to move between states by name. @property currentState @type Ember.State */ currentState: null, /** The path of the current state. Returns a string representation of the current state. @property currentPath @type String */ currentPath: Ember.computed('currentState', function() { return get(this, 'currentState.path'); }), /** The name of transitionEvent that this stateManager will dispatch @property transitionEvent @type String @default 'setup' */ transitionEvent: 'setup', /** If set to true, `errorOnUnhandledEvents` will cause an exception to be raised if you attempt to send an event to a state manager that is not handled by the current state or any of its parent states. @property errorOnUnhandledEvents @type Boolean @default true */ errorOnUnhandledEvent: true, send: function(event) { var contexts = [].slice.call(arguments, 1); Ember.assert('Cannot send event "' + event + '" while currentState is ' + get(this, 'currentState'), get(this, 'currentState')); return sendEvent.call(this, event, contexts, false); }, unhandledEvent: function(manager, event) { if (get(this, 'errorOnUnhandledEvent')) { throw new Ember.Error(this.toString() + " could not respond to event " + event + " in state " + get(this, 'currentState.path') + "."); } }, /** Finds a state by its state path. Example: ```javascript manager = Ember.StateManager.create({ root: Ember.State.create({ dashboard: Ember.State.create() }) }); manager.getStateByPath(manager, "root.dashboard") // returns the dashboard state ``` @method getStateByPath @param {Ember.State} root the state to start searching from @param {String} path the state path to follow @return {Ember.State} the state at the end of the path */ getStateByPath: function(root, path) { var parts = path.split('.'), state = root; for (var i=0, len=parts.length; i<len; i++) { state = get(get(state, 'states'), parts[i]); if (!state) { break; } } return state; }, findStateByPath: function(state, path) { var possible; while (!possible && state) { possible = this.getStateByPath(state, path); state = get(state, 'parentState'); } return possible; }, /** A state stores its child states in its `states` hash. This code takes a path like `posts.show` and looks up `root.states.posts.states.show`. It returns a list of all of the states from the root, which is the list of states to call `enter` on. @method getStatesInPath @param root @param path */ getStatesInPath: function(root, path) { if (!path || path === "") { return undefined; } var parts = path.split('.'), result = [], states, state; for (var i=0, len=parts.length; i<len; i++) { states = get(root, 'states'); if (!states) { return undefined; } state = get(states, parts[i]); if (state) { root = state; result.push(state); } else { return undefined; } } return result; }, goToState: function() { // not deprecating this yet so people don't constantly need to // make trivial changes for little reason. return this.transitionTo.apply(this, arguments); }, transitionTo: function(path, context) { // XXX When is transitionTo called with no path if (Ember.isEmpty(path)) { return; } // The ES6 signature of this function is `path, ...contexts` var contexts = context ? Array.prototype.slice.call(arguments, 1) : [], currentState = get(this, 'currentState') || this; // First, get the enter, exit and resolve states for the current state // and specified path. If possible, use an existing cache. var hash = this.contextFreeTransition(currentState, path); // Next, process the raw state information for the contexts passed in. var transition = new Transition(hash).normalize(this, contexts); this.enterState(transition); this.triggerSetupContext(transition); }, contextFreeTransition: function(currentState, path) { var cache = currentState.pathsCache[path]; if (cache) { return cache; } var enterStates = this.getStatesInPath(currentState, path), exitStates = [], resolveState = currentState; // Walk up the states. For each state, check whether a state matching // the `path` is nested underneath. This will find the closest // parent state containing `path`. // // This allows the user to pass in a relative path. For example, for // the following state hierarchy: // // | |root // | |- posts // | | |- show (* current) // | |- comments // | | |- show // // If the current state is `<root.posts.show>`, an attempt to // transition to `comments.show` will match `<root.comments.show>`. // // First, this code will look for root.posts.show.comments.show. // Next, it will look for root.posts.comments.show. Finally, // it will look for `root.comments.show`, and find the state. // // After this process, the following variables will exist: // // * resolveState: a common parent state between the current // and target state. In the above example, `<root>` is the // `resolveState`. // * enterStates: a list of all of the states represented // by the path from the `resolveState`. For example, for // the path `root.comments.show`, `enterStates` would have // `[<root.comments>, <root.comments.show>]` // * exitStates: a list of all of the states from the // `resolveState` to the `currentState`. In the above // example, `exitStates` would have // `[<root.posts>`, `<root.posts.show>]`. while (resolveState && !enterStates) { exitStates.unshift(resolveState); resolveState = get(resolveState, 'parentState'); if (!resolveState) { enterStates = this.getStatesInPath(this, path); if (!enterStates) { Ember.assert('Could not find state for path: "'+path+'"'); return; } } enterStates = this.getStatesInPath(resolveState, path); } // If the path contains some states that are parents of both the // current state and the target state, remove them. // // For example, in the following hierarchy: // // |- root // | |- post // | | |- index (* current) // | | |- show // // If the `path` is `root.post.show`, the three variables will // be: // // * resolveState: `<state manager>` // * enterStates: `[<root>, <root.post>, <root.post.show>]` // * exitStates: `[<root>, <root.post>, <root.post.index>]` // // The goal of this code is to remove the common states, so we // have: // // * resolveState: `<root.post>` // * enterStates: `[<root.post.show>]` // * exitStates: `[<root.post.index>]` // // This avoid unnecessary calls to the enter and exit transitions. while (enterStates.length > 0 && enterStates[0] === exitStates[0]) { resolveState = enterStates.shift(); exitStates.shift(); } // Cache the enterStates, exitStates, and resolveState for the // current state and the `path`. var transitions = currentState.pathsCache[path] = { exitStates: exitStates, enterStates: enterStates, resolveState: resolveState }; return transitions; }, triggerSetupContext: function(transitions) { var contexts = transitions.contexts, offset = transitions.enterStates.length - contexts.length, enterStates = transitions.enterStates, transitionEvent = get(this, 'transitionEvent'); Ember.assert("More contexts provided than states", offset >= 0); arrayForEach.call(enterStates, function(state, idx) { state.trigger(transitionEvent, this, contexts[idx-offset]); }, this); }, getState: function(name) { var state = get(this, name), parentState = get(this, 'parentState'); if (state) { return state; } else if (parentState) { return parentState.getState(name); } }, enterState: function(transition) { var log = this.enableLogging; var exitStates = transition.exitStates.slice(0).reverse(); arrayForEach.call(exitStates, function(state) { state.trigger('exit', this); }, this); arrayForEach.call(transition.enterStates, function(state) { if (log) { Ember.Logger.log("STATEMANAGER: Entering " + get(state, 'path')); } state.trigger('enter', this); }, this); set(this, 'currentState', transition.finalState); } }); })(); (function() { /** Ember States @module ember @submodule ember-states @requires ember-runtime */ })(); })(); // Version: v1.0.0-pre.3-19-g015138e // Last commit: 015138e (2013-01-17 23:02:17 -0800) (function() { /** Ember @module ember */ })();
// # Ghost Foot Helper // Usage: `{{ghost_foot}}` // // Outputs scripts and other assets at the bottom of a Ghost theme // // We use the name ghost_foot to match the helper for consistency: // jscs:disable requireCamelCaseOrUpperCaseIdentifiers var hbs = require('express-hbs'), _ = require('lodash'), filters = require('../filters'), api = require('../api'), ghost_foot; ghost_foot = function (options) { /*jshint unused:false*/ var foot = []; return api.settings.read({key: 'ghost_foot'}).then(function (response) { foot.push(response.settings[0].value); return filters.doFilter('ghost_foot', foot); }).then(function (foot) { var footString = _.reduce(foot, function (memo, item) { return memo + ' ' + item; }, ''); return new hbs.handlebars.SafeString(footString.trim()); }); }; module.exports = ghost_foot;
this is file 354
;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edges'); /** * This edge renderer will display edges as curves with arrow heading. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edges.curvedArrow = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'), cp = {}, size = edge[prefix + 'size'] || 1, tSize = target[prefix + 'size'], sX = source[prefix + 'x'], sY = source[prefix + 'y'], tX = target[prefix + 'x'], tY = target[prefix + 'y'], aSize = Math.max(size * 2.5, settings('minArrowSize')), d, aX, aY, vX, vY; cp = (source.id === target.id) ? sigma.utils.getSelfLoopControlPoints(sX, sY, tSize) : sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY); if (source.id === target.id) { d = Math.sqrt(Math.pow(tX - cp.x1, 2) + Math.pow(tY - cp.y1, 2)); aX = cp.x1 + (tX - cp.x1) * (d - aSize - tSize) / d; aY = cp.y1 + (tY - cp.y1) * (d - aSize - tSize) / d; vX = (tX - cp.x1) * aSize / d; vY = (tY - cp.y1) * aSize / d; } else { d = Math.sqrt(Math.pow(tX - cp.x, 2) + Math.pow(tY - cp.y, 2)); aX = cp.x + (tX - cp.x) * (d - aSize - tSize) / d; aY = cp.y + (tY - cp.y) * (d - aSize - tSize) / d; vX = (tX - cp.x) * aSize / d; vY = (tY - cp.y) * aSize / d; } if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo(sX, sY); if (source.id === target.id) { context.bezierCurveTo(cp.x2, cp.y2, cp.x1, cp.y1, aX, aY); } else { context.quadraticCurveTo(cp.x, cp.y, aX, aY); } context.stroke(); context.fillStyle = color; context.beginPath(); context.moveTo(aX + vX, aY + vY); context.lineTo(aX + vY * 0.6, aY - vX * 0.6); context.lineTo(aX - vY * 0.6, aY + vX * 0.6); context.lineTo(aX + vX, aY + vY); context.closePath(); context.fill(); }; })();
/* * Snap.js * * Copyright 2013, Jacob Kelley - http://jakiestfu.com/ * Released under the MIT Licence * http://opensource.org/licenses/MIT * * Github: http://github.com/jakiestfu/Snap.js/ * Version: 1.9.3 */ /*jslint browser: true*/ /*global define, module, ender*/ (function(win, doc) { 'use strict'; var backdrop = null; var Snap = Snap || function(userOpts) { var settings = { element: null, dragger: null, disable: 'none', addBodyClasses: true, hyperextensible: true, resistance: 0.5, flickThreshold: 50, transitionSpeed: 0.3, easing: 'ease', maxPosition: 266, minPosition: -266, tapToClose: true, touchToDrag: true, slideIntent: 40, // degrees minDragDistance: 5 }, cache = { simpleStates: { opening: null, towards: null, hyperExtending: null, halfway: null, flick: null, translation: { absolute: 0, relative: 0, sinceDirectionChange: 0, percentage: 0 } } }, eventList = {}, utils = { hasTouch: ('ontouchstart' in doc.documentElement || win.navigator.msPointerEnabled), eventType: function(action) { var eventTypes = { down: (utils.hasTouch ? 'touchstart' : 'mousedown'), move: (utils.hasTouch ? 'touchmove' : 'mousemove'), up: (utils.hasTouch ? 'touchend' : 'mouseup'), out: (utils.hasTouch ? 'touchcancel' : 'mouseout') }; return eventTypes[action]; }, page: function(t, e){ return (utils.hasTouch && e.touches.length && e.touches[0]) ? e.touches[0]['page'+t] : e['page'+t]; }, klass: { has: function(el, name){ return (el.className).indexOf(name) !== -1; }, add: function(el, name){ if(!utils.klass.has(el, name) && settings.addBodyClasses){ el.className += " "+name; } }, remove: function(el, name){ if(settings.addBodyClasses){ el.className = (el.className).replace(name, "").replace(/^\s+|\s+$/g, ''); } } }, dispatchEvent: function(type) { if (typeof eventList[type] === 'function') { return eventList[type].call(); } }, // @phonon createBackdrop: function() { if(!backdrop) { var bd = document.createElement('div'); bd.classList.add('backdrop-panel'); backdrop = bd; document.querySelector('.app-active').appendChild(backdrop); } }, removeBackdrop: function() { if(backdrop) { // Set backdrop to null immediately var _backdrop = backdrop; backdrop = null; // query the current page in case of page navigation with a side panel link var page = document.querySelector('.app-active'); var closed = function () { _backdrop.classList.remove('fadeout'); page.removeChild(_backdrop); _backdrop.off(phonon.event.transitionEnd, closed); }; _backdrop.classList.add('fadeout'); _backdrop.on(phonon.event.transitionEnd, closed); } }, vendor: function(){ var tmp = doc.createElement("div"), prefixes = 'webkit Moz O ms'.split(' '), i; for (i in prefixes) { if (typeof tmp.style[prefixes[i] + 'Transition'] !== 'undefined') { return prefixes[i]; } } }, transitionCallback: function(){ return (cache.vendor==='Moz' || cache.vendor==='ms') ? 'transitionend' : cache.vendor+'TransitionEnd'; }, canTransform: function(){ return typeof settings.element.style[cache.vendor+'Transform'] !== 'undefined'; }, deepExtend: function(destination, source) { var property; for (property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; utils.deepExtend(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; }, angleOfDrag: function(x, y) { var degrees, theta; // Calc Theta theta = Math.atan2(-(cache.startDragY - y), (cache.startDragX - x)); if (theta < 0) { theta += 2 * Math.PI; } // Calc Degrees degrees = Math.floor(theta * (180 / Math.PI) - 180); if (degrees < 0 && degrees > -180) { degrees = 360 - Math.abs(degrees); } return Math.abs(degrees); }, events: { addEvent: function addEvent(element, eventName, func) { if (element.addEventListener) { return element.addEventListener(eventName, func, false); } else if (element.attachEvent) { return element.attachEvent("on" + eventName, func); } }, removeEvent: function addEvent(element, eventName, func) { if (element.addEventListener) { return element.removeEventListener(eventName, func, false); } else if (element.attachEvent) { return element.detachEvent("on" + eventName, func); } }, prevent: function(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } }, parentUntil: function(el, attr) { var isStr = typeof attr === 'string'; while (el.parentNode) { if (isStr && el.getAttribute && el.getAttribute(attr)){ return el; } else if(!isStr && el === attr){ return el; } el = el.parentNode; } return null; } }, action = { translate: { get: { matrix: function(index) { if( !utils.canTransform() ){ return parseInt(settings.element.style.left, 10); } else { var matrix = win.getComputedStyle(settings.element)[cache.vendor+'Transform'].match(/\((.*)\)/), ieOffset = 8; if (matrix) { matrix = matrix[1].split(','); if(matrix.length===16){ index+=ieOffset; } return parseInt(matrix[index], 10); } return 0; } } }, easeCallback: function(){ settings.element.style[cache.vendor+'Transition'] = ''; cache.translation = action.translate.get.matrix(4); cache.easing = false; clearInterval(cache.animatingInterval); if(cache.easingTo===0){ utils.klass.remove(doc.body, 'snapjs-right'); utils.klass.remove(doc.body, 'snapjs-left'); } utils.dispatchEvent('animated'); utils.events.removeEvent(settings.element, utils.transitionCallback(), action.translate.easeCallback); }, easeTo: function(n) { // @phonon if(n === 0) { utils.removeBackdrop(); } if( !utils.canTransform() ){ cache.translation = n; action.translate.x(n); } else { cache.easing = true; cache.easingTo = n; settings.element.style[cache.vendor+'Transition'] = 'all ' + settings.transitionSpeed + 's ' + settings.easing; cache.animatingInterval = setInterval(function() { utils.dispatchEvent('animating'); }, 1); utils.events.addEvent(settings.element, utils.transitionCallback(), action.translate.easeCallback); action.translate.x(n); } if(n===0){ settings.element.style[cache.vendor+'Transform'] = ''; } }, x: function(n) { if( (settings.disable==='left' && n>0) || (settings.disable==='right' && n<0) ){ return; } if( !settings.hyperextensible ){ if( n===settings.maxPosition || n>settings.maxPosition ){ n=settings.maxPosition; } else if( n===settings.minPosition || n<settings.minPosition ){ n=settings.minPosition; } } n = parseInt(n, 10); if(isNaN(n)){ n = 0; } if( utils.canTransform() ){ var theTranslate = 'translate3d(' + n + 'px, 0,0)'; settings.element.style[cache.vendor+'Transform'] = theTranslate; } else { settings.element.style.width = (win.innerWidth || doc.documentElement.clientWidth)+'px'; settings.element.style.left = n+'px'; settings.element.style.right = ''; } } }, drag: { listen: function() { cache.translation = 0; cache.easing = false; utils.events.addEvent(settings.element, utils.eventType('down'), action.drag.startDrag); utils.events.addEvent(settings.element, utils.eventType('move'), action.drag.dragging); utils.events.addEvent(settings.element, utils.eventType('up'), action.drag.endDrag); }, stopListening: function() { utils.events.removeEvent(settings.element, utils.eventType('down'), action.drag.startDrag); utils.events.removeEvent(settings.element, utils.eventType('move'), action.drag.dragging); utils.events.removeEvent(settings.element, utils.eventType('up'), action.drag.endDrag); }, startDrag: function(e) { // No drag on ignored elements var target = e.target ? e.target : e.srcElement, ignoreParent = utils.parentUntil(target, 'data-snap-ignore'); if (ignoreParent) { utils.dispatchEvent('ignore'); return; } if(settings.dragger){ var dragParent = utils.parentUntil(target, settings.dragger); // Only use dragger if we're in a closed state if( !dragParent && (cache.translation !== settings.minPosition && cache.translation !== settings.maxPosition )){ return; } } utils.dispatchEvent('start'); settings.element.style[cache.vendor+'Transition'] = ''; cache.isDragging = true; cache.hasIntent = null; cache.intentChecked = false; cache.startDragX = utils.page('X', e); cache.startDragY = utils.page('Y', e); cache.dragWatchers = { current: 0, last: 0, hold: 0, state: '' }; cache.simpleStates = { opening: null, towards: null, hyperExtending: null, halfway: null, flick: null, translation: { absolute: 0, relative: 0, sinceDirectionChange: 0, percentage: 0 } }; }, dragging: function(e) { if (cache.isDragging && settings.touchToDrag) { var thePageX = utils.page('X', e), thePageY = utils.page('Y', e), translated = cache.translation, absoluteTranslation = action.translate.get.matrix(4), whileDragX = thePageX - cache.startDragX, openingLeft = absoluteTranslation > 0, translateTo = whileDragX, diff; // Shown no intent already if((cache.intentChecked && !cache.hasIntent)){ return; } if(settings.addBodyClasses){ if((absoluteTranslation)>0){ utils.klass.add(doc.body, 'snapjs-left'); utils.klass.remove(doc.body, 'snapjs-right'); } else if((absoluteTranslation)<0){ utils.klass.add(doc.body, 'snapjs-right'); utils.klass.remove(doc.body, 'snapjs-left'); } } if (cache.hasIntent === false || cache.hasIntent === null) { var deg = utils.angleOfDrag(thePageX, thePageY), inRightRange = (deg >= 0 && deg <= settings.slideIntent) || (deg <= 360 && deg > (360 - settings.slideIntent)), inLeftRange = (deg >= 180 && deg <= (180 + settings.slideIntent)) || (deg <= 180 && deg >= (180 - settings.slideIntent)); if (!inLeftRange && !inRightRange) { cache.hasIntent = false; } else { cache.hasIntent = true; } cache.intentChecked = true; } if ( (settings.minDragDistance>=Math.abs(thePageX-cache.startDragX)) || // Has user met minimum drag distance? (cache.hasIntent === false) ) { return; } utils.events.prevent(e); utils.dispatchEvent('drag'); cache.dragWatchers.current = thePageX; // Determine which direction we are going if (cache.dragWatchers.last > thePageX) { if (cache.dragWatchers.state !== 'left') { cache.dragWatchers.state = 'left'; cache.dragWatchers.hold = thePageX; } cache.dragWatchers.last = thePageX; } else if (cache.dragWatchers.last < thePageX) { if (cache.dragWatchers.state !== 'right') { cache.dragWatchers.state = 'right'; cache.dragWatchers.hold = thePageX; } cache.dragWatchers.last = thePageX; } if (openingLeft) { // Pulling too far to the right if (settings.maxPosition < absoluteTranslation) { diff = (absoluteTranslation - settings.maxPosition) * settings.resistance; translateTo = whileDragX - diff; } cache.simpleStates = { opening: 'left', towards: cache.dragWatchers.state, hyperExtending: settings.maxPosition < absoluteTranslation, halfway: absoluteTranslation > (settings.maxPosition / 2), flick: Math.abs(cache.dragWatchers.current - cache.dragWatchers.hold) > settings.flickThreshold, translation: { absolute: absoluteTranslation, relative: whileDragX, sinceDirectionChange: (cache.dragWatchers.current - cache.dragWatchers.hold), percentage: (absoluteTranslation/settings.maxPosition)*100 } }; } else { // Pulling too far to the left if (settings.minPosition > absoluteTranslation) { diff = (absoluteTranslation - settings.minPosition) * settings.resistance; translateTo = whileDragX - diff; } cache.simpleStates = { opening: 'right', towards: cache.dragWatchers.state, hyperExtending: settings.minPosition > absoluteTranslation, halfway: absoluteTranslation < (settings.minPosition / 2), flick: Math.abs(cache.dragWatchers.current - cache.dragWatchers.hold) > settings.flickThreshold, translation: { absolute: absoluteTranslation, relative: whileDragX, sinceDirectionChange: (cache.dragWatchers.current - cache.dragWatchers.hold), percentage: (absoluteTranslation/settings.minPosition)*100 } }; } action.translate.x(translateTo + translated); } // @phonon if(translateTo > 5) { utils.createBackdrop(); } }, endDrag: function(e) { if (cache.isDragging) { utils.dispatchEvent('end'); var translated = action.translate.get.matrix(4); // Tap Close if (cache.dragWatchers.current === 0 && translated !== 0 && settings.tapToClose) { utils.dispatchEvent('close'); utils.events.prevent(e); action.translate.easeTo(0); cache.isDragging = false; cache.startDragX = 0; return; } // Revealing Left if (cache.simpleStates.opening === 'left') { // Halfway, Flicking, or Too Far Out if ((cache.simpleStates.halfway || cache.simpleStates.hyperExtending || cache.simpleStates.flick)) { if (cache.simpleStates.flick && cache.simpleStates.towards === 'left') { // Flicking Closed action.translate.easeTo(0); } else if ( (cache.simpleStates.flick && cache.simpleStates.towards === 'right') || // Flicking Open OR (cache.simpleStates.halfway || cache.simpleStates.hyperExtending) // At least halfway open OR hyperextending ) { action.translate.easeTo(settings.maxPosition); // Open Left } } else { action.translate.easeTo(0); // Close Left } // Revealing Right } else if (cache.simpleStates.opening === 'right') { // Halfway, Flicking, or Too Far Out if ((cache.simpleStates.halfway || cache.simpleStates.hyperExtending || cache.simpleStates.flick)) { if (cache.simpleStates.flick && cache.simpleStates.towards === 'right') { // Flicking Closed action.translate.easeTo(0); } else if ( (cache.simpleStates.flick && cache.simpleStates.towards === 'left') || // Flicking Open OR (cache.simpleStates.halfway || cache.simpleStates.hyperExtending) // At least halfway open OR hyperextending ) { action.translate.easeTo(settings.minPosition); // Open Right } } else { action.translate.easeTo(0); // Close Right } } cache.isDragging = false; cache.startDragX = utils.page('X', e); } } } }, init = function(opts) { if (opts.element) { utils.deepExtend(settings, opts); cache.vendor = utils.vendor(); action.drag.listen(); } }; /* * Public */ this.open = function(side) { // @phonon utils.createBackdrop(); utils.dispatchEvent('open'); utils.klass.remove(doc.body, 'snapjs-expand-left'); utils.klass.remove(doc.body, 'snapjs-expand-right'); if (side === 'left') { cache.simpleStates.opening = 'left'; cache.simpleStates.towards = 'right'; utils.klass.add(doc.body, 'snapjs-left'); utils.klass.remove(doc.body, 'snapjs-right'); action.translate.easeTo(settings.maxPosition); } else if (side === 'right') { cache.simpleStates.opening = 'right'; cache.simpleStates.towards = 'left'; utils.klass.remove(doc.body, 'snapjs-left'); utils.klass.add(doc.body, 'snapjs-right'); action.translate.easeTo(settings.minPosition); } }; this.close = function() { utils.dispatchEvent('close'); action.translate.easeTo(0); }; this.expand = function(side){ var to = win.innerWidth || doc.documentElement.clientWidth; if(side==='left'){ utils.dispatchEvent('expandLeft'); utils.klass.add(doc.body, 'snapjs-expand-left'); utils.klass.remove(doc.body, 'snapjs-expand-right'); } else { utils.dispatchEvent('expandRight'); utils.klass.add(doc.body, 'snapjs-expand-right'); utils.klass.remove(doc.body, 'snapjs-expand-left'); to *= -1; } action.translate.easeTo(to); }; this.on = function(evt, fn) { eventList[evt] = fn; return this; }; this.off = function(evt) { if (eventList[evt]) { eventList[evt] = false; } }; this.enable = function() { utils.dispatchEvent('enable'); action.drag.listen(); }; this.disable = function() { utils.dispatchEvent('disable'); action.drag.stopListening(); }; this.settings = function(opts){ utils.deepExtend(settings, opts); }; this.state = function() { var state, fromLeft = action.translate.get.matrix(4); if (fromLeft === settings.maxPosition) { state = 'left'; } else if (fromLeft === settings.minPosition) { state = 'right'; } else { state = 'closed'; } return { state: state, info: cache.simpleStates }; }; init(userOpts); }; if ((typeof module !== 'undefined') && module.exports) { module.exports = Snap; } if (typeof ender === 'undefined') { this.Snap = Snap; } if ((typeof define === "function") && define.amd) { define("snap", [], function() { return Snap; }); } }).call(this, window, document); /* ======================================================================== * Phonon: side-panels.js v0.0.1 * http://phonon.quarkdev.com * ======================================================================== * Licensed under MIT (http://phonon.quarkdev.com) * ======================================================================== */ ;(function (window, phonon) { 'use strict'; var isPhone = matchMedia('only screen and (min-width: 641px)').matches ? false : true; var sidePanels = []; var sidePanelActive = null; function findSidebar(id) { var i = sidePanels.length - 1; for (; i >= 0; i--) { if(sidePanels[i].el.id === id) { return sidePanels[i]; } } } /** * Render the sidebar of the current page */ function render(evt) { var currentPage = (typeof evt !== 'undefined' ? evt.detail.page : phonon.navigator().currentPage); var pageEl = document.querySelector(currentPage); var tabs = pageEl.querySelector('[data-tab-contents="true"]'); var i = sidePanels.length - 1; for (; i >= 0; i--) { var sb = sidePanels[i]; var page = sb.el.getAttribute('data-page'); var exposeAside = sb.el.getAttribute('data-expose-aside'); if(page !== currentPage) { sb.el.style.display = 'none'; sb.el.style.visibility = 'hidden'; } else { sb.el.style.display = 'block'; sb.el.style.visibility = 'visible'; // If tabs are present, disable drag, then setup if(tabs) { sidePanels[i].snapper.disable(); } // Expose side bar if(exposeAside === 'left' || exposeAside === 'right') { if(!pageEl.classList.contains('expose-aside-' + exposeAside)) { pageEl.classList.add('expose-aside-' + exposeAside); } } // On tablet, the sidebar is draggable only if it is not exposed on a side if(!isPhone) { if(!tabs && exposeAside !== 'left' && exposeAside !== 'right') { sb.snapper.settings( {touchToDrag: true} ); sb.snapper.enable(); } else { sb.snapper.settings( {touchToDrag: false} ); sb.snapper.disable(); } } // On phone, the sidebar is draggable only if tabs are not present if(!tabs && isPhone) { sb.snapper.settings( {touchToDrag: true} ); sb.snapper.enable(); } } } } /** * When the window is resized, update the width of sidebars */ function resize() { var oldValue = isPhone; isPhone = matchMedia('only screen and (min-width: 641px)').matches ? false : true; if(oldValue !== isPhone) { // Update the min/max position for drag window.setTimeout(function() { var i = sidePanels.length - 1; for (; i >= 0; i--) { var sb = sidePanels[i]; sb.snapper.settings({ maxPosition: sb.el.clientWidth, minPosition: -(sb.el.clientWidth) }); } }, 500); // finaly update settings render(); } } phonon.onReady(function() { var spEls = document.querySelectorAll('.side-panel'); var i = spEls.length - 1; for (; i >= 0; i--) { var el = spEls[i]; var disable = el.getAttribute('data-disable'); var page = el.getAttribute('data-page'); var pageEl = document.querySelector(page); // Options var options = { element: pageEl, disable: (disable === null ? 'none' : disable), hyperextensible: false, touchToDrag: false, maxPosition: el.clientWidth, minPosition: -(el.clientWidth) }; var snapper = new Snap(options); sidePanels.push({snapper: snapper, el: el, direction: (el.classList.contains('side-panel-left') ? 'left' : 'right')}); } }); function open(sb) { sidePanelActive = sb; sb.snapper.open(sb.direction); document.on(phonon.event.end, onBackdrop); } function close(sb) { sb.snapper.close(); sidePanelActive = null; document.off(phonon.event.end, onBackdrop); } function onSidebar(target) { var isSidebar = false; for (; target && target !== document; target = target.parentNode) { if (target.classList.contains('side-panel')) { isSidebar = true; break; } } return isSidebar; } document.on(phonon.event.tap, function(evt) { var target = evt.target; var sidebarId = target.getAttribute('data-side-panel-id'); var sidebarClose = target.getAttribute('data-side-panel-close'); if(sidebarClose === 'true') { if(sidePanelActive) close(sidePanelActive); return; } if(sidebarId !== null) { var sb = findSidebar(sidebarId); if(sb) { var data = sb.snapper.state(); // /!\ if not exposed var exposeAside = sb.el.getAttribute('data-expose-aside'); // Toggle if(data.state === 'closed') { if(exposeAside !== 'left' && exposeAside !== 'right' || isPhone) open(sb); } else { if(exposeAside !== 'left' && exposeAside !== 'right' || isPhone) close(sb); } } } }); var onBackdrop = function(evt) { var target = evt.target; var onSidebar = false; if(sidePanelActive === null) return; for (; target && target !== document; target = target.parentNode) { if (target.classList.contains('side-panel')) { onSidebar = true; break; } } if(sidePanelActive && !onSidebar) { close(sidePanelActive); sidePanelActive = null; } }; phonon.sidePanel = function() { return { closeActive: function() { var currentPage = phonon.navigator().currentPage; var i = sidePanels.length - 1; for (; i >= 0; i--) { var sb = sidePanels[i]; var page = sb.el.getAttribute('data-page'); var exposeAside = sb.el.getAttribute('data-expose-aside'); if(page === currentPage) { var data = sb.snapper.state(); if(data.state !== 'closed') { if(isPhone) { close(sb); return true; } if(!isPhone && exposeAside !== 'left' && exposeAside !== 'right') { close(sb); return true; } } return false; } } return false; } }; } window.on('resize', resize); document.on('pageopened', render); }(typeof window !== 'undefined' ? window : this, window.phonon || {}));
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Datastructure: Hash Map. * * @author arv@google.com (Erik Arvidsson) * * This file contains an implementation of a Map structure. It implements a lot * of the methods used in goog.structs so those functions work on hashes. This * is best suited for complex key types. For simple keys such as numbers and * strings consider using the lighter-weight utilities in goog.object. */ goog.provide('goog.structs.Map'); goog.require('goog.iter.Iterator'); goog.require('goog.iter.StopIteration'); goog.require('goog.object'); /** * Class for Hash Map datastructure. * @param {*=} opt_map Map or Object to initialize the map with. * @param {...*} var_args If 2 or more arguments are present then they * will be used as key-value pairs. * @constructor * @template K, V */ goog.structs.Map = function(opt_map, var_args) { /** * Underlying JS object used to implement the map. * @private {!Object} */ this.map_ = {}; /** * An array of keys. This is necessary for two reasons: * 1. Iterating the keys using for (var key in this.map_) allocates an * object for every key in IE which is really bad for IE6 GC perf. * 2. Without a side data structure, we would need to escape all the keys * as that would be the only way we could tell during iteration if the * key was an internal key or a property of the object. * * This array can contain deleted keys so it's necessary to check the map * as well to see if the key is still in the map (this doesn't require a * memory allocation in IE). * @private {!Array<string>} */ this.keys_ = []; /** * The number of key value pairs in the map. * @private {number} */ this.count_ = 0; /** * Version used to detect changes while iterating. * @private {number} */ this.version_ = 0; var argLength = arguments.length; if (argLength > 1) { if (argLength % 2) { throw Error('Uneven number of arguments'); } for (var i = 0; i < argLength; i += 2) { this.set(arguments[i], arguments[i + 1]); } } else if (opt_map) { this.addAll(/** @type {Object} */ (opt_map)); } }; /** * @return {number} The number of key-value pairs in the map. */ goog.structs.Map.prototype.getCount = function() { return this.count_; }; /** * Returns the values of the map. * @return {!Array<V>} The values in the map. */ goog.structs.Map.prototype.getValues = function() { this.cleanupKeysArray_(); var rv = []; for (var i = 0; i < this.keys_.length; i++) { var key = this.keys_[i]; rv.push(this.map_[key]); } return rv; }; /** * Returns the keys of the map. * @return {!Array<string>} Array of string values. */ goog.structs.Map.prototype.getKeys = function() { this.cleanupKeysArray_(); return /** @type {!Array<string>} */ (this.keys_.concat()); }; /** * Whether the map contains the given key. * @param {*} key The key to check for. * @return {boolean} Whether the map contains the key. */ goog.structs.Map.prototype.containsKey = function(key) { return goog.structs.Map.hasKey_(this.map_, key); }; /** * Whether the map contains the given value. This is O(n). * @param {V} val The value to check for. * @return {boolean} Whether the map contains the value. */ goog.structs.Map.prototype.containsValue = function(val) { for (var i = 0; i < this.keys_.length; i++) { var key = this.keys_[i]; if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) { return true; } } return false; }; /** * Whether this map is equal to the argument map. * @param {goog.structs.Map} otherMap The map against which to test equality. * @param {function(V, V): boolean=} opt_equalityFn Optional equality function * to test equality of values. If not specified, this will test whether * the values contained in each map are identical objects. * @return {boolean} Whether the maps are equal. */ goog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) { if (this === otherMap) { return true; } if (this.count_ != otherMap.getCount()) { return false; } var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals; this.cleanupKeysArray_(); for (var key, i = 0; key = this.keys_[i]; i++) { if (!equalityFn(this.get(key), otherMap.get(key))) { return false; } } return true; }; /** * Default equality test for values. * @param {*} a The first value. * @param {*} b The second value. * @return {boolean} Whether a and b reference the same object. */ goog.structs.Map.defaultEquals = function(a, b) { return a === b; }; /** * @return {boolean} Whether the map is empty. */ goog.structs.Map.prototype.isEmpty = function() { return this.count_ == 0; }; /** * Removes all key-value pairs from the map. */ goog.structs.Map.prototype.clear = function() { this.map_ = {}; this.keys_.length = 0; this.count_ = 0; this.version_ = 0; }; /** * Removes a key-value pair based on the key. This is O(logN) amortized due to * updating the keys array whenever the count becomes half the size of the keys * in the keys array. * @param {*} key The key to remove. * @return {boolean} Whether object was removed. */ goog.structs.Map.prototype.remove = function(key) { if (goog.structs.Map.hasKey_(this.map_, key)) { delete this.map_[key]; this.count_--; this.version_++; // clean up the keys array if the threshhold is hit if (this.keys_.length > 2 * this.count_) { this.cleanupKeysArray_(); } return true; } return false; }; /** * Cleans up the temp keys array by removing entries that are no longer in the * map. * @private */ goog.structs.Map.prototype.cleanupKeysArray_ = function() { if (this.count_ != this.keys_.length) { // First remove keys that are no longer in the map. var srcIndex = 0; var destIndex = 0; while (srcIndex < this.keys_.length) { var key = this.keys_[srcIndex]; if (goog.structs.Map.hasKey_(this.map_, key)) { this.keys_[destIndex++] = key; } srcIndex++; } this.keys_.length = destIndex; } if (this.count_ != this.keys_.length) { // If the count still isn't correct, that means we have duplicates. This can // happen when the same key is added and removed multiple times. Now we have // to allocate one extra Object to remove the duplicates. This could have // been done in the first pass, but in the common case, we can avoid // allocating an extra object by only doing this when necessary. var seen = {}; var srcIndex = 0; var destIndex = 0; while (srcIndex < this.keys_.length) { var key = this.keys_[srcIndex]; if (!(goog.structs.Map.hasKey_(seen, key))) { this.keys_[destIndex++] = key; seen[key] = 1; } srcIndex++; } this.keys_.length = destIndex; } }; /** * Returns the value for the given key. If the key is not found and the default * value is not given this will return {@code undefined}. * @param {*} key The key to get the value for. * @param {DEFAULT=} opt_val The value to return if no item is found for the * given key, defaults to undefined. * @return {V|DEFAULT} The value for the given key. * @template DEFAULT */ goog.structs.Map.prototype.get = function(key, opt_val) { if (goog.structs.Map.hasKey_(this.map_, key)) { return this.map_[key]; } return opt_val; }; /** * Adds a key-value pair to the map. * @param {*} key The key. * @param {V} value The value to add. * @return {*} Some subclasses return a value. */ goog.structs.Map.prototype.set = function(key, value) { if (!(goog.structs.Map.hasKey_(this.map_, key))) { this.count_++; // TODO(johnlenz): This class lies, it claims to return an array of string // keys, but instead returns the original object used. this.keys_.push(/** @type {?} */ (key)); // Only change the version if we add a new key. this.version_++; } this.map_[key] = value; }; /** * Adds multiple key-value pairs from another goog.structs.Map or Object. * @param {Object} map Object containing the data to add. */ goog.structs.Map.prototype.addAll = function(map) { var keys, values; if (map instanceof goog.structs.Map) { keys = map.getKeys(); values = map.getValues(); } else { keys = goog.object.getKeys(map); values = goog.object.getValues(map); } // we could use goog.array.forEach here but I don't want to introduce that // dependency just for this. for (var i = 0; i < keys.length; i++) { this.set(keys[i], values[i]); } }; /** * Calls the given function on each entry in the map. * @param {function(this:T, V, K, goog.structs.Map<K,V>)} f * @param {T=} opt_obj The value of "this" inside f. * @template T */ goog.structs.Map.prototype.forEach = function(f, opt_obj) { var keys = this.getKeys(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = this.get(key); f.call(opt_obj, value, key, this); } }; /** * Clones a map and returns a new map. * @return {!goog.structs.Map} A new map with the same key-value pairs. */ goog.structs.Map.prototype.clone = function() { return new goog.structs.Map(this); }; /** * Returns a new map in which all the keys and values are interchanged * (keys become values and values become keys). If multiple keys map to the * same value, the chosen transposed value is implementation-dependent. * * It acts very similarly to {goog.object.transpose(Object)}. * * @return {!goog.structs.Map} The transposed map. */ goog.structs.Map.prototype.transpose = function() { var transposed = new goog.structs.Map(); for (var i = 0; i < this.keys_.length; i++) { var key = this.keys_[i]; var value = this.map_[key]; transposed.set(value, key); } return transposed; }; /** * @return {!Object} Object representation of the map. */ goog.structs.Map.prototype.toObject = function() { this.cleanupKeysArray_(); var obj = {}; for (var i = 0; i < this.keys_.length; i++) { var key = this.keys_[i]; obj[key] = this.map_[key]; } return obj; }; /** * Returns an iterator that iterates over the keys in the map. Removal of keys * while iterating might have undesired side effects. * @return {!goog.iter.Iterator} An iterator over the keys in the map. */ goog.structs.Map.prototype.getKeyIterator = function() { return this.__iterator__(true); }; /** * Returns an iterator that iterates over the values in the map. Removal of * keys while iterating might have undesired side effects. * @return {!goog.iter.Iterator} An iterator over the values in the map. */ goog.structs.Map.prototype.getValueIterator = function() { return this.__iterator__(false); }; /** * Returns an iterator that iterates over the values or the keys in the map. * This throws an exception if the map was mutated since the iterator was * created. * @param {boolean=} opt_keys True to iterate over the keys. False to iterate * over the values. The default value is false. * @return {!goog.iter.Iterator} An iterator over the values or keys in the map. */ goog.structs.Map.prototype.__iterator__ = function(opt_keys) { // Clean up keys to minimize the risk of iterating over dead keys. this.cleanupKeysArray_(); var i = 0; var version = this.version_; var selfObj = this; var newIter = new goog.iter.Iterator; newIter.next = function() { if (version != selfObj.version_) { throw Error('The map has changed since the iterator was created'); } if (i >= selfObj.keys_.length) { throw goog.iter.StopIteration; } var key = selfObj.keys_[i++]; return opt_keys ? key : selfObj.map_[key]; }; return newIter; }; /** * Safe way to test for hasOwnProperty. It even allows testing for * 'hasOwnProperty'. * @param {Object} obj The object to test for presence of the given key. * @param {*} key The key to check for. * @return {boolean} Whether the object has the key. * @private */ goog.structs.Map.hasKey_ = function(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); };
module.exports = function(opalParam) { var Opal = opalParam || require('opal-npm-wrapper').Opal; /* Generated by Opal 0.9.0.beta2 */ Opal.modules["asciidoctor/converter/docbook5"] = function(Opal) { Opal.dynamic_require_severity = "ignore"; var OPAL_CONFIG = { method_missing: false, arity_check: false, freezing: true, tainting: true }; function $rb_times(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs * rhs : lhs['$*'](rhs); } function $rb_le(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs <= rhs : lhs['$<='](rhs); } function $rb_minus(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs - rhs : lhs['$-'](rhs); } function $rb_plus(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs + rhs : lhs['$+'](rhs); } function $rb_gt(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs > rhs : lhs['$>'](rhs); } function $rb_lt(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs < rhs : lhs['$<'](rhs); } var self = Opal.top, $scope = Opal, nil = Opal.nil, $breaker = Opal.breaker, $slice = Opal.slice, $module = Opal.module, $klass = Opal.klass, $hash2 = Opal.hash2; return (function($base) { var self = $module($base, 'Asciidoctor'); var def = self.$$proto, $scope = self.$$scope; (function($base, $super) { function $DocBook5Converter(){}; var self = $DocBook5Converter = $klass($base, $super, 'DocBook5Converter', $DocBook5Converter); var def = self.$$proto, $scope = self.$$scope, $a, $b; def.asciimath_loaded = nil; Opal.defn(self, '$document', function(node) { var $a, self = this, result = nil, root_tag_name = nil, doctype_line = nil, lang_attribute = nil, footer_docinfo = nil; result = []; if (((root_tag_name = node.$doctype()))['$==']("manpage")) { root_tag_name = "refentry"}; result['$<<']("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if ((($a = (doctype_line = self.$doctype_declaration(root_tag_name))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](doctype_line)}; if ((($a = node['$attr?']("toc")) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = node['$attr?']("toclevels")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<?asciidoc-toc maxdepth=\"" + (node.$attr("toclevels")) + "\"?>") } else { result['$<<']("<?asciidoc-toc?>") }}; if ((($a = node['$attr?']("sectnums")) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = node['$attr?']("sectnumlevels")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<?asciidoc-numbered maxdepth=\"" + (node.$attr("sectnumlevels")) + "\"?>") } else { result['$<<']("<?asciidoc-numbered?>") }}; lang_attribute = (function() {if ((($a = (node['$attr?']("nolang"))) !== nil && (!$a.$$is_boolean || $a == true))) { return nil } else { return " " + (self.$lang_attribute_name()) + "=\"" + (node.$attr("lang", "en")) + "\"" }; return nil; })(); result['$<<']("<" + (root_tag_name) + (self.$document_ns_attributes(node)) + (lang_attribute) + ">"); result['$<<']((self.$document_info_element(node, root_tag_name))); if ((($a = node['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](node.$content())}; if ((($a = ((footer_docinfo = node.$docinfo("footer")))['$empty?']()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { result['$<<'](footer_docinfo) }; result['$<<']("</" + (root_tag_name) + ">"); return $rb_times(result, $scope.get('EOL')); }); Opal.alias(self, 'embedded', 'content'); Opal.defn(self, '$section', function(node) { var $a, $b, self = this, doctype = nil, tag_name = nil; doctype = node.$document().$doctype(); tag_name = (function() {if ((($a = node.$special()) !== nil && (!$a.$$is_boolean || $a == true))) { if ($rb_le(node.$level(), 1)) { return node.$sectname() } else { return "section" } } else if ((($a = (($b = doctype['$==']("book")) ? $rb_le(node.$level(), 1) : doctype['$==']("book"))) !== nil && (!$a.$$is_boolean || $a == true))) { return ((function() {if (node.$level()['$=='](0)) { return "part" } else { return "chapter" }; return nil; })()) } else { return "section" }; return nil; })(); if (doctype['$==']("manpage")) { if (tag_name['$==']("section")) { tag_name = "refsection" } else if (tag_name['$==']("synopsis")) { tag_name = "refsynopsisdiv"}}; return "<" + (tag_name) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n" + (node.$content()) + "\n</" + (tag_name) + ">"; }); Opal.defn(self, '$admonition', function(node) { var self = this, tag_name = nil; return "<" + (tag_name = node.$attr("name")) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$title_tag(node)) + (self.$resolve_content(node)) + "\n</" + (tag_name) + ">"; }); Opal.alias(self, 'audio', 'skip'); Opal.defn(self, '$colist', function(node) { var $a, $b, TMP_1, self = this, result = nil; result = []; result['$<<']("<calloutlist" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($b = node.$items()).$each, $a.$$p = (TMP_1 = function(item){var self = TMP_1.$$s || this, $a; if (item == null) item = nil; result['$<<']("<callout arearefs=\"" + (item.$attr("coids")) + "\">"); result['$<<']("<para>" + (item.$text()) + "</para>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</callout>");}, TMP_1.$$s = self, TMP_1), $a).call($b); result['$<<']("</calloutlist>"); return $rb_times(result, $scope.get('EOL')); }); (($a = [$scope.get('DLIST_TAGS')['$[]']("labeled")]), $b = (Opal.cdecl($scope, 'DLIST_TAGS', $hash2(["labeled", "qanda", "glossary"], {"labeled": $hash2(["list", "entry", "term", "item"], {"list": "variablelist", "entry": "varlistentry", "term": "term", "item": "listitem"}), "qanda": $hash2(["list", "entry", "label", "term", "item"], {"list": "qandaset", "entry": "qandaentry", "label": "question", "term": "simpara", "item": "answer"}), "glossary": $hash2(["list", "entry", "term", "item"], {"list": nil, "entry": "glossentry", "term": "glossterm", "item": "glossdef"})}))), $b['$default='].apply($b, $a), $a[$a.length-1]); Opal.defn(self, '$dlist', function(node) { var $a, $b, TMP_2, $c, TMP_4, self = this, result = nil, tag_name = nil, tags = nil, list_tag = nil, entry_tag = nil, label_tag = nil, term_tag = nil, item_tag = nil; result = []; if (node.$style()['$==']("horizontal")) { result['$<<']("<" + (tag_name = (function() {if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "table" } else { return "informaltable" }; return nil; })()) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + " tabstyle=\"horizontal\" frame=\"none\" colsep=\"0\" rowsep=\"0\">\n" + (self.$title_tag(node)) + "<tgroup cols=\"2\">\n<colspec colwidth=\"" + (node.$attr("labelwidth", 15)) + "*\"/>\n<colspec colwidth=\"" + (node.$attr("itemwidth", 85)) + "*\"/>\n<tbody valign=\"top\">"); ($a = ($b = node.$items()).$each, $a.$$p = (TMP_2 = function(terms, dd){var self = TMP_2.$$s || this, $a, $b, TMP_3; if (terms == null) terms = nil;if (dd == null) dd = nil; result['$<<']("<row>\n<entry>"); ($a = ($b = [].concat(Opal.to_a(terms))).$each, $a.$$p = (TMP_3 = function(dt){var self = TMP_3.$$s || this; if (dt == null) dt = nil; return result['$<<']("<simpara>" + (dt.$text()) + "</simpara>")}, TMP_3.$$s = self, TMP_3), $a).call($b); result['$<<']("</entry>\n<entry>"); if ((($a = dd['$nil?']()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { if ((($a = dd['$text?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<simpara>" + (dd.$text()) + "</simpara>")}; if ((($a = dd['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](dd.$content())}; }; return result['$<<']("</entry>\n</row>");}, TMP_2.$$s = self, TMP_2), $a).call($b); result['$<<']("</tbody>\n</tgroup>\n</" + (tag_name) + ">"); } else { tags = $scope.get('DLIST_TAGS')['$[]'](node.$style()); list_tag = tags['$[]']("list"); entry_tag = tags['$[]']("entry"); label_tag = tags['$[]']("label"); term_tag = tags['$[]']("term"); item_tag = tags['$[]']("item"); if (list_tag !== false && list_tag !== nil) { result['$<<']("<" + (list_tag) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")};}; ($a = ($c = node.$items()).$each, $a.$$p = (TMP_4 = function(terms, dd){var self = TMP_4.$$s || this, $a, $b, TMP_5; if (terms == null) terms = nil;if (dd == null) dd = nil; result['$<<']("<" + (entry_tag) + ">"); if (label_tag !== false && label_tag !== nil) { result['$<<']("<" + (label_tag) + ">")}; ($a = ($b = [].concat(Opal.to_a(terms))).$each, $a.$$p = (TMP_5 = function(dt){var self = TMP_5.$$s || this; if (dt == null) dt = nil; return result['$<<']("<" + (term_tag) + ">" + (dt.$text()) + "</" + (term_tag) + ">")}, TMP_5.$$s = self, TMP_5), $a).call($b); if (label_tag !== false && label_tag !== nil) { result['$<<']("</" + (label_tag) + ">")}; result['$<<']("<" + (item_tag) + ">"); if ((($a = dd['$nil?']()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { if ((($a = dd['$text?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<simpara>" + (dd.$text()) + "</simpara>")}; if ((($a = dd['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](dd.$content())}; }; result['$<<']("</" + (item_tag) + ">"); return result['$<<']("</" + (entry_tag) + ">");}, TMP_4.$$s = self, TMP_4), $a).call($c); if (list_tag !== false && list_tag !== nil) { result['$<<']("</" + (list_tag) + ">")}; }; return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$example', function(node) { var $a, self = this; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<example" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n" + (self.$resolve_content(node)) + "\n</example>" } else { return "<informalexample" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$resolve_content(node)) + "\n</informalexample>" }; }); Opal.defn(self, '$floating_title', function(node) { var self = this; return "<bridgehead" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + " renderas=\"sect" + (node.$level()) + "\">" + (node.$title()) + "</bridgehead>"; }); Opal.defn(self, '$image', function(node) { var $a, self = this, width_attribute = nil, depth_attribute = nil, swidth_attribute = nil, scale_attribute = nil, align_attribute = nil, mediaobject = nil; width_attribute = (function() {if ((($a = (node['$attr?']("width"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " contentwidth=\"" + (node.$attr("width")) + "\"" } else { return nil }; return nil; })(); depth_attribute = (function() {if ((($a = (node['$attr?']("height"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " contentdepth=\"" + (node.$attr("height")) + "\"" } else { return nil }; return nil; })(); swidth_attribute = (function() {if ((($a = (node['$attr?']("scaledwidth"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " width=\"" + (node.$attr("scaledwidth")) + "\" scalefit=\"1\"" } else { return nil }; return nil; })(); scale_attribute = (function() {if ((($a = (node['$attr?']("scale"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " scale=\"" + (node.$attr("scale")) + "\"" } else { return nil }; return nil; })(); align_attribute = (function() {if ((($a = (node['$attr?']("align"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " align=\"" + (node.$attr("align")) + "\"" } else { return nil }; return nil; })(); mediaobject = "<mediaobject>\n<imageobject>\n<imagedata fileref=\"" + (node.$image_uri(node.$attr("target"))) + "\"" + (width_attribute) + (depth_attribute) + (swidth_attribute) + (scale_attribute) + (align_attribute) + "/>\n</imageobject>\n<textobject><phrase>" + (node.$attr("alt")) + "</phrase></textobject>\n</mediaobject>"; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<figure" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n" + (mediaobject) + "\n</figure>" } else { return "<informalfigure" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (mediaobject) + "\n</informalfigure>" }; }); Opal.defn(self, '$listing', function(node) { var $a, $b, self = this, informal = nil, listing_attributes = nil, numbering = nil, listing_content = nil; informal = node['$title?']()['$!'](); listing_attributes = (self.$common_attributes(node.$id(), node.$role(), node.$reftext())); if ((($a = (($b = node.$style()['$==']("source")) ? (node['$attr?']("language")) : node.$style()['$==']("source"))) !== nil && (!$a.$$is_boolean || $a == true))) { numbering = (function() {if ((($a = (node['$attr?']("linenums"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "numbered" } else { return "unnumbered" }; return nil; })(); listing_content = "<programlisting" + ((function() {if (informal !== false && informal !== nil) { return listing_attributes } else { return nil }; return nil; })()) + " language=\"" + (node.$attr("language", nil, false)) + "\" linenumbering=\"" + (numbering) + "\">" + (node.$content()) + "</programlisting>"; } else { listing_content = "<screen" + ((function() {if (informal !== false && informal !== nil) { return listing_attributes } else { return nil }; return nil; })()) + ">" + (node.$content()) + "</screen>" }; if (informal !== false && informal !== nil) { return listing_content } else { return "<formalpara" + (listing_attributes) + ">\n<title>" + (node.$title()) + "</title>\n<para>\n" + (listing_content) + "\n</para>\n</formalpara>" }; }); Opal.defn(self, '$literal', function(node) { var $a, self = this; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<formalpara" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n<para>\n<literallayout class=\"monospaced\">" + (node.$content()) + "</literallayout>\n</para>\n</formalpara>" } else { return "<literallayout" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + " class=\"monospaced\">" + (node.$content()) + "</literallayout>" }; }); Opal.defn(self, '$stem', function(node) { var $a, $b, $c, $d, $e, self = this, idx = nil, equation = nil, equation_data = nil; if ((($a = (idx = node.$subs().$index("specialcharacters"))) !== nil && (!$a.$$is_boolean || $a == true))) { node.$subs().$delete("specialcharacters")}; equation = node.$content(); if (idx !== false && idx !== nil) { node.$subs().$insert(idx, "specialcharacters")}; if (node.$style()['$==']("latexmath")) { equation_data = "<alt><![CDATA[" + (equation) + "]]></alt>\n<mediaobject><textobject><phrase></phrase></textobject></mediaobject>" } else if ((($a = (($b = node.$style()['$==']("asciimath")) ? (((($c = ((Opal.Object.$$scope.AsciiMath == null ? nil : 'constant'))) !== false && $c !== nil) ? $c : ((function() {if ((($d = ((($e = self['asciimath_loaded'], $e != null && $e !== nil) ? 'instance-variable' : nil))['$!']()) !== nil && (!$d.$$is_boolean || $d == true))) { return (self.asciimath_loaded = $scope.get('Helpers').$require_library("asciimath", true, "warn")) } else { return self.asciimath_loaded }; return nil; })()))) : node.$style()['$==']("asciimath"))) !== nil && (!$a.$$is_boolean || $a == true))) { equation_data = Opal.get('AsciiMath').$parse(equation).$to_mathml("mml:", $hash2(["xmlns:mml"], {"xmlns:mml": "http://www.w3.org/1998/Math/MathML"})) } else { equation_data = "<mediaobject><textobject><phrase><![CDATA[" + (equation) + "]]></phrase></textobject></mediaobject>" }; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<equation" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n" + (equation_data) + "\n</equation>" } else { return "<informalequation" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (equation_data) + "\n</informalequation>" }; }); Opal.defn(self, '$olist', function(node) { var $a, $b, TMP_6, self = this, result = nil, num_attribute = nil, start_attribute = nil; result = []; num_attribute = (function() {if ((($a = node.$style()) !== nil && (!$a.$$is_boolean || $a == true))) { return " numeration=\"" + (node.$style()) + "\"" } else { return nil }; return nil; })(); start_attribute = (function() {if ((($a = (node['$attr?']("start"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " startingnumber=\"" + (node.$attr("start")) + "\"" } else { return nil }; return nil; })(); result['$<<']("<orderedlist" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + (num_attribute) + (start_attribute) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($b = node.$items()).$each, $a.$$p = (TMP_6 = function(item){var self = TMP_6.$$s || this, $a; if (item == null) item = nil; result['$<<']("<listitem>"); result['$<<']("<simpara>" + (item.$text()) + "</simpara>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</listitem>");}, TMP_6.$$s = self, TMP_6), $a).call($b); result['$<<']("</orderedlist>"); return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$open', function(node) { var $a, $b, $c, self = this, $case = nil; return (function() {$case = node.$style();if ("abstract"['$===']($case)) {if ((($a = (($b = node.$parent()['$=='](node.$document())) ? node.$document()['$attr?']("doctype", "book") : node.$parent()['$=='](node.$document()))) !== nil && (!$a.$$is_boolean || $a == true))) { self.$warn("asciidoctor: WARNING: abstract block cannot be used in a document without a title when doctype is book. Excluding block content."); return ""; } else { return "<abstract>\n" + (self.$title_tag(node)) + (self.$resolve_content(node)) + "\n</abstract>" }}else if ("partintro"['$===']($case)) {if ((($a = ($b = (($c = node.$level()['$=='](0)) ? node.$parent().$context()['$==']("section") : node.$level()['$=='](0)), $b !== false && $b !== nil ?node.$document().$doctype()['$==']("book") : $b)) !== nil && (!$a.$$is_boolean || $a == true))) { return "<partintro" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$title_tag(node)) + (self.$resolve_content(node)) + "\n</partintro>" } else { self.$warn("asciidoctor: ERROR: partintro block can only be used when doctype is book and it's a child of a part section. Excluding block content."); return ""; }}else {return node.$content()}})(); }); Opal.defn(self, '$page_break', function(node) { var self = this; return "<simpara><?asciidoc-pagebreak?></simpara>"; }); Opal.defn(self, '$paragraph', function(node) { var $a, self = this; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<formalpara" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n<para>" + (node.$content()) + "</para>\n</formalpara>" } else { return "<simpara" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">" + (node.$content()) + "</simpara>" }; }); Opal.defn(self, '$preamble', function(node) { var self = this; if (node.$document().$doctype()['$==']("book")) { return "<preface" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$title_tag(node, false)) + (node.$content()) + "\n</preface>" } else { return node.$content() }; }); Opal.defn(self, '$quote', function(node) { var $a, $b, self = this, result = nil; result = []; result['$<<']("<blockquote" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; if ((($a = ((($b = (node['$attr?']("attribution"))) !== false && $b !== nil) ? $b : (node['$attr?']("citetitle")))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<attribution>"); if ((($a = node['$attr?']("attribution")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']((node.$attr("attribution")))}; if ((($a = node['$attr?']("citetitle")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<citetitle>" + (node.$attr("citetitle")) + "</citetitle>")}; result['$<<']("</attribution>");}; result['$<<']((self.$resolve_content(node))); result['$<<']("</blockquote>"); return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$thematic_break', function(node) { var self = this; return "<simpara><?asciidoc-hr?></simpara>"; }); Opal.defn(self, '$sidebar', function(node) { var self = this; return "<sidebar" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$title_tag(node)) + (self.$resolve_content(node)) + "\n</sidebar>"; }); Opal.cdecl($scope, 'TABLE_PI_NAMES', ["dbhtml", "dbfo", "dblatex"]); Opal.cdecl($scope, 'TABLE_SECTIONS', ["head", "foot", "body"]); Opal.defn(self, '$table', function(node) { var $a, $b, TMP_7, $c, TMP_8, $d, TMP_9, $e, $f, TMP_14, self = this, has_body = nil, result = nil, pgwide_attribute = nil, tag_name = nil, width = nil; has_body = false; result = []; pgwide_attribute = (function() {if ((($a = (node['$option?']("pgwide"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " pgwide=\"1\"" } else { return nil }; return nil; })(); result['$<<']("<" + (tag_name = (function() {if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "table" } else { return "informaltable" }; return nil; })()) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + (pgwide_attribute) + " frame=\"" + (node.$attr("frame", "all")) + "\" rowsep=\"" + ((function() {if ((($a = ["none", "cols"]['$include?'](node.$attr("grid"))) !== nil && (!$a.$$is_boolean || $a == true))) { return 0 } else { return 1 }; return nil; })()) + "\" colsep=\"" + ((function() {if ((($a = ["none", "rows"]['$include?'](node.$attr("grid"))) !== nil && (!$a.$$is_boolean || $a == true))) { return 0 } else { return 1 }; return nil; })()) + "\">"); if ((($a = (node['$option?']("unbreakable"))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<?dbfo keep-together=\"always\"?>") } else if ((($a = (node['$option?']("breakable"))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<?dbfo keep-together=\"auto\"?>")}; if (tag_name['$==']("table")) { result['$<<']("<title>" + (node.$title()) + "</title>")}; if ((($a = (width = (function() {if ((($b = (node['$attr?']("width"))) !== nil && (!$b.$$is_boolean || $b == true))) { return (node.$attr("width")) } else { return nil }; return nil; })())) !== nil && (!$a.$$is_boolean || $a == true))) { ($a = ($b = $scope.get('TABLE_PI_NAMES')).$each, $a.$$p = (TMP_7 = function(pi_name){var self = TMP_7.$$s || this; if (pi_name == null) pi_name = nil; return result['$<<']("<?" + (pi_name) + " table-width=\"" + (width) + "\"?>")}, TMP_7.$$s = self, TMP_7), $a).call($b)}; result['$<<']("<tgroup cols=\"" + (node.$attr("colcount")) + "\">"); ($a = ($c = node.$columns()).$each, $a.$$p = (TMP_8 = function(col){var self = TMP_8.$$s || this; if (col == null) col = nil; return result['$<<']("<colspec colname=\"col_" + (col.$attr("colnumber")) + "\" colwidth=\"" + (col.$attr((function() {if (width !== false && width !== nil) { return "colabswidth" } else { return "colpcwidth" }; return nil; })())) + "*\"/>")}, TMP_8.$$s = self, TMP_8), $a).call($c); ($a = ($d = ($e = ($f = $scope.get('TABLE_SECTIONS')).$select, $e.$$p = (TMP_14 = function(tblsec){var self = TMP_14.$$s || this; if (tblsec == null) tblsec = nil; return node.$rows()['$[]'](tblsec)['$empty?']()['$!']()}, TMP_14.$$s = self, TMP_14), $e).call($f)).$each, $a.$$p = (TMP_9 = function(tblsec){var self = TMP_9.$$s || this, $a, $b, TMP_10; if (tblsec == null) tblsec = nil; if (tblsec['$==']("body")) { has_body = true}; result['$<<']("<t" + (tblsec) + ">"); ($a = ($b = node.$rows()['$[]'](tblsec)).$each, $a.$$p = (TMP_10 = function(row){var self = TMP_10.$$s || this, $a, $b, TMP_11; if (row == null) row = nil; result['$<<']("<row>"); ($a = ($b = row).$each, $a.$$p = (TMP_11 = function(cell){var self = TMP_11.$$s || this, $a, $b, TMP_12, $c, TMP_13, halign_attribute = nil, valign_attribute = nil, colspan_attribute = nil, colnum = nil, rowspan_attribute = nil, entry_start = nil, cell_content = nil, $case = nil, entry_end = nil; if (cell == null) cell = nil; halign_attribute = (function() {if ((($a = (cell['$attr?']("halign"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " align=\"" + (cell.$attr("halign")) + "\"" } else { return nil }; return nil; })(); valign_attribute = (function() {if ((($a = (cell['$attr?']("valign"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " valign=\"" + (cell.$attr("valign")) + "\"" } else { return nil }; return nil; })(); colspan_attribute = (function() {if ((($a = cell.$colspan()) !== nil && (!$a.$$is_boolean || $a == true))) { return " namest=\"col_" + (colnum = cell.$column().$attr("colnumber")) + "\" nameend=\"col_" + ($rb_minus($rb_plus(colnum, cell.$colspan()), 1)) + "\"" } else { return nil }; return nil; })(); rowspan_attribute = (function() {if ((($a = cell.$rowspan()) !== nil && (!$a.$$is_boolean || $a == true))) { return " morerows=\"" + ($rb_minus(cell.$rowspan(), 1)) + "\"" } else { return nil }; return nil; })(); entry_start = "<entry" + (halign_attribute) + (valign_attribute) + (colspan_attribute) + (rowspan_attribute) + ">"; cell_content = (function() {if (tblsec['$==']("head")) { return cell.$text() } else { return (function() {$case = cell.$style();if ("asciidoc"['$===']($case)) {return cell.$content()}else if ("verse"['$===']($case)) {return "<literallayout>" + (cell.$text()) + "</literallayout>"}else if ("literal"['$===']($case)) {return "<literallayout class=\"monospaced\">" + (cell.$text()) + "</literallayout>"}else if ("header"['$===']($case)) {return ($a = ($b = cell.$content()).$map, $a.$$p = (TMP_12 = function(text){var self = TMP_12.$$s || this; if (text == null) text = nil; return "<simpara><emphasis role=\"strong\">" + (text) + "</emphasis></simpara>"}, TMP_12.$$s = self, TMP_12), $a).call($b).$join()}else {return ($a = ($c = cell.$content()).$map, $a.$$p = (TMP_13 = function(text){var self = TMP_13.$$s || this; if (text == null) text = nil; return "<simpara>" + (text) + "</simpara>"}, TMP_13.$$s = self, TMP_13), $a).call($c).$join()}})() }; return nil; })(); entry_end = (function() {if ((($a = (node.$document()['$attr?']("cellbgcolor"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "<?dbfo bgcolor=\"" + (node.$document().$attr("cellbgcolor")) + "\"?></entry>" } else { return "</entry>" }; return nil; })(); return result['$<<']("" + (entry_start) + (cell_content) + (entry_end));}, TMP_11.$$s = self, TMP_11), $a).call($b); return result['$<<']("</row>");}, TMP_10.$$s = self, TMP_10), $a).call($b); return result['$<<']("</t" + (tblsec) + ">");}, TMP_9.$$s = self, TMP_9), $a).call($d); result['$<<']("</tgroup>"); result['$<<']("</" + (tag_name) + ">"); if (has_body !== false && has_body !== nil) { } else { self.$warn("asciidoctor: WARNING: tables must have at least one body row") }; return $rb_times(result, $scope.get('EOL')); }); Opal.alias(self, 'toc', 'skip'); Opal.defn(self, '$ulist', function(node) { var $a, $b, TMP_15, $c, TMP_16, self = this, result = nil, mark_type = nil, checklist = nil, mark_attribute = nil; result = []; if (node.$style()['$==']("bibliography")) { result['$<<']("<bibliodiv" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($b = node.$items()).$each, $a.$$p = (TMP_15 = function(item){var self = TMP_15.$$s || this, $a; if (item == null) item = nil; result['$<<']("<bibliomixed>"); result['$<<']("<bibliomisc>" + (item.$text()) + "</bibliomisc>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</bibliomixed>");}, TMP_15.$$s = self, TMP_15), $a).call($b); result['$<<']("</bibliodiv>"); } else { mark_type = (function() {if ((($a = (checklist = node['$option?']("checklist"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "none" } else { return node.$style() }; return nil; })(); mark_attribute = (function() {if (mark_type !== false && mark_type !== nil) { return " mark=\"" + (mark_type) + "\"" } else { return nil }; return nil; })(); result['$<<']("<itemizedlist" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + (mark_attribute) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($c = node.$items()).$each, $a.$$p = (TMP_16 = function(item){var self = TMP_16.$$s || this, $a, $b, text_marker = nil; if (item == null) item = nil; text_marker = (function() {if ((($a = (($b = checklist !== false && checklist !== nil) ? (item['$attr?']("checkbox")) : checklist)) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = (item['$attr?']("checked"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "&#10003; " } else { return "&#10063; " } } else { return nil }; return nil; })(); result['$<<']("<listitem>"); result['$<<']("<simpara>" + (text_marker) + (item.$text()) + "</simpara>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</listitem>");}, TMP_16.$$s = self, TMP_16), $a).call($c); result['$<<']("</itemizedlist>"); }; return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$verse', function(node) { var $a, $b, self = this, result = nil; result = []; result['$<<']("<blockquote" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; if ((($a = ((($b = (node['$attr?']("attribution"))) !== false && $b !== nil) ? $b : (node['$attr?']("citetitle")))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<attribution>"); if ((($a = node['$attr?']("attribution")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']((node.$attr("attribution")))}; if ((($a = node['$attr?']("citetitle")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<citetitle>" + (node.$attr("citetitle")) + "</citetitle>")}; result['$<<']("</attribution>");}; result['$<<']("<literallayout>" + (node.$content()) + "</literallayout>"); result['$<<']("</blockquote>"); return $rb_times(result, $scope.get('EOL')); }); Opal.alias(self, 'video', 'skip'); Opal.defn(self, '$inline_anchor', function(node) { var $a, self = this, $case = nil, path = nil, linkend = nil, text = nil, target = nil; return (function() {$case = node.$type();if ("ref"['$===']($case)) {return "<anchor" + (self.$common_attributes(node.$target(), nil, node.$text())) + "/>"}else if ("xref"['$===']($case)) {if ((($a = (path = node.$attributes()['$[]']("path"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "<link xlink:href=\"" + (node.$target()) + "\">" + (((($a = node.$text()) !== false && $a !== nil) ? $a : path)) + "</link>" } else { linkend = ((($a = node.$attributes()['$[]']("fragment")) !== false && $a !== nil) ? $a : node.$target()); if ((($a = (text = node.$text())) !== nil && (!$a.$$is_boolean || $a == true))) { return "<link linkend=\"" + (linkend) + "\">" + (text) + "</link>" } else { return "<xref linkend=\"" + (linkend) + "\"/>" }; }}else if ("link"['$===']($case)) {return "<link xlink:href=\"" + (node.$target()) + "\">" + (node.$text()) + "</link>"}else if ("bibref"['$===']($case)) {target = node.$target(); return "<anchor" + (self.$common_attributes(target, nil, "[" + (target) + "]")) + "/>[" + (target) + "]";}else {return self.$warn("asciidoctor: WARNING: unknown anchor type: " + (node.$type().$inspect()))}})(); }); Opal.defn(self, '$inline_break', function(node) { var self = this; return "" + (node.$text()) + "<?asciidoc-br?>"; }); Opal.defn(self, '$inline_button', function(node) { var self = this; return "<guibutton>" + (node.$text()) + "</guibutton>"; }); Opal.defn(self, '$inline_callout', function(node) { var self = this; return "<co" + (self.$common_attributes(node.$id())) + "/>"; }); Opal.defn(self, '$inline_footnote', function(node) { var self = this; if (node.$type()['$==']("xref")) { return "<footnoteref linkend=\"" + (node.$target()) + "\"/>" } else { return "<footnote" + (self.$common_attributes(node.$id())) + "><simpara>" + (node.$text()) + "</simpara></footnote>" }; }); Opal.defn(self, '$inline_image', function(node) { var $a, self = this, width_attribute = nil, depth_attribute = nil; width_attribute = (function() {if ((($a = (node['$attr?']("width"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " contentwidth=\"" + (node.$attr("width")) + "\"" } else { return nil }; return nil; })(); depth_attribute = (function() {if ((($a = (node['$attr?']("height"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " contentdepth=\"" + (node.$attr("height")) + "\"" } else { return nil }; return nil; })(); return "<inlinemediaobject>\n<imageobject>\n<imagedata fileref=\"" + ((function() {if (node.$type()['$==']("icon")) { return (node.$icon_uri(node.$target())) } else { return (node.$image_uri(node.$target())) }; return nil; })()) + "\"" + (width_attribute) + (depth_attribute) + "/>\n</imageobject>\n<textobject><phrase>" + (node.$attr("alt")) + "</phrase></textobject>\n</inlinemediaobject>"; }); Opal.defn(self, '$inline_indexterm', function(node) { var self = this, terms = nil, result = nil, numterms = nil; if (node.$type()['$==']("visible")) { return "<indexterm><primary>" + (node.$text()) + "</primary></indexterm>" + (node.$text()) } else { terms = node.$attr("terms"); result = []; if ($rb_gt((numterms = terms.$size()), 2)) { result['$<<']("<indexterm>\n<primary>" + (terms['$[]'](0)) + "</primary><secondary>" + (terms['$[]'](1)) + "</secondary><tertiary>" + (terms['$[]'](2)) + "</tertiary>\n</indexterm>")}; if ($rb_gt(numterms, 1)) { result['$<<']("<indexterm>\n<primary>" + (terms['$[]'](-2)) + "</primary><secondary>" + (terms['$[]'](-1)) + "</secondary>\n</indexterm>")}; result['$<<']("<indexterm>\n<primary>" + (terms['$[]'](-1)) + "</primary>\n</indexterm>"); return $rb_times(result, $scope.get('EOL')); }; }); Opal.defn(self, '$inline_kbd', function(node) { var $a, $b, TMP_17, self = this, keys = nil; if (((keys = node.$attr("keys"))).$size()['$=='](1)) { return "<keycap>" + (keys['$[]'](0)) + "</keycap>" } else { return "<keycombo>" + (($a = ($b = keys).$map, $a.$$p = (TMP_17 = function(key){var self = TMP_17.$$s || this; if (key == null) key = nil; return "<keycap>" + (key) + "</keycap>"}, TMP_17.$$s = self, TMP_17), $a).call($b).$join()) + "</keycombo>" }; }); Opal.defn(self, '$inline_menu', function(node) { var $a, $b, TMP_18, self = this, menu = nil, submenus = nil, submenu_path = nil, menuitem = nil; menu = node.$attr("menu"); if ((($a = ((submenus = node.$attr("submenus")))['$empty?']()['$!']()) !== nil && (!$a.$$is_boolean || $a == true))) { submenu_path = ($a = ($b = submenus).$map, $a.$$p = (TMP_18 = function(submenu){var self = TMP_18.$$s || this; if (submenu == null) submenu = nil; return "<guisubmenu>" + (submenu) + "</guisubmenu> "}, TMP_18.$$s = self, TMP_18), $a).call($b).$join().$chop(); return "<menuchoice><guimenu>" + (menu) + "</guimenu> " + (submenu_path) + " <guimenuitem>" + (node.$attr("menuitem")) + "</guimenuitem></menuchoice>"; } else if ((($a = (menuitem = node.$attr("menuitem"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "<menuchoice><guimenu>" + (menu) + "</guimenu> <guimenuitem>" + (menuitem) + "</guimenuitem></menuchoice>" } else { return "<guimenu>" + (menu) + "</guimenu>" }; }); (($a = [[nil, nil, true]]), $b = (Opal.cdecl($scope, 'QUOTE_TAGS', $hash2(["emphasis", "strong", "monospaced", "superscript", "subscript", "double", "single", "mark"], {"emphasis": ["<emphasis>", "</emphasis>", true], "strong": ["<emphasis role=\"strong\">", "</emphasis>", true], "monospaced": ["<literal>", "</literal>", false], "superscript": ["<superscript>", "</superscript>", false], "subscript": ["<subscript>", "</subscript>", false], "double": ["&#8220;", "&#8221;", true], "single": ["&#8216;", "&#8217;", true], "mark": ["<emphasis role=\"marked\">", "</emphasis>", false]}))), $b['$default='].apply($b, $a), $a[$a.length-1]); Opal.defn(self, '$inline_quoted', function(node) { var $a, self = this, type = nil, open = nil, close = nil, supports_phrase = nil, text = nil, role = nil, quoted_text = nil; if (((type = node.$type()))['$==']("latexmath")) { return "<inlineequation>\n<alt><![CDATA[" + (node.$text()) + "]]></alt>\n<inlinemediaobject><textobject><phrase><![CDATA[" + (node.$text()) + "]]></phrase></textobject></inlinemediaobject>\n</inlineequation>" } else { $a = Opal.to_ary($scope.get('QUOTE_TAGS')['$[]'](type)), open = ($a[0] == null ? nil : $a[0]), close = ($a[1] == null ? nil : $a[1]), supports_phrase = ($a[2] == null ? nil : $a[2]); text = node.$text(); if ((($a = (role = node.$role())) !== nil && (!$a.$$is_boolean || $a == true))) { if (supports_phrase !== false && supports_phrase !== nil) { quoted_text = "" + (open) + "<phrase role=\"" + (role) + "\">" + (text) + "</phrase>" + (close) } else { quoted_text = "" + (open.$chop()) + " role=\"" + (role) + "\">" + (text) + (close) } } else { quoted_text = "" + (open) + (text) + (close) }; if ((($a = node.$id()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<anchor" + (self.$common_attributes(node.$id(), nil, text)) + "/>" + (quoted_text) } else { return quoted_text }; }; }); Opal.defn(self, '$author_element', function(doc, index) { var $a, self = this, firstname_key = nil, middlename_key = nil, lastname_key = nil, email_key = nil, result = nil; if (index == null) { index = nil } firstname_key = (function() {if (index !== false && index !== nil) { return "firstname_" + (index) } else { return "firstname" }; return nil; })(); middlename_key = (function() {if (index !== false && index !== nil) { return "middlename_" + (index) } else { return "middlename" }; return nil; })(); lastname_key = (function() {if (index !== false && index !== nil) { return "lastname_" + (index) } else { return "lastname" }; return nil; })(); email_key = (function() {if (index !== false && index !== nil) { return "email_" + (index) } else { return "email" }; return nil; })(); result = []; result['$<<']("<author>"); result['$<<']("<personname>"); if ((($a = doc['$attr?'](firstname_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<firstname>" + (doc.$attr(firstname_key)) + "</firstname>")}; if ((($a = doc['$attr?'](middlename_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<othername>" + (doc.$attr(middlename_key)) + "</othername>")}; if ((($a = doc['$attr?'](lastname_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<surname>" + (doc.$attr(lastname_key)) + "</surname>")}; result['$<<']("</personname>"); if ((($a = doc['$attr?'](email_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<email>" + (doc.$attr(email_key)) + "</email>")}; result['$<<']("</author>"); return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$common_attributes', function(id, role, reftext) { var self = this, res = nil; if (role == null) { role = nil } if (reftext == null) { reftext = nil } res = (function() {if (id !== false && id !== nil) { return " xml:id=\"" + (id) + "\"" } else { return "" }; return nil; })(); if (role !== false && role !== nil) { res = "" + (res) + " role=\"" + (role) + "\""}; if (reftext !== false && reftext !== nil) { res = "" + (res) + " xreflabel=\"" + (reftext) + "\""}; return res; }); Opal.defn(self, '$doctype_declaration', function(root_tag_name) { var self = this; return nil; }); Opal.defn(self, '$document_info_element', function(doc, info_tag_prefix, use_info_tag_prefix) { var $a, $b, TMP_19, $c, $d, self = this, result = nil, authorcount = nil, head_docinfo = nil; if (use_info_tag_prefix == null) { use_info_tag_prefix = false } if (use_info_tag_prefix !== false && use_info_tag_prefix !== nil) { } else { info_tag_prefix = "" }; result = []; result['$<<']("<" + (info_tag_prefix) + "info>"); if ((($a = doc.$notitle()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { result['$<<'](self.$document_title_tags(doc.$doctitle($hash2(["partition", "use_fallback"], {"partition": true, "use_fallback": true})))) }; result['$<<']("<date>" + ((function() {if ((($a = (doc['$attr?']("revdate"))) !== nil && (!$a.$$is_boolean || $a == true))) { return (doc.$attr("revdate")) } else { return (doc.$attr("docdate")) }; return nil; })()) + "</date>"); if ((($a = doc['$has_header?']()) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = doc['$attr?']("author")) !== nil && (!$a.$$is_boolean || $a == true))) { if ($rb_lt((authorcount = (doc.$attr("authorcount")).$to_i()), 2)) { result['$<<']((self.$author_element(doc))); if ((($a = doc['$attr?']("authorinitials")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<authorinitials>" + (doc.$attr("authorinitials")) + "</authorinitials>")}; } else { result['$<<']("<authorgroup>"); ($a = ($b = authorcount).$times, $a.$$p = (TMP_19 = function(index){var self = TMP_19.$$s || this; if (index == null) index = nil; return result['$<<']((self.$author_element(doc, $rb_plus(index, 1))))}, TMP_19.$$s = self, TMP_19), $a).call($b); result['$<<']("</authorgroup>"); }}; if ((($a = ($c = (doc['$attr?']("revdate")), $c !== false && $c !== nil ?(((($d = (doc['$attr?']("revnumber"))) !== false && $d !== nil) ? $d : (doc['$attr?']("revremark")))) : $c)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<revhistory>\n<revision>"); if ((($a = doc['$attr?']("revnumber")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<revnumber>" + (doc.$attr("revnumber")) + "</revnumber>")}; if ((($a = doc['$attr?']("revdate")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<date>" + (doc.$attr("revdate")) + "</date>")}; if ((($a = doc['$attr?']("authorinitials")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<authorinitials>" + (doc.$attr("authorinitials")) + "</authorinitials>")}; if ((($a = doc['$attr?']("revremark")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<revremark>" + (doc.$attr("revremark")) + "</revremark>")}; result['$<<']("</revision>\n</revhistory>");}; if ((($a = ((head_docinfo = doc.$docinfo()))['$empty?']()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { result['$<<'](head_docinfo) }; if ((($a = doc['$attr?']("orgname")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<orgname>" + (doc.$attr("orgname")) + "</orgname>")};}; result['$<<']("</" + (info_tag_prefix) + "info>"); if (doc.$doctype()['$==']("manpage")) { result['$<<']("<refmeta>"); if ((($a = doc['$attr?']("mantitle")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<refentrytitle>" + (doc.$attr("mantitle")) + "</refentrytitle>")}; if ((($a = doc['$attr?']("manvolnum")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<manvolnum>" + (doc.$attr("manvolnum")) + "</manvolnum>")}; result['$<<']("</refmeta>"); result['$<<']("<refnamediv>"); if ((($a = doc['$attr?']("manname")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<refname>" + (doc.$attr("manname")) + "</refname>")}; if ((($a = doc['$attr?']("manpurpose")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<refpurpose>" + (doc.$attr("manpurpose")) + "</refpurpose>")}; result['$<<']("</refnamediv>");}; return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$document_ns_attributes', function(doc) { var self = this; return " xmlns=\"http://docbook.org/ns/docbook\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"5.0\""; }); Opal.defn(self, '$lang_attribute_name', function() { var self = this; return "xml:lang"; }); Opal.defn(self, '$document_title_tags', function(title) { var $a, self = this; if ((($a = title['$subtitle?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<title>" + (title.$main()) + "</title>\n<subtitle>" + (title.$subtitle()) + "</subtitle>" } else { return "<title>" + (title) + "</title>" }; }); Opal.defn(self, '$resolve_content', function(node) { var self = this; if (node.$content_model()['$==']("compound")) { return node.$content() } else { return "<simpara>" + (node.$content()) + "</simpara>" }; }); return (Opal.defn(self, '$title_tag', function(node, optional) { var $a, $b, self = this; if (optional == null) { optional = true } if ((($a = ((($b = optional['$!']()) !== false && $b !== nil) ? $b : node['$title?']())) !== nil && (!$a.$$is_boolean || $a == true))) { return "<title>" + (node.$title()) + "</title>\n" } else { return nil }; }), nil) && 'title_tag'; })($scope.get('Converter'), (($scope.get('Converter')).$$scope.get('BuiltIn'))) })($scope.base) }; /* Generated by Opal 0.9.0.beta2 */ Opal.modules["asciidoctor/converter/docbook45"] = function(Opal) { Opal.dynamic_require_severity = "ignore"; var OPAL_CONFIG = { method_missing: false, arity_check: false, freezing: true, tainting: true }; function $rb_times(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs * rhs : lhs['$*'](rhs); } var self = Opal.top, $scope = Opal, nil = Opal.nil, $breaker = Opal.breaker, $slice = Opal.slice, $module = Opal.module, $klass = Opal.klass; self.$require("asciidoctor/converter/docbook5"); return (function($base) { var self = $module($base, 'Asciidoctor'); var def = self.$$proto, $scope = self.$$scope; (function($base, $super) { function $DocBook45Converter(){}; var self = $DocBook45Converter = $klass($base, $super, 'DocBook45Converter', $DocBook45Converter); var def = self.$$proto, $scope = self.$$scope, TMP_1, TMP_3; Opal.defn(self, '$admonition', TMP_1 = function(node) {var $zuper = $slice.call(arguments, 0); var self = this, $iter = TMP_1.$$p, $yield = $iter || nil; TMP_1.$$p = null; if (node.$parent().$context()['$==']("example")) { return "<para>\n" + (Opal.find_super_dispatcher(self, 'admonition', TMP_1, $iter).apply(self, $zuper)) + "\n</para>" } else { return Opal.find_super_dispatcher(self, 'admonition', TMP_1, $iter).apply(self, $zuper) }; }); Opal.defn(self, '$olist', function(node) { var $a, $b, TMP_2, self = this, result = nil, num_attribute = nil, start_attribute = nil; result = []; num_attribute = (function() {if ((($a = node.$style()) !== nil && (!$a.$$is_boolean || $a == true))) { return " numeration=\"" + (node.$style()) + "\"" } else { return nil }; return nil; })(); start_attribute = (function() {if ((($a = (node['$attr?']("start"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " override=\"" + (node.$attr("start")) + "\"" } else { return nil }; return nil; })(); result['$<<']("<orderedlist" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + (num_attribute) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($b = node.$items()).$each_with_index, $a.$$p = (TMP_2 = function(item, idx){var self = TMP_2.$$s || this, $a; if (item == null) item = nil;if (idx == null) idx = nil; result['$<<'](((function() {if (idx['$=='](0)) { return "<listitem" + (start_attribute) + ">" } else { return "<listitem>" }; return nil; })())); result['$<<']("<simpara>" + (item.$text()) + "</simpara>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</listitem>");}, TMP_2.$$s = self, TMP_2), $a).call($b); result['$<<']("</orderedlist>"); return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$inline_anchor', function(node) { var $a, self = this, $case = nil, path = nil, linkend = nil, text = nil, target = nil; return (function() {$case = node.$type();if ("ref"['$===']($case)) {return "<anchor" + (self.$common_attributes(node.$target(), nil, node.$text())) + "/>"}else if ("xref"['$===']($case)) {if ((($a = (path = node.$attributes()['$[]']("path"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "<ulink url=\"" + (node.$target()) + "\">" + (((($a = node.$text()) !== false && $a !== nil) ? $a : path)) + "</ulink>" } else { linkend = ((($a = node.$attributes()['$[]']("fragment")) !== false && $a !== nil) ? $a : node.$target()); if ((($a = (text = node.$text())) !== nil && (!$a.$$is_boolean || $a == true))) { return "<link linkend=\"" + (linkend) + "\">" + (text) + "</link>" } else { return "<xref linkend=\"" + (linkend) + "\"/>" }; }}else if ("link"['$===']($case)) {return "<ulink url=\"" + (node.$target()) + "\">" + (node.$text()) + "</ulink>"}else if ("bibref"['$===']($case)) {target = node.$target(); return "<anchor" + (self.$common_attributes(target, nil, "[" + (target) + "]")) + "/>[" + (target) + "]";}else { return nil }})(); }); Opal.defn(self, '$author_element', function(doc, index) { var $a, self = this, firstname_key = nil, middlename_key = nil, lastname_key = nil, email_key = nil, result = nil; if (index == null) { index = nil } firstname_key = (function() {if (index !== false && index !== nil) { return "firstname_" + (index) } else { return "firstname" }; return nil; })(); middlename_key = (function() {if (index !== false && index !== nil) { return "middlename_" + (index) } else { return "middlename" }; return nil; })(); lastname_key = (function() {if (index !== false && index !== nil) { return "lastname_" + (index) } else { return "lastname" }; return nil; })(); email_key = (function() {if (index !== false && index !== nil) { return "email_" + (index) } else { return "email" }; return nil; })(); result = []; result['$<<']("<author>"); if ((($a = doc['$attr?'](firstname_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<firstname>" + (doc.$attr(firstname_key)) + "</firstname>")}; if ((($a = doc['$attr?'](middlename_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<othername>" + (doc.$attr(middlename_key)) + "</othername>")}; if ((($a = doc['$attr?'](lastname_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<surname>" + (doc.$attr(lastname_key)) + "</surname>")}; if ((($a = doc['$attr?'](email_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<email>" + (doc.$attr(email_key)) + "</email>")}; result['$<<']("</author>"); return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$common_attributes', function(id, role, reftext) { var self = this, res = nil; if (role == null) { role = nil } if (reftext == null) { reftext = nil } res = (function() {if (id !== false && id !== nil) { return " id=\"" + (id) + "\"" } else { return "" }; return nil; })(); if (role !== false && role !== nil) { res = "" + (res) + " role=\"" + (role) + "\""}; if (reftext !== false && reftext !== nil) { res = "" + (res) + " xreflabel=\"" + (reftext) + "\""}; return res; }); Opal.defn(self, '$doctype_declaration', function(root_tag_name) { var self = this; return "<!DOCTYPE " + (root_tag_name) + " PUBLIC \"-//OASIS//DTD DocBook XML V4.5//EN\" \"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd\">"; }); Opal.defn(self, '$document_info_element', TMP_3 = function(doc, info_tag_prefix) { var self = this, $iter = TMP_3.$$p, $yield = $iter || nil; TMP_3.$$p = null; return Opal.find_super_dispatcher(self, 'document_info_element', TMP_3, null).apply(self, [doc, info_tag_prefix, true]); }); Opal.defn(self, '$lang_attribute_name', function() { var self = this; return "lang"; }); return (Opal.defn(self, '$document_ns_attributes', function(doc) { var $a, self = this, ns = nil; if ((($a = (ns = doc.$attr("xmlns"))) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = ns['$empty?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return " xmlns=\"http://docbook.org/ns/docbook\"" } else { return " xmlns=\"" + (ns) + "\"" } } else { return nil }; }), nil) && 'document_ns_attributes'; })($scope.get('Converter'), (($scope.get('Converter')).$$scope.get('DocBook5Converter'))) })($scope.base); }; /* Generated by Opal 0.9.0.beta2 */ Opal.modules["asciidoctor/converter/docbook5"] = function(Opal) { Opal.dynamic_require_severity = "ignore"; var OPAL_CONFIG = { method_missing: false, arity_check: false, freezing: true, tainting: true }; function $rb_times(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs * rhs : lhs['$*'](rhs); } function $rb_le(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs <= rhs : lhs['$<='](rhs); } function $rb_minus(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs - rhs : lhs['$-'](rhs); } function $rb_plus(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs + rhs : lhs['$+'](rhs); } function $rb_gt(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs > rhs : lhs['$>'](rhs); } function $rb_lt(lhs, rhs) { return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs < rhs : lhs['$<'](rhs); } var self = Opal.top, $scope = Opal, nil = Opal.nil, $breaker = Opal.breaker, $slice = Opal.slice, $module = Opal.module, $klass = Opal.klass, $hash2 = Opal.hash2; return (function($base) { var self = $module($base, 'Asciidoctor'); var def = self.$$proto, $scope = self.$$scope; (function($base, $super) { function $DocBook5Converter(){}; var self = $DocBook5Converter = $klass($base, $super, 'DocBook5Converter', $DocBook5Converter); var def = self.$$proto, $scope = self.$$scope, $a, $b; def.asciimath_loaded = nil; Opal.defn(self, '$document', function(node) { var $a, self = this, result = nil, root_tag_name = nil, doctype_line = nil, lang_attribute = nil, footer_docinfo = nil; result = []; if (((root_tag_name = node.$doctype()))['$==']("manpage")) { root_tag_name = "refentry"}; result['$<<']("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if ((($a = (doctype_line = self.$doctype_declaration(root_tag_name))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](doctype_line)}; if ((($a = node['$attr?']("toc")) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = node['$attr?']("toclevels")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<?asciidoc-toc maxdepth=\"" + (node.$attr("toclevels")) + "\"?>") } else { result['$<<']("<?asciidoc-toc?>") }}; if ((($a = node['$attr?']("sectnums")) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = node['$attr?']("sectnumlevels")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<?asciidoc-numbered maxdepth=\"" + (node.$attr("sectnumlevels")) + "\"?>") } else { result['$<<']("<?asciidoc-numbered?>") }}; lang_attribute = (function() {if ((($a = (node['$attr?']("nolang"))) !== nil && (!$a.$$is_boolean || $a == true))) { return nil } else { return " " + (self.$lang_attribute_name()) + "=\"" + (node.$attr("lang", "en")) + "\"" }; return nil; })(); result['$<<']("<" + (root_tag_name) + (self.$document_ns_attributes(node)) + (lang_attribute) + ">"); result['$<<']((self.$document_info_element(node, root_tag_name))); if ((($a = node['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](node.$content())}; if ((($a = ((footer_docinfo = node.$docinfo("footer")))['$empty?']()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { result['$<<'](footer_docinfo) }; result['$<<']("</" + (root_tag_name) + ">"); return $rb_times(result, $scope.get('EOL')); }); Opal.alias(self, 'embedded', 'content'); Opal.defn(self, '$section', function(node) { var $a, $b, self = this, doctype = nil, tag_name = nil; doctype = node.$document().$doctype(); tag_name = (function() {if ((($a = node.$special()) !== nil && (!$a.$$is_boolean || $a == true))) { if ($rb_le(node.$level(), 1)) { return node.$sectname() } else { return "section" } } else if ((($a = (($b = doctype['$==']("book")) ? $rb_le(node.$level(), 1) : doctype['$==']("book"))) !== nil && (!$a.$$is_boolean || $a == true))) { return ((function() {if (node.$level()['$=='](0)) { return "part" } else { return "chapter" }; return nil; })()) } else { return "section" }; return nil; })(); if (doctype['$==']("manpage")) { if (tag_name['$==']("section")) { tag_name = "refsection" } else if (tag_name['$==']("synopsis")) { tag_name = "refsynopsisdiv"}}; return "<" + (tag_name) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n" + (node.$content()) + "\n</" + (tag_name) + ">"; }); Opal.defn(self, '$admonition', function(node) { var self = this, tag_name = nil; return "<" + (tag_name = node.$attr("name")) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$title_tag(node)) + (self.$resolve_content(node)) + "\n</" + (tag_name) + ">"; }); Opal.alias(self, 'audio', 'skip'); Opal.defn(self, '$colist', function(node) { var $a, $b, TMP_1, self = this, result = nil; result = []; result['$<<']("<calloutlist" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($b = node.$items()).$each, $a.$$p = (TMP_1 = function(item){var self = TMP_1.$$s || this, $a; if (item == null) item = nil; result['$<<']("<callout arearefs=\"" + (item.$attr("coids")) + "\">"); result['$<<']("<para>" + (item.$text()) + "</para>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</callout>");}, TMP_1.$$s = self, TMP_1), $a).call($b); result['$<<']("</calloutlist>"); return $rb_times(result, $scope.get('EOL')); }); (($a = [$hash2(["list", "entry", "term", "item"], {"list": "variablelist", "entry": "varlistentry", "term": "term", "item": "listitem"})]), $b = (Opal.cdecl($scope, 'DLIST_TAGS', $hash2(["labeled", "qanda", "glossary"], {"labeled": $hash2(["list", "entry", "term", "item"], {"list": "variablelist", "entry": "varlistentry", "term": "term", "item": "listitem"}), "qanda": $hash2(["list", "entry", "label", "term", "item"], {"list": "qandaset", "entry": "qandaentry", "label": "question", "term": "simpara", "item": "answer"}), "glossary": $hash2(["list", "entry", "term", "item"], {"list": nil, "entry": "glossentry", "term": "glossterm", "item": "glossdef"})}))), $b['$default='].apply($b, $a), $a[$a.length-1]); Opal.defn(self, '$dlist', function(node) { var $a, $b, TMP_2, $c, TMP_4, self = this, result = nil, tag_name = nil, tags = nil, list_tag = nil, entry_tag = nil, label_tag = nil, term_tag = nil, item_tag = nil; result = []; if (node.$style()['$==']("horizontal")) { result['$<<']("<" + (tag_name = (function() {if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "table" } else { return "informaltable" }; return nil; })()) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + " tabstyle=\"horizontal\" frame=\"none\" colsep=\"0\" rowsep=\"0\">\n" + (self.$title_tag(node)) + "<tgroup cols=\"2\">\n<colspec colwidth=\"" + (node.$attr("labelwidth", 15)) + "*\"/>\n<colspec colwidth=\"" + (node.$attr("itemwidth", 85)) + "*\"/>\n<tbody valign=\"top\">"); ($a = ($b = node.$items()).$each, $a.$$p = (TMP_2 = function(terms, dd){var self = TMP_2.$$s || this, $a, $b, TMP_3; if (terms == null) terms = nil;if (dd == null) dd = nil; result['$<<']("<row>\n<entry>"); ($a = ($b = [].concat(Opal.to_a(terms))).$each, $a.$$p = (TMP_3 = function(dt){var self = TMP_3.$$s || this; if (dt == null) dt = nil; return result['$<<']("<simpara>" + (dt.$text()) + "</simpara>")}, TMP_3.$$s = self, TMP_3), $a).call($b); result['$<<']("</entry>\n<entry>"); if ((($a = dd['$nil?']()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { if ((($a = dd['$text?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<simpara>" + (dd.$text()) + "</simpara>")}; if ((($a = dd['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](dd.$content())}; }; return result['$<<']("</entry>\n</row>");}, TMP_2.$$s = self, TMP_2), $a).call($b); result['$<<']("</tbody>\n</tgroup>\n</" + (tag_name) + ">"); } else { tags = $scope.get('DLIST_TAGS')['$[]'](node.$style()); list_tag = tags['$[]']("list"); entry_tag = tags['$[]']("entry"); label_tag = tags['$[]']("label"); term_tag = tags['$[]']("term"); item_tag = tags['$[]']("item"); if (list_tag !== false && list_tag !== nil) { result['$<<']("<" + (list_tag) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")};}; ($a = ($c = node.$items()).$each, $a.$$p = (TMP_4 = function(terms, dd){var self = TMP_4.$$s || this, $a, $b, TMP_5; if (terms == null) terms = nil;if (dd == null) dd = nil; result['$<<']("<" + (entry_tag) + ">"); if (label_tag !== false && label_tag !== nil) { result['$<<']("<" + (label_tag) + ">")}; ($a = ($b = [].concat(Opal.to_a(terms))).$each, $a.$$p = (TMP_5 = function(dt){var self = TMP_5.$$s || this; if (dt == null) dt = nil; return result['$<<']("<" + (term_tag) + ">" + (dt.$text()) + "</" + (term_tag) + ">")}, TMP_5.$$s = self, TMP_5), $a).call($b); if (label_tag !== false && label_tag !== nil) { result['$<<']("</" + (label_tag) + ">")}; result['$<<']("<" + (item_tag) + ">"); if ((($a = dd['$nil?']()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { if ((($a = dd['$text?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<simpara>" + (dd.$text()) + "</simpara>")}; if ((($a = dd['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](dd.$content())}; }; result['$<<']("</" + (item_tag) + ">"); return result['$<<']("</" + (entry_tag) + ">");}, TMP_4.$$s = self, TMP_4), $a).call($c); if (list_tag !== false && list_tag !== nil) { result['$<<']("</" + (list_tag) + ">")}; }; return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$example', function(node) { var $a, self = this; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<example" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n" + (self.$resolve_content(node)) + "\n</example>" } else { return "<informalexample" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$resolve_content(node)) + "\n</informalexample>" }; }); Opal.defn(self, '$floating_title', function(node) { var self = this; return "<bridgehead" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + " renderas=\"sect" + (node.$level()) + "\">" + (node.$title()) + "</bridgehead>"; }); Opal.defn(self, '$image', function(node) { var $a, self = this, width_attribute = nil, depth_attribute = nil, swidth_attribute = nil, scale_attribute = nil, align_attribute = nil, mediaobject = nil; width_attribute = (function() {if ((($a = (node['$attr?']("width"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " contentwidth=\"" + (node.$attr("width")) + "\"" } else { return nil }; return nil; })(); depth_attribute = (function() {if ((($a = (node['$attr?']("height"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " contentdepth=\"" + (node.$attr("height")) + "\"" } else { return nil }; return nil; })(); swidth_attribute = (function() {if ((($a = (node['$attr?']("scaledwidth"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " width=\"" + (node.$attr("scaledwidth")) + "\" scalefit=\"1\"" } else { return nil }; return nil; })(); scale_attribute = (function() {if ((($a = (node['$attr?']("scale"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " scale=\"" + (node.$attr("scale")) + "\"" } else { return nil }; return nil; })(); align_attribute = (function() {if ((($a = (node['$attr?']("align"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " align=\"" + (node.$attr("align")) + "\"" } else { return nil }; return nil; })(); mediaobject = "<mediaobject>\n<imageobject>\n<imagedata fileref=\"" + (node.$image_uri(node.$attr("target"))) + "\"" + (width_attribute) + (depth_attribute) + (swidth_attribute) + (scale_attribute) + (align_attribute) + "/>\n</imageobject>\n<textobject><phrase>" + (node.$attr("alt")) + "</phrase></textobject>\n</mediaobject>"; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<figure" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n" + (mediaobject) + "\n</figure>" } else { return "<informalfigure" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (mediaobject) + "\n</informalfigure>" }; }); Opal.defn(self, '$listing', function(node) { var $a, $b, self = this, informal = nil, listing_attributes = nil, numbering = nil, listing_content = nil; informal = node['$title?']()['$!'](); listing_attributes = (self.$common_attributes(node.$id(), node.$role(), node.$reftext())); if ((($a = (($b = node.$style()['$==']("source")) ? (node['$attr?']("language")) : node.$style()['$==']("source"))) !== nil && (!$a.$$is_boolean || $a == true))) { numbering = (function() {if ((($a = (node['$attr?']("linenums"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "numbered" } else { return "unnumbered" }; return nil; })(); listing_content = "<programlisting" + ((function() {if (informal !== false && informal !== nil) { return listing_attributes } else { return nil }; return nil; })()) + " language=\"" + (node.$attr("language", nil, false)) + "\" linenumbering=\"" + (numbering) + "\">" + (node.$content()) + "</programlisting>"; } else { listing_content = "<screen" + ((function() {if (informal !== false && informal !== nil) { return listing_attributes } else { return nil }; return nil; })()) + ">" + (node.$content()) + "</screen>" }; if (informal !== false && informal !== nil) { return listing_content } else { return "<formalpara" + (listing_attributes) + ">\n<title>" + (node.$title()) + "</title>\n<para>\n" + (listing_content) + "\n</para>\n</formalpara>" }; }); Opal.defn(self, '$literal', function(node) { var $a, self = this; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<formalpara" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n<para>\n<literallayout class=\"monospaced\">" + (node.$content()) + "</literallayout>\n</para>\n</formalpara>" } else { return "<literallayout" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + " class=\"monospaced\">" + (node.$content()) + "</literallayout>" }; }); Opal.defn(self, '$stem', function(node) { var $a, $b, $c, $d, $e, self = this, idx = nil, equation = nil, equation_data = nil; if ((($a = (idx = node.$subs().$index("specialcharacters"))) !== nil && (!$a.$$is_boolean || $a == true))) { node.$subs().$delete("specialcharacters")}; equation = node.$content(); if (idx !== false && idx !== nil) { node.$subs().$insert(idx, "specialcharacters")}; if (node.$style()['$==']("latexmath")) { equation_data = "<alt><![CDATA[" + (equation) + "]]></alt>\n<mediaobject><textobject><phrase></phrase></textobject></mediaobject>" } else if ((($a = (($b = node.$style()['$==']("asciimath")) ? (((($c = ((Opal.Object.$$scope.AsciiMath == null ? nil : 'constant'))) !== false && $c !== nil) ? $c : ((function() {if ((($d = ((($e = self['asciimath_loaded'], $e != null && $e !== nil) ? 'instance-variable' : nil))['$!']()) !== nil && (!$d.$$is_boolean || $d == true))) { return (self.asciimath_loaded = $scope.get('Helpers').$require_library("asciimath", true, "warn")) } else { return self.asciimath_loaded }; return nil; })()))) : node.$style()['$==']("asciimath"))) !== nil && (!$a.$$is_boolean || $a == true))) { equation_data = Opal.get('AsciiMath').$parse(equation).$to_mathml("mml:", $hash2(["xmlns:mml"], {"xmlns:mml": "http://www.w3.org/1998/Math/MathML"})) } else { equation_data = "<mediaobject><textobject><phrase><![CDATA[" + (equation) + "]]></phrase></textobject></mediaobject>" }; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<equation" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n" + (equation_data) + "\n</equation>" } else { return "<informalequation" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (equation_data) + "\n</informalequation>" }; }); Opal.defn(self, '$olist', function(node) { var $a, $b, TMP_6, self = this, result = nil, num_attribute = nil, start_attribute = nil; result = []; num_attribute = (function() {if ((($a = node.$style()) !== nil && (!$a.$$is_boolean || $a == true))) { return " numeration=\"" + (node.$style()) + "\"" } else { return nil }; return nil; })(); start_attribute = (function() {if ((($a = (node['$attr?']("start"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " startingnumber=\"" + (node.$attr("start")) + "\"" } else { return nil }; return nil; })(); result['$<<']("<orderedlist" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + (num_attribute) + (start_attribute) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($b = node.$items()).$each, $a.$$p = (TMP_6 = function(item){var self = TMP_6.$$s || this, $a; if (item == null) item = nil; result['$<<']("<listitem>"); result['$<<']("<simpara>" + (item.$text()) + "</simpara>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</listitem>");}, TMP_6.$$s = self, TMP_6), $a).call($b); result['$<<']("</orderedlist>"); return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$open', function(node) { var $a, $b, $c, self = this, $case = nil; return (function() {$case = node.$style();if ("abstract"['$===']($case)) {if ((($a = (($b = node.$parent()['$=='](node.$document())) ? node.$document()['$attr?']("doctype", "book") : node.$parent()['$=='](node.$document()))) !== nil && (!$a.$$is_boolean || $a == true))) { self.$warn("asciidoctor: WARNING: abstract block cannot be used in a document without a title when doctype is book. Excluding block content."); return ""; } else { return "<abstract>\n" + (self.$title_tag(node)) + (self.$resolve_content(node)) + "\n</abstract>" }}else if ("partintro"['$===']($case)) {if ((($a = ($b = (($c = node.$level()['$=='](0)) ? node.$parent().$context()['$==']("section") : node.$level()['$=='](0)), $b !== false && $b !== nil ?node.$document().$doctype()['$==']("book") : $b)) !== nil && (!$a.$$is_boolean || $a == true))) { return "<partintro" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$title_tag(node)) + (self.$resolve_content(node)) + "\n</partintro>" } else { self.$warn("asciidoctor: ERROR: partintro block can only be used when doctype is book and it's a child of a part section. Excluding block content."); return ""; }}else {return node.$content()}})(); }); Opal.defn(self, '$page_break', function(node) { var self = this; return "<simpara><?asciidoc-pagebreak?></simpara>"; }); Opal.defn(self, '$paragraph', function(node) { var $a, self = this; if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<formalpara" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n<title>" + (node.$title()) + "</title>\n<para>" + (node.$content()) + "</para>\n</formalpara>" } else { return "<simpara" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">" + (node.$content()) + "</simpara>" }; }); Opal.defn(self, '$preamble', function(node) { var self = this; if (node.$document().$doctype()['$==']("book")) { return "<preface" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$title_tag(node, false)) + (node.$content()) + "\n</preface>" } else { return node.$content() }; }); Opal.defn(self, '$quote', function(node) { var $a, $b, self = this, result = nil; result = []; result['$<<']("<blockquote" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; if ((($a = ((($b = (node['$attr?']("attribution"))) !== false && $b !== nil) ? $b : (node['$attr?']("citetitle")))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<attribution>"); if ((($a = node['$attr?']("attribution")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']((node.$attr("attribution")))}; if ((($a = node['$attr?']("citetitle")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<citetitle>" + (node.$attr("citetitle")) + "</citetitle>")}; result['$<<']("</attribution>");}; result['$<<']((self.$resolve_content(node))); result['$<<']("</blockquote>"); return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$thematic_break', function(node) { var self = this; return "<simpara><?asciidoc-hr?></simpara>"; }); Opal.defn(self, '$sidebar', function(node) { var self = this; return "<sidebar" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">\n" + (self.$title_tag(node)) + (self.$resolve_content(node)) + "\n</sidebar>"; }); Opal.cdecl($scope, 'TABLE_PI_NAMES', ["dbhtml", "dbfo", "dblatex"]); Opal.cdecl($scope, 'TABLE_SECTIONS', ["head", "foot", "body"]); Opal.defn(self, '$table', function(node) { var $a, $b, TMP_7, $c, TMP_8, $d, TMP_9, $e, $f, TMP_14, self = this, has_body = nil, result = nil, pgwide_attribute = nil, tag_name = nil, width = nil; has_body = false; result = []; pgwide_attribute = (function() {if ((($a = (node['$option?']("pgwide"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " pgwide=\"1\"" } else { return nil }; return nil; })(); result['$<<']("<" + (tag_name = (function() {if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "table" } else { return "informaltable" }; return nil; })()) + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + (pgwide_attribute) + " frame=\"" + (node.$attr("frame", "all")) + "\" rowsep=\"" + ((function() {if ((($a = ["none", "cols"]['$include?'](node.$attr("grid"))) !== nil && (!$a.$$is_boolean || $a == true))) { return 0 } else { return 1 }; return nil; })()) + "\" colsep=\"" + ((function() {if ((($a = ["none", "rows"]['$include?'](node.$attr("grid"))) !== nil && (!$a.$$is_boolean || $a == true))) { return 0 } else { return 1 }; return nil; })()) + "\">"); if ((($a = (node['$option?']("unbreakable"))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<?dbfo keep-together=\"always\"?>") } else if ((($a = (node['$option?']("breakable"))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<?dbfo keep-together=\"auto\"?>")}; if (tag_name['$==']("table")) { result['$<<']("<title>" + (node.$title()) + "</title>")}; if ((($a = (width = (function() {if ((($b = (node['$attr?']("width"))) !== nil && (!$b.$$is_boolean || $b == true))) { return (node.$attr("width")) } else { return nil }; return nil; })())) !== nil && (!$a.$$is_boolean || $a == true))) { ($a = ($b = $scope.get('TABLE_PI_NAMES')).$each, $a.$$p = (TMP_7 = function(pi_name){var self = TMP_7.$$s || this; if (pi_name == null) pi_name = nil; return result['$<<']("<?" + (pi_name) + " table-width=\"" + (width) + "\"?>")}, TMP_7.$$s = self, TMP_7), $a).call($b)}; result['$<<']("<tgroup cols=\"" + (node.$attr("colcount")) + "\">"); ($a = ($c = node.$columns()).$each, $a.$$p = (TMP_8 = function(col){var self = TMP_8.$$s || this; if (col == null) col = nil; return result['$<<']("<colspec colname=\"col_" + (col.$attr("colnumber")) + "\" colwidth=\"" + (col.$attr((function() {if (width !== false && width !== nil) { return "colabswidth" } else { return "colpcwidth" }; return nil; })())) + "*\"/>")}, TMP_8.$$s = self, TMP_8), $a).call($c); ($a = ($d = ($e = ($f = $scope.get('TABLE_SECTIONS')).$select, $e.$$p = (TMP_14 = function(tblsec){var self = TMP_14.$$s || this; if (tblsec == null) tblsec = nil; return node.$rows()['$[]'](tblsec)['$empty?']()['$!']()}, TMP_14.$$s = self, TMP_14), $e).call($f)).$each, $a.$$p = (TMP_9 = function(tblsec){var self = TMP_9.$$s || this, $a, $b, TMP_10; if (tblsec == null) tblsec = nil; if (tblsec['$==']("body")) { has_body = true}; result['$<<']("<t" + (tblsec) + ">"); ($a = ($b = node.$rows()['$[]'](tblsec)).$each, $a.$$p = (TMP_10 = function(row){var self = TMP_10.$$s || this, $a, $b, TMP_11; if (row == null) row = nil; result['$<<']("<row>"); ($a = ($b = row).$each, $a.$$p = (TMP_11 = function(cell){var self = TMP_11.$$s || this, $a, $b, TMP_12, $c, TMP_13, halign_attribute = nil, valign_attribute = nil, colspan_attribute = nil, colnum = nil, rowspan_attribute = nil, entry_start = nil, cell_content = nil, $case = nil, entry_end = nil; if (cell == null) cell = nil; halign_attribute = (function() {if ((($a = (cell['$attr?']("halign"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " align=\"" + (cell.$attr("halign")) + "\"" } else { return nil }; return nil; })(); valign_attribute = (function() {if ((($a = (cell['$attr?']("valign"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " valign=\"" + (cell.$attr("valign")) + "\"" } else { return nil }; return nil; })(); colspan_attribute = (function() {if ((($a = cell.$colspan()) !== nil && (!$a.$$is_boolean || $a == true))) { return " namest=\"col_" + (colnum = cell.$column().$attr("colnumber")) + "\" nameend=\"col_" + ($rb_minus($rb_plus(colnum, cell.$colspan()), 1)) + "\"" } else { return nil }; return nil; })(); rowspan_attribute = (function() {if ((($a = cell.$rowspan()) !== nil && (!$a.$$is_boolean || $a == true))) { return " morerows=\"" + ($rb_minus(cell.$rowspan(), 1)) + "\"" } else { return nil }; return nil; })(); entry_start = "<entry" + (halign_attribute) + (valign_attribute) + (colspan_attribute) + (rowspan_attribute) + ">"; cell_content = (function() {if (tblsec['$==']("head")) { return cell.$text() } else { return (function() {$case = cell.$style();if ("asciidoc"['$===']($case)) {return cell.$content()}else if ("verse"['$===']($case)) {return "<literallayout>" + (cell.$text()) + "</literallayout>"}else if ("literal"['$===']($case)) {return "<literallayout class=\"monospaced\">" + (cell.$text()) + "</literallayout>"}else if ("header"['$===']($case)) {return ($a = ($b = cell.$content()).$map, $a.$$p = (TMP_12 = function(text){var self = TMP_12.$$s || this; if (text == null) text = nil; return "<simpara><emphasis role=\"strong\">" + (text) + "</emphasis></simpara>"}, TMP_12.$$s = self, TMP_12), $a).call($b).$join()}else {return ($a = ($c = cell.$content()).$map, $a.$$p = (TMP_13 = function(text){var self = TMP_13.$$s || this; if (text == null) text = nil; return "<simpara>" + (text) + "</simpara>"}, TMP_13.$$s = self, TMP_13), $a).call($c).$join()}})() }; return nil; })(); entry_end = (function() {if ((($a = (node.$document()['$attr?']("cellbgcolor"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "<?dbfo bgcolor=\"" + (node.$document().$attr("cellbgcolor")) + "\"?></entry>" } else { return "</entry>" }; return nil; })(); return result['$<<']("" + (entry_start) + (cell_content) + (entry_end));}, TMP_11.$$s = self, TMP_11), $a).call($b); return result['$<<']("</row>");}, TMP_10.$$s = self, TMP_10), $a).call($b); return result['$<<']("</t" + (tblsec) + ">");}, TMP_9.$$s = self, TMP_9), $a).call($d); result['$<<']("</tgroup>"); result['$<<']("</" + (tag_name) + ">"); if (has_body !== false && has_body !== nil) { } else { self.$warn("asciidoctor: WARNING: tables must have at least one body row") }; return $rb_times(result, $scope.get('EOL')); }); Opal.alias(self, 'toc', 'skip'); Opal.defn(self, '$ulist', function(node) { var $a, $b, TMP_15, $c, TMP_16, self = this, result = nil, mark_type = nil, checklist = nil, mark_attribute = nil; result = []; if (node.$style()['$==']("bibliography")) { result['$<<']("<bibliodiv" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($b = node.$items()).$each, $a.$$p = (TMP_15 = function(item){var self = TMP_15.$$s || this, $a; if (item == null) item = nil; result['$<<']("<bibliomixed>"); result['$<<']("<bibliomisc>" + (item.$text()) + "</bibliomisc>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</bibliomixed>");}, TMP_15.$$s = self, TMP_15), $a).call($b); result['$<<']("</bibliodiv>"); } else { mark_type = (function() {if ((($a = (checklist = node['$option?']("checklist"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "none" } else { return node.$style() }; return nil; })(); mark_attribute = (function() {if (mark_type !== false && mark_type !== nil) { return " mark=\"" + (mark_type) + "\"" } else { return nil }; return nil; })(); result['$<<']("<itemizedlist" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + (mark_attribute) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; ($a = ($c = node.$items()).$each, $a.$$p = (TMP_16 = function(item){var self = TMP_16.$$s || this, $a, $b, text_marker = nil; if (item == null) item = nil; text_marker = (function() {if ((($a = (($b = checklist !== false && checklist !== nil) ? (item['$attr?']("checkbox")) : checklist)) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = (item['$attr?']("checked"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "&#10003; " } else { return "&#10063; " } } else { return nil }; return nil; })(); result['$<<']("<listitem>"); result['$<<']("<simpara>" + (text_marker) + (item.$text()) + "</simpara>"); if ((($a = item['$blocks?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<'](item.$content())}; return result['$<<']("</listitem>");}, TMP_16.$$s = self, TMP_16), $a).call($c); result['$<<']("</itemizedlist>"); }; return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$verse', function(node) { var $a, $b, self = this, result = nil; result = []; result['$<<']("<blockquote" + (self.$common_attributes(node.$id(), node.$role(), node.$reftext())) + ">"); if ((($a = node['$title?']()) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<title>" + (node.$title()) + "</title>")}; if ((($a = ((($b = (node['$attr?']("attribution"))) !== false && $b !== nil) ? $b : (node['$attr?']("citetitle")))) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<attribution>"); if ((($a = node['$attr?']("attribution")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']((node.$attr("attribution")))}; if ((($a = node['$attr?']("citetitle")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<citetitle>" + (node.$attr("citetitle")) + "</citetitle>")}; result['$<<']("</attribution>");}; result['$<<']("<literallayout>" + (node.$content()) + "</literallayout>"); result['$<<']("</blockquote>"); return $rb_times(result, $scope.get('EOL')); }); Opal.alias(self, 'video', 'skip'); Opal.defn(self, '$inline_anchor', function(node) { var $a, self = this, $case = nil, path = nil, linkend = nil, text = nil, target = nil; return (function() {$case = node.$type();if ("ref"['$===']($case)) {return "<anchor" + (self.$common_attributes(node.$target(), nil, node.$text())) + "/>"}else if ("xref"['$===']($case)) {if ((($a = (path = node.$attributes()['$[]']("path"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "<link xlink:href=\"" + (node.$target()) + "\">" + (((($a = node.$text()) !== false && $a !== nil) ? $a : path)) + "</link>" } else { linkend = ((($a = node.$attributes()['$[]']("fragment")) !== false && $a !== nil) ? $a : node.$target()); if ((($a = (text = node.$text())) !== nil && (!$a.$$is_boolean || $a == true))) { return "<link linkend=\"" + (linkend) + "\">" + (text) + "</link>" } else { return "<xref linkend=\"" + (linkend) + "\"/>" }; }}else if ("link"['$===']($case)) {return "<link xlink:href=\"" + (node.$target()) + "\">" + (node.$text()) + "</link>"}else if ("bibref"['$===']($case)) {target = node.$target(); return "<anchor" + (self.$common_attributes(target, nil, "[" + (target) + "]")) + "/>[" + (target) + "]";}else {return self.$warn("asciidoctor: WARNING: unknown anchor type: " + (node.$type().$inspect()))}})(); }); Opal.defn(self, '$inline_break', function(node) { var self = this; return "" + (node.$text()) + "<?asciidoc-br?>"; }); Opal.defn(self, '$inline_button', function(node) { var self = this; return "<guibutton>" + (node.$text()) + "</guibutton>"; }); Opal.defn(self, '$inline_callout', function(node) { var self = this; return "<co" + (self.$common_attributes(node.$id())) + "/>"; }); Opal.defn(self, '$inline_footnote', function(node) { var self = this; if (node.$type()['$==']("xref")) { return "<footnoteref linkend=\"" + (node.$target()) + "\"/>" } else { return "<footnote" + (self.$common_attributes(node.$id())) + "><simpara>" + (node.$text()) + "</simpara></footnote>" }; }); Opal.defn(self, '$inline_image', function(node) { var $a, self = this, width_attribute = nil, depth_attribute = nil; width_attribute = (function() {if ((($a = (node['$attr?']("width"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " contentwidth=\"" + (node.$attr("width")) + "\"" } else { return nil }; return nil; })(); depth_attribute = (function() {if ((($a = (node['$attr?']("height"))) !== nil && (!$a.$$is_boolean || $a == true))) { return " contentdepth=\"" + (node.$attr("height")) + "\"" } else { return nil }; return nil; })(); return "<inlinemediaobject>\n<imageobject>\n<imagedata fileref=\"" + ((function() {if (node.$type()['$==']("icon")) { return (node.$icon_uri(node.$target())) } else { return (node.$image_uri(node.$target())) }; return nil; })()) + "\"" + (width_attribute) + (depth_attribute) + "/>\n</imageobject>\n<textobject><phrase>" + (node.$attr("alt")) + "</phrase></textobject>\n</inlinemediaobject>"; }); Opal.defn(self, '$inline_indexterm', function(node) { var self = this, terms = nil, result = nil, numterms = nil; if (node.$type()['$==']("visible")) { return "<indexterm><primary>" + (node.$text()) + "</primary></indexterm>" + (node.$text()) } else { terms = node.$attr("terms"); result = []; if ($rb_gt((numterms = terms.$size()), 2)) { result['$<<']("<indexterm>\n<primary>" + (terms['$[]'](0)) + "</primary><secondary>" + (terms['$[]'](1)) + "</secondary><tertiary>" + (terms['$[]'](2)) + "</tertiary>\n</indexterm>")}; if ($rb_gt(numterms, 1)) { result['$<<']("<indexterm>\n<primary>" + (terms['$[]'](-2)) + "</primary><secondary>" + (terms['$[]'](-1)) + "</secondary>\n</indexterm>")}; result['$<<']("<indexterm>\n<primary>" + (terms['$[]'](-1)) + "</primary>\n</indexterm>"); return $rb_times(result, $scope.get('EOL')); }; }); Opal.defn(self, '$inline_kbd', function(node) { var $a, $b, TMP_17, self = this, keys = nil; if (((keys = node.$attr("keys"))).$size()['$=='](1)) { return "<keycap>" + (keys['$[]'](0)) + "</keycap>" } else { return "<keycombo>" + (($a = ($b = keys).$map, $a.$$p = (TMP_17 = function(key){var self = TMP_17.$$s || this; if (key == null) key = nil; return "<keycap>" + (key) + "</keycap>"}, TMP_17.$$s = self, TMP_17), $a).call($b).$join()) + "</keycombo>" }; }); Opal.defn(self, '$inline_menu', function(node) { var $a, $b, TMP_18, self = this, menu = nil, submenus = nil, submenu_path = nil, menuitem = nil; menu = node.$attr("menu"); if ((($a = ((submenus = node.$attr("submenus")))['$empty?']()['$!']()) !== nil && (!$a.$$is_boolean || $a == true))) { submenu_path = ($a = ($b = submenus).$map, $a.$$p = (TMP_18 = function(submenu){var self = TMP_18.$$s || this; if (submenu == null) submenu = nil; return "<guisubmenu>" + (submenu) + "</guisubmenu> "}, TMP_18.$$s = self, TMP_18), $a).call($b).$join().$chop(); return "<menuchoice><guimenu>" + (menu) + "</guimenu> " + (submenu_path) + " <guimenuitem>" + (node.$attr("menuitem")) + "</guimenuitem></menuchoice>"; } else if ((($a = (menuitem = node.$attr("menuitem"))) !== nil && (!$a.$$is_boolean || $a == true))) { return "<menuchoice><guimenu>" + (menu) + "</guimenu> <guimenuitem>" + (menuitem) + "</guimenuitem></menuchoice>" } else { return "<guimenu>" + (menu) + "</guimenu>" }; }); (($a = [[nil, nil, true]]), $b = (Opal.cdecl($scope, 'QUOTE_TAGS', $hash2(["emphasis", "strong", "monospaced", "superscript", "subscript", "double", "single", "mark"], {"emphasis": ["<emphasis>", "</emphasis>", true], "strong": ["<emphasis role=\"strong\">", "</emphasis>", true], "monospaced": ["<literal>", "</literal>", false], "superscript": ["<superscript>", "</superscript>", false], "subscript": ["<subscript>", "</subscript>", false], "double": ["&#8220;", "&#8221;", true], "single": ["&#8216;", "&#8217;", true], "mark": ["<emphasis role=\"marked\">", "</emphasis>", false]}))), $b['$default='].apply($b, $a), $a[$a.length-1]); Opal.defn(self, '$inline_quoted', function(node) { var $a, self = this, type = nil, open = nil, close = nil, supports_phrase = nil, text = nil, role = nil, quoted_text = nil; if (((type = node.$type()))['$==']("latexmath")) { return "<inlineequation>\n<alt><![CDATA[" + (node.$text()) + "]]></alt>\n<inlinemediaobject><textobject><phrase><![CDATA[" + (node.$text()) + "]]></phrase></textobject></inlinemediaobject>\n</inlineequation>" } else { $a = Opal.to_ary($scope.get('QUOTE_TAGS')['$[]'](type)), open = ($a[0] == null ? nil : $a[0]), close = ($a[1] == null ? nil : $a[1]), supports_phrase = ($a[2] == null ? nil : $a[2]); text = node.$text(); if ((($a = (role = node.$role())) !== nil && (!$a.$$is_boolean || $a == true))) { if (supports_phrase !== false && supports_phrase !== nil) { quoted_text = "" + (open) + "<phrase role=\"" + (role) + "\">" + (text) + "</phrase>" + (close) } else { quoted_text = "" + (open.$chop()) + " role=\"" + (role) + "\">" + (text) + (close) } } else { quoted_text = "" + (open) + (text) + (close) }; if ((($a = node.$id()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<anchor" + (self.$common_attributes(node.$id(), nil, text)) + "/>" + (quoted_text) } else { return quoted_text }; }; }); Opal.defn(self, '$author_element', function(doc, index) { var $a, self = this, firstname_key = nil, middlename_key = nil, lastname_key = nil, email_key = nil, result = nil; if (index == null) { index = nil } firstname_key = (function() {if (index !== false && index !== nil) { return "firstname_" + (index) } else { return "firstname" }; return nil; })(); middlename_key = (function() {if (index !== false && index !== nil) { return "middlename_" + (index) } else { return "middlename" }; return nil; })(); lastname_key = (function() {if (index !== false && index !== nil) { return "lastname_" + (index) } else { return "lastname" }; return nil; })(); email_key = (function() {if (index !== false && index !== nil) { return "email_" + (index) } else { return "email" }; return nil; })(); result = []; result['$<<']("<author>"); result['$<<']("<personname>"); if ((($a = doc['$attr?'](firstname_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<firstname>" + (doc.$attr(firstname_key)) + "</firstname>")}; if ((($a = doc['$attr?'](middlename_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<othername>" + (doc.$attr(middlename_key)) + "</othername>")}; if ((($a = doc['$attr?'](lastname_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<surname>" + (doc.$attr(lastname_key)) + "</surname>")}; result['$<<']("</personname>"); if ((($a = doc['$attr?'](email_key)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<email>" + (doc.$attr(email_key)) + "</email>")}; result['$<<']("</author>"); return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$common_attributes', function(id, role, reftext) { var self = this, res = nil; if (role == null) { role = nil } if (reftext == null) { reftext = nil } res = (function() {if (id !== false && id !== nil) { return " xml:id=\"" + (id) + "\"" } else { return "" }; return nil; })(); if (role !== false && role !== nil) { res = "" + (res) + " role=\"" + (role) + "\""}; if (reftext !== false && reftext !== nil) { res = "" + (res) + " xreflabel=\"" + (reftext) + "\""}; return res; }); Opal.defn(self, '$doctype_declaration', function(root_tag_name) { var self = this; return nil; }); Opal.defn(self, '$document_info_element', function(doc, info_tag_prefix, use_info_tag_prefix) { var $a, $b, TMP_19, $c, $d, self = this, result = nil, authorcount = nil, head_docinfo = nil; if (use_info_tag_prefix == null) { use_info_tag_prefix = false } if (use_info_tag_prefix !== false && use_info_tag_prefix !== nil) { } else { info_tag_prefix = "" }; result = []; result['$<<']("<" + (info_tag_prefix) + "info>"); if ((($a = doc.$notitle()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { result['$<<'](self.$document_title_tags(doc.$doctitle($hash2(["partition", "use_fallback"], {"partition": true, "use_fallback": true})))) }; result['$<<']("<date>" + ((function() {if ((($a = (doc['$attr?']("revdate"))) !== nil && (!$a.$$is_boolean || $a == true))) { return (doc.$attr("revdate")) } else { return (doc.$attr("docdate")) }; return nil; })()) + "</date>"); if ((($a = doc['$has_header?']()) !== nil && (!$a.$$is_boolean || $a == true))) { if ((($a = doc['$attr?']("author")) !== nil && (!$a.$$is_boolean || $a == true))) { if ($rb_lt((authorcount = (doc.$attr("authorcount")).$to_i()), 2)) { result['$<<']((self.$author_element(doc))); if ((($a = doc['$attr?']("authorinitials")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<authorinitials>" + (doc.$attr("authorinitials")) + "</authorinitials>")}; } else { result['$<<']("<authorgroup>"); ($a = ($b = authorcount).$times, $a.$$p = (TMP_19 = function(index){var self = TMP_19.$$s || this; if (index == null) index = nil; return result['$<<']((self.$author_element(doc, $rb_plus(index, 1))))}, TMP_19.$$s = self, TMP_19), $a).call($b); result['$<<']("</authorgroup>"); }}; if ((($a = ($c = (doc['$attr?']("revdate")), $c !== false && $c !== nil ?(((($d = (doc['$attr?']("revnumber"))) !== false && $d !== nil) ? $d : (doc['$attr?']("revremark")))) : $c)) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<revhistory>\n<revision>"); if ((($a = doc['$attr?']("revnumber")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<revnumber>" + (doc.$attr("revnumber")) + "</revnumber>")}; if ((($a = doc['$attr?']("revdate")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<date>" + (doc.$attr("revdate")) + "</date>")}; if ((($a = doc['$attr?']("authorinitials")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<authorinitials>" + (doc.$attr("authorinitials")) + "</authorinitials>")}; if ((($a = doc['$attr?']("revremark")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<revremark>" + (doc.$attr("revremark")) + "</revremark>")}; result['$<<']("</revision>\n</revhistory>");}; if ((($a = ((head_docinfo = doc.$docinfo()))['$empty?']()) !== nil && (!$a.$$is_boolean || $a == true))) { } else { result['$<<'](head_docinfo) }; if ((($a = doc['$attr?']("orgname")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<orgname>" + (doc.$attr("orgname")) + "</orgname>")};}; result['$<<']("</" + (info_tag_prefix) + "info>"); if (doc.$doctype()['$==']("manpage")) { result['$<<']("<refmeta>"); if ((($a = doc['$attr?']("mantitle")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<refentrytitle>" + (doc.$attr("mantitle")) + "</refentrytitle>")}; if ((($a = doc['$attr?']("manvolnum")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<manvolnum>" + (doc.$attr("manvolnum")) + "</manvolnum>")}; result['$<<']("</refmeta>"); result['$<<']("<refnamediv>"); if ((($a = doc['$attr?']("manname")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<refname>" + (doc.$attr("manname")) + "</refname>")}; if ((($a = doc['$attr?']("manpurpose")) !== nil && (!$a.$$is_boolean || $a == true))) { result['$<<']("<refpurpose>" + (doc.$attr("manpurpose")) + "</refpurpose>")}; result['$<<']("</refnamediv>");}; return $rb_times(result, $scope.get('EOL')); }); Opal.defn(self, '$document_ns_attributes', function(doc) { var self = this; return " xmlns=\"http://docbook.org/ns/docbook\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"5.0\""; }); Opal.defn(self, '$lang_attribute_name', function() { var self = this; return "xml:lang"; }); Opal.defn(self, '$document_title_tags', function(title) { var $a, self = this; if ((($a = title['$subtitle?']()) !== nil && (!$a.$$is_boolean || $a == true))) { return "<title>" + (title.$main()) + "</title>\n<subtitle>" + (title.$subtitle()) + "</subtitle>" } else { return "<title>" + (title) + "</title>" }; }); Opal.defn(self, '$resolve_content', function(node) { var self = this; if (node.$content_model()['$==']("compound")) { return node.$content() } else { return "<simpara>" + (node.$content()) + "</simpara>" }; }); return (Opal.defn(self, '$title_tag', function(node, optional) { var $a, $b, self = this; if (optional == null) { optional = true } if ((($a = ((($b = optional['$!']()) !== false && $b !== nil) ? $b : node['$title?']())) !== nil && (!$a.$$is_boolean || $a == true))) { return "<title>" + (node.$title()) + "</title>\n" } else { return nil }; }), nil) && 'title_tag'; })($scope.get('Converter'), (($scope.get('Converter')).$$scope.get('BuiltIn'))) })($scope.base) }; // By default automatically require Asciidoctor Docbook module unless variable AsciidoctorConfiguration.autoRequireModule is set to 'false' if (typeof AsciidoctorConfiguration === 'undefined' || typeof AsciidoctorConfiguration.autoRequireModule === 'undefined' || Boolean(AsciidoctorConfiguration.autoRequireModule)) { Opal.require('asciidoctor/converter'); Opal.require('asciidoctor/converter/docbook5'); } };
(function ($) { // register namespace $.extend(true, window, { "Slick": { "CheckboxSelectColumn": CheckboxSelectColumn } }); function CheckboxSelectColumn(options) { var _grid; var _self = this; var _handler = new Slick.EventHandler(); var _selectedRowsLookup = {}; var _defaults = { columnId: "_checkbox_selector", cssClass: null, toolTip: "Select/Deselect All", width: 30 }; var _options = $.extend(true, {}, _defaults, options); function init(grid) { _grid = grid; _handler .subscribe(_grid.onSelectedRowsChanged, handleSelectedRowsChanged) .subscribe(_grid.onClick, handleClick) .subscribe(_grid.onHeaderClick, handleHeaderClick) .subscribe(_grid.onKeyDown, handleKeyDown); } function destroy() { _handler.unsubscribeAll(); } function handleSelectedRowsChanged(e, args) { var UID = createUID(); var selectedRows = _grid.getSelectedRows(); var lookup = {}, row, i; for (i = 0; i < selectedRows.length; i++) { row = selectedRows[i]; lookup[row] = true; if (lookup[row] !== _selectedRowsLookup[row]) { _grid.invalidateRow(row); delete _selectedRowsLookup[row]; } } for (i in _selectedRowsLookup) { _grid.invalidateRow(i); } _selectedRowsLookup = lookup; _grid.render(); if (selectedRows.length && selectedRows.length == _grid.getDataLength()) { _grid.updateColumnHeader(_options.columnId, "<input id='header-selector" + UID + "' type='checkbox' checked='checked'><label for='header-selector" + UID + "'></label>", _options.toolTip); } else { _grid.updateColumnHeader(_options.columnId, "<input id='header-selector" + UID + "' type='checkbox'><label for='header-selector" + UID + "'></label>", _options.toolTip); } } function handleKeyDown(e, args) { if (e.which == 32) { if (_grid.getColumns()[args.cell].id === _options.columnId) { // if editing, try to commit if (!_grid.getEditorLock().isActive() || _grid.getEditorLock().commitCurrentEdit()) { toggleRowSelection(args.row); } e.preventDefault(); e.stopImmediatePropagation(); } } } function handleClick(e, args) { // clicking on a row select checkbox if (_grid.getColumns()[args.cell].id === _options.columnId && $(e.target).is(":checkbox")) { // if editing, try to commit if (_grid.getEditorLock().isActive() && !_grid.getEditorLock().commitCurrentEdit()) { e.preventDefault(); e.stopImmediatePropagation(); return; } toggleRowSelection(args.row); e.stopPropagation(); e.stopImmediatePropagation(); } } function toggleRowSelection(row) { if (_selectedRowsLookup[row]) { _grid.setSelectedRows($.grep(_grid.getSelectedRows(), function (n) { return n != row })); } else { _grid.setSelectedRows(_grid.getSelectedRows().concat(row)); } _grid.setActiveCell(row, getCheckboxColumnCellIndex()); _grid.focus(); } function selectRows(rowArray) { var i, l=rowArray.length, addRows = []; for(i=0; i<l; i++) { if (!_selectedRowsLookup[rowArray[i]]) { addRows[addRows.length] = rowArray[i]; } } _grid.setSelectedRows(_grid.getSelectedRows().concat(addRows)); } function deSelectRows(rowArray) { var i, l=rowArray.length, removeRows = []; for(i=0; i<l; i++) { if (_selectedRowsLookup[rowArray[i]]) { removeRows[removeRows.length] = rowArray[i]; } } _grid.setSelectedRows($.grep(_grid.getSelectedRows(), function (n) { return removeRows.indexOf(n)<0 })); } function handleHeaderClick(e, args) { if (args.column.id == _options.columnId && $(e.target).is(":checkbox")) { // if editing, try to commit if (_grid.getEditorLock().isActive() && !_grid.getEditorLock().commitCurrentEdit()) { e.preventDefault(); e.stopImmediatePropagation(); return; } if ($(e.target).is(":checked")) { var rows = []; for (var i = 0; i < _grid.getDataLength(); i++) { rows.push(i); } _grid.setSelectedRows(rows); } else { _grid.setSelectedRows([]); } e.stopPropagation(); e.stopImmediatePropagation(); } } var _checkboxColumnCellIndex = null; function getCheckboxColumnCellIndex() { if (_checkboxColumnCellIndex === null) { _checkboxColumnCellIndex = 0; var colArr = _grid.getColumns(); for (var i=0; i < colArr.length; i++) { if (colArr[i].id == _options.columnId) { _checkboxColumnCellIndex = i; } } } return _checkboxColumnCellIndex; } function getColumnDefinition() { var UID = createUID(); return { id: _options.columnId, name: "<input id='header-selector" + UID + "' type='checkbox'><label for='header-selector" + UID + "'></label>", toolTip: _options.toolTip, field: "sel", width: _options.width, resizable: false, sortable: false, cssClass: _options.cssClass, formatter: checkboxSelectionFormatter }; } function createUID() { return Math.round(10000000 * Math.random()); } function checkboxSelectionFormatter(row, cell, value, columnDef, dataContext) { var UID = createUID() + row; if (dataContext) { return _selectedRowsLookup[row] ? "<input id='selector" + UID + "' type='checkbox' checked='checked'><label for='selector" + UID + "'></label>" : "<input id='selector" + UID + "' type='checkbox'><label for='selector" + UID + "'></label>"; } return null; } $.extend(this, { "init": init, "destroy": destroy, "deSelectRows": deSelectRows, "selectRows": selectRows, "getColumnDefinition": getColumnDefinition }); } })(jQuery);
$(function () { 'use strict' QUnit.module('dropdowns plugin') QUnit.test('should be defined on jquery object', function (assert) { assert.expect(1) assert.ok($(document.body).dropdown, 'dropdown method is defined') }) QUnit.module('dropdowns', { beforeEach: function () { // Run all tests in noConflict mode -- it's the only way to ensure that the plugin works in noConflict mode $.fn.bootstrapDropdown = $.fn.dropdown.noConflict() }, afterEach: function () { $.fn.dropdown = $.fn.bootstrapDropdown delete $.fn.bootstrapDropdown } }) QUnit.test('should provide no conflict', function (assert) { assert.expect(1) assert.strictEqual($.fn.dropdown, undefined, 'dropdown was set back to undefined (org value)') }) QUnit.test('should throw explicit error on undefined method', function (assert) { assert.expect(1) var $el = $('<div/>') $el.bootstrapDropdown() try { $el.bootstrapDropdown('noMethod') } catch (err) { assert.strictEqual(err.message, 'No method named "noMethod"') } }) QUnit.test('should return jquery collection containing the element', function (assert) { assert.expect(2) var $el = $('<div/>') var $dropdown = $el.bootstrapDropdown() assert.ok($dropdown instanceof $, 'returns jquery collection') assert.strictEqual($dropdown[0], $el[0], 'collection contains element') }) QUnit.test('should not open dropdown if target is disabled via attribute', function (assert) { assert.expect(1) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<button disabled href="#" class="btn dropdown-toggle" data-toggle="dropdown">Dropdown</button>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML).find('[data-toggle="dropdown"]').bootstrapDropdown().trigger('click') assert.ok(!$dropdown.parent('.dropdown').hasClass('show'), '"show" class added on click') }) QUnit.test('should set aria-expanded="true" on target when dropdown menu is shown', function (assert) { assert.expect(1) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML) .find('[data-toggle="dropdown"]') .bootstrapDropdown() .trigger('click') assert.strictEqual($dropdown.attr('aria-expanded'), 'true', 'aria-expanded is set to string "true" on click') }) QUnit.test('should set aria-expanded="false" on target when dropdown menu is hidden', function (assert) { assert.expect(1) var done = assert.async() var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" aria-expanded="false" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() $dropdown .parent('.dropdown') .on('hidden.bs.dropdown', function () { assert.strictEqual($dropdown.attr('aria-expanded'), 'false', 'aria-expanded is set to string "false" on hide') done() }) $dropdown.trigger('click') $(document.body).trigger('click') }) QUnit.test('should not open dropdown if target is disabled via class', function (assert) { assert.expect(1) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<button href="#" class="btn dropdown-toggle disabled" data-toggle="dropdown">Dropdown</button>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML).find('[data-toggle="dropdown"]').bootstrapDropdown().trigger('click') assert.ok(!$dropdown.parent('.dropdown').hasClass('show'), '"show" class added on click') }) QUnit.test('should add class show to menu if clicked', function (assert) { assert.expect(1) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML).find('[data-toggle="dropdown"]').bootstrapDropdown().trigger('click') assert.ok($dropdown.parent('.dropdown').hasClass('show'), '"show" class added on click') }) QUnit.test('should test if element has a # before assuming it\'s a selector', function (assert) { assert.expect(1) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="/foo/" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML).find('[data-toggle="dropdown"]').bootstrapDropdown().trigger('click') assert.ok($dropdown.parent('.dropdown').hasClass('show'), '"show" class added on click') }) QUnit.test('should remove "show" class if body is clicked', function (assert) { assert.expect(2) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() .trigger('click') assert.ok($dropdown.parent('.dropdown').hasClass('show'), '"show" class added on click') $(document.body).trigger('click') assert.ok(!$dropdown.parent('.dropdown').hasClass('show'), '"show" class removed') }) QUnit.test('should remove "show" class if body is focused', function (assert) { assert.expect(2) var dropdownHTML = '<div class="tabs">' + '<div class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<div class="dropdown-menu">' + '<a class="dropdown-item" href="#">Secondary link</a>' + '<a class="dropdown-item" href="#">Something else here</a>' + '<div class="dropdown-divider"/>' + '<a class="dropdown-item" href="#">Another link</a>' + '</div>' + '</div>' + '</div>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() .trigger('click') assert.ok($dropdown.parent('.dropdown').hasClass('show'), '"show" class added on click') $(document.body).trigger('focusin') assert.ok(!$dropdown.parent('.dropdown').hasClass('show'), '"show" class removed') }) QUnit.test('should remove "show" class if body is clicked, with multiple dropdowns', function (assert) { assert.expect(7) var dropdownHTML = '<ul class="nav">' + '<li><a href="#menu1">Menu 1</a></li>' + '<li class="dropdown" id="testmenu">' + '<a class="dropdown-toggle" data-toggle="dropdown" href="#testmenu">Test menu <span class="caret"/></a>' + '<ul class="dropdown-menu">' + '<li><a href="#sub1">Submenu 1</a></li>' + '</ul>' + '</li>' + '</ul>' + '<div class="btn-group">' + '<button class="btn">Actions</button>' + '<button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"/></button>' + '<ul class="dropdown-menu">' + '<li><a href="#">Action 1</a></li>' + '</ul>' + '</div>' var $dropdowns = $(dropdownHTML).appendTo('#qunit-fixture').find('[data-toggle="dropdown"]') var $first = $dropdowns.first() var $last = $dropdowns.last() assert.strictEqual($dropdowns.length, 2, 'two dropdowns') $first.trigger('click') assert.strictEqual($first.parents('.show').length, 1, '"show" class added on click') assert.strictEqual($('#qunit-fixture .show').length, 1, 'only one dropdown is shown') $(document.body).trigger('click') assert.strictEqual($('#qunit-fixture .show').length, 0, '"show" class removed') $last.trigger('click') assert.strictEqual($last.parent('.show').length, 1, '"show" class added on click') assert.strictEqual($('#qunit-fixture .show').length, 1, 'only one dropdown is shown') $(document.body).trigger('click') assert.strictEqual($('#qunit-fixture .show').length, 0, '"show" class removed') }) QUnit.test('should remove "show" class if body is focused, with multiple dropdowns', function (assert) { assert.expect(7) var dropdownHTML = '<div class="nav">' + '<div class="dropdown" id="testmenu">' + '<a class="dropdown-toggle" data-toggle="dropdown" href="#testmenu">Test menu <span class="caret"/></a>' + '<div class="dropdown-menu">' + '<a class="dropdown-item" href="#sub1">Submenu 1</a>' + '</div>' + '</div>' + '</div>' + '<div class="btn-group">' + '<button class="btn">Actions</button>' + '<button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"/></button>' + '<div class="dropdown-menu">' + '<a class="dropdown-item" href="#">Action 1</a>' + '</div>' + '</div>' var $dropdowns = $(dropdownHTML).appendTo('#qunit-fixture').find('[data-toggle="dropdown"]') var $first = $dropdowns.first() var $last = $dropdowns.last() assert.strictEqual($dropdowns.length, 2, 'two dropdowns') $first.trigger('click') assert.strictEqual($first.parents('.show').length, 1, '"show" class added on click') assert.strictEqual($('#qunit-fixture .show').length, 1, 'only one dropdown is show') $(document.body).trigger('focusin') assert.strictEqual($('#qunit-fixture .show').length, 0, '"show" class removed') $last.trigger('click') assert.strictEqual($last.parent('.show').length, 1, '"show" class added on click') assert.strictEqual($('#qunit-fixture .show').length, 1, 'only one dropdown is show') $(document.body).trigger('focusin') assert.strictEqual($('#qunit-fixture .show').length, 0, '"show" class removed') }) QUnit.test('should fire show and hide event', function (assert) { assert.expect(2) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() var done = assert.async() $dropdown .parent('.dropdown') .on('show.bs.dropdown', function () { assert.ok(true, 'show was fired') }) .on('hide.bs.dropdown', function () { assert.ok(true, 'hide was fired') done() }) $dropdown.trigger('click') $(document.body).trigger('click') }) QUnit.test('should fire shown and hidden event', function (assert) { assert.expect(2) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() var done = assert.async() $dropdown .parent('.dropdown') .on('shown.bs.dropdown', function () { assert.ok(true, 'shown was fired') }) .on('hidden.bs.dropdown', function () { assert.ok(true, 'hidden was fired') done() }) $dropdown.trigger('click') $(document.body).trigger('click') }) QUnit.test('should fire shown and hidden event with a relatedTarget', function (assert) { assert.expect(2) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() var done = assert.async() $dropdown.parent('.dropdown') .on('hidden.bs.dropdown', function (e) { assert.strictEqual(e.relatedTarget, $dropdown[0]) done() }) .on('shown.bs.dropdown', function (e) { assert.strictEqual(e.relatedTarget, $dropdown[0]) $(document.body).trigger('click') }) $dropdown.trigger('click') }) QUnit.test('should ignore keyboard events within <input>s and <textarea>s', function (assert) { assert.expect(3) var done = assert.async() var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li><a href="#">Secondary link</a></li>' + '<li><a href="#">Something else here</a></li>' + '<li class="divider"/>' + '<li><a href="#">Another link</a></li>' + '<li><input type="text" id="input"></li>' + '<li><textarea id="textarea"/></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() var $input = $('#input') var $textarea = $('#textarea') $dropdown .parent('.dropdown') .on('shown.bs.dropdown', function () { assert.ok(true, 'shown was fired') $input.trigger('focus').trigger($.Event('keydown', { which: 38 })) assert.ok($(document.activeElement).is($input), 'input still focused') $textarea.trigger('focus').trigger($.Event('keydown', { which: 38 })) assert.ok($(document.activeElement).is($textarea), 'textarea still focused') done() }) $dropdown.trigger('click') }) QUnit.test('should skip disabled element when using keyboard navigation', function (assert) { assert.expect(1) var dropdownHTML = '<ul class="tabs">' + '<li class="dropdown">' + '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>' + '<ul class="dropdown-menu">' + '<li class="disabled"><a href="#">Disabled link</a></li>' + '<li><a href="#">Another link</a></li>' + '</ul>' + '</li>' + '</ul>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() .trigger('click') $dropdown.trigger($.Event('keydown', { which: 40 })) $dropdown.trigger($.Event('keydown', { which: 40 })) assert.ok(!$(document.activeElement).parent().is('.disabled'), '.disabled is not focused') }) QUnit.test('should not close the dropdown if the user clicks on a text field', function (assert) { assert.expect(1) var dropdownHTML = '<div class="btn-group">' + '<button type="button" data-toggle="dropdown">Dropdown</button>' + '<ul class="dropdown-menu">' + '<li><input id="textField" type="text" /></li>' + '</ul>' + '</div>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() .trigger('click') $('#textField').trigger('click') assert.ok($dropdown.parent('.btn-group').hasClass('show'), 'dropdown menu is shown') }) QUnit.test('should not close the dropdown if the user clicks on a textarea', function (assert) { assert.expect(1) var dropdownHTML = '<div class="btn-group">' + '<button type="button" data-toggle="dropdown">Dropdown</button>' + '<ul class="dropdown-menu">' + '<li><textarea id="textArea"></textarea></li>' + '</ul>' + '</div>' var $dropdown = $(dropdownHTML) .appendTo('#qunit-fixture') .find('[data-toggle="dropdown"]') .bootstrapDropdown() .trigger('click') $('#textArea').trigger('click') assert.ok($dropdown.parent('.btn-group').hasClass('show'), 'dropdown menu is shown') }) })
(function($){"use strict";$.fn.select2.locales["ko"]={formatNoMatches:function(){return"결과 없음"},formatInputTooShort:function(input,min){var n=min-input.length;return"너무 짧습니다. "+n+"글자 더 입력해주세요."},formatInputTooLong:function(input,max){var n=input.length-max;return"너무 깁니다. "+n+"글자 지워주세요."},formatSelectionTooBig:function(limit){return"최대 "+limit+"개까지만 선택하실 수 있습니다."},formatLoadMore:function(pageNumber){return"불러오는 중…"},formatSearching:function(){return"검색 중…"}};$.extend($.fn.select2.defaults,$.fn.select2.locales["ko"])})(jQuery);
/* --- MooTools: the javascript framework copyrights: - [MooTools](http://mootools.net) licenses: - [MIT License](http://mootools.net/license.txt) ... */ (function(){this.MooTools={version:"1.5.0",build:"0f7b690afee9349b15909f33016a25d2e4d9f4e3"};var e=this.typeOf=function(i){if(i==null){return"null";}if(i.$family!=null){return i.$family(); }if(i.nodeName){if(i.nodeType==1){return"element";}if(i.nodeType==3){return(/\S/).test(i.nodeValue)?"textnode":"whitespace";}}else{if(typeof i.length=="number"){if("callee" in i){return"arguments"; }if("item" in i){return"collection";}}}return typeof i;};var u=this.instanceOf=function(w,i){if(w==null){return false;}var v=w.$constructor||w.constructor; while(v){if(v===i){return true;}v=v.parent;}if(!w.hasOwnProperty){return false;}return w instanceof i;};var f=this.Function;var r=true;for(var q in {toString:1}){r=null; }if(r){r=["hasOwnProperty","valueOf","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","constructor"];}f.prototype.overloadSetter=function(v){var i=this; return function(x,w){if(x==null){return this;}if(v||typeof x!="string"){for(var y in x){i.call(this,y,x[y]);}if(r){for(var z=r.length;z--;){y=r[z];if(x.hasOwnProperty(y)){i.call(this,y,x[y]); }}}}else{i.call(this,x,w);}return this;};};f.prototype.overloadGetter=function(v){var i=this;return function(x){var y,w;if(typeof x!="string"){y=x;}else{if(arguments.length>1){y=arguments; }else{if(v){y=[x];}}}if(y){w={};for(var z=0;z<y.length;z++){w[y[z]]=i.call(this,y[z]);}}else{w=i.call(this,x);}return w;};};f.prototype.extend=function(i,v){this[i]=v; }.overloadSetter();f.prototype.implement=function(i,v){this.prototype[i]=v;}.overloadSetter();var o=Array.prototype.slice;f.from=function(i){return(e(i)=="function")?i:function(){return i; };};Array.from=function(i){if(i==null){return[];}return(k.isEnumerable(i)&&typeof i!="string")?(e(i)=="array")?i:o.call(i):[i];};Number.from=function(v){var i=parseFloat(v); return isFinite(i)?i:null;};String.from=function(i){return i+"";};f.implement({hide:function(){this.$hidden=true;return this;},protect:function(){this.$protected=true; return this;}});var k=this.Type=function(x,w){if(x){var v=x.toLowerCase();var i=function(y){return(e(y)==v);};k["is"+x]=i;if(w!=null){w.prototype.$family=(function(){return v; }).hide();w.type=i;}}if(w==null){return null;}w.extend(this);w.$constructor=k;w.prototype.$constructor=w;return w;};var p=Object.prototype.toString;k.isEnumerable=function(i){return(i!=null&&typeof i.length=="number"&&p.call(i)!="[object Function]"); };var b={};var d=function(i){var v=e(i.prototype);return b[v]||(b[v]=[]);};var h=function(w,A){if(A&&A.$hidden){return;}var v=d(this);for(var x=0;x<v.length; x++){var z=v[x];if(e(z)=="type"){h.call(z,w,A);}else{z.call(this,w,A);}}var y=this.prototype[w];if(y==null||!y.$protected){this.prototype[w]=A;}if(this[w]==null&&e(A)=="function"){t.call(this,w,function(i){return A.apply(i,o.call(arguments,1)); });}};var t=function(i,w){if(w&&w.$hidden){return;}var v=this[i];if(v==null||!v.$protected){this[i]=w;}};k.implement({implement:h.overloadSetter(),extend:t.overloadSetter(),alias:function(i,v){h.call(this,i,this.prototype[v]); }.overloadSetter(),mirror:function(i){d(this).push(i);return this;}});new k("Type",k);var c=function(v,A,y){var x=(A!=Object),E=A.prototype;if(x){A=new k(v,A); }for(var B=0,z=y.length;B<z;B++){var F=y[B],D=A[F],C=E[F];if(D){D.protect();}if(x&&C){A.implement(F,C.protect());}}if(x){var w=E.propertyIsEnumerable(y[0]); A.forEachMethod=function(J){if(!w){for(var I=0,G=y.length;I<G;I++){J.call(E,E[y[I]],y[I]);}}for(var H in E){J.call(E,E[H],H);}};}return c;};c("String",String,["charAt","charCodeAt","concat","contains","indexOf","lastIndexOf","match","quote","replace","search","slice","split","substr","substring","trim","toLowerCase","toUpperCase"])("Array",Array,["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice","indexOf","lastIndexOf","filter","forEach","every","map","some","reduce","reduceRight"])("Number",Number,["toExponential","toFixed","toLocaleString","toPrecision"])("Function",f,["apply","call","bind"])("RegExp",RegExp,["exec","test"])("Object",Object,["create","defineProperty","defineProperties","keys","getPrototypeOf","getOwnPropertyDescriptor","getOwnPropertyNames","preventExtensions","isExtensible","seal","isSealed","freeze","isFrozen"])("Date",Date,["now"]); Object.extend=t.overloadSetter();Date.extend("now",function(){return +(new Date);});new k("Boolean",Boolean);Number.prototype.$family=function(){return isFinite(this)?"number":"null"; }.hide();Number.extend("random",function(v,i){return Math.floor(Math.random()*(i-v+1)+v);});var l=Object.prototype.hasOwnProperty;Object.extend("forEach",function(i,w,x){for(var v in i){if(l.call(i,v)){w.call(x,i[v],v,i); }}});Object.each=Object.forEach;Array.implement({forEach:function(x,y){for(var w=0,v=this.length;w<v;w++){if(w in this){x.call(y,this[w],w,this);}}},each:function(i,v){Array.forEach(this,i,v); return this;}});var s=function(i){switch(e(i)){case"array":return i.clone();case"object":return Object.clone(i);default:return i;}};Array.implement("clone",function(){var v=this.length,w=new Array(v); while(v--){w[v]=s(this[v]);}return w;});var a=function(v,i,w){switch(e(w)){case"object":if(e(v[i])=="object"){Object.merge(v[i],w);}else{v[i]=Object.clone(w); }break;case"array":v[i]=w.clone();break;default:v[i]=w;}return v;};Object.extend({merge:function(C,y,x){if(e(y)=="string"){return a(C,y,x);}for(var B=1,w=arguments.length; B<w;B++){var z=arguments[B];for(var A in z){a(C,A,z[A]);}}return C;},clone:function(i){var w={};for(var v in i){w[v]=s(i[v]);}return w;},append:function(z){for(var y=1,w=arguments.length; y<w;y++){var v=arguments[y]||{};for(var x in v){z[x]=v[x];}}return z;}});["Object","WhiteSpace","TextNode","Collection","Arguments"].each(function(i){new k(i); });var j=Date.now();String.extend("uniqueID",function(){return(j++).toString(36);});var g=this.Hash=new k("Hash",function(i){if(e(i)=="hash"){i=Object.clone(i.getClean()); }for(var v in i){this[v]=i[v];}return this;});g.implement({forEach:function(i,v){Object.forEach(this,i,v);},getClean:function(){var v={};for(var i in this){if(this.hasOwnProperty(i)){v[i]=this[i]; }}return v;},getLength:function(){var v=0;for(var i in this){if(this.hasOwnProperty(i)){v++;}}return v;}});g.alias("each","forEach");Object.type=k.isObject; var n=this.Native=function(i){return new k(i.name,i.initialize);};n.type=k.type;n.implement=function(x,v){for(var w=0;w<x.length;w++){x[w].implement(v); }return n;};var m=Array.type;Array.type=function(i){return u(i,Array)||m(i);};this.$A=function(i){return Array.from(i).slice();};this.$arguments=function(v){return function(){return arguments[v]; };};this.$chk=function(i){return !!(i||i===0);};this.$clear=function(i){clearTimeout(i);clearInterval(i);return null;};this.$defined=function(i){return(i!=null); };this.$each=function(w,v,x){var i=e(w);((i=="arguments"||i=="collection"||i=="array"||i=="elements")?Array:Object).each(w,v,x);};this.$empty=function(){}; this.$extend=function(v,i){return Object.append(v,i);};this.$H=function(i){return new g(i);};this.$merge=function(){var i=Array.slice(arguments);i.unshift({}); return Object.merge.apply(null,i);};this.$lambda=f.from;this.$mixin=Object.merge;this.$random=Number.random;this.$splat=Array.from;this.$time=Date.now; this.$type=function(i){var v=e(i);if(v=="elements"){return"array";}return(v=="null")?false:v;};this.$unlink=function(i){switch(e(i)){case"object":return Object.clone(i); case"array":return Array.clone(i);case"hash":return new g(i);default:return i;}};})();Array.implement({every:function(c,d){for(var b=0,a=this.length>>>0; b<a;b++){if((b in this)&&!c.call(d,this[b],b,this)){return false;}}return true;},filter:function(d,f){var c=[];for(var e,b=0,a=this.length>>>0;b<a;b++){if(b in this){e=this[b]; if(d.call(f,e,b,this)){c.push(e);}}}return c;},indexOf:function(c,d){var b=this.length>>>0;for(var a=(d<0)?Math.max(0,b+d):d||0;a<b;a++){if(this[a]===c){return a; }}return -1;},map:function(c,e){var d=this.length>>>0,b=Array(d);for(var a=0;a<d;a++){if(a in this){b[a]=c.call(e,this[a],a,this);}}return b;},some:function(c,d){for(var b=0,a=this.length>>>0; b<a;b++){if((b in this)&&c.call(d,this[b],b,this)){return true;}}return false;},clean:function(){return this.filter(function(a){return a!=null;});},invoke:function(a){var b=Array.slice(arguments,1); return this.map(function(c){return c[a].apply(c,b);});},associate:function(c){var d={},b=Math.min(this.length,c.length);for(var a=0;a<b;a++){d[c[a]]=this[a]; }return d;},link:function(c){var a={};for(var e=0,b=this.length;e<b;e++){for(var d in c){if(c[d](this[e])){a[d]=this[e];delete c[d];break;}}}return a;},contains:function(a,b){return this.indexOf(a,b)!=-1; },append:function(a){this.push.apply(this,a);return this;},getLast:function(){return(this.length)?this[this.length-1]:null;},getRandom:function(){return(this.length)?this[Number.random(0,this.length-1)]:null; },include:function(a){if(!this.contains(a)){this.push(a);}return this;},combine:function(c){for(var b=0,a=c.length;b<a;b++){this.include(c[b]);}return this; },erase:function(b){for(var a=this.length;a--;){if(this[a]===b){this.splice(a,1);}}return this;},empty:function(){this.length=0;return this;},flatten:function(){var d=[]; for(var b=0,a=this.length;b<a;b++){var c=typeOf(this[b]);if(c=="null"){continue;}d=d.concat((c=="array"||c=="collection"||c=="arguments"||instanceOf(this[b],Array))?Array.flatten(this[b]):this[b]); }return d;},pick:function(){for(var b=0,a=this.length;b<a;b++){if(this[b]!=null){return this[b];}}return null;},hexToRgb:function(b){if(this.length!=3){return null; }var a=this.map(function(c){if(c.length==1){c+=c;}return parseInt(c,16);});return(b)?a:"rgb("+a+")";},rgbToHex:function(d){if(this.length<3){return null; }if(this.length==4&&this[3]==0&&!d){return"transparent";}var b=[];for(var a=0;a<3;a++){var c=(this[a]-0).toString(16);b.push((c.length==1)?"0"+c:c);}return(d)?b:"#"+b.join(""); }});Array.alias("extend","append");var $pick=function(){return Array.from(arguments).pick();};String.implement({contains:function(b,a){return(a?String(this).slice(a):String(this)).indexOf(b)>-1; },test:function(a,b){return((typeOf(a)=="regexp")?a:new RegExp(""+a,b)).test(this);},trim:function(){return String(this).replace(/^\s+|\s+$/g,"");},clean:function(){return String(this).replace(/\s+/g," ").trim(); },camelCase:function(){return String(this).replace(/-\D/g,function(a){return a.charAt(1).toUpperCase();});},hyphenate:function(){return String(this).replace(/[A-Z]/g,function(a){return("-"+a.charAt(0).toLowerCase()); });},capitalize:function(){return String(this).replace(/\b[a-z]/g,function(a){return a.toUpperCase();});},escapeRegExp:function(){return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1"); },toInt:function(a){return parseInt(this,a||10);},toFloat:function(){return parseFloat(this);},hexToRgb:function(b){var a=String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); return(a)?a.slice(1).hexToRgb(b):null;},rgbToHex:function(b){var a=String(this).match(/\d{1,3}/g);return(a)?a.rgbToHex(b):null;},substitute:function(a,b){return String(this).replace(b||(/\\?\{([^{}]+)\}/g),function(d,c){if(d.charAt(0)=="\\"){return d.slice(1); }return(a[c]!=null)?a[c]:"";});}});String.prototype.contains=function(a,b){return(b)?(b+this+b).indexOf(b+a+b)>-1:String(this).indexOf(a)>-1;};Number.implement({limit:function(b,a){return Math.min(a,Math.max(b,this)); },round:function(a){a=Math.pow(10,a||0).toFixed(a<0?-a:0);return Math.round(this*a)/a;},times:function(b,c){for(var a=0;a<this;a++){b.call(c,a,this);}},toFloat:function(){return parseFloat(this); },toInt:function(a){return parseInt(this,a||10);}});Number.alias("each","times");(function(b){var a={};b.each(function(c){if(!Number[c]){a[c]=function(){return Math[c].apply(null,[this].concat(Array.from(arguments))); };}});Number.implement(a);})(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);Function.extend({attempt:function(){for(var b=0,a=arguments.length; b<a;b++){try{return arguments[b]();}catch(c){}}return null;}});Function.implement({attempt:function(a,c){try{return this.apply(c,Array.from(a));}catch(b){}return null; },bind:function(e){var a=this,b=arguments.length>1?Array.slice(arguments,1):null,d=function(){};var c=function(){var g=e,h=arguments.length;if(this instanceof c){d.prototype=a.prototype; g=new d;}var f=(!b&&!h)?a.call(g):a.apply(g,b&&h?b.concat(Array.slice(arguments)):b||arguments);return g==e?f:g;};return c;},pass:function(b,c){var a=this; if(b!=null){b=Array.from(b);}return function(){return a.apply(c,b||arguments);};},delay:function(b,c,a){return setTimeout(this.pass((a==null?[]:a),c),b); },periodical:function(c,b,a){return setInterval(this.pass((a==null?[]:a),b),c);}});delete Function.prototype.bind;Function.implement({create:function(b){var a=this; b=b||{};return function(d){var c=b.arguments;c=(c!=null)?Array.from(c):Array.slice(arguments,(b.event)?1:0);if(b.event){c=[d||window.event].extend(c);}var e=function(){return a.apply(b.bind||null,c); };if(b.delay){return setTimeout(e,b.delay);}if(b.periodical){return setInterval(e,b.periodical);}if(b.attempt){return Function.attempt(e);}return e();}; },bind:function(c,b){var a=this;if(b!=null){b=Array.from(b);}return function(){return a.apply(c,b||arguments);};},bindWithEvent:function(c,b){var a=this; if(b!=null){b=Array.from(b);}return function(d){return a.apply(c,(b==null)?arguments:[d].concat(b));};},run:function(a,b){return this.apply(b,Array.from(a)); }});if(Object.create==Function.prototype.create){Object.create=null;}var $try=Function.attempt;(function(){var a=Object.prototype.hasOwnProperty;Object.extend({subset:function(d,g){var f={}; for(var e=0,b=g.length;e<b;e++){var c=g[e];if(c in d){f[c]=d[c];}}return f;},map:function(b,e,f){var d={};for(var c in b){if(a.call(b,c)){d[c]=e.call(f,b[c],c,b); }}return d;},filter:function(b,e,g){var d={};for(var c in b){var f=b[c];if(a.call(b,c)&&e.call(g,f,c,b)){d[c]=f;}}return d;},every:function(b,d,e){for(var c in b){if(a.call(b,c)&&!d.call(e,b[c],c)){return false; }}return true;},some:function(b,d,e){for(var c in b){if(a.call(b,c)&&d.call(e,b[c],c)){return true;}}return false;},keys:function(b){var d=[];for(var c in b){if(a.call(b,c)){d.push(c); }}return d;},values:function(c){var b=[];for(var d in c){if(a.call(c,d)){b.push(c[d]);}}return b;},getLength:function(b){return Object.keys(b).length;},keyOf:function(b,d){for(var c in b){if(a.call(b,c)&&b[c]===d){return c; }}return null;},contains:function(b,c){return Object.keyOf(b,c)!=null;},toQueryString:function(b,c){var d=[];Object.each(b,function(h,g){if(c){g=c+"["+g+"]"; }var f;switch(typeOf(h)){case"object":f=Object.toQueryString(h,g);break;case"array":var e={};h.each(function(k,j){e[j]=k;});f=Object.toQueryString(e,g); break;default:f=g+"="+encodeURIComponent(h);}if(h!=null){d.push(f);}});return d.join("&");}});})();Hash.implement({has:Object.prototype.hasOwnProperty,keyOf:function(a){return Object.keyOf(this,a); },hasValue:function(a){return Object.contains(this,a);},extend:function(a){Hash.each(a||{},function(c,b){Hash.set(this,b,c);},this);return this;},combine:function(a){Hash.each(a||{},function(c,b){Hash.include(this,b,c); },this);return this;},erase:function(a){if(this.hasOwnProperty(a)){delete this[a];}return this;},get:function(a){return(this.hasOwnProperty(a))?this[a]:null; },set:function(a,b){if(!this[a]||this.hasOwnProperty(a)){this[a]=b;}return this;},empty:function(){Hash.each(this,function(b,a){delete this[a];},this); return this;},include:function(a,b){if(this[a]==null){this[a]=b;}return this;},map:function(a,b){return new Hash(Object.map(this,a,b));},filter:function(a,b){return new Hash(Object.filter(this,a,b)); },every:function(a,b){return Object.every(this,a,b);},some:function(a,b){return Object.some(this,a,b);},getKeys:function(){return Object.keys(this);},getValues:function(){return Object.values(this); },toQueryString:function(a){return Object.toQueryString(this,a);}});Hash.extend=Object.append;Hash.alias({indexOf:"keyOf",contains:"hasValue"});(function(){var i=this.document; var g=i.window=this;var b=function(n,e){n=n.toLowerCase();e=(e?e.toLowerCase():"");var o=n.match(/(opera|ie|firefox|chrome|trident|crios|version)[\s\/:]([\w\d\.]+)?.*?(safari|(?:rv[\s\/:]|version[\s\/:])([\w\d\.]+)|$)/)||[null,"unknown",0]; if(o[1]=="trident"){o[1]="ie";if(o[4]){o[2]=o[4];}}else{if(o[1]=="crios"){o[1]="chrome";}}var e=n.match(/ip(?:ad|od|hone)/)?"ios":(n.match(/(?:webos|android)/)||e.match(/mac|win|linux/)||["other"])[0]; if(e=="win"){e="windows";}return{extend:Function.prototype.extend,name:(o[1]=="version")?o[3]:o[1],version:parseFloat((o[1]=="opera"&&o[4])?o[4]:o[2]),platform:e}; };var m=this.Browser=b(navigator.userAgent,navigator.platform);if(m.ie){m.version=i.documentMode;}m.extend({Features:{xpath:!!(i.evaluate),air:!!(g.runtime),query:!!(i.querySelector),json:!!(g.JSON)},parseUA:b}); m[m.name]=true;m[m.name+parseInt(m.version,10)]=true;if(m.name=="ie"&&m.version>="11"){delete m.ie;}var a=m.platform;if(a=="windows"){a="win";}m.Platform={name:a}; m.Platform[a]=true;m.Request=(function(){var o=function(){return new XMLHttpRequest();};var n=function(){return new ActiveXObject("MSXML2.XMLHTTP");};var e=function(){return new ActiveXObject("Microsoft.XMLHTTP"); };return Function.attempt(function(){o();return o;},function(){n();return n;},function(){e();return e;});})();m.Features.xhr=!!(m.Request);var h=(Function.attempt(function(){return navigator.plugins["Shockwave Flash"].description; },function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);m.Plugins={Flash:{version:Number(h[0]||"0."+h[1])||0,build:Number(h[2])||0}}; m.exec=function(n){if(!n){return n;}if(g.execScript){g.execScript(n);}else{var e=i.createElement("script");e.setAttribute("type","text/javascript");e.text=n; i.head.appendChild(e);i.head.removeChild(e);}return n;};String.implement("stripScripts",function(n){var e="";var o=this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(p,q){e+=q+"\n"; return"";});if(n===true){m.exec(e);}else{if(typeOf(n)=="function"){n(e,o);}}return o;});m.extend({Document:this.Document,Window:this.Window,Element:this.Element,Event:this.Event}); this.Window=this.$constructor=new Type("Window",function(){});this.$family=Function.from("window").hide();Window.mirror(function(e,n){g[e]=n;});this.Document=i.$constructor=new Type("Document",function(){}); i.$family=Function.from("document").hide();Document.mirror(function(e,n){i[e]=n;});i.html=i.documentElement;if(!i.head){i.head=i.getElementsByTagName("head")[0]; }if(i.execCommand){try{i.execCommand("BackgroundImageCache",false,true);}catch(f){}}if(this.attachEvent&&!this.addEventListener){var c=function(){this.detachEvent("onunload",c); i.head=i.html=i.window=null;};this.attachEvent("onunload",c);}var k=Array.from;try{k(i.html.childNodes);}catch(f){Array.from=function(n){if(typeof n!="string"&&Type.isEnumerable(n)&&typeOf(n)!="array"){var e=n.length,o=new Array(e); while(e--){o[e]=n[e];}return o;}return k(n);};var j=Array.prototype,l=j.slice;["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice"].each(function(e){var n=j[e]; Array[e]=function(o){return n.apply(Array.from(o),l.call(arguments,1));};});}if(m.Platform.ios){m.Platform.ipod=true;}m.Engine={};var d=function(n,e){m.Engine.name=n; m.Engine[n+e]=true;m.Engine.version=e;};if(m.ie){m.Engine.trident=true;switch(m.version){case 6:d("trident",4);break;case 7:d("trident",5);break;case 8:d("trident",6); }}if(m.firefox){m.Engine.gecko=true;if(m.version>=3){d("gecko",19);}else{d("gecko",18);}}if(m.safari||m.chrome){m.Engine.webkit=true;switch(m.version){case 2:d("webkit",419); break;case 3:d("webkit",420);break;case 4:d("webkit",525);}}if(m.opera){m.Engine.presto=true;if(m.version>=9.6){d("presto",960);}else{if(m.version>=9.5){d("presto",950); }else{d("presto",925);}}}if(m.name=="unknown"){switch((navigator.userAgent.toLowerCase().match(/(?:webkit|khtml|gecko)/)||[])[0]){case"webkit":case"khtml":m.Engine.webkit=true; break;case"gecko":m.Engine.gecko=true;}}this.$exec=m.exec;})();(function(){var b={};var a=this.DOMEvent=new Type("DOMEvent",function(c,g){if(!g){g=window; }c=c||g.event;if(c.$extended){return c;}this.event=c;this.$extended=true;this.shift=c.shiftKey;this.control=c.ctrlKey;this.alt=c.altKey;this.meta=c.metaKey; var i=this.type=c.type;var h=c.target||c.srcElement;while(h&&h.nodeType==3){h=h.parentNode;}this.target=document.id(h);if(i.indexOf("key")==0){var d=this.code=(c.which||c.keyCode); this.key=b[d]||Object.keyOf(Event.Keys,d);if(i=="keydown"||i=="keyup"){if(d>111&&d<124){this.key="f"+(d-111);}else{if(d>95&&d<106){this.key=d-96;}}}if(this.key==null){this.key=String.fromCharCode(d).toLowerCase(); }}else{if(i=="click"||i=="dblclick"||i=="contextmenu"||i=="DOMMouseScroll"||i.indexOf("mouse")==0){var j=g.document;j=(!j.compatMode||j.compatMode=="CSS1Compat")?j.html:j.body; this.page={x:(c.pageX!=null)?c.pageX:c.clientX+j.scrollLeft,y:(c.pageY!=null)?c.pageY:c.clientY+j.scrollTop};this.client={x:(c.pageX!=null)?c.pageX-g.pageXOffset:c.clientX,y:(c.pageY!=null)?c.pageY-g.pageYOffset:c.clientY}; if(i=="DOMMouseScroll"||i=="mousewheel"){this.wheel=(c.wheelDelta)?c.wheelDelta/120:-(c.detail||0)/3;}this.rightClick=(c.which==3||c.button==2);if(i=="mouseover"||i=="mouseout"){var k=c.relatedTarget||c[(i=="mouseover"?"from":"to")+"Element"]; while(k&&k.nodeType==3){k=k.parentNode;}this.relatedTarget=document.id(k);}}else{if(i.indexOf("touch")==0||i.indexOf("gesture")==0){this.rotation=c.rotation; this.scale=c.scale;this.targetTouches=c.targetTouches;this.changedTouches=c.changedTouches;var f=this.touches=c.touches;if(f&&f[0]){var e=f[0];this.page={x:e.pageX,y:e.pageY}; this.client={x:e.clientX,y:e.clientY};}}}}if(!this.client){this.client={};}if(!this.page){this.page={};}});a.implement({stop:function(){return this.preventDefault().stopPropagation(); },stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault(); }else{this.event.returnValue=false;}return this;}});a.defineKey=function(d,c){b[d]=c;return this;};a.defineKeys=a.defineKey.overloadSetter(true);a.defineKeys({"38":"up","40":"down","37":"left","39":"right","27":"esc","32":"space","8":"backspace","9":"tab","46":"delete","13":"enter"}); })();var Event=DOMEvent;Event.Keys={};Event.Keys=new Hash(Event.Keys);(function(){var a=this.Class=new Type("Class",function(h){if(instanceOf(h,Function)){h={initialize:h}; }var g=function(){e(this);if(g.$prototyping){return this;}this.$caller=null;var i=(this.initialize)?this.initialize.apply(this,arguments):this;this.$caller=this.caller=null; return i;}.extend(this).implement(h);g.$constructor=a;g.prototype.$constructor=g;g.prototype.parent=c;return g;});var c=function(){if(!this.$caller){throw new Error('The method "parent" cannot be called.'); }var g=this.$caller.$name,h=this.$caller.$owner.parent,i=(h)?h.prototype[g]:null;if(!i){throw new Error('The method "'+g+'" has no parent.');}return i.apply(this,arguments); };var e=function(g){for(var h in g){var j=g[h];switch(typeOf(j)){case"object":var i=function(){};i.prototype=j;g[h]=e(new i);break;case"array":g[h]=j.clone(); break;}}return g;};var b=function(g,h,j){if(j.$origin){j=j.$origin;}var i=function(){if(j.$protected&&this.$caller==null){throw new Error('The method "'+h+'" cannot be called.'); }var l=this.caller,m=this.$caller;this.caller=m;this.$caller=i;var k=j.apply(this,arguments);this.$caller=m;this.caller=l;return k;}.extend({$owner:g,$origin:j,$name:h}); return i;};var f=function(h,i,g){if(a.Mutators.hasOwnProperty(h)){i=a.Mutators[h].call(this,i);if(i==null){return this;}}if(typeOf(i)=="function"){if(i.$hidden){return this; }this.prototype[h]=(g)?i:b(this,h,i);}else{Object.merge(this.prototype,h,i);}return this;};var d=function(g){g.$prototyping=true;var h=new g;delete g.$prototyping; return h;};a.implement("implement",f.overloadSetter());a.Mutators={Extends:function(g){this.parent=g;this.prototype=d(g);},Implements:function(g){Array.from(g).each(function(j){var h=new j; for(var i in h){f.call(this,i,h[i],true);}},this);}};})();(function(){this.Chain=new Class({$chain:[],chain:function(){this.$chain.append(Array.flatten(arguments)); return this;},callChain:function(){return(this.$chain.length)?this.$chain.shift().apply(this,arguments):false;},clearChain:function(){this.$chain.empty(); return this;}});var a=function(b){return b.replace(/^on([A-Z])/,function(c,d){return d.toLowerCase();});};this.Events=new Class({$events:{},addEvent:function(d,c,b){d=a(d); if(c==$empty){return this;}this.$events[d]=(this.$events[d]||[]).include(c);if(b){c.internal=true;}return this;},addEvents:function(b){for(var c in b){this.addEvent(c,b[c]); }return this;},fireEvent:function(e,c,b){e=a(e);var d=this.$events[e];if(!d){return this;}c=Array.from(c);d.each(function(f){if(b){f.delay(b,this,c);}else{f.apply(this,c); }},this);return this;},removeEvent:function(e,d){e=a(e);var c=this.$events[e];if(c&&!d.internal){var b=c.indexOf(d);if(b!=-1){delete c[b];}}return this; },removeEvents:function(d){var e;if(typeOf(d)=="object"){for(e in d){this.removeEvent(e,d[e]);}return this;}if(d){d=a(d);}for(e in this.$events){if(d&&d!=e){continue; }var c=this.$events[e];for(var b=c.length;b--;){if(b in c){this.removeEvent(e,c[b]);}}}return this;}});this.Options=new Class({setOptions:function(){var b=this.options=Object.merge.apply(null,[{},this.options].append(arguments)); if(this.addEvent){for(var c in b){if(typeOf(b[c])!="function"||!(/^on[A-Z]/).test(c)){continue;}this.addEvent(c,b[c]);delete b[c];}}return this;}});})(); (function(){var k,n,l,g,a={},c={},m=/\\/g;var e=function(q,p){if(q==null){return null;}if(q.Slick===true){return q;}q=(""+q).replace(/^\s+|\s+$/g,"");g=!!p; var o=(g)?c:a;if(o[q]){return o[q];}k={Slick:true,expressions:[],raw:q,reverse:function(){return e(this.raw,true);}};n=-1;while(q!=(q=q.replace(j,b))){}k.length=k.expressions.length; return o[k.raw]=(g)?h(k):k;};var i=function(o){if(o==="!"){return" ";}else{if(o===" "){return"!";}else{if((/^!/).test(o)){return o.replace(/^!/,"");}else{return"!"+o; }}}};var h=function(u){var r=u.expressions;for(var p=0;p<r.length;p++){var t=r[p];var q={parts:[],tag:"*",combinator:i(t[0].combinator)};for(var o=0;o<t.length; o++){var s=t[o];if(!s.reverseCombinator){s.reverseCombinator=" ";}s.combinator=s.reverseCombinator;delete s.reverseCombinator;}t.reverse().push(q);}return u; };var f=function(o){return o.replace(/[-[\]{}()*+?.\\^$|,#\s]/g,function(p){return"\\"+p;});};var j=new RegExp("^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)".replace(/<combinator>/,"["+f(">+~`!@$%^&={}\\;</")+"]").replace(/<unicode>/g,"(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])").replace(/<unicode1>/g,"(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])")); function b(x,s,D,z,r,C,q,B,A,y,u,F,G,v,p,w){if(s||n===-1){k.expressions[++n]=[];l=-1;if(s){return"";}}if(D||z||l===-1){D=D||" ";var t=k.expressions[n]; if(g&&t[l]){t[l].reverseCombinator=i(D);}t[++l]={combinator:D,tag:"*"};}var o=k.expressions[n][l];if(r){o.tag=r.replace(m,"");}else{if(C){o.id=C.replace(m,""); }else{if(q){q=q.replace(m,"");if(!o.classList){o.classList=[];}if(!o.classes){o.classes=[];}o.classList.push(q);o.classes.push({value:q,regexp:new RegExp("(^|\\s)"+f(q)+"(\\s|$)")}); }else{if(G){w=w||p;w=w?w.replace(m,""):null;if(!o.pseudos){o.pseudos=[];}o.pseudos.push({key:G.replace(m,""),value:w,type:F.length==1?"class":"element"}); }else{if(B){B=B.replace(m,"");u=(u||"").replace(m,"");var E,H;switch(A){case"^=":H=new RegExp("^"+f(u));break;case"$=":H=new RegExp(f(u)+"$");break;case"~=":H=new RegExp("(^|\\s)"+f(u)+"(\\s|$)"); break;case"|=":H=new RegExp("^"+f(u)+"(-|$)");break;case"=":E=function(I){return u==I;};break;case"*=":E=function(I){return I&&I.indexOf(u)>-1;};break; case"!=":E=function(I){return u!=I;};break;default:E=function(I){return !!I;};}if(u==""&&(/^[*$^]=$/).test(A)){E=function(){return false;};}if(!E){E=function(I){return I&&H.test(I); };}if(!o.attributes){o.attributes=[];}o.attributes.push({key:B,operator:A,value:u,test:E});}}}}}return"";}var d=(this.Slick||{});d.parse=function(o){return e(o); };d.escapeRegExp=f;if(!this.Slick){this.Slick=d;}}).apply((typeof exports!="undefined")?exports:this);(function(){var k={},m={},d=Object.prototype.toString; k.isNativeCode=function(c){return(/\{\s*\[native code\]\s*\}/).test(""+c);};k.isXML=function(c){return(!!c.xmlVersion)||(!!c.xml)||(d.call(c)=="[object XMLDocument]")||(c.nodeType==9&&c.documentElement.nodeName!="HTML"); };k.setDocument=function(w){var p=w.nodeType;if(p==9){}else{if(p){w=w.ownerDocument;}else{if(w.navigator){w=w.document;}else{return;}}}if(this.document===w){return; }this.document=w;var A=w.documentElement,o=this.getUIDXML(A),s=m[o],r;if(s){for(r in s){this[r]=s[r];}return;}s=m[o]={};s.root=A;s.isXMLDocument=this.isXML(w); s.brokenStarGEBTN=s.starSelectsClosedQSA=s.idGetsName=s.brokenMixedCaseQSA=s.brokenGEBCN=s.brokenCheckedQSA=s.brokenEmptyAttributeQSA=s.isHTMLDocument=s.nativeMatchesSelector=false; var q,u,y,z,t;var x,v="slick_uniqueid";var c=w.createElement("div");var n=w.body||w.getElementsByTagName("body")[0]||A;n.appendChild(c);try{c.innerHTML='<a id="'+v+'"></a>'; s.isHTMLDocument=!!w.getElementById(v);}catch(C){}if(s.isHTMLDocument){c.style.display="none";c.appendChild(w.createComment(""));u=(c.getElementsByTagName("*").length>1); try{c.innerHTML="foo</foo>";x=c.getElementsByTagName("*");q=(x&&!!x.length&&x[0].nodeName.charAt(0)=="/");}catch(C){}s.brokenStarGEBTN=u||q;try{c.innerHTML='<a name="'+v+'"></a><b id="'+v+'"></b>'; s.idGetsName=w.getElementById(v)===c.firstChild;}catch(C){}if(c.getElementsByClassName){try{c.innerHTML='<a class="f"></a><a class="b"></a>';c.getElementsByClassName("b").length; c.firstChild.className="b";z=(c.getElementsByClassName("b").length!=2);}catch(C){}try{c.innerHTML='<a class="a"></a><a class="f b a"></a>';y=(c.getElementsByClassName("a").length!=2); }catch(C){}s.brokenGEBCN=z||y;}if(c.querySelectorAll){try{c.innerHTML="foo</foo>";x=c.querySelectorAll("*");s.starSelectsClosedQSA=(x&&!!x.length&&x[0].nodeName.charAt(0)=="/"); }catch(C){}try{c.innerHTML='<a class="MiX"></a>';s.brokenMixedCaseQSA=!c.querySelectorAll(".MiX").length;}catch(C){}try{c.innerHTML='<select><option selected="selected">a</option></select>'; s.brokenCheckedQSA=(c.querySelectorAll(":checked").length==0);}catch(C){}try{c.innerHTML='<a class=""></a>';s.brokenEmptyAttributeQSA=(c.querySelectorAll('[class*=""]').length!=0); }catch(C){}}try{c.innerHTML='<form action="s"><input id="action"/></form>';t=(c.firstChild.getAttribute("action")!="s");}catch(C){}s.nativeMatchesSelector=A.matches||A.mozMatchesSelector||A.webkitMatchesSelector; if(s.nativeMatchesSelector){try{s.nativeMatchesSelector.call(A,":slick");s.nativeMatchesSelector=null;}catch(C){}}}try{A.slick_expando=1;delete A.slick_expando; s.getUID=this.getUIDHTML;}catch(C){s.getUID=this.getUIDXML;}n.removeChild(c);c=x=n=null;s.getAttribute=(s.isHTMLDocument&&t)?function(G,E){var H=this.attributeGetters[E]; if(H){return H.call(G);}var F=G.getAttributeNode(E);return(F)?F.nodeValue:null;}:function(F,E){var G=this.attributeGetters[E];return(G)?G.call(F):F.getAttribute(E); };s.hasAttribute=(A&&this.isNativeCode(A.hasAttribute))?function(F,E){return F.hasAttribute(E);}:function(F,E){F=F.getAttributeNode(E);return !!(F&&(F.specified||F.nodeValue)); };var D=A&&this.isNativeCode(A.contains),B=w&&this.isNativeCode(w.contains);s.contains=(D&&B)?function(E,F){return E.contains(F);}:(D&&!B)?function(E,F){return E===F||((E===w)?w.documentElement:E).contains(F); }:(A&&A.compareDocumentPosition)?function(E,F){return E===F||!!(E.compareDocumentPosition(F)&16);}:function(E,F){if(F){do{if(F===E){return true;}}while((F=F.parentNode)); }return false;};s.documentSorter=(A.compareDocumentPosition)?function(F,E){if(!F.compareDocumentPosition||!E.compareDocumentPosition){return 0;}return F.compareDocumentPosition(E)&4?-1:F===E?0:1; }:("sourceIndex" in A)?function(F,E){if(!F.sourceIndex||!E.sourceIndex){return 0;}return F.sourceIndex-E.sourceIndex;}:(w.createRange)?function(H,F){if(!H.ownerDocument||!F.ownerDocument){return 0; }var G=H.ownerDocument.createRange(),E=F.ownerDocument.createRange();G.setStart(H,0);G.setEnd(H,0);E.setStart(F,0);E.setEnd(F,0);return G.compareBoundaryPoints(Range.START_TO_END,E); }:null;A=null;for(r in s){this[r]=s[r];}};var f=/^([#.]?)((?:[\w-]+|\*))$/,h=/\[.+[*$^]=(?:""|'')?\]/,g={};k.search=function(U,z,H,s){var p=this.found=(s)?null:(H||[]); if(!U){return p;}else{if(U.navigator){U=U.document;}else{if(!U.nodeType){return p;}}}var F,O,V=this.uniques={},I=!!(H&&H.length),y=(U.nodeType==9);if(this.document!==(y?U:U.ownerDocument)){this.setDocument(U); }if(I){for(O=p.length;O--;){V[this.getUID(p[O])]=true;}}if(typeof z=="string"){var r=z.match(f);simpleSelectors:if(r){var u=r[1],v=r[2],A,E;if(!u){if(v=="*"&&this.brokenStarGEBTN){break simpleSelectors; }E=U.getElementsByTagName(v);if(s){return E[0]||null;}for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}else{if(u=="#"){if(!this.isHTMLDocument||!y){break simpleSelectors; }A=U.getElementById(v);if(!A){return p;}if(this.idGetsName&&A.getAttributeNode("id").nodeValue!=v){break simpleSelectors;}if(s){return A||null;}if(!(I&&V[this.getUID(A)])){p.push(A); }}else{if(u=="."){if(!this.isHTMLDocument||((!U.getElementsByClassName||this.brokenGEBCN)&&U.querySelectorAll)){break simpleSelectors;}if(U.getElementsByClassName&&!this.brokenGEBCN){E=U.getElementsByClassName(v); if(s){return E[0]||null;}for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}else{var T=new RegExp("(^|\\s)"+e.escapeRegExp(v)+"(\\s|$)");E=U.getElementsByTagName("*"); for(O=0;A=E[O++];){className=A.className;if(!(className&&T.test(className))){continue;}if(s){return A;}if(!(I&&V[this.getUID(A)])){p.push(A);}}}}}}if(I){this.sort(p); }return(s)?null:p;}querySelector:if(U.querySelectorAll){if(!this.isHTMLDocument||g[z]||this.brokenMixedCaseQSA||(this.brokenCheckedQSA&&z.indexOf(":checked")>-1)||(this.brokenEmptyAttributeQSA&&h.test(z))||(!y&&z.indexOf(",")>-1)||e.disableQSA){break querySelector; }var S=z,x=U;if(!y){var C=x.getAttribute("id"),t="slickid__";x.setAttribute("id",t);S="#"+t+" "+S;U=x.parentNode;}try{if(s){return U.querySelector(S)||null; }else{E=U.querySelectorAll(S);}}catch(Q){g[z]=1;break querySelector;}finally{if(!y){if(C){x.setAttribute("id",C);}else{x.removeAttribute("id");}U=x;}}if(this.starSelectsClosedQSA){for(O=0; A=E[O++];){if(A.nodeName>"@"&&!(I&&V[this.getUID(A)])){p.push(A);}}}else{for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}if(I){this.sort(p); }return p;}F=this.Slick.parse(z);if(!F.length){return p;}}else{if(z==null){return p;}else{if(z.Slick){F=z;}else{if(this.contains(U.documentElement||U,z)){(p)?p.push(z):p=z; return p;}else{return p;}}}}this.posNTH={};this.posNTHLast={};this.posNTHType={};this.posNTHTypeLast={};this.push=(!I&&(s||(F.length==1&&F.expressions[0].length==1)))?this.pushArray:this.pushUID; if(p==null){p=[];}var M,L,K;var B,J,D,c,q,G,W;var N,P,o,w,R=F.expressions;search:for(O=0;(P=R[O]);O++){for(M=0;(o=P[M]);M++){B="combinator:"+o.combinator; if(!this[B]){continue search;}J=(this.isXMLDocument)?o.tag:o.tag.toUpperCase();D=o.id;c=o.classList;q=o.classes;G=o.attributes;W=o.pseudos;w=(M===(P.length-1)); this.bitUniques={};if(w){this.uniques=V;this.found=p;}else{this.uniques={};this.found=[];}if(M===0){this[B](U,J,D,q,G,W,c);if(s&&w&&p.length){break search; }}else{if(s&&w){for(L=0,K=N.length;L<K;L++){this[B](N[L],J,D,q,G,W,c);if(p.length){break search;}}}else{for(L=0,K=N.length;L<K;L++){this[B](N[L],J,D,q,G,W,c); }}}N=this.found;}}if(I||(F.expressions.length>1)){this.sort(p);}return(s)?(p[0]||null):p;};k.uidx=1;k.uidk="slick-uniqueid";k.getUIDXML=function(n){var c=n.getAttribute(this.uidk); if(!c){c=this.uidx++;n.setAttribute(this.uidk,c);}return c;};k.getUIDHTML=function(c){return c.uniqueNumber||(c.uniqueNumber=this.uidx++);};k.sort=function(c){if(!this.documentSorter){return c; }c.sort(this.documentSorter);return c;};k.cacheNTH={};k.matchNTH=/^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;k.parseNTHArgument=function(q){var o=q.match(this.matchNTH); if(!o){return false;}var p=o[2]||false;var n=o[1]||1;if(n=="-"){n=-1;}var c=+o[3]||0;o=(p=="n")?{a:n,b:c}:(p=="odd")?{a:2,b:1}:(p=="even")?{a:2,b:0}:{a:0,b:n}; return(this.cacheNTH[q]=o);};k.createNTHPseudo=function(p,n,c,o){return function(s,q){var u=this.getUID(s);if(!this[c][u]){var A=s.parentNode;if(!A){return false; }var r=A[p],t=1;if(o){var z=s.nodeName;do{if(r.nodeName!=z){continue;}this[c][this.getUID(r)]=t++;}while((r=r[n]));}else{do{if(r.nodeType!=1){continue; }this[c][this.getUID(r)]=t++;}while((r=r[n]));}}q=q||"n";var v=this.cacheNTH[q]||this.parseNTHArgument(q);if(!v){return false;}var y=v.a,x=v.b,w=this[c][u]; if(y==0){return x==w;}if(y>0){if(w<x){return false;}}else{if(x<w){return false;}}return((w-x)%y)==0;};};k.pushArray=function(p,c,r,o,n,q){if(this.matchSelector(p,c,r,o,n,q)){this.found.push(p); }};k.pushUID=function(q,c,s,p,n,r){var o=this.getUID(q);if(!this.uniques[o]&&this.matchSelector(q,c,s,p,n,r)){this.uniques[o]=true;this.found.push(q);}}; k.matchNode=function(n,o){if(this.isHTMLDocument&&this.nativeMatchesSelector){try{return this.nativeMatchesSelector.call(n,o.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g,'[$1="$2"]')); }catch(u){}}var t=this.Slick.parse(o);if(!t){return true;}var r=t.expressions,s=0,q;for(q=0;(currentExpression=r[q]);q++){if(currentExpression.length==1){var p=currentExpression[0]; if(this.matchSelector(n,(this.isXMLDocument)?p.tag:p.tag.toUpperCase(),p.id,p.classes,p.attributes,p.pseudos)){return true;}s++;}}if(s==t.length){return false; }var c=this.search(this.document,t),v;for(q=0;v=c[q++];){if(v===n){return true;}}return false;};k.matchPseudo=function(q,c,p){var n="pseudo:"+c;if(this[n]){return this[n](q,p); }var o=this.getAttribute(q,c);return(p)?p==o:!!o;};k.matchSelector=function(o,v,c,p,q,s){if(v){var t=(this.isXMLDocument)?o.nodeName:o.nodeName.toUpperCase(); if(v=="*"){if(t<"@"){return false;}}else{if(t!=v){return false;}}}if(c&&o.getAttribute("id")!=c){return false;}var r,n,u;if(p){for(r=p.length;r--;){u=this.getAttribute(o,"class"); if(!(u&&p[r].regexp.test(u))){return false;}}}if(q){for(r=q.length;r--;){n=q[r];if(n.operator?!n.test(this.getAttribute(o,n.key)):!this.hasAttribute(o,n.key)){return false; }}}if(s){for(r=s.length;r--;){n=s[r];if(!this.matchPseudo(o,n.key,n.value)){return false;}}}return true;};var j={" ":function(q,w,n,r,s,u,p){var t,v,o; if(this.isHTMLDocument){getById:if(n){v=this.document.getElementById(n);if((!v&&q.all)||(this.idGetsName&&v&&v.getAttributeNode("id").nodeValue!=n)){o=q.all[n]; if(!o){return;}if(!o[0]){o=[o];}for(t=0;v=o[t++];){var c=v.getAttributeNode("id");if(c&&c.nodeValue==n){this.push(v,w,null,r,s,u);break;}}return;}if(!v){if(this.contains(this.root,q)){return; }else{break getById;}}else{if(this.document!==q&&!this.contains(q,v)){return;}}this.push(v,w,null,r,s,u);return;}getByClass:if(r&&q.getElementsByClassName&&!this.brokenGEBCN){o=q.getElementsByClassName(p.join(" ")); if(!(o&&o.length)){break getByClass;}for(t=0;v=o[t++];){this.push(v,w,n,null,s,u);}return;}}getByTag:{o=q.getElementsByTagName(w);if(!(o&&o.length)){break getByTag; }if(!this.brokenStarGEBTN){w=null;}for(t=0;v=o[t++];){this.push(v,w,n,r,s,u);}}},">":function(p,c,r,o,n,q){if((p=p.firstChild)){do{if(p.nodeType==1){this.push(p,c,r,o,n,q); }}while((p=p.nextSibling));}},"+":function(p,c,r,o,n,q){while((p=p.nextSibling)){if(p.nodeType==1){this.push(p,c,r,o,n,q);break;}}},"^":function(p,c,r,o,n,q){p=p.firstChild; if(p){if(p.nodeType==1){this.push(p,c,r,o,n,q);}else{this["combinator:+"](p,c,r,o,n,q);}}},"~":function(q,c,s,p,n,r){while((q=q.nextSibling)){if(q.nodeType!=1){continue; }var o=this.getUID(q);if(this.bitUniques[o]){break;}this.bitUniques[o]=true;this.push(q,c,s,p,n,r);}},"++":function(p,c,r,o,n,q){this["combinator:+"](p,c,r,o,n,q); this["combinator:!+"](p,c,r,o,n,q);},"~~":function(p,c,r,o,n,q){this["combinator:~"](p,c,r,o,n,q);this["combinator:!~"](p,c,r,o,n,q);},"!":function(p,c,r,o,n,q){while((p=p.parentNode)){if(p!==this.document){this.push(p,c,r,o,n,q); }}},"!>":function(p,c,r,o,n,q){p=p.parentNode;if(p!==this.document){this.push(p,c,r,o,n,q);}},"!+":function(p,c,r,o,n,q){while((p=p.previousSibling)){if(p.nodeType==1){this.push(p,c,r,o,n,q); break;}}},"!^":function(p,c,r,o,n,q){p=p.lastChild;if(p){if(p.nodeType==1){this.push(p,c,r,o,n,q);}else{this["combinator:!+"](p,c,r,o,n,q);}}},"!~":function(q,c,s,p,n,r){while((q=q.previousSibling)){if(q.nodeType!=1){continue; }var o=this.getUID(q);if(this.bitUniques[o]){break;}this.bitUniques[o]=true;this.push(q,c,s,p,n,r);}}};for(var i in j){k["combinator:"+i]=j[i];}var l={empty:function(c){var n=c.firstChild; return !(n&&n.nodeType==1)&&!(c.innerText||c.textContent||"").length;},not:function(c,n){return !this.matchNode(c,n);},contains:function(c,n){return(c.innerText||c.textContent||"").indexOf(n)>-1; },"first-child":function(c){while((c=c.previousSibling)){if(c.nodeType==1){return false;}}return true;},"last-child":function(c){while((c=c.nextSibling)){if(c.nodeType==1){return false; }}return true;},"only-child":function(o){var n=o;while((n=n.previousSibling)){if(n.nodeType==1){return false;}}var c=o;while((c=c.nextSibling)){if(c.nodeType==1){return false; }}return true;},"nth-child":k.createNTHPseudo("firstChild","nextSibling","posNTH"),"nth-last-child":k.createNTHPseudo("lastChild","previousSibling","posNTHLast"),"nth-of-type":k.createNTHPseudo("firstChild","nextSibling","posNTHType",true),"nth-last-of-type":k.createNTHPseudo("lastChild","previousSibling","posNTHTypeLast",true),index:function(n,c){return this["pseudo:nth-child"](n,""+(c+1)); },even:function(c){return this["pseudo:nth-child"](c,"2n");},odd:function(c){return this["pseudo:nth-child"](c,"2n+1");},"first-of-type":function(c){var n=c.nodeName; while((c=c.previousSibling)){if(c.nodeName==n){return false;}}return true;},"last-of-type":function(c){var n=c.nodeName;while((c=c.nextSibling)){if(c.nodeName==n){return false; }}return true;},"only-of-type":function(o){var n=o,p=o.nodeName;while((n=n.previousSibling)){if(n.nodeName==p){return false;}}var c=o;while((c=c.nextSibling)){if(c.nodeName==p){return false; }}return true;},enabled:function(c){return !c.disabled;},disabled:function(c){return c.disabled;},checked:function(c){return c.checked||c.selected;},focus:function(c){return this.isHTMLDocument&&this.document.activeElement===c&&(c.href||c.type||this.hasAttribute(c,"tabindex")); },root:function(c){return(c===this.root);},selected:function(c){return c.selected;}};for(var b in l){k["pseudo:"+b]=l[b];}var a=k.attributeGetters={"for":function(){return("htmlFor" in this)?this.htmlFor:this.getAttribute("for"); },href:function(){return("href" in this)?this.getAttribute("href",2):this.getAttribute("href");},style:function(){return(this.style)?this.style.cssText:this.getAttribute("style"); },tabindex:function(){var c=this.getAttributeNode("tabindex");return(c&&c.specified)?c.nodeValue:null;},type:function(){return this.getAttribute("type"); },maxlength:function(){var c=this.getAttributeNode("maxLength");return(c&&c.specified)?c.nodeValue:null;}};a.MAXLENGTH=a.maxLength=a.maxlength;var e=k.Slick=(this.Slick||{}); e.version="1.1.7";e.search=function(n,o,c){return k.search(n,o,c);};e.find=function(c,n){return k.search(c,n,null,true);};e.contains=function(c,n){k.setDocument(c); return k.contains(c,n);};e.getAttribute=function(n,c){k.setDocument(n);return k.getAttribute(n,c);};e.hasAttribute=function(n,c){k.setDocument(n);return k.hasAttribute(n,c); };e.match=function(n,c){if(!(n&&c)){return false;}if(!c||c===n){return true;}k.setDocument(n);return k.matchNode(n,c);};e.defineAttributeGetter=function(c,n){k.attributeGetters[c]=n; return this;};e.lookupAttributeGetter=function(c){return k.attributeGetters[c];};e.definePseudo=function(c,n){k["pseudo:"+c]=function(p,o){return n.call(p,o); };return this;};e.lookupPseudo=function(c){var n=k["pseudo:"+c];if(n){return function(o){return n.call(this,o);};}return null;};e.override=function(n,c){k.override(n,c); return this;};e.isXML=k.isXML;e.uidOf=function(c){return k.getUIDHTML(c);};if(!this.Slick){this.Slick=e;}}).apply((typeof exports!="undefined")?exports:this); var Element=this.Element=function(b,g){var h=Element.Constructors[b];if(h){return h(g);}if(typeof b!="string"){return document.id(b).set(g);}if(!g){g={}; }if(!(/^[\w-]+$/).test(b)){var e=Slick.parse(b).expressions[0][0];b=(e.tag=="*")?"div":e.tag;if(e.id&&g.id==null){g.id=e.id;}var d=e.attributes;if(d){for(var a,f=0,c=d.length; f<c;f++){a=d[f];if(g[a.key]!=null){continue;}if(a.value!=null&&a.operator=="="){g[a.key]=a.value;}else{if(!a.value&&!a.operator){g[a.key]=true;}}}}if(e.classList&&g["class"]==null){g["class"]=e.classList.join(" "); }}return document.newElement(b,g);};if(Browser.Element){Element.prototype=Browser.Element.prototype;Element.prototype._fireEvent=(function(a){return function(b,c){return a.call(this,b,c); };})(Element.prototype.fireEvent);}new Type("Element",Element).mirror(function(a){if(Array.prototype[a]){return;}var b={};b[a]=function(){var h=[],e=arguments,j=true; for(var g=0,d=this.length;g<d;g++){var f=this[g],c=h[g]=f[a].apply(f,e);j=(j&&typeOf(c)=="element");}return(j)?new Elements(h):h;};Elements.implement(b); });if(!Browser.Element){Element.parent=Object;Element.Prototype={"$constructor":Element,"$family":Function.from("element").hide()};Element.mirror(function(a,b){Element.Prototype[a]=b; });}Element.Constructors={};Element.Constructors=new Hash;var IFrame=new Type("IFrame",function(){var e=Array.link(arguments,{properties:Type.isObject,iframe:function(f){return(f!=null); }});var c=e.properties||{},b;if(e.iframe){b=document.id(e.iframe);}var d=c.onload||function(){};delete c.onload;c.id=c.name=[c.id,c.name,b?(b.id||b.name):"IFrame_"+String.uniqueID()].pick(); b=new Element(b||"iframe",c);var a=function(){d.call(b.contentWindow);};if(window.frames[c.id]){a();}else{b.addListener("load",a);}return b;});var Elements=this.Elements=function(a){if(a&&a.length){var e={},d; for(var c=0;d=a[c++];){var b=Slick.uidOf(d);if(!e[b]){e[b]=true;this.push(d);}}}};Elements.prototype={length:0};Elements.parent=Array;new Type("Elements",Elements).implement({filter:function(a,b){if(!a){return this; }return new Elements(Array.filter(this,(typeOf(a)=="string")?function(c){return c.match(a);}:a,b));}.protect(),push:function(){var d=this.length;for(var b=0,a=arguments.length; b<a;b++){var c=document.id(arguments[b]);if(c){this[d++]=c;}}return(this.length=d);}.protect(),unshift:function(){var b=[];for(var c=0,a=arguments.length; c<a;c++){var d=document.id(arguments[c]);if(d){b.push(d);}}return Array.prototype.unshift.apply(this,b);}.protect(),concat:function(){var b=new Elements(this); for(var c=0,a=arguments.length;c<a;c++){var d=arguments[c];if(Type.isEnumerable(d)){b.append(d);}else{b.push(d);}}return b;}.protect(),append:function(c){for(var b=0,a=c.length; b<a;b++){this.push(c[b]);}return this;}.protect(),empty:function(){while(this.length){delete this[--this.length];}return this;}.protect()});Elements.alias("extend","append"); (function(){var f=Array.prototype.splice,a={"0":0,"1":1,length:2};f.call(a,1,1);if(a[1]==1){Elements.implement("splice",function(){var g=this.length;var e=f.apply(this,arguments); while(g>=this.length){delete this[g--];}return e;}.protect());}Array.forEachMethod(function(g,e){Elements.implement(e,g);});Array.mirror(Elements);var d; try{d=(document.createElement("<input name=x>").name=="x");}catch(b){}var c=function(e){return(""+e).replace(/&/g,"&amp;").replace(/"/g,"&quot;");};Document.implement({newElement:function(e,g){if(g&&g.checked!=null){g.defaultChecked=g.checked; }if(d&&g){e="<"+e;if(g.name){e+=' name="'+c(g.name)+'"';}if(g.type){e+=' type="'+c(g.type)+'"';}e+=">";delete g.name;delete g.type;}return this.id(this.createElement(e)).set(g); }});})();(function(){Slick.uidOf(window);Slick.uidOf(document);Document.implement({newTextNode:function(e){return this.createTextNode(e);},getDocument:function(){return this; },getWindow:function(){return this.window;},id:(function(){var e={string:function(L,K,l){L=Slick.find(l,"#"+L.replace(/(\W)/g,"\\$1"));return(L)?e.element(L,K):null; },element:function(K,L){Slick.uidOf(K);if(!L&&!K.$family&&!(/^(?:object|embed)$/i).test(K.tagName)){var l=K.fireEvent;K._fireEvent=function(M,N){return l(M,N); };Object.append(K,Element.Prototype);}return K;},object:function(K,L,l){if(K.toElement){return e.element(K.toElement(l),L);}return null;}};e.textnode=e.whitespace=e.window=e.document=function(l){return l; };return function(K,M,L){if(K&&K.$family&&K.uniqueNumber){return K;}var l=typeOf(K);return(e[l])?e[l](K,M,L||document):null;};})()});if(window.$==null){Window.implement("$",function(e,l){return document.id(e,l,this.document); });}Window.implement({getDocument:function(){return this.document;},getWindow:function(){return this;}});[Document,Element].invoke("implement",{getElements:function(e){return Slick.search(this,e,new Elements); },getElement:function(e){return document.id(Slick.find(this,e));}});var p={contains:function(e){return Slick.contains(this,e);}};if(!document.contains){Document.implement(p); }if(!document.createElement("div").contains){Element.implement(p);}Element.implement("hasChild",function(e){return this!==e&&this.contains(e);});(function(l,L,e){this.Selectors={}; var M=this.Selectors.Pseudo=new Hash();var K=function(){for(var N in M){if(M.hasOwnProperty(N)){Slick.definePseudo(N,M[N]);delete M[N];}}};Slick.search=function(O,P,N){K(); return l.call(this,O,P,N);};Slick.find=function(N,O){K();return L.call(this,N,O);};Slick.match=function(O,N){K();return e.call(this,O,N);};})(Slick.search,Slick.find,Slick.match); var v=function(L,K){if(!L){return K;}L=Object.clone(Slick.parse(L));var l=L.expressions;for(var e=l.length;e--;){l[e][0].combinator=K;}return L;};Object.forEach({getNext:"~",getPrevious:"!~",getParent:"!"},function(e,l){Element.implement(l,function(K){return this.getElement(v(K,e)); });});Object.forEach({getAllNext:"~",getAllPrevious:"!~",getSiblings:"~~",getChildren:">",getParents:"!"},function(e,l){Element.implement(l,function(K){return this.getElements(v(K,e)); });});Element.implement({getFirst:function(e){return document.id(Slick.search(this,v(e,">"))[0]);},getLast:function(e){return document.id(Slick.search(this,v(e,">")).getLast()); },getWindow:function(){return this.ownerDocument.window;},getDocument:function(){return this.ownerDocument;},getElementById:function(e){return document.id(Slick.find(this,"#"+(""+e).replace(/(\W)/g,"\\$1"))); },match:function(e){return !e||Slick.match(this,e);}});if(window.$$==null){Window.implement("$$",function(e){var O=new Elements;if(arguments.length==1&&typeof e=="string"){return Slick.search(this.document,e,O); }var L=Array.flatten(arguments);for(var M=0,K=L.length;M<K;M++){var N=L[M];switch(typeOf(N)){case"element":O.push(N);break;case"string":Slick.search(this.document,N,O); }}return O;});}if(window.$$==null){Window.implement("$$",function(e){if(arguments.length==1){if(typeof e=="string"){return Slick.search(this.document,e,new Elements); }else{if(Type.isEnumerable(e)){return new Elements(e);}}}return new Elements(arguments);});}var A={before:function(l,e){var K=e.parentNode;if(K){K.insertBefore(l,e); }},after:function(l,e){var K=e.parentNode;if(K){K.insertBefore(l,e.nextSibling);}},bottom:function(l,e){e.appendChild(l);},top:function(l,e){e.insertBefore(l,e.firstChild); }};A.inside=A.bottom;Object.each(A,function(l,K){K=K.capitalize();var e={};e["inject"+K]=function(L){l(this,document.id(L,true));return this;};e["grab"+K]=function(L){l(document.id(L,true),this); return this;};Element.implement(e);});var n={},d={};var o={};Array.forEach(["type","value","defaultValue","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","rowSpan","tabIndex","useMap"],function(e){o[e.toLowerCase()]=e; });o.html="innerHTML";o.text=(document.createElement("div").textContent==null)?"innerText":"textContent";Object.forEach(o,function(l,e){d[e]=function(K,L){K[l]=L; };n[e]=function(K){return K[l];};});var B=["compact","nowrap","ismap","declare","noshade","checked","disabled","readOnly","multiple","selected","noresize","defer","defaultChecked","autofocus","controls","autoplay","loop"]; var k={};Array.forEach(B,function(e){var l=e.toLowerCase();k[l]=e;d[l]=function(K,L){K[e]=!!L;};n[l]=function(K){return !!K[e];};});Object.append(d,{"class":function(e,l){("className" in e)?e.className=(l||""):e.setAttribute("class",l); },"for":function(e,l){("htmlFor" in e)?e.htmlFor=l:e.setAttribute("for",l);},style:function(e,l){(e.style)?e.style.cssText=l:e.setAttribute("style",l); },value:function(e,l){e.value=(l!=null)?l:"";}});n["class"]=function(e){return("className" in e)?e.className||null:e.getAttribute("class");};var f=document.createElement("button"); try{f.type="button";}catch(E){}if(f.type!="button"){d.type=function(e,l){e.setAttribute("type",l);};}f=null;var s=document.createElement("input");s.value="t"; s.type="submit";if(s.value!="t"){d.type=function(l,e){var K=l.value;l.type=e;l.value=K;};}s=null;var u=(function(e){e.random="attribute";return(e.getAttribute("random")=="attribute"); })(document.createElement("div"));var i=(function(e){e.innerHTML='<object><param name="should_fix" value="the unknown"></object>';return e.cloneNode(true).firstChild.childNodes.length!=1; })(document.createElement("div"));var j=!!document.createElement("div").classList;var F=function(e){var l=(e||"").clean().split(" "),K={};return l.filter(function(L){if(L!==""&&!K[L]){return K[L]=L; }});};var t=function(e){this.classList.add(e);};var g=function(e){this.classList.remove(e);};Element.implement({setProperty:function(l,K){var L=d[l.toLowerCase()]; if(L){L(this,K);}else{var e;if(u){e=this.retrieve("$attributeWhiteList",{});}if(K==null){this.removeAttribute(l);if(u){delete e[l];}}else{this.setAttribute(l,""+K); if(u){e[l]=true;}}}return this;},setProperties:function(e){for(var l in e){this.setProperty(l,e[l]);}return this;},getProperty:function(M){var K=n[M.toLowerCase()]; if(K){return K(this);}if(u){var l=this.getAttributeNode(M),L=this.retrieve("$attributeWhiteList",{});if(!l){return null;}if(l.expando&&!L[M]){var N=this.outerHTML; if(N.substr(0,N.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(M)<0){return null;}L[M]=true;}}var e=Slick.getAttribute(this,M);return(!e&&!Slick.hasAttribute(this,M))?null:e; },getProperties:function(){var e=Array.from(arguments);return e.map(this.getProperty,this).associate(e);},removeProperty:function(e){return this.setProperty(e,null); },removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this;},set:function(K,l){var e=Element.Properties[K];(e&&e.set)?e.set.call(this,l):this.setProperty(K,l); }.overloadSetter(),get:function(l){var e=Element.Properties[l];return(e&&e.get)?e.get.apply(this):this.getProperty(l);}.overloadGetter(),erase:function(l){var e=Element.Properties[l]; (e&&e.erase)?e.erase.apply(this):this.removeProperty(l);return this;},hasClass:j?function(e){return this.classList.contains(e);}:function(e){return this.className.clean().contains(e," "); },addClass:j?function(e){F(e).forEach(t,this);return this;}:function(e){this.className=F(e+" "+this.className).join(" ");return this;},removeClass:j?function(e){F(e).forEach(g,this); return this;}:function(e){var l=F(this.className);F(e).forEach(l.erase,l);this.className=l.join(" ");return this;},toggleClass:function(e,l){if(l==null){l=!this.hasClass(e); }return(l)?this.addClass(e):this.removeClass(e);},adopt:function(){var L=this,e,N=Array.flatten(arguments),M=N.length;if(M>1){L=e=document.createDocumentFragment(); }for(var K=0;K<M;K++){var l=document.id(N[K],true);if(l){L.appendChild(l);}}if(e){this.appendChild(e);}return this;},appendText:function(l,e){return this.grab(this.getDocument().newTextNode(l),e); },grab:function(l,e){A[e||"bottom"](document.id(l,true),this);return this;},inject:function(l,e){A[e||"bottom"](this,document.id(l,true));return this;},replaces:function(e){e=document.id(e,true); e.parentNode.replaceChild(this,e);return this;},wraps:function(l,e){l=document.id(l,true);return this.replaces(l).grab(l,e);},getSelected:function(){this.selectedIndex; return new Elements(Array.from(this.options).filter(function(e){return e.selected;}));},toQueryString:function(){var e=[];this.getElements("input, select, textarea").each(function(K){var l=K.type; if(!K.name||K.disabled||l=="submit"||l=="reset"||l=="file"||l=="image"){return;}var L=(K.get("tag")=="select")?K.getSelected().map(function(M){return document.id(M).get("value"); }):((l=="radio"||l=="checkbox")&&!K.checked)?null:K.get("value");Array.from(L).each(function(M){if(typeof M!="undefined"){e.push(encodeURIComponent(K.name)+"="+encodeURIComponent(M)); }});});return e.join("&");}});var I={before:"beforeBegin",after:"afterEnd",bottom:"beforeEnd",top:"afterBegin",inside:"beforeEnd"};Element.implement("appendHTML",("insertAdjacentHTML" in document.createElement("div"))?function(l,e){this.insertAdjacentHTML(I[e||"bottom"],l); return this;}:function(P,M){var K=new Element("div",{html:P}),O=K.childNodes,L=K.firstChild;if(!L){return this;}if(O.length>1){L=document.createDocumentFragment(); for(var N=0,e=O.length;N<e;N++){L.appendChild(O[N]);}}A[M||"bottom"](L,this);return this;});var m={},D={};var G=function(e){return(D[e]||(D[e]={}));};var z=function(l){var e=l.uniqueNumber; if(l.removeEvents){l.removeEvents();}if(l.clearAttributes){l.clearAttributes();}if(e!=null){delete m[e];delete D[e];}return l;};var H={input:"checked",option:"selected",textarea:"value"}; Element.implement({destroy:function(){var e=z(this).getElementsByTagName("*");Array.each(e,z);Element.dispose(this);return null;},empty:function(){Array.from(this.childNodes).each(Element.dispose); return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this;},clone:function(N,L){N=N!==false;var S=this.cloneNode(N),K=[S],M=[this],Q; if(N){K.append(Array.from(S.getElementsByTagName("*")));M.append(Array.from(this.getElementsByTagName("*")));}for(Q=K.length;Q--;){var O=K[Q],R=M[Q];if(!L){O.removeAttribute("id"); }if(O.clearAttributes){O.clearAttributes();O.mergeAttributes(R);O.removeAttribute("uniqueNumber");if(O.options){var V=O.options,e=R.options;for(var P=V.length; P--;){V[P].selected=e[P].selected;}}}var l=H[R.tagName.toLowerCase()];if(l&&R[l]){O[l]=R[l];}}if(i){var T=S.getElementsByTagName("object"),U=this.getElementsByTagName("object"); for(Q=T.length;Q--;){T[Q].outerHTML=U[Q].outerHTML;}}return document.id(S);}});[Element,Window,Document].invoke("implement",{addListener:function(l,e){if(window.attachEvent&&!window.addEventListener){m[Slick.uidOf(this)]=this; }if(this.addEventListener){this.addEventListener(l,e,!!arguments[2]);}else{this.attachEvent("on"+l,e);}return this;},removeListener:function(l,e){if(this.removeEventListener){this.removeEventListener(l,e,!!arguments[2]); }else{this.detachEvent("on"+l,e);}return this;},retrieve:function(l,e){var L=G(Slick.uidOf(this)),K=L[l];if(e!=null&&K==null){K=L[l]=e;}return K!=null?K:null; },store:function(l,e){var K=G(Slick.uidOf(this));K[l]=e;return this;},eliminate:function(e){var l=G(Slick.uidOf(this));delete l[e];return this;}});if(window.attachEvent&&!window.addEventListener){var J=function(){Object.each(m,z); if(window.CollectGarbage){CollectGarbage();}window.removeListener("unload",J);};window.addListener("unload",J);}Element.Properties={};Element.Properties=new Hash; Element.Properties.style={set:function(e){this.style.cssText=e;},get:function(){return this.style.cssText;},erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase(); }};Element.Properties.html={set:function(e){if(e==null){e="";}else{if(typeOf(e)=="array"){e=e.join("");}}this.innerHTML=e;},erase:function(){this.innerHTML=""; }};var a=true,h=true,C=true;var x=document.createElement("div");x.innerHTML="<nav></nav>";a=(x.childNodes.length==1);if(!a){var w="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video".split(" "),b=document.createDocumentFragment(),y=w.length; while(y--){b.createElement(w[y]);}}x=null;h=Function.attempt(function(){var e=document.createElement("table");e.innerHTML="<tr><td></td></tr>";return true; });var c=document.createElement("tr"),r="<td></td>";c.innerHTML=r;C=(c.innerHTML==r);c=null;if(!h||!C||!a){Element.Properties.html.set=(function(l){var e={table:[1,"<table>","</table>"],select:[1,"<select>","</select>"],tbody:[2,"<table><tbody>","</tbody></table>"],tr:[3,"<table><tbody><tr>","</tr></tbody></table>"]}; e.thead=e.tfoot=e.tbody;return function(K){var L=e[this.get("tag")];if(!L&&!a){L=[0,"",""];}if(!L){return l.call(this,K);}var O=L[0],N=document.createElement("div"),M=N; if(!a){b.appendChild(N);}N.innerHTML=[L[1],K,L[2]].flatten().join("");while(O--){M=M.firstChild;}this.empty().adopt(M.childNodes);if(!a){b.removeChild(N); }N=null;};})(Element.Properties.html.set);}var q=document.createElement("form");q.innerHTML="<select><option>s</option></select>";if(q.firstChild.value!="s"){Element.Properties.value={set:function(N){var l=this.get("tag"); if(l!="select"){return this.setProperty("value",N);}var K=this.getElements("option");N=String(N);for(var L=0;L<K.length;L++){var M=K[L],e=M.getAttributeNode("value"),O=(e&&e.specified)?M.value:M.get("text"); if(O===N){return M.selected=true;}}},get:function(){var K=this,l=K.get("tag");if(l!="select"&&l!="option"){return this.getProperty("value");}if(l=="select"&&!(K=K.getSelected()[0])){return""; }var e=K.getAttributeNode("value");return(e&&e.specified)?K.value:K.get("text");}};}q=null;if(document.createElement("div").getAttributeNode("id")){Element.Properties.id={set:function(e){this.id=this.getAttributeNode("id").value=e; },get:function(){return this.id||null;},erase:function(){this.id=this.getAttributeNode("id").value="";}};}})();(function(){var l=document.html,f;f=document.createElement("div"); f.style.color="red";f.style.color=null;var e=f.style.color=="red";var k="1px solid #123abc";f.style.border=k;var o=f.style.border!=k;f=null;var n=!!window.getComputedStyle; Element.Properties.styles={set:function(r){this.setStyles(r);}};var j=(l.style.opacity!=null),g=(l.style.filter!=null),q=/alpha\(opacity=([\d.]+)\)/i;var b=function(s,r){s.store("$opacity",r); s.style.visibility=r>0||r==null?"visible":"hidden";};var p=function(r,v,u){var t=r.style,s=t.filter||r.getComputedStyle("filter")||"";t.filter=(v.test(s)?s.replace(v,u):s+" "+u).trim(); if(!t.filter){t.removeAttribute("filter");}};var h=(j?function(s,r){s.style.opacity=r;}:(g?function(s,r){if(!s.currentStyle||!s.currentStyle.hasLayout){s.style.zoom=1; }if(r==null||r==1){p(s,q,"");if(r==1&&i(s)!=1){p(s,q,"alpha(opacity=100)");}}else{p(s,q,"alpha(opacity="+(r*100).limit(0,100).round()+")");}}:b));var i=(j?function(s){var r=s.style.opacity||s.getComputedStyle("opacity"); return(r=="")?1:r.toFloat();}:(g?function(s){var t=(s.style.filter||s.getComputedStyle("filter")),r;if(t){r=t.match(q);}return(r==null||t==null)?1:(r[1]/100); }:function(s){var r=s.retrieve("$opacity");if(r==null){r=(s.style.visibility=="hidden"?0:1);}return r;}));var d=(l.style.cssFloat==null)?"styleFloat":"cssFloat",a={left:"0%",top:"0%",center:"50%",right:"100%",bottom:"100%"},c=(l.style.backgroundPositionX!=null); var m=function(r,s){if(s=="backgroundPosition"){r.removeAttribute(s+"X");s+="Y";}r.removeAttribute(s);};Element.implement({getComputedStyle:function(t){if(!n&&this.currentStyle){return this.currentStyle[t.camelCase()]; }var s=Element.getDocument(this).defaultView,r=s?s.getComputedStyle(this,null):null;return(r)?r.getPropertyValue((t==d)?"float":t.hyphenate()):"";},setStyle:function(s,r){if(s=="opacity"){if(r!=null){r=parseFloat(r); }h(this,r);return this;}s=(s=="float"?d:s).camelCase();if(typeOf(r)!="string"){var t=(Element.Styles[s]||"@").split(" ");r=Array.from(r).map(function(v,u){if(!t[u]){return""; }return(typeOf(v)=="number")?t[u].replace("@",Math.round(v)):v;}).join(" ");}else{if(r==String(Number(r))){r=Math.round(r);}}this.style[s]=r;if((r==""||r==null)&&e&&this.style.removeAttribute){m(this.style,s); }return this;},getStyle:function(x){if(x=="opacity"){return i(this);}x=(x=="float"?d:x).camelCase();var r=this.style[x];if(!r||x=="zIndex"){if(Element.ShortStyles.hasOwnProperty(x)){r=[]; for(var w in Element.ShortStyles[x]){r.push(this.getStyle(w));}return r.join(" ");}r=this.getComputedStyle(x);}if(c&&/^backgroundPosition[XY]?$/.test(x)){return r.replace(/(top|right|bottom|left)/g,function(s){return a[s]; })||"0px";}if(!r&&x=="backgroundPosition"){return"0px 0px";}if(r){r=String(r);var u=r.match(/rgba?\([\d\s,]+\)/);if(u){r=r.replace(u[0],u[0].rgbToHex()); }}if(!n&&!this.style[x]){if((/^(height|width)$/).test(x)&&!(/px$/.test(r))){var t=(x=="width")?["left","right"]:["top","bottom"],v=0;t.each(function(s){v+=this.getStyle("border-"+s+"-width").toInt()+this.getStyle("padding-"+s).toInt(); },this);return this["offset"+x.capitalize()]-v+"px";}if((/^border(.+)Width|margin|padding/).test(x)&&isNaN(parseFloat(r))){return"0px";}}if(o&&/^border(Top|Right|Bottom|Left)?$/.test(x)&&/^#/.test(r)){return r.replace(/^(.+)\s(.+)\s(.+)$/,"$2 $3 $1"); }return r;},setStyles:function(s){for(var r in s){this.setStyle(r,s[r]);}return this;},getStyles:function(){var r={};Array.flatten(arguments).each(function(s){r[s]=this.getStyle(s); },this);return r;}});Element.Styles={left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundSize:"@px",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"}; Element.implement({setOpacity:function(r){h(this,r);return this;},getOpacity:function(){return i(this);}});Element.Properties.opacity={set:function(r){h(this,r); b(this,r);},get:function(){return i(this);}};Element.Styles=new Hash(Element.Styles);Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}}; ["Top","Right","Bottom","Left"].each(function(x){var w=Element.ShortStyles;var s=Element.Styles;["margin","padding"].each(function(y){var z=y+x;w[y][z]=s[z]="@px"; });var v="border"+x;w.border[v]=s[v]="@px @ rgb(@, @, @)";var u=v+"Width",r=v+"Style",t=v+"Color";w[v]={};w.borderWidth[u]=w[v][u]=s[u]="@px";w.borderStyle[r]=w[v][r]=s[r]="@"; w.borderColor[t]=w[v][t]=s[t]="rgb(@, @, @)";});if(c){Element.ShortStyles.backgroundPosition={backgroundPositionX:"@",backgroundPositionY:"@"};}})();(function(){Element.Properties.events={set:function(b){this.addEvents(b); }};[Element,Window,Document].invoke("implement",{addEvent:function(f,h){var i=this.retrieve("events",{});if(!i[f]){i[f]={keys:[],values:[]};}if(i[f].keys.contains(h)){return this; }i[f].keys.push(h);var g=f,b=Element.Events[f],d=h,j=this;if(b){if(b.onAdd){b.onAdd.call(this,h,f);}if(b.condition){d=function(k){if(b.condition.call(this,k,f)){return h.call(this,k); }return true;};}if(b.base){g=Function.from(b.base).call(this,f);}}var e=function(){return h.call(j);};var c=Element.NativeEvents[g];if(c){if(c==2){e=function(k){k=new DOMEvent(k,j.getWindow()); if(d.call(j,k)===false){k.stop();}};}this.addListener(g,e,arguments[2]);}i[f].values.push(e);return this;},removeEvent:function(e,d){var c=this.retrieve("events"); if(!c||!c[e]){return this;}var h=c[e];var b=h.keys.indexOf(d);if(b==-1){return this;}var g=h.values[b];delete h.keys[b];delete h.values[b];var f=Element.Events[e]; if(f){if(f.onRemove){f.onRemove.call(this,d,e);}if(f.base){e=Function.from(f.base).call(this,e);}}return(Element.NativeEvents[e])?this.removeListener(e,g,arguments[2]):this; },addEvents:function(b){for(var c in b){this.addEvent(c,b[c]);}return this;},removeEvents:function(b){var d;if(typeOf(b)=="object"){for(d in b){this.removeEvent(d,b[d]); }return this;}var c=this.retrieve("events");if(!c){return this;}if(!b){for(d in c){this.removeEvents(d);}this.eliminate("events");}else{if(c[b]){c[b].keys.each(function(e){this.removeEvent(b,e); },this);delete c[b];}}return this;},fireEvent:function(e,c,b){var d=this.retrieve("events");if(!d||!d[e]){return this;}c=Array.from(c);d[e].keys.each(function(f){if(b){f.delay(b,this,c); }else{f.apply(this,c);}},this);return this;},cloneEvents:function(e,d){e=document.id(e);var c=e.retrieve("events");if(!c){return this;}if(!d){for(var b in c){this.cloneEvents(e,b); }}else{if(c[d]){c[d].keys.each(function(f){this.addEvent(d,f);},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,orientationchange:2,touchstart:2,touchmove:2,touchend:2,touchcancel:2,gesturestart:2,gesturechange:2,gestureend:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,paste:2,input:2,load:2,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,hashchange:1,popstate:2,error:1,abort:1,scroll:1}; Element.Events={mousewheel:{base:"onwheel" in document?"wheel":"onmousewheel" in document?"mousewheel":"DOMMouseScroll"}};var a=function(b){var c=b.relatedTarget; if(c==null){return true;}if(!c){return false;}return(c!=this&&c.prefix!="xul"&&typeOf(this)!="document"&&!this.contains(c));};if("onmouseenter" in document.documentElement){Element.NativeEvents.mouseenter=Element.NativeEvents.mouseleave=2; Element.MouseenterCheck=a;}else{Element.Events.mouseenter={base:"mouseover",condition:a};Element.Events.mouseleave={base:"mouseout",condition:a};}if(!window.addEventListener){Element.NativeEvents.propertychange=2; Element.Events.change={base:function(){var b=this.type;return(this.get("tag")=="input"&&(b=="radio"||b=="checkbox"))?"propertychange":"change";},condition:function(b){return b.type!="propertychange"||b.event.propertyName=="checked"; }};}Element.Events=new Hash(Element.Events);})();(function(){var c=!!window.addEventListener;Element.NativeEvents.focusin=Element.NativeEvents.focusout=2; var k=function(l,m,n,o,p){while(p&&p!=l){if(m(p,o)){return n.call(p,o,p);}p=document.id(p.parentNode);}};var a={mouseenter:{base:"mouseover",condition:Element.MouseenterCheck},mouseleave:{base:"mouseout",condition:Element.MouseenterCheck},focus:{base:"focus"+(c?"":"in"),capture:true},blur:{base:c?"blur":"focusout",capture:true}}; var b="$delegation:";var i=function(l){return{base:"focusin",remove:function(m,o){var p=m.retrieve(b+l+"listeners",{})[o];if(p&&p.forms){for(var n=p.forms.length; n--;){p.forms[n].removeEvent(l,p.fns[n]);}}},listen:function(x,r,v,n,t,s){var o=(t.get("tag")=="form")?t:n.target.getParent("form");if(!o){return;}var u=x.retrieve(b+l+"listeners",{}),p=u[s]||{forms:[],fns:[]},m=p.forms,w=p.fns; if(m.indexOf(o)!=-1){return;}m.push(o);var q=function(y){k(x,r,v,y,t);};o.addEvent(l,q);w.push(q);u[s]=p;x.store(b+l+"listeners",u);}};};var d=function(l){return{base:"focusin",listen:function(m,n,p,q,r){var o={blur:function(){this.removeEvents(o); }};o[l]=function(s){k(m,n,p,s,r);};q.target.addEvents(o);}};};if(!c){Object.append(a,{submit:i("submit"),reset:i("reset"),change:d("change"),select:d("select")}); }var h=Element.prototype,f=h.addEvent,j=h.removeEvent;var e=function(l,m){return function(r,q,n){if(r.indexOf(":relay")==-1){return l.call(this,r,q,n); }var o=Slick.parse(r).expressions[0][0];if(o.pseudos[0].key!="relay"){return l.call(this,r,q,n);}var p=o.tag;o.pseudos.slice(1).each(function(s){p+=":"+s.key+(s.value?"("+s.value+")":""); });l.call(this,r,q);return m.call(this,p,o.pseudos[0].value,q);};};var g={addEvent:function(v,q,x){var t=this.retrieve("$delegates",{}),r=t[v];if(r){for(var y in r){if(r[y].fn==x&&r[y].match==q){return this; }}}var p=v,u=q,o=x,n=a[v]||{};v=n.base||p;q=function(B){return Slick.match(B,u);};var w=Element.Events[p];if(n.condition||w&&w.condition){var l=q,m=n.condition||w.condition; q=function(C,B){return l(C,B)&&m.call(C,B,v);};}var z=this,s=String.uniqueID();var A=n.listen?function(B,C){if(!C&&B&&B.target){C=B.target;}if(C){n.listen(z,q,x,B,C,s); }}:function(B,C){if(!C&&B&&B.target){C=B.target;}if(C){k(z,q,x,B,C);}};if(!r){r={};}r[s]={match:u,fn:o,delegator:A};t[p]=r;return f.call(this,v,A,n.capture); },removeEvent:function(r,n,t,u){var q=this.retrieve("$delegates",{}),p=q[r];if(!p){return this;}if(u){var m=r,w=p[u].delegator,l=a[r]||{};r=l.base||m;if(l.remove){l.remove(this,u); }delete p[u];q[m]=p;return j.call(this,r,w,l.capture);}var o,v;if(t){for(o in p){v=p[o];if(v.match==n&&v.fn==t){return g.removeEvent.call(this,r,n,t,o); }}}else{for(o in p){v=p[o];if(v.match==n){g.removeEvent.call(this,r,n,v.fn,o);}}}return this;}};[Element,Window,Document].invoke("implement",{addEvent:e(f,g.addEvent),removeEvent:e(j,g.removeEvent)}); })();(function(){var h=document.createElement("div"),e=document.createElement("div");h.style.height="0";h.appendChild(e);var d=(e.offsetParent===h);h=e=null; var l=function(m){return k(m,"position")!="static"||a(m);};var i=function(m){return l(m)||(/^(?:table|td|th)$/i).test(m.tagName);};Element.implement({scrollTo:function(m,n){if(a(this)){this.getWindow().scrollTo(m,n); }else{this.scrollLeft=m;this.scrollTop=n;}return this;},getSize:function(){if(a(this)){return this.getWindow().getSize();}return{x:this.offsetWidth,y:this.offsetHeight}; },getScrollSize:function(){if(a(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight};},getScroll:function(){if(a(this)){return this.getWindow().getScroll(); }return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var n=this.parentNode,m={x:0,y:0};while(n&&!a(n)){m.x+=n.scrollLeft;m.y+=n.scrollTop; n=n.parentNode;}return m;},getOffsetParent:d?function(){var m=this;if(a(m)||k(m,"position")=="fixed"){return null;}var n=(k(m,"position")=="static")?i:l; while((m=m.parentNode)){if(n(m)){return m;}}return null;}:function(){var m=this;if(a(m)||k(m,"position")=="fixed"){return null;}try{return m.offsetParent; }catch(n){}return null;},getOffsets:function(){var t=this.getBoundingClientRect;t=t&&!Browser.Platform.ios;if(t){var n=this.getBoundingClientRect(),q=document.id(this.getDocument().documentElement),u=q.getScroll(),o=this.getScrolls(),m=(k(this,"position")=="fixed"); return{x:n.left.toInt()+o.x+((m)?0:u.x)-q.clientLeft,y:n.top.toInt()+o.y+((m)?0:u.y)-q.clientTop};}var p=this,r={x:0,y:0};if(a(this)){return r;}while(p&&!a(p)){r.x+=p.offsetLeft; r.y+=p.offsetTop;if(Browser.firefox){if(!c(p)){r.x+=b(p);r.y+=g(p);}var s=p.parentNode;if(s&&k(s,"overflow")!="visible"){r.x+=b(s);r.y+=g(s);}}else{if(p!=this&&Browser.safari){r.x+=b(p); r.y+=g(p);}}p=p.offsetParent;}if(Browser.firefox&&!c(this)){r.x-=b(this);r.y-=g(this);}return r;},getPosition:function(p){var q=this.getOffsets(),n=this.getScrolls(); var m={x:q.x-n.x,y:q.y-n.y};if(p&&(p=document.id(p))){var o=p.getPosition();return{x:m.x-o.x-b(p),y:m.y-o.y-g(p)};}return m;},getCoordinates:function(o){if(a(this)){return this.getWindow().getCoordinates(); }var m=this.getPosition(o),n=this.getSize();var p={left:m.x,top:m.y,width:n.x,height:n.y};p.right=p.left+p.width;p.bottom=p.top+p.height;return p;},computePosition:function(m){return{left:m.x-j(this,"margin-left"),top:m.y-j(this,"margin-top")}; },setPosition:function(m){return this.setStyles(this.computePosition(m));}});[Document,Window].invoke("implement",{getSize:function(){var m=f(this);return{x:m.clientWidth,y:m.clientHeight}; },getScroll:function(){var n=this.getWindow(),m=f(this);return{x:n.pageXOffset||m.scrollLeft,y:n.pageYOffset||m.scrollTop};},getScrollSize:function(){var o=f(this),n=this.getSize(),m=this.getDocument().body; return{x:Math.max(o.scrollWidth,m.scrollWidth,n.x),y:Math.max(o.scrollHeight,m.scrollHeight,n.y)};},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var m=this.getSize(); return{top:0,left:0,bottom:m.y,right:m.x,height:m.y,width:m.x};}});var k=Element.getComputedStyle;function j(m,n){return k(m,n).toInt()||0;}function c(m){return k(m,"-moz-box-sizing")=="border-box"; }function g(m){return j(m,"border-top-width");}function b(m){return j(m,"border-left-width");}function a(m){return(/^(?:body|html)$/i).test(m.tagName); }function f(m){var n=m.getDocument();return(!n.compatMode||n.compatMode=="CSS1Compat")?n.html:n.body;}})();Element.alias({position:"setPosition"});[Window,Document,Element].invoke("implement",{getHeight:function(){return this.getSize().y; },getWidth:function(){return this.getSize().x;},getScrollTop:function(){return this.getScroll().y;},getScrollLeft:function(){return this.getScroll().x; },getScrollHeight:function(){return this.getScrollSize().y;},getScrollWidth:function(){return this.getScrollSize().x;},getTop:function(){return this.getPosition().y; },getLeft:function(){return this.getPosition().x;}});(function(){var f=this.Fx=new Class({Implements:[Chain,Events,Options],options:{fps:60,unit:false,duration:500,frames:null,frameSkip:true,link:"ignore"},initialize:function(g){this.subject=this.subject||this; this.setOptions(g);},getTransition:function(){return function(g){return -(Math.cos(Math.PI*g)-1)/2;};},step:function(g){if(this.options.frameSkip){var h=(this.time!=null)?(g-this.time):0,i=h/this.frameInterval; this.time=g;this.frame+=i;}else{this.frame++;}if(this.frame<this.frames){var j=this.transition(this.frame/this.frames);this.set(this.compute(this.from,this.to,j)); }else{this.frame=this.frames;this.set(this.compute(this.from,this.to,1));this.stop();}},set:function(g){return g;},compute:function(i,h,g){return f.compute(i,h,g); },check:function(){if(!this.isRunning()){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.pass(arguments,this)); return false;}return false;},start:function(k,j){if(!this.check(k,j)){return this;}this.from=k;this.to=j;this.frame=(this.options.frameSkip)?0:-1;this.time=null; this.transition=this.getTransition();var i=this.options.frames,h=this.options.fps,g=this.options.duration;this.duration=f.Durations[g]||g.toInt();this.frameInterval=1000/h; this.frames=i||Math.round(this.duration/this.frameInterval);this.fireEvent("start",this.subject);b.call(this,h);return this;},stop:function(){if(this.isRunning()){this.time=null; d.call(this,this.options.fps);if(this.frames==this.frame){this.fireEvent("complete",this.subject);if(!this.callChain()){this.fireEvent("chainComplete",this.subject); }}else{this.fireEvent("stop",this.subject);}}return this;},cancel:function(){if(this.isRunning()){this.time=null;d.call(this,this.options.fps);this.frame=this.frames; this.fireEvent("cancel",this.subject).clearChain();}return this;},pause:function(){if(this.isRunning()){this.time=null;d.call(this,this.options.fps);}return this; },resume:function(){if(this.isPaused()){b.call(this,this.options.fps);}return this;},isRunning:function(){var g=e[this.options.fps];return g&&g.contains(this); },isPaused:function(){return(this.frame<this.frames)&&!this.isRunning();}});f.compute=function(i,h,g){return(h-i)*g+i;};f.Durations={"short":250,normal:500,"long":1000}; var e={},c={};var a=function(){var h=Date.now();for(var j=this.length;j--;){var g=this[j];if(g){g.step(h);}}};var b=function(h){var g=e[h]||(e[h]=[]);g.push(this); if(!c[h]){c[h]=a.periodical(Math.round(1000/h),g);}};var d=function(h){var g=e[h];if(g){g.erase(this);if(!g.length&&c[h]){delete e[h];c[h]=clearInterval(c[h]); }}};})();Fx.CSS=new Class({Extends:Fx,prepare:function(b,e,a){a=Array.from(a);var h=a[0],g=a[1];if(g==null){g=h;h=b.getStyle(e);var c=this.options.unit; if(c&&h&&typeof h=="string"&&h.slice(-c.length)!=c&&parseFloat(h)!=0){b.setStyle(e,g+c);var d=b.getComputedStyle(e);if(!(/px$/.test(d))){d=b.style[("pixel-"+e).camelCase()]; if(d==null){var f=b.style.left;b.style.left=g+c;d=b.style.pixelLeft;b.style.left=f;}}h=(g||1)/(parseFloat(d)||1)*(parseFloat(h)||0);b.setStyle(e,h+c);}}return{from:this.parse(h),to:this.parse(g)}; },parse:function(a){a=Function.from(a)();a=(typeof a=="string")?a.split(" "):Array.from(a);return a.map(function(c){c=String(c);var b=false;Object.each(Fx.CSS.Parsers,function(f,e){if(b){return; }var d=f.parse(c);if(d||d===0){b={value:d,parser:f};}});b=b||{value:c,parser:Fx.CSS.Parsers.String};return b;});},compute:function(d,c,b){var a=[];(Math.min(d.length,c.length)).times(function(e){a.push({value:d[e].parser.compute(d[e].value,c[e].value,b),parser:d[e].parser}); });a.$family=Function.from("fx:css:value");return a;},serve:function(c,b){if(typeOf(c)!="fx:css:value"){c=this.parse(c);}var a=[];c.each(function(d){a=a.concat(d.parser.serve(d.value,b)); });return a;},render:function(a,d,c,b){a.setStyle(d,this.serve(c,b));},search:function(a){if(Fx.CSS.Cache[a]){return Fx.CSS.Cache[a];}var d={},c=new RegExp("^"+a.escapeRegExp()+"$"); var b=function(e){Array.each(e,function(h,f){if(h.media){b(h.rules||h.cssRules);return;}if(!h.style){return;}var g=(h.selectorText)?h.selectorText.replace(/^\w+/,function(i){return i.toLowerCase(); }):null;if(!g||!c.test(g)){return;}Object.each(Element.Styles,function(j,i){if(!h.style[i]||Element.ShortStyles[i]){return;}j=String(h.style[i]);d[i]=((/^rgb/).test(j))?j.rgbToHex():j; });});};Array.each(document.styleSheets,function(g,f){var e=g.href;if(e&&e.indexOf("://")>-1&&e.indexOf(document.domain)==-1){return;}var h=g.rules||g.cssRules; b(h);});return Fx.CSS.Cache[a]=d;}});Fx.CSS.Cache={};Fx.CSS.Parsers={Color:{parse:function(a){if(a.match(/^#[0-9a-f]{3,6}$/i)){return a.hexToRgb(true); }return((a=a.match(/(\d+),\s*(\d+),\s*(\d+)/)))?[a[1],a[2],a[3]]:false;},compute:function(c,b,a){return c.map(function(e,d){return Math.round(Fx.compute(c[d],b[d],a)); });},serve:function(a){return a.map(Number);}},Number:{parse:parseFloat,compute:Fx.compute,serve:function(b,a){return(a)?b+a:b;}},String:{parse:Function.from(false),compute:function(b,a){return a; },serve:function(a){return a;}}};Fx.CSS.Parsers=new Hash(Fx.CSS.Parsers);Fx.Tween=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b); this.parent(a);},set:function(b,a){if(arguments.length==1){a=b;b=this.property||this.options.property;}this.render(this.element,b,a,this.options.unit); return this;},start:function(c,e,d){if(!this.check(c,e,d)){return this;}var b=Array.flatten(arguments);this.property=this.options.property||b.shift();var a=this.prepare(this.element,this.property,b); return this.parent(a.from,a.to);}});Element.Properties.tween={set:function(a){this.get("tween").cancel().setOptions(a);return this;},get:function(){var a=this.retrieve("tween"); if(!a){a=new Fx.Tween(this,{link:"cancel"});this.store("tween",a);}return a;}};Element.implement({tween:function(a,c,b){this.get("tween").start(a,c,b); return this;},fade:function(d){var e=this.get("tween"),g,c=["opacity"].append(arguments),a;if(c[1]==null){c[1]="toggle";}switch(c[1]){case"in":g="start"; c[1]=1;break;case"out":g="start";c[1]=0;break;case"show":g="set";c[1]=1;break;case"hide":g="set";c[1]=0;break;case"toggle":var b=this.retrieve("fade:flag",this.getStyle("opacity")==1); g="start";c[1]=b?0:1;this.store("fade:flag",!b);a=true;break;default:g="start";}if(!a){this.eliminate("fade:flag");}e[g].apply(e,c);var f=c[c.length-1]; if(g=="set"||f!=0){this.setStyle("visibility",f==0?"hidden":"visible");}else{e.chain(function(){this.element.setStyle("visibility","hidden");this.callChain(); });}return this;},highlight:function(c,a){if(!a){a=this.retrieve("highlight:original",this.getStyle("background-color"));a=(a=="transparent")?"#fff":a; }var b=this.get("tween");b.start("background-color",c||"#ffff88",a).chain(function(){this.setStyle("background-color",this.retrieve("highlight:original")); b.callChain();}.bind(this));return this;}});Fx.Morph=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);this.parent(a); },set:function(a){if(typeof a=="string"){a=this.search(a);}for(var b in a){this.render(this.element,b,a[b],this.options.unit);}return this;},compute:function(e,d,c){var a={}; for(var b in e){a[b]=this.parent(e[b],d[b],c);}return a;},start:function(b){if(!this.check(b)){return this;}if(typeof b=="string"){b=this.search(b);}var e={},d={}; for(var c in b){var a=this.prepare(this.element,c,b[c]);e[c]=a.from;d[c]=a.to;}return this.parent(e,d);}});Element.Properties.morph={set:function(a){this.get("morph").cancel().setOptions(a); return this;},get:function(){var a=this.retrieve("morph");if(!a){a=new Fx.Morph(this,{link:"cancel"});this.store("morph",a);}return a;}};Element.implement({morph:function(a){this.get("morph").start(a); return this;}});Fx.implement({getTransition:function(){var a=this.options.transition||Fx.Transitions.Sine.easeInOut;if(typeof a=="string"){var b=a.split(":"); a=Fx.Transitions;a=a[b[0]]||a[b[0].capitalize()];if(b[1]){a=a["ease"+b[1].capitalize()+(b[2]?b[2].capitalize():"")];}}return a;}});Fx.Transition=function(c,b){b=Array.from(b); var a=function(d){return c(d,b);};return Object.append(a,{easeIn:a,easeOut:function(d){return 1-c(1-d,b);},easeInOut:function(d){return(d<=0.5?c(2*d,b):(2-c(2*(1-d),b)))/2; }});};Fx.Transitions={linear:function(a){return a;}};Fx.Transitions=new Hash(Fx.Transitions);Fx.Transitions.extend=function(a){for(var b in a){Fx.Transitions[b]=new Fx.Transition(a[b]); }};Fx.Transitions.extend({Pow:function(b,a){return Math.pow(b,a&&a[0]||6);},Expo:function(a){return Math.pow(2,8*(a-1));},Circ:function(a){return 1-Math.sin(Math.acos(a)); },Sine:function(a){return 1-Math.cos(a*Math.PI/2);},Back:function(b,a){a=a&&a[0]||1.618;return Math.pow(b,2)*((a+1)*b-a);},Bounce:function(f){var e;for(var d=0,c=1; 1;d+=c,c/=2){if(f>=(7-4*d)/11){e=c*c-Math.pow((11-6*d-11*f)/4,2);break;}}return e;},Elastic:function(b,a){return Math.pow(2,10*--b)*Math.cos(20*b*Math.PI*(a&&a[0]||1)/3); }});["Quad","Cubic","Quart","Quint"].each(function(b,a){Fx.Transitions[b]=new Fx.Transition(function(c){return Math.pow(c,a+2);});});(function(){var d=function(){},a=("onprogress" in new Browser.Request); var c=this.Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false,timeout:0,noCache:false},initialize:function(e){this.xhr=new Browser.Request(); this.setOptions(e);this.headers=this.options.headers;},onStateChange:function(){var e=this.xhr;if(e.readyState!=4||!this.running){return;}this.running=false; this.status=0;Function.attempt(function(){var f=e.status;this.status=(f==1223)?204:f;}.bind(this));e.onreadystatechange=d;if(a){e.onprogress=e.onloadstart=d; }clearTimeout(this.timer);this.response={text:this.xhr.responseText||"",xml:this.xhr.responseXML};if(this.options.isSuccess.call(this,this.status)){this.success(this.response.text,this.response.xml); }else{this.failure();}},isSuccess:function(){var e=this.status;return(e>=200&&e<300);},isRunning:function(){return !!this.running;},processScripts:function(e){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return Browser.exec(e); }return e.stripScripts(this.options.evalScripts);},success:function(f,e){this.onSuccess(this.processScripts(f),e);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain(); },failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},loadstart:function(e){this.fireEvent("loadstart",[e,this.xhr]); },progress:function(e){this.fireEvent("progress",[e,this.xhr]);},timeout:function(){this.fireEvent("timeout",this.xhr);},setHeader:function(e,f){this.headers[e]=f; return this;},getHeader:function(e){return Function.attempt(function(){return this.xhr.getResponseHeader(e);}.bind(this));},check:function(){if(!this.running){return true; }switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.pass(arguments,this));return false;}return false;},send:function(o){if(!this.check(o)){return this; }this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.running=true;var l=typeOf(o);if(l=="string"||l=="element"){o={data:o};}var h=this.options; o=Object.append({data:h.data,url:h.url,method:h.method},o);var j=o.data,f=String(o.url),e=o.method.toLowerCase();switch(typeOf(j)){case"element":j=document.id(j).toQueryString(); break;case"object":case"hash":j=Object.toQueryString(j);}if(this.options.format){var m="format="+this.options.format;j=(j)?m+"&"+j:m;}if(this.options.emulation&&!["get","post"].contains(e)){var k="_method="+e; j=(j)?k+"&"+j:k;e="post";}if(this.options.urlEncoded&&["post","put"].contains(e)){var g=(this.options.encoding)?"; charset="+this.options.encoding:"";this.headers["Content-type"]="application/x-www-form-urlencoded"+g; }if(!f){f=document.location.pathname;}var i=f.lastIndexOf("/");if(i>-1&&(i=f.indexOf("#"))>-1){f=f.substr(0,i);}if(this.options.noCache){f+=(f.indexOf("?")>-1?"&":"?")+String.uniqueID(); }if(j&&(e=="get"||e=="delete")){f+=(f.indexOf("?")>-1?"&":"?")+j;j=null;}var n=this.xhr;if(a){n.onloadstart=this.loadstart.bind(this);n.onprogress=this.progress.bind(this); }n.open(e.toUpperCase(),f,this.options.async,this.options.user,this.options.password);if(this.options.user&&"withCredentials" in n){n.withCredentials=true; }n.onreadystatechange=this.onStateChange.bind(this);Object.each(this.headers,function(q,p){try{n.setRequestHeader(p,q);}catch(r){this.fireEvent("exception",[p,q]); }},this);this.fireEvent("request");n.send(j);if(!this.options.async){this.onStateChange();}else{if(this.options.timeout){this.timer=this.timeout.delay(this.options.timeout,this); }}return this;},cancel:function(){if(!this.running){return this;}this.running=false;var e=this.xhr;e.abort();clearTimeout(this.timer);e.onreadystatechange=d; if(a){e.onprogress=e.onloadstart=d;}this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});var b={};["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(e){b[e]=function(g){var f={method:e}; if(g!=null){f.data=g;}return this.send(f);};});c.implement(b);Element.Properties.send={set:function(e){var f=this.get("send").cancel();f.setOptions(e); return this;},get:function(){var e=this.retrieve("send");if(!e){e=new c({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")}); this.store("send",e);}return e;}};Element.implement({send:function(e){var f=this.get("send");f.send({data:this,url:e||f.options.url});return this;}});})(); Request.HTML=new Class({Extends:Request,options:{update:false,append:false,evalScripts:true,filter:false,headers:{Accept:"text/html, application/xml, text/xml, */*"}},success:function(f){var e=this.options,c=this.response; c.html=f.stripScripts(function(h){c.javascript=h;});var d=c.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);if(d){c.html=d[1];}var b=new Element("div").set("html",c.html); c.tree=b.childNodes;c.elements=b.getElements(e.filter||"*");if(e.filter){c.tree=c.elements;}if(e.update){var g=document.id(e.update).empty();if(e.filter){g.adopt(c.elements); }else{g.set("html",c.html);}}else{if(e.append){var a=document.id(e.append);if(e.filter){c.elements.reverse().inject(a);}else{a.adopt(b.getChildren());}}}if(e.evalScripts){Browser.exec(c.javascript); }this.onSuccess(c.tree,c.elements,c.html,c.javascript);}});Element.Properties.load={set:function(a){var b=this.get("load").cancel();b.setOptions(a);return this; },get:function(){var a=this.retrieve("load");if(!a){a=new Request.HTML({data:this,link:"cancel",update:this,method:"get"});this.store("load",a);}return a; }};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Type.isObject,url:Type.isString}));return this;}});if(typeof JSON=="undefined"){this.JSON={}; }JSON=new Hash({stringify:JSON.stringify,parse:JSON.parse});(function(){var special={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"}; var escape=function(chr){return special[chr]||"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4);};JSON.validate=function(string){string=string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""); return(/^[\],:{}\s]*$/).test(string);};JSON.encode=JSON.stringify?function(obj){return JSON.stringify(obj);}:function(obj){if(obj&&obj.toJSON){obj=obj.toJSON(); }switch(typeOf(obj)){case"string":return'"'+obj.replace(/[\x00-\x1f\\"]/g,escape)+'"';case"array":return"["+obj.map(JSON.encode).clean()+"]";case"object":case"hash":var string=[]; Object.each(obj,function(value,key){var json=JSON.encode(value);if(json){string.push(JSON.encode(key)+":"+json);}});return"{"+string+"}";case"number":case"boolean":return""+obj; case"null":return"null";}return null;};JSON.secure=true;JSON.secure=false;JSON.decode=function(string,secure){if(!string||typeOf(string)!="string"){return null; }if(secure==null){secure=JSON.secure;}if(secure){if(JSON.parse){return JSON.parse(string);}if(!JSON.validate(string)){throw new Error("JSON could not decode the input; security is enabled and the value is not secure."); }}return eval("("+string+")");};})();Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(a){this.parent(a);Object.append(this.headers,{Accept:"application/json","X-Request":"JSON"}); },success:function(c){var b;try{b=this.response.json=JSON.decode(c,this.options.secure);}catch(a){this.fireEvent("error",[c,a]);return;}if(b==null){this.onFailure(); }else{this.onSuccess(b,c);}}});var Cookie=new Class({Implements:Options,options:{path:"/",domain:false,duration:false,secure:false,document:document,encode:true},initialize:function(b,a){this.key=b; this.setOptions(a);},write:function(b){if(this.options.encode){b=encodeURIComponent(b);}if(this.options.domain){b+="; domain="+this.options.domain;}if(this.options.path){b+="; path="+this.options.path; }if(this.options.duration){var a=new Date();a.setTime(a.getTime()+this.options.duration*24*60*60*1000);b+="; expires="+a.toGMTString();}if(this.options.secure){b+="; secure"; }this.options.document.cookie=this.key+"="+b;return this;},read:function(){var a=this.options.document.cookie.match("(?:^|;)\\s*"+this.key.escapeRegExp()+"=([^;]*)"); return(a)?decodeURIComponent(a[1]):null;},dispose:function(){new Cookie(this.key,Object.merge({},this.options,{duration:-1})).write("");return this;}}); Cookie.write=function(b,c,a){return new Cookie(b,a).write(c);};Cookie.read=function(a){return new Cookie(a).read();};Cookie.dispose=function(b,a){return new Cookie(b,a).dispose(); };(function(i,k){var l,f,e=[],c,b,d=k.createElement("div");var g=function(){clearTimeout(b);if(l){return;}Browser.loaded=l=true;k.removeListener("DOMContentLoaded",g).removeListener("readystatechange",a); k.fireEvent("domready");i.fireEvent("domready");};var a=function(){for(var m=e.length;m--;){if(e[m]()){g();return true;}}return false;};var j=function(){clearTimeout(b); if(!a()){b=setTimeout(j,10);}};k.addListener("DOMContentLoaded",g);var h=function(){try{d.doScroll();return true;}catch(m){}return false;};if(d.doScroll&&!h()){e.push(h); c=true;}if(k.readyState){e.push(function(){var m=k.readyState;return(m=="loaded"||m=="complete");});}if("onreadystatechange" in k){k.addListener("readystatechange",a); }else{c=true;}if(c){j();}Element.Events.domready={onAdd:function(m){if(l){m.call(this);}}};Element.Events.load={base:"load",onAdd:function(m){if(f&&this==i){m.call(this); }},condition:function(){if(this==i){g();delete Element.Events.load;}return true;}};i.addEvent("load",function(){f=true;});})(window,document);
(function () { //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-transition',['jquery'], function () { (function () { /* =================================================== * bootstrap-transition.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#transitions * =================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { // jshint ;_; /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) * ======================================================= */ $(function () { $.support.transition = (function () { var transitionEnd = (function () { var el = document.createElement('bootstrap') , transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } , name for (name in transEndEventNames){ if (el.style[name] !== undefined) { return transEndEventNames[name] } } }()) return transitionEnd && { end: transitionEnd } })() }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-affix',['bootstrap/bootstrap-transition'], function () { (function () { /* ========================================================== * bootstrap-affix.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#affix * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { // jshint ;_; /* AFFIX CLASS DEFINITION * ====================== */ var Affix = function (element, options) { this.options = $.extend({}, $.fn.affix.defaults, options) this.$window = $(window) .on('scroll.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this)) this.$element = $(element) this.checkPosition() } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() , scrollTop = this.$window.scrollTop() , position = this.$element.offset() , offset = this.options.offset , offsetBottom = offset.bottom , offsetTop = offset.top , reset = 'affix affix-top affix-bottom' , affix if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && scrollTop <= offsetTop ? 'top' : false if (this.affixed === affix) return this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : '')) } /* AFFIX PLUGIN DEFINITION * ======================= */ var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('affix') , options = typeof option == 'object' && option if (!data) $this.data('affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix $.fn.affix.defaults = { offset: 0 } /* AFFIX NO CONFLICT * ================= */ $.fn.affix.noConflict = function () { $.fn.affix = old return this } /* AFFIX DATA-API * ============== */ $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) , data = $spy.data() data.offset = data.offset || {} data.offsetBottom && (data.offset.bottom = data.offsetBottom) data.offsetTop && (data.offset.top = data.offsetTop) $spy.affix(data) }) }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-alert',['bootstrap/bootstrap-transition'], function () { (function () { /* ========================================================== * bootstrap-alert.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#alerts * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { // jshint ;_; /* ALERT CLASS DEFINITION * ====================== */ var dismiss = '[data-dismiss="alert"]' , Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) , selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) e && e.preventDefault() $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) $parent.trigger(e = $.Event('close')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent .trigger('closed') .remove() } $.support.transition && $parent.hasClass('fade') ? $parent.on($.support.transition.end, removeElement) : removeElement() } /* ALERT PLUGIN DEFINITION * ======================= */ var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('alert') if (!data) $this.data('alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert /* ALERT NO CONFLICT * ================= */ $.fn.alert.noConflict = function () { $.fn.alert = old return this } /* ALERT DATA-API * ============== */ $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-button',['bootstrap/bootstrap-transition'], function () { (function () { /* ============================================================ * bootstrap-button.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#buttons * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { // jshint ;_; /* BUTTON PUBLIC CLASS DEFINITION * ============================== */ var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.button.defaults, options) } Button.prototype.setState = function (state) { var d = 'disabled' , $el = this.$element , data = $el.data() , val = $el.is('input') ? 'val' : 'html' state = state + 'Text' data.resetText || $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d) }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-toggle="buttons-radio"]') $parent && $parent .find('.active') .removeClass('active') this.$element.toggleClass('active') } /* BUTTON PLUGIN DEFINITION * ======================== */ var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('button') , options = typeof option == 'object' && option if (!data) $this.data('button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.defaults = { loadingText: 'loading...' } $.fn.button.Constructor = Button /* BUTTON NO CONFLICT * ================== */ $.fn.button.noConflict = function () { $.fn.button = old return this } /* BUTTON DATA-API * =============== */ $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-carousel',['bootstrap/bootstrap-transition'], function () { (function () { /* ========================================================== * bootstrap-carousel.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#carousel * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { // jshint ;_; /* CAROUSEL CLASS DEFINITION * ========================= */ var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.prototype = { cycle: function (e) { if (!e) this.paused = false if (this.interval) clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } , getActiveIndex: function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } , to: function (pos) { var activeIndex = this.getActiveIndex() , that = this if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { that.to(pos) }) } if (activeIndex == pos) { return this.pause().cycle() } return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } , pause: function (e) { if (!e) this.paused = true if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } clearInterval(this.interval) this.interval = null return this } , next: function () { if (this.sliding) return return this.slide('next') } , prev: function () { if (this.sliding) return return this.slide('prev') } , slide: function (type, next) { var $active = this.$element.find('.item.active') , $next = next || $active[type]() , isCycling = this.interval , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this , e this.sliding = true isCycling && this.pause() $next = $next.length ? $next : this.$element.find('.item')[fallback]() e = $.Event('slide', { relatedTarget: $next[0] , direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) this.$element.one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } } /* CAROUSEL PLUGIN DEFINITION * ========================== */ var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('carousel') , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) $this.data('carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.defaults = { interval: 5000 , pause: 'hover' } $.fn.carousel.Constructor = Carousel /* CAROUSEL NO CONFLICT * ==================== */ $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } /* CAROUSEL DATA-API * ================= */ $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) , slideIndex $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('carousel').pause().to(slideIndex).cycle() } e.preventDefault() }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-collapse',['bootstrap/bootstrap-transition'], function () { (function () { /* ============================================================= * bootstrap-collapse.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning || this.$element.hasClass('in')) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') $.support.transition && this.$element[dimension](this.$element[0][scroll]) } , hide: function () { var dimension if (this.transitioning || !this.$element.hasClass('in')) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function (size) { var dimension = this.dimension() this.$element .removeClass('collapse') [dimension](size || 'auto') [0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , toggle: function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } } /* COLLAPSE PLUGIN DEFINITION * ========================== */ var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('collapse') , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSE NO CONFLICT * ==================== */ $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } /* COLLAPSE DATA-API * ================= */ $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href , target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target).data('collapse') ? 'toggle' : $this.data() $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') $(target).collapse(option) }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-dropdown',['bootstrap/bootstrap-transition'], function () { (function () { /* ============================================================ * bootstrap-dropdown.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { // jshint ;_; /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle=dropdown]' , Dropdown = function (element) { var $el = $(element).on('click.dropdown.data-api', this.toggle) $('html').on('click.dropdown.data-api', function () { $el.parent().removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function (e) { var $this = $(this) , $parent , isActive if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement) { // if mobile we we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus) } $parent.toggleClass('open') } $this.focus() return false } , keydown: function (e) { var $this , $items , $active , $parent , isActive , index if (!/(38|40|27)/.test(e.keyCode)) return $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items .eq(index) .focus() } } function clearMenus() { $('.dropdown-backdrop').remove() $(toggle).each(function () { getParent($(this)).removeClass('open') }) } function getParent($this) { var selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = selector && $(selector) if (!$parent || !$parent.length) $parent = $this.parent() return $parent } /* DROPDOWN PLUGIN DEFINITION * ========================== */ var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown /* DROPDOWN NO CONFLICT * ==================== */ $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } /* APPLY TO STANDARD DROPDOWN ELEMENTS * =================================== */ $(document) .on('click.dropdown.data-api', clearMenus) .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-modal',['bootstrap/bootstrap-transition'], function () { (function () { /* ========================================================= * bootstrap-modal.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ !function ($) { // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden') }) } , removeBackdrop: function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-tooltip',['bootstrap/bootstrap-transition'], function () { (function () { /* =========================================================== * bootstrap-tooltip.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#tooltips * Inspired by the original jQuery.tipsy by Jason Frame * =========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { // jshint ;_; /* TOOLTIP PUBLIC CLASS DEFINITION * =============================== */ var Tooltip = function (element, options) { this.init('tooltip', element, options) } Tooltip.prototype = { constructor: Tooltip , init: function (type, element, options) { var eventIn , eventOut , triggers , trigger , i this.type = type this.$element = $(element) this.options = this.getOptions(options) this.enabled = true triggers = this.options.trigger.split(' ') for (i = triggers.length; i--;) { trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } , getOptions: function (options) { options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } , enter: function (e) { var defaults = $.fn[this.type].defaults , options = {} , self this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) self = $(e.currentTarget)[this.type](options).data(this.type) if (!self.options.delay || !self.options.delay.show) return self.show() clearTimeout(this.timeout) self.hoverState = 'in' this.timeout = setTimeout(function() { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } , leave: function (e) { var self = $(e.currentTarget)[this.type](this._options).data(this.type) if (this.timeout) clearTimeout(this.timeout) if (!self.options.delay || !self.options.delay.hide) return self.hide() self.hoverState = 'out' this.timeout = setTimeout(function() { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } , show: function () { var $tip , pos , actualWidth , actualHeight , placement , tp , e = $.Event('show') if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip = this.tip() this.setContent() if (this.options.animation) { $tip.addClass('fade') } placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement $tip .detach() .css({ top: 0, left: 0, display: 'block' }) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) pos = this.getPosition() actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight switch (placement) { case 'bottom': tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'top': tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'left': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} break case 'right': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} break } this.applyPlacement(tp, placement) this.$element.trigger('shown') } } , applyPlacement: function(offset, placement){ var $tip = this.tip() , width = $tip[0].offsetWidth , height = $tip[0].offsetHeight , actualWidth , actualHeight , delta , replace $tip .offset(offset) .addClass(placement) .addClass('in') actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight replace = true } if (placement == 'bottom' || placement == 'top') { delta = 0 if (offset.left < 0){ delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } , replaceArrow: function(delta, dimension, position){ this .arrow() .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } , setContent: function () { var $tip = this.tip() , title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } , hide: function () { var that = this , $tip = this.tip() , e = $.Event('hide') this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') function removeWithAnimation() { var timeout = setTimeout(function () { $tip.off($.support.transition.end).detach() }, 500) $tip.one($.support.transition.end, function () { clearTimeout(timeout) $tip.detach() }) } $.support.transition && this.$tip.hasClass('fade') ? removeWithAnimation() : $tip.detach() this.$element.trigger('hidden') return this } , fixTitle: function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } , hasContent: function () { return this.getTitle() } , getPosition: function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } , getTitle: function () { var title , $e = this.$element , o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } , tip: function () { return this.$tip = this.$tip || $(this.options.template) } , arrow: function(){ return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") } , validate: function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } , enable: function () { this.enabled = true } , disable: function () { this.enabled = false } , toggleEnabled: function () { this.enabled = !this.enabled } , toggle: function (e) { var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this self.tip().hasClass('in') ? self.hide() : self.show() } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } } /* TOOLTIP PLUGIN DEFINITION * ========================= */ var old = $.fn.tooltip $.fn.tooltip = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tooltip') , options = typeof option == 'object' && option if (!data) $this.data('tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip $.fn.tooltip.defaults = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } /* TOOLTIP NO CONFLICT * =================== */ $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-popover',['bootstrap/bootstrap-transition','bootstrap/bootstrap-tooltip'], function () { (function () { /* =========================================================== * bootstrap-popover.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#popovers * =========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================================================== */ !function ($) { // jshint ;_; /* POPOVER PUBLIC CLASS DEFINITION * =============================== */ var Popover = function (element, options) { this.init('popover', element, options) } /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js ========================================== */ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, { constructor: Popover , setContent: function () { var $tip = this.tip() , title = this.getTitle() , content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') } , hasContent: function () { return this.getTitle() || this.getContent() } , getContent: function () { var content , $e = this.$element , o = this.options content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) || $e.attr('data-content') return content } , tip: function () { if (!this.$tip) { this.$tip = $(this.options.template) } return this.$tip } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } }) /* POPOVER PLUGIN DEFINITION * ======================= */ var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('popover') , options = typeof option == 'object' && option if (!data) $this.data('popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, { placement: 'right' , trigger: 'click' , content: '' , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) /* POPOVER NO CONFLICT * =================== */ $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-scrollspy',['bootstrap/bootstrap-transition'], function () { (function () { /* ============================================================= * bootstrap-scrollspy.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#scrollspy * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================== */ !function ($) { // jshint ;_; /* SCROLLSPY CLASS DEFINITION * ========================== */ function ScrollSpy(element, options) { var process = $.proxy(this.process, this) , $element = $(element).is('body') ? $(window) : $(element) , href this.options = $.extend({}, $.fn.scrollspy.defaults, options) this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.$body = $('body') this.refresh() this.process() } ScrollSpy.prototype = { constructor: ScrollSpy , refresh: function () { var self = this , $targets this.offsets = $([]) this.targets = $([]) $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) , href = $el.data('target') || $el.attr('href') , $href = /^#\w/.test(href) && $(href) return ( $href && $href.length && [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } , process: function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset , scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight , maxScroll = scrollHeight - this.$scrollElement.height() , offsets = this.offsets , targets = this.targets , activeTarget = this.activeTarget , i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate ( i ) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } , activate: function (target) { var active , selector this.activeTarget = target $(this.selector) .parent('.active') .removeClass('active') selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' active = $(selector) .parent('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active.closest('li.dropdown').addClass('active') } active.trigger('activate') } } /* SCROLLSPY PLUGIN DEFINITION * =========================== */ var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('scrollspy') , options = typeof option == 'object' && option if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy $.fn.scrollspy.defaults = { offset: 10 } /* SCROLLSPY NO CONFLICT * ===================== */ $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } /* SCROLLSPY DATA-API * ================== */ $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-tab',['bootstrap/bootstrap-transition'], function () { (function () { /* ======================================================== * bootstrap-tab.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#tabs * ======================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================== */ !function ($) { // jshint ;_; /* TAB CLASS DEFINITION * ==================== */ var Tab = function (element) { this.element = $(element) } Tab.prototype = { constructor: Tab , show: function () { var $this = this.element , $ul = $this.closest('ul:not(.dropdown-menu)') , selector = $this.attr('data-target') , previous , $target , e if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ( $this.parent('li').hasClass('active') ) return previous = $ul.find('.active:last a')[0] e = $.Event('show', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown' , relatedTarget: previous }) }) } , activate: function ( element, container, callback) { var $active = container.find('> .active') , transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if ( element.parent('.dropdown-menu') ) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active.one($.support.transition.end, next) : next() $active.removeClass('in') } } /* TAB PLUGIN DEFINITION * ===================== */ var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tab') if (!data) $this.data('tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab /* TAB NO CONFLICT * =============== */ $.fn.tab.noConflict = function () { $.fn.tab = old return this } /* TAB DATA-API * ============ */ $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); //Wrapped in an outer function to preserve global this (function (root) { var amdExports; define('bootstrap/bootstrap-typeahead',['bootstrap/bootstrap-transition'], function () { (function () { /* ============================================================= * bootstrap-typeahead.js v2.3.2 * http://twitter.github.com/bootstrap/javascript.html#typeahead * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function($){ // jshint ;_; /* TYPEAHEAD PUBLIC CLASS DEFINITION * ================================= */ var Typeahead = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.typeahead.defaults, options) this.matcher = this.options.matcher || this.matcher this.sorter = this.options.sorter || this.sorter this.highlighter = this.options.highlighter || this.highlighter this.updater = this.options.updater || this.updater this.source = this.options.source this.$menu = $(this.options.menu) this.shown = false this.listen() } Typeahead.prototype = { constructor: Typeahead , select: function () { var val = this.$menu.find('.active').attr('data-value') this.$element .val(this.updater(val)) .change() return this.hide() } , updater: function (item) { return item } , show: function () { var pos = $.extend({}, this.$element.position(), { height: this.$element[0].offsetHeight }) this.$menu .insertAfter(this.$element) .css({ top: pos.top + pos.height , left: pos.left }) .show() this.shown = true return this } , hide: function () { this.$menu.hide() this.shown = false return this } , lookup: function (event) { var items this.query = this.$element.val() if (!this.query || this.query.length < this.options.minLength) { return this.shown ? this.hide() : this } items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source return items ? this.process(items) : this } , process: function (items) { var that = this items = $.grep(items, function (item) { return that.matcher(item) }) items = this.sorter(items) if (!items.length) { return this.shown ? this.hide() : this } return this.render(items.slice(0, this.options.items)).show() } , matcher: function (item) { return ~item.toLowerCase().indexOf(this.query.toLowerCase()) } , sorter: function (items) { var beginswith = [] , caseSensitive = [] , caseInsensitive = [] , item while (item = items.shift()) { if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item) else if (~item.indexOf(this.query)) caseSensitive.push(item) else caseInsensitive.push(item) } return beginswith.concat(caseSensitive, caseInsensitive) } , highlighter: function (item) { var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { return '<strong>' + match + '</strong>' }) } , render: function (items) { var that = this items = $(items).map(function (i, item) { i = $(that.options.item).attr('data-value', item) i.find('a').html(that.highlighter(item)) return i[0] }) items.first().addClass('active') this.$menu.html(items) return this } , next: function (event) { var active = this.$menu.find('.active').removeClass('active') , next = active.next() if (!next.length) { next = $(this.$menu.find('li')[0]) } next.addClass('active') } , prev: function (event) { var active = this.$menu.find('.active').removeClass('active') , prev = active.prev() if (!prev.length) { prev = this.$menu.find('li').last() } prev.addClass('active') } , listen: function () { this.$element .on('focus', $.proxy(this.focus, this)) .on('blur', $.proxy(this.blur, this)) .on('keypress', $.proxy(this.keypress, this)) .on('keyup', $.proxy(this.keyup, this)) if (this.eventSupported('keydown')) { this.$element.on('keydown', $.proxy(this.keydown, this)) } this.$menu .on('click', $.proxy(this.click, this)) .on('mouseenter', 'li', $.proxy(this.mouseenter, this)) .on('mouseleave', 'li', $.proxy(this.mouseleave, this)) } , eventSupported: function(eventName) { var isSupported = eventName in this.$element if (!isSupported) { this.$element.setAttribute(eventName, 'return;') isSupported = typeof this.$element[eventName] === 'function' } return isSupported } , move: function (e) { if (!this.shown) return switch(e.keyCode) { case 9: // tab case 13: // enter case 27: // escape e.preventDefault() break case 38: // up arrow e.preventDefault() this.prev() break case 40: // down arrow e.preventDefault() this.next() break } e.stopPropagation() } , keydown: function (e) { this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27]) this.move(e) } , keypress: function (e) { if (this.suppressKeyPressRepeat) return this.move(e) } , keyup: function (e) { switch(e.keyCode) { case 40: // down arrow case 38: // up arrow case 16: // shift case 17: // ctrl case 18: // alt break case 9: // tab case 13: // enter if (!this.shown) return this.select() break case 27: // escape if (!this.shown) return this.hide() break default: this.lookup() } e.stopPropagation() e.preventDefault() } , focus: function (e) { this.focused = true } , blur: function (e) { this.focused = false if (!this.mousedover && this.shown) this.hide() } , click: function (e) { e.stopPropagation() e.preventDefault() this.select() this.$element.focus() } , mouseenter: function (e) { this.mousedover = true this.$menu.find('.active').removeClass('active') $(e.currentTarget).addClass('active') } , mouseleave: function (e) { this.mousedover = false if (!this.focused && this.shown) this.hide() } } /* TYPEAHEAD PLUGIN DEFINITION * =========================== */ var old = $.fn.typeahead $.fn.typeahead = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('typeahead') , options = typeof option == 'object' && option if (!data) $this.data('typeahead', (data = new Typeahead(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.typeahead.defaults = { source: [] , items: 8 , menu: '<ul class="typeahead dropdown-menu"></ul>' , item: '<li><a href="#"></a></li>' , minLength: 1 } $.fn.typeahead.Constructor = Typeahead /* TYPEAHEAD NO CONFLICT * =================== */ $.fn.typeahead.noConflict = function () { $.fn.typeahead = old return this } /* TYPEAHEAD DATA-API * ================== */ $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) { var $this = $(this) if ($this.data('typeahead')) return $this.typeahead($this.data()) }) }(window.jQuery); }.call(root)); return amdExports; }); }(this)); /* * Fuel UX Checkbox * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/checkbox',['require','jquery'],function (require) { var $ = require('jquery'); // CHECKBOX CONSTRUCTOR AND PROTOTYPE var Checkbox = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.checkbox.defaults, options); // cache elements this.$label = this.$element.parent(); this.$icon = this.$label.find('i'); this.$chk = this.$label.find('input[type=checkbox]'); // set default state this.setState(this.$chk); // handle events this.$chk.on('change', $.proxy(this.itemchecked, this)); }; Checkbox.prototype = { constructor: Checkbox, setState: function ($chk) { $chk = $chk || this.$chk; var checked = $chk.is(':checked'); var disabled = $chk.is(':disabled'); // reset classes this.$icon.removeClass('checked disabled'); // set state of checkbox if (checked === true) { this.$icon.addClass('checked'); } if (disabled === true) { this.$icon.addClass('disabled'); } }, enable: function () { this.$chk.attr('disabled', false); this.$icon.removeClass('disabled'); }, disable: function () { this.$chk.attr('disabled', true); this.$icon.addClass('disabled'); }, toggle: function () { this.$chk.click(); }, itemchecked: function (e) { var chk = $(e.target); this.setState(chk); }, check: function () { this.$chk.prop('checked', true); this.setState(this.$chk); }, uncheck: function () { this.$chk.prop('checked', false); this.setState(this.$chk); }, isChecked: function () { return this.$chk.is(':checked'); } }; // CHECKBOX PLUGIN DEFINITION $.fn.checkbox = function (option, value) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('checkbox'); var options = typeof option === 'object' && option; if (!data) $this.data('checkbox', (data = new Checkbox(this, options))); if (typeof option === 'string') methodReturn = data[option](value); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.checkbox.defaults = {}; $.fn.checkbox.Constructor = Checkbox; // CHECKBOX DATA-API $(function () { $(window).on('load', function () { //$('i.checkbox').each(function () { $('.checkbox-custom > input[type=checkbox]').each(function () { var $this = $(this); if ($this.data('checkbox')) return; $this.checkbox($this.data()); }); }); }); }); /* * Fuel UX Utilities * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/util',['require','jquery'],function (require) { var $ = require('jquery'); // custom case-insensitive match expression function fuelTextExactCI(elem, text) { return (elem.textContent || elem.innerText || $(elem).text() || '').toLowerCase() === (text || '').toLowerCase(); } $.expr[':'].fuelTextExactCI = $.expr.createPseudo ? $.expr.createPseudo(function (text) { return function (elem) { return fuelTextExactCI(elem, text); }; }) : function (elem, i, match) { return fuelTextExactCI(elem, match[3]); }; }); /* * Fuel UX Combobox * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/combobox',['require','jquery','./util'],function (require) { var $ = require('jquery'); require('./util'); // COMBOBOX CONSTRUCTOR AND PROTOTYPE var Combobox = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.combobox.defaults, options); this.$element.on('click', 'a', $.proxy(this.itemclicked, this)); this.$element.on('change', 'input', $.proxy(this.inputchanged, this)); this.$input = this.$element.find('input'); this.$button = this.$element.find('.btn'); // set default selection this.setDefaultSelection(); }; Combobox.prototype = { constructor: Combobox, selectedItem: function () { var item = this.$selectedItem; var data = {}; if (item) { var txt = this.$selectedItem.text(); data = $.extend({ text: txt }, this.$selectedItem.data()); } else { data = { text: this.$input.val()}; } return data; }, selectByText: function (text) { var selector = 'li:fuelTextExactCI(' + text + ')'; this.selectBySelector(selector); }, selectByValue: function (value) { var selector = 'li[data-value="' + value + '"]'; this.selectBySelector(selector); }, selectByIndex: function (index) { // zero-based index var selector = 'li:eq(' + index + ')'; this.selectBySelector(selector); }, selectBySelector: function (selector) { var $item = this.$element.find(selector); if (typeof $item[0] !== 'undefined') { this.$selectedItem = $item; this.$input.val(this.$selectedItem.text()); } else { this.$selectedItem = null; } }, setDefaultSelection: function () { var selector = 'li[data-selected=true]:first'; var item = this.$element.find(selector); if (item.length > 0) { // select by data-attribute this.selectBySelector(selector); item.removeData('selected'); item.removeAttr('data-selected'); } }, enable: function () { this.$input.removeAttr('disabled'); this.$button.removeClass('disabled'); }, disable: function () { this.$input.attr('disabled', true); this.$button.addClass('disabled'); }, itemclicked: function (e) { this.$selectedItem = $(e.target).parent(); // set input text and trigger input change event marked as synthetic this.$input.val(this.$selectedItem.text()).trigger('change', { synthetic: true }); // pass object including text and any data-attributes // to onchange event var data = this.selectedItem(); // trigger changed event this.$element.trigger('changed', data); e.preventDefault(); }, inputchanged: function (e, extra) { // skip processing for internally-generated synthetic event // to avoid double processing if (extra && extra.synthetic) return; var val = $(e.target).val(); this.selectByText(val); // find match based on input // if no match, pass the input value var data = this.selectedItem(); if (data.text.length === 0) { data = { text: val }; } // trigger changed event this.$element.trigger('changed', data); } }; // COMBOBOX PLUGIN DEFINITION $.fn.combobox = function (option, value) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('combobox'); var options = typeof option === 'object' && option; if (!data) $this.data('combobox', (data = new Combobox(this, options))); if (typeof option === 'string') methodReturn = data[option](value); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.combobox.defaults = {}; $.fn.combobox.Constructor = Combobox; // COMBOBOX DATA-API $(function () { $(window).on('load', function () { $('.combobox').each(function () { var $this = $(this); if ($this.data('combobox')) return; $this.combobox($this.data()); }); }); $('body').on('mousedown.combobox.data-api', '.combobox', function () { var $this = $(this); if ($this.data('combobox')) return; $this.combobox($this.data()); }); }); }); /* * Fuel UX Datagrid * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/datagrid',['require','jquery'],function (require) { var $ = require('jquery'); // Relates to thead .sorted styles in datagrid.less var SORTED_HEADER_OFFSET = 22; // DATAGRID CONSTRUCTOR AND PROTOTYPE var Datagrid = function (element, options) { this.$element = $(element); this.$thead = this.$element.find('thead'); this.$tfoot = this.$element.find('tfoot'); this.$footer = this.$element.find('tfoot th'); this.$footerchildren = this.$footer.children().show().css('visibility', 'hidden'); this.$topheader = this.$element.find('thead th'); this.$searchcontrol = this.$element.find('.datagrid-search'); this.$filtercontrol = this.$element.find('.filter'); this.$pagesize = this.$element.find('.grid-pagesize'); this.$pageinput = this.$element.find('.grid-pager input'); this.$pagedropdown = this.$element.find('.grid-pager .dropdown-menu'); this.$prevpagebtn = this.$element.find('.grid-prevpage'); this.$nextpagebtn = this.$element.find('.grid-nextpage'); this.$pageslabel = this.$element.find('.grid-pages'); this.$countlabel = this.$element.find('.grid-count'); this.$startlabel = this.$element.find('.grid-start'); this.$endlabel = this.$element.find('.grid-end'); this.$tbody = $('<tbody>').insertAfter(this.$thead); this.$colheader = $('<tr>').appendTo(this.$thead); this.options = $.extend(true, {}, $.fn.datagrid.defaults, options); // Shim until v3 -- account for FuelUX select or native select for page size: if (this.$pagesize.hasClass('select')) { this.$pagesize.select('selectByValue', this.options.dataOptions.pageSize); this.options.dataOptions.pageSize = parseInt(this.$pagesize.select('selectedItem').value, 10); } else { var pageSize = this.options.dataOptions.pageSize; this.$pagesize.find('option').filter(function() { return $(this).text() === pageSize.toString(); }).attr('selected', true); this.options.dataOptions.pageSize = parseInt(this.$pagesize.val(), 10); } // Shim until v3 -- account for older search class: if (this.$searchcontrol.length <= 0) { this.$searchcontrol = this.$element.find('.search'); } this.columns = this.options.dataSource.columns(); this.$nextpagebtn.on('click', $.proxy(this.next, this)); this.$prevpagebtn.on('click', $.proxy(this.previous, this)); this.$searchcontrol.on('searched cleared', $.proxy(this.searchChanged, this)); this.$filtercontrol.on('changed', $.proxy(this.filterChanged, this)); this.$colheader.on('click', 'th', $.proxy(this.headerClicked, this)); if (this.$pagesize.hasClass('select')) { this.$pagesize.on('changed', $.proxy(this.pagesizeChanged, this)); } else { this.$pagesize.on('change', $.proxy(this.pagesizeChanged, this)); } this.$pageinput.on('change', $.proxy(this.pageChanged, this)); this.renderColumns(); if (this.options.stretchHeight) this.initStretchHeight(); this.renderData(); }; Datagrid.prototype = { constructor: Datagrid, renderColumns: function () { var self = this; this.$footer.attr('colspan', this.columns.length); this.$topheader.attr('colspan', this.columns.length); var colHTML = ''; $.each(this.columns, function (index, column) { colHTML += '<th data-property="' + column.property + '"'; if (column.sortable) colHTML += ' class="sortable"'; colHTML += '>' + column.label + '</th>'; }); self.$colheader.append(colHTML); }, updateColumns: function ($target, direction) { this._updateColumns(this.$colheader, $target, direction); if (this.$sizingHeader) { this._updateColumns(this.$sizingHeader, this.$sizingHeader.find('th').eq($target.index()), direction); } }, _updateColumns: function ($header, $target, direction) { var className = (direction === 'asc') ? 'icon-chevron-up' : 'icon-chevron-down'; $header.find('i.datagrid-sort').remove(); $header.find('th').removeClass('sorted'); $('<i>').addClass(className + ' datagrid-sort').appendTo($target); $target.addClass('sorted'); }, updatePageDropdown: function (data) { var pageHTML = ''; for (var i = 1; i <= data.pages; i++) { pageHTML += '<li><a>' + i + '</a></li>'; } this.$pagedropdown.html(pageHTML); }, updatePageButtons: function (data) { if (data.page === 1) { this.$prevpagebtn.attr('disabled', 'disabled'); } else { this.$prevpagebtn.removeAttr('disabled'); } if (data.page === data.pages) { this.$nextpagebtn.attr('disabled', 'disabled'); } else { this.$nextpagebtn.removeAttr('disabled'); } }, renderData: function () { var self = this; this.$tbody.html(this.placeholderRowHTML(this.options.loadingHTML)); this.options.dataSource.data(this.options.dataOptions, function (data) { var itemdesc = (data.count === 1) ? self.options.itemText : self.options.itemsText; var rowHTML = ''; self.$footerchildren.css('visibility', function () { return (data.count > 0) ? 'visible' : 'hidden'; }); self.$pageinput.val(data.page); self.$pageslabel.text(data.pages); self.$countlabel.text(data.count + ' ' + itemdesc); self.$startlabel.text(data.start); self.$endlabel.text(data.end); self.updatePageDropdown(data); self.updatePageButtons(data); $.each(data.data, function (index, row) { rowHTML += '<tr>'; $.each(self.columns, function (index, column) { rowHTML += '<td'; if (column.cssClass) { rowHTML += ' class="' + column.cssClass + '"'; } rowHTML += '>' + row[column.property] + '</td>'; }); rowHTML += '</tr>'; }); if (!rowHTML) rowHTML = self.placeholderRowHTML(self.options.noDataFoundHTML); self.$tbody.html(rowHTML); self.stretchHeight(); self.$element.trigger('loaded'); }); }, placeholderRowHTML: function (content) { return '<tr><td style="text-align:center;padding:20px;border-bottom:none;" colspan="' + this.columns.length + '">' + content + '</td></tr>'; }, headerClicked: function (e) { var $target = $(e.target); if (!$target.hasClass('sortable')) return; var direction = this.options.dataOptions.sortDirection; var sort = this.options.dataOptions.sortProperty; var property = $target.data('property'); if (sort === property) { this.options.dataOptions.sortDirection = (direction === 'asc') ? 'desc' : 'asc'; } else { this.options.dataOptions.sortDirection = 'asc'; this.options.dataOptions.sortProperty = property; } this.options.dataOptions.pageIndex = 0; this.updateColumns($target, this.options.dataOptions.sortDirection); this.renderData(); }, pagesizeChanged: function (e, pageSize) { if (pageSize) { this.options.dataOptions.pageSize = parseInt(pageSize.value, 10); } else { this.options.dataOptions.pageSize = parseInt($(e.target).val(), 10); } this.options.dataOptions.pageIndex = 0; this.renderData(); }, pageChanged: function (e) { var pageRequested = parseInt($(e.target).val(), 10); pageRequested = (isNaN(pageRequested)) ? 1 : pageRequested; var maxPages = this.$pageslabel.text(); this.options.dataOptions.pageIndex = (pageRequested > maxPages) ? maxPages - 1 : pageRequested - 1; this.renderData(); }, searchChanged: function (e, search) { this.options.dataOptions.search = search; this.options.dataOptions.pageIndex = 0; this.renderData(); }, filterChanged: function (e, filter) { this.options.dataOptions.filter = filter; this.options.dataOptions.pageIndex = 0; this.renderData(); }, previous: function () { this.$nextpagebtn.attr('disabled', 'disabled'); this.$prevpagebtn.attr('disabled', 'disabled'); this.options.dataOptions.pageIndex--; this.renderData(); }, next: function () { this.$nextpagebtn.attr('disabled', 'disabled'); this.$prevpagebtn.attr('disabled', 'disabled'); this.options.dataOptions.pageIndex++; this.renderData(); }, reload: function () { this.options.dataOptions.pageIndex = 0; this.renderData(); }, initStretchHeight: function () { this.$gridContainer = this.$element.parent(); this.$element.wrap('<div class="datagrid-stretch-wrapper">'); this.$stretchWrapper = this.$element.parent(); this.$headerTable = $('<table>').attr('class', this.$element.attr('class')); this.$footerTable = this.$headerTable.clone(); this.$headerTable.prependTo(this.$gridContainer).addClass('datagrid-stretch-header'); this.$thead.detach().appendTo(this.$headerTable); this.$sizingHeader = this.$thead.clone(); this.$sizingHeader.find('tr:first').remove(); this.$footerTable.appendTo(this.$gridContainer).addClass('datagrid-stretch-footer'); this.$tfoot.detach().appendTo(this.$footerTable); }, stretchHeight: function () { if (!this.$gridContainer) return; this.setColumnWidths(); var targetHeight = this.$gridContainer.height(); var headerHeight = this.$headerTable.outerHeight(); var footerHeight = this.$footerTable.outerHeight(); var overhead = headerHeight + footerHeight; this.$stretchWrapper.height(targetHeight - overhead); }, setColumnWidths: function () { if (!this.$sizingHeader) return; this.$element.prepend(this.$sizingHeader); var $sizingCells = this.$sizingHeader.find('th'); var columnCount = $sizingCells.length; function matchSizingCellWidth(i, el) { if (i === columnCount - 1) return; var $el = $(el); var $sourceCell = $sizingCells.eq(i); var width = $sourceCell.width(); // TD needs extra width to match sorted column header if ($sourceCell.hasClass('sorted') && $el.prop('tagName') === 'TD') width = width + SORTED_HEADER_OFFSET; $el.width(width); } this.$colheader.find('th').each(matchSizingCellWidth); this.$tbody.find('tr:first > td').each(matchSizingCellWidth); this.$sizingHeader.detach(); } }; // DATAGRID PLUGIN DEFINITION $.fn.datagrid = function (option) { return this.each(function () { var $this = $(this); var data = $this.data('datagrid'); var options = typeof option === 'object' && option; if (!data) $this.data('datagrid', (data = new Datagrid(this, options))); if (typeof option === 'string') data[option](); }); }; $.fn.datagrid.defaults = { dataOptions: { pageIndex: 0, pageSize: 10 }, loadingHTML: '<div class="progress progress-striped active" style="width:50%;margin:auto;"><div class="bar" style="width:100%;"></div></div>', itemsText: 'items', itemText: 'item', noDataFoundHTML: '0 items' }; $.fn.datagrid.Constructor = Datagrid; }); /* * Fuel UX Intelligent Bootstrap Dropdowns * https://github.com/ExactTarget/fuelux * * Copyright (c) 2013 ExactTarget * Licensed under the MIT license. */ define('fuelux/intelligent-dropdown',[ "jquery", "fuelux/all"], function($) { $(function() { $(document.body).on("click", "[data-toggle=dropdown][data-direction]", function( event ) { var dataDirection = $(this).data().direction; // if data-direction is not auto or up, default to bootstraps dropdown if( dataDirection === "auto" || dataDirection === "up" ) { // only changing css positioning if position is set to static // if this doesn"t happen, dropUp will not be correct // works correctly for absolute, relative, and fixed positioning if( $(this).parent().css("position") === "static" ) { $(this).parent().css({ position: "relative"}); } // only continue into this function if the click came from a user if( event.hasOwnProperty("originalEvent") ) { // stopping bootstrap event propagation event.stopPropagation(); // deciding what to do based on data-direction attribute if( dataDirection === "auto" ) { // have the drop down intelligently decide where to place itself forceAutoDropDown( $(this) ); } else if ( dataDirection === "up" ) { forceDropUp( $(this) ); } } } }); function forceDropUp( element ) { var dropDown = element.next(); var dropUpPadding = 5; var topPosition; $(dropDown).addClass("dropUp"); topPosition = ( ( dropDown.outerHeight() + dropUpPadding ) * -1 ) + "px"; dropDown.css({ visibility: "visible", top: topPosition }); element.click(); } function forceAutoDropDown( element ) { var dropDown = element.next(); var dropUpPadding = 5; var topPosition; // setting this so I can get height of dropDown without it being shown dropDown.css({ visibility: "hidden" }); // deciding where to put menu if( dropUpCheck( dropDown ) ) { $(dropDown).addClass("dropUp"); topPosition = ( ( dropDown.outerHeight() + dropUpPadding ) * -1 ) + "px"; } else { $(dropDown).removeClass("dropUp"); topPosition = "auto"; } dropDown.css({ visibility: "visible", top: topPosition }); element.click(); } function dropUpCheck( element ) { // caching container var $container = getContainer( element ); // building object with measurementsances for later use var measurements = {}; measurements.parentHeight = element.parent().outerHeight(); measurements.parentOffsetTop = element.parent().offset().top; measurements.dropdownHeight = element.outerHeight(); measurements.containerHeight = $container.overflowElement.outerHeight(); // this needs to be different if the window is the container or another element is measurements.containerOffsetTop = ( !! $container.isWindow ) ? $container.overflowElement.scrollTop() : $container.overflowElement.offset().top; // doing the calculations measurements.fromTop = measurements.parentOffsetTop - measurements.containerOffsetTop; measurements.fromBottom = measurements.containerHeight - measurements.parentHeight - ( measurements.parentOffsetTop - measurements.containerOffsetTop ); // actual determination of where to put menu // false = drop down // true = drop up if( measurements.dropdownHeight < measurements.fromBottom ) { return false; } else if ( measurements.dropdownHeight < measurements.fromTop ) { return true; } else if ( measurements.dropdownHeight >= measurements.fromTop && measurements.dropdownHeight >= measurements.fromBottom ) { // decide which one is bigger and put it there if( measurements.fromTop >= measurements.fromBottom ) { return true; } else { return false; } } } function getContainer( element ) { var containerElement = window; var isWindow = true; $.each( element.parents(), function(index, value) { if( $(value).css('overflow') !== 'visible' ) { containerElement = value; isWindow = false; return false; } }); return { overflowElement: $( containerElement ), isWindow: isWindow }; } }); }); /* * Fuel UX Pillbox * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/pillbox',['require','jquery'],function(require) { var $ = require('jquery'); // PILLBOX CONSTRUCTOR AND PROTOTYPE var Pillbox = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.pillbox.defaults, options); this.$element.on('click', 'li', $.proxy(this.itemclicked, this)); }; Pillbox.prototype = { constructor : Pillbox, items: function() { return this.$element.find('li').map(function() { var $this = $(this); return $.extend({ text : $this.text() }, $this.data()); }).get(); }, itemclicked: function(e) { var $li = $(e.currentTarget); var data = $.extend({ text : $li.html() }, $li.data()); $li.remove(); e.preventDefault(); this.$element.trigger('removed', data); }, itemCount: function() { return this.$element.find('li').length; }, addItem: function(text, value) { value = value || text; //<li data-value="foo">Item One</li> var $li = $('<li data-value="' + value + '">' + text + '</li>'); this.$element.find('ul').append($li); return $li; }, removeBySelector: function(selector) { this.$element.find('ul').find(selector).remove(); }, removeByValue: function(value) { var selector = 'li[data-value="' + value + '"]'; this.removeBySelector(selector); }, removeByText: function(text) { var selector = 'li:contains("' + text + '")'; this.removeBySelector(selector); }, clear: function() { this.$element.find('ul').empty(); } }; // PILLBOX PLUGIN DEFINITION $.fn.pillbox = function (option, value1, value2) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('pillbox'); var options = typeof option === 'object' && option; if (!data) $this.data('pillbox', ( data = new Pillbox(this, options))); if ( typeof option === 'string') methodReturn = data[option](value1, value2); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.pillbox.defaults = {}; $.fn.pillbox.Constructor = Pillbox; // PILLBOX DATA-API $(function () { $('body').on('mousedown.pillbox.data-api', '.pillbox', function () { var $this = $(this); if ($this.data('pillbox')) return; $this.pillbox($this.data()); }); }); }); /* * Fuel UX Radio * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/radio',['require','jquery'],function (require) { var $ = require('jquery'); // RADIO CONSTRUCTOR AND PROTOTYPE var Radio = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.radio.defaults, options); // cache elements this.$label = this.$element.parent(); this.$icon = this.$label.find('i'); this.$radio = this.$label.find('input[type=radio]'); this.groupName = this.$radio.attr('name'); // set default state this.setState(this.$radio); // handle events this.$radio.on('change', $.proxy(this.itemchecked, this)); }; Radio.prototype = { constructor: Radio, setState: function ($radio) { $radio = $radio || this.$radio; var checked = $radio.is(':checked'); var disabled = $radio.is(':disabled'); // reset classes this.$icon.removeClass('checked').removeClass('disabled'); this.$icon.removeClass('checked disabled'); // set state of radio if (checked === true) { this.$icon.addClass('checked'); } if (disabled === true) { this.$icon.addClass('disabled'); } }, resetGroup: function () { // reset all radio buttons in group $('input[name=' + this.groupName + ']').next().removeClass('checked'); }, enable: function () { this.$radio.attr('disabled', false); this.$icon.removeClass('disabled'); }, disable: function () { this.$radio.attr('disabled', true); this.$icon.addClass('disabled'); }, itemchecked: function (e) { var radio = $(e.target); this.resetGroup(); this.setState(radio); }, check: function () { this.resetGroup(); this.$radio.prop('checked', true); this.setState(this.$radio); }, uncheck: function () { this.$radio.prop('checked', false); this.setState(this.$radio); }, isChecked: function () { return this.$radio.is(':checked'); } }; // RADIO PLUGIN DEFINITION $.fn.radio = function (option, value) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('radio'); var options = typeof option === 'object' && option; if (!data) $this.data('radio', (data = new Radio(this, options))); if (typeof option === 'string') methodReturn = data[option](value); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.radio.defaults = {}; $.fn.radio.Constructor = Radio; // RADIO DATA-API $(function () { $(window).on('load', function () { //$('i.radio').each(function () { $('.radio-custom > input[type=radio]').each(function () { var $this = $(this); if ($this.data('radio')) return; $this.radio($this.data()); }); }); }); }); /* * Fuel UX Search * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/search',['require','jquery'],function(require) { var $ = require('jquery'); // SEARCH CONSTRUCTOR AND PROTOTYPE var Search = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.search.defaults, options); this.$button = this.$element.find('button') .on('click', $.proxy(this.buttonclicked, this)); this.$input = this.$element.find('input') .on('keydown', $.proxy(this.keypress, this)) .on('keyup', $.proxy(this.keypressed, this)); this.$icon = this.$element.find('i'); this.activeSearch = ''; }; Search.prototype = { constructor: Search, search: function (searchText) { this.$icon.attr('class', 'icon-remove'); this.activeSearch = searchText; this.$element.trigger('searched', searchText); }, clear: function () { this.$icon.attr('class', 'icon-search'); this.activeSearch = ''; this.$input.val(''); this.$element.trigger('cleared'); }, action: function () { var val = this.$input.val(); var inputEmptyOrUnchanged = val === '' || val === this.activeSearch; if (this.activeSearch && inputEmptyOrUnchanged) { this.clear(); } else if (val) { this.search(val); } }, buttonclicked: function (e) { e.preventDefault(); if ($(e.currentTarget).is('.disabled, :disabled')) return; this.action(); }, keypress: function (e) { if (e.which === 13) { e.preventDefault(); } }, keypressed: function (e) { var val, inputPresentAndUnchanged; if (e.which === 13) { e.preventDefault(); this.action(); } else { val = this.$input.val(); inputPresentAndUnchanged = val && (val === this.activeSearch); this.$icon.attr('class', inputPresentAndUnchanged ? 'icon-remove' : 'icon-search'); } }, disable: function () { this.$input.attr('disabled', 'disabled'); this.$button.addClass('disabled'); }, enable: function () { this.$input.removeAttr('disabled'); this.$button.removeClass('disabled'); } }; // SEARCH PLUGIN DEFINITION $.fn.search = function (option) { return this.each(function () { var $this = $(this); var data = $this.data('search'); var options = typeof option === 'object' && option; if (!data) $this.data('search', (data = new Search(this, options))); if (typeof option === 'string') data[option](); }); }; $.fn.search.defaults = {}; $.fn.search.Constructor = Search; // SEARCH DATA-API $(function () { $('body').on('mousedown.search.data-api', '.search', function () { var $this = $(this); if ($this.data('search')) return; $this.search($this.data()); }); }); }); /* * Fuel UX Spinner * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/spinner',['require','jquery'],function(require) { var $ = require('jquery'); // SPINNER CONSTRUCTOR AND PROTOTYPE var Spinner = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.spinner.defaults, options); this.$input = this.$element.find('.spinner-input'); this.$element.on('keyup', this.$input, $.proxy(this.change, this)); if (this.options.hold) { this.$element.on('mousedown', '.spinner-up', $.proxy(function() { this.startSpin(true); } , this)); this.$element.on('mouseup', '.spinner-up, .spinner-down', $.proxy(this.stopSpin, this)); this.$element.on('mouseout', '.spinner-up, .spinner-down', $.proxy(this.stopSpin, this)); this.$element.on('mousedown', '.spinner-down', $.proxy(function() {this.startSpin(false);} , this)); } else { this.$element.on('click', '.spinner-up', $.proxy(function() { this.step(true); } , this)); this.$element.on('click', '.spinner-down', $.proxy(function() { this.step(false); }, this)); } this.switches = { count: 1, enabled: true }; if (this.options.speed === 'medium') { this.switches.speed = 300; } else if (this.options.speed === 'fast') { this.switches.speed = 100; } else { this.switches.speed = 500; } this.lastValue = null; this.render(); if (this.options.disabled) { this.disable(); } }; Spinner.prototype = { constructor: Spinner, render: function () { var inputValue = this.$input.val(); if (inputValue) { this.value(inputValue); } else { this.$input.val(this.options.value); } this.$input.attr('maxlength', (this.options.max + '').split('').length); }, change: function () { var newVal = this.$input.val(); if(newVal/1){ this.options.value = newVal/1; }else{ newVal = newVal.replace(/[^0-9]/g,''); this.$input.val(newVal); this.options.value = newVal/1; } this.triggerChangedEvent(); }, stopSpin: function () { clearTimeout(this.switches.timeout); this.switches.count = 1; this.triggerChangedEvent(); }, triggerChangedEvent: function () { var currentValue = this.value(); if (currentValue === this.lastValue) return; this.lastValue = currentValue; // Primary changed event this.$element.trigger('changed', currentValue); // Undocumented, kept for backward compatibility this.$element.trigger('change'); }, startSpin: function (type) { if (!this.options.disabled) { var divisor = this.switches.count; if (divisor === 1) { this.step(type); divisor = 1; } else if (divisor < 3){ divisor = 1.5; } else if (divisor < 8){ divisor = 2.5; } else { divisor = 4; } this.switches.timeout = setTimeout($.proxy(function() {this.iterator(type);} ,this),this.switches.speed/divisor); this.switches.count++; } }, iterator: function (type) { this.step(type); this.startSpin(type); }, step: function (dir) { var curValue = this.options.value; var limValue = dir ? this.options.max : this.options.min; if ((dir ? curValue < limValue : curValue > limValue)) { var newVal = curValue + (dir ? 1 : -1) * this.options.step; if (dir ? newVal > limValue : newVal < limValue) { this.value(limValue); } else { this.value(newVal); } } else if (this.options.cycle) { var cycleVal = dir ? this.options.min : this.options.max; this.value(cycleVal); } }, value: function (value) { if (!isNaN(parseFloat(value)) && isFinite(value)) { value = parseFloat(value); this.options.value = value; this.$input.val(value); return this; } else { return this.options.value; } }, disable: function () { this.options.disabled = true; this.$input.attr('disabled',''); this.$element.find('button').addClass('disabled'); }, enable: function () { this.options.disabled = false; this.$input.removeAttr("disabled"); this.$element.find('button').removeClass('disabled'); } }; // SPINNER PLUGIN DEFINITION $.fn.spinner = function (option,value) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('spinner'); var options = typeof option === 'object' && option; if (!data) $this.data('spinner', (data = new Spinner(this, options))); if (typeof option === 'string') methodReturn = data[option](value); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.spinner.defaults = { value: 1, min: 1, max: 999, step: 1, hold: true, speed: 'medium', disabled: false }; $.fn.spinner.Constructor = Spinner; // SPINNER DATA-API $(function () { $('body').on('mousedown.spinner.data-api', '.spinner', function () { var $this = $(this); if ($this.data('spinner')) return; $this.spinner($this.data()); }); }); }); /* * Fuel UX Select * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/select',['require','jquery','./util'],function(require) { var $ = require('jquery'); require('./util'); // SELECT CONSTRUCTOR AND PROTOTYPE var Select = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.select.defaults, options); this.$element.on('click', 'a', $.proxy(this.itemclicked, this)); this.$button = this.$element.find('.btn'); this.$label = this.$element.find('.dropdown-label'); this.setDefaultSelection(); if (options.resize === 'auto') { this.resize(); } }; Select.prototype = { constructor: Select, itemclicked: function (e) { this.$selectedItem = $(e.target).parent(); this.$label.text(this.$selectedItem.text()); // pass object including text and any data-attributes // to onchange event var data = this.selectedItem(); // trigger changed event this.$element.trigger('changed', data); e.preventDefault(); }, resize: function() { var newWidth = 0; var sizer = $('<div/>').addClass('select-sizer'); var width = 0; $('body').append(sizer); // iterate through each item to find longest string this.$element.find('a').each(function () { sizer.text($(this).text()); newWidth = sizer.outerWidth(); if(newWidth > width) { width = newWidth; } }); sizer.remove(); this.$label.width(width); }, selectedItem: function() { var txt = this.$selectedItem.text(); return $.extend({ text: txt }, this.$selectedItem.data()); }, selectByText: function(text) { var selector = 'li a:fuelTextExactCI(' + text + ')'; this.selectBySelector(selector); }, selectByValue: function(value) { var selector = 'li[data-value="' + value + '"]'; this.selectBySelector(selector); }, selectByIndex: function(index) { // zero-based index var selector = 'li:eq(' + index + ')'; this.selectBySelector(selector); }, selectBySelector: function(selector) { var item = this.$element.find(selector); this.$selectedItem = item; this.$label.text(this.$selectedItem.text()); }, setDefaultSelection: function() { var selector = 'li[data-selected=true]:first'; var item = this.$element.find(selector); if(item.length === 0) { // select first item this.selectByIndex(0); } else { // select by data-attribute this.selectBySelector(selector); item.removeData('selected'); item.removeAttr('data-selected'); } }, enable: function() { this.$button.removeClass('disabled'); }, disable: function() { this.$button.addClass('disabled'); } }; // SELECT PLUGIN DEFINITION $.fn.select = function (option,value) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('select'); var options = typeof option === 'object' && option; if (!data) $this.data('select', (data = new Select(this, options))); if (typeof option === 'string') methodReturn = data[option](value); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.select.defaults = {}; $.fn.select.Constructor = Select; // SELECT DATA-API $(function () { $(window).on('load', function () { $('.select').each(function () { var $this = $(this); if ($this.data('select')) return; $this.select($this.data()); }); }); $('body').on('mousedown.select.data-api', '.select', function () { var $this = $(this); if ($this.data('select')) return; $this.select($this.data()); }); }); }); /* * Fuel UX Tree * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/tree',['require','jquery'],function(require) { var $ = require('jquery'); // TREE CONSTRUCTOR AND PROTOTYPE var Tree = function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.tree.defaults, options); this.$element.on('click', '.tree-item', $.proxy( function(ev) { this.selectItem(ev.currentTarget); } ,this)); this.$element.on('click', '.tree-folder-header', $.proxy( function(ev) { this.selectFolder(ev.currentTarget); }, this)); this.render(); }; Tree.prototype = { constructor: Tree, render: function () { this.populate(this.$element); }, populate: function ($el) { var self = this; var $parent = $el.parent(); var loader = $parent.find('.tree-loader:eq(0)'); loader.show(); this.options.dataSource.data($el.data(), function (items) { loader.hide(); $.each( items.data, function(index, value) { var $entity; if(value.type === "folder") { $entity = self.$element.find('.tree-folder:eq(0)').clone().show(); $entity.find('.tree-folder-name').html(value.name); $entity.find('.tree-loader').html(self.options.loadingHTML); $entity.find('.tree-folder-header').data(value); } else if (value.type === "item") { $entity = self.$element.find('.tree-item:eq(0)').clone().show(); $entity.find('.tree-item-name').html(value.name); $entity.data(value); } // Decorate $entity with data making the element // easily accessable with libraries like jQuery. // // Values are contained within the object returned // for folders and items as dataAttributes: // // { // name: "An Item", // type: 'item', // dataAttributes = { // 'classes': 'required-item red-text', // 'data-parent': parentId, // 'guid': guid // } // }; var dataAttributes = value.dataAttributes || []; $.each(dataAttributes, function(key, value) { switch (key) { case 'class': case 'classes': case 'className': $entity.addClass(value); break; // id, style, data-* default: $entity.attr(key, value); break; } }); if($el.hasClass('tree-folder-header')) { $parent.find('.tree-folder-content:eq(0)').append($entity); } else { $el.append($entity); } }); // return newly populated folder self.$element.trigger('loaded', $parent); }); }, selectItem: function (el) { var $el = $(el); var $all = this.$element.find('.tree-selected'); var data = []; if (this.options.multiSelect) { $.each($all, function(index, value) { var $val = $(value); if($val[0] !== $el[0]) { data.push( $(value).data() ); } }); } else if ($all[0] !== $el[0]) { $all.removeClass('tree-selected') .find('i').removeClass('icon-ok').addClass('tree-dot'); data.push($el.data()); } var eventType = 'selected'; if($el.hasClass('tree-selected')) { eventType = 'unselected'; $el.removeClass('tree-selected'); $el.find('i').removeClass('icon-ok').addClass('tree-dot'); } else { $el.addClass ('tree-selected'); $el.find('i').removeClass('tree-dot').addClass('icon-ok'); if (this.options.multiSelect) { data.push( $el.data() ); } } if(data.length) { this.$element.trigger('selected', {info: data}); } // Return new list of selected items, the item // clicked, and the type of event: $el.trigger('updated', { info: data, item: $el, eventType: eventType }); }, selectFolder: function (el) { var $el = $(el); var $parent = $el.parent(); var $treeFolderContent = $parent.find('.tree-folder-content'); var $treeFolderContentFirstChild = $treeFolderContent.eq(0); var eventType, classToTarget, classToAdd; if ($el.find('.icon-folder-close').length) { eventType = 'opened'; classToTarget = '.icon-folder-close'; classToAdd = 'icon-folder-open'; $treeFolderContentFirstChild.show(); if (!$treeFolderContent.children().length) { this.populate($el); } } else { eventType = 'closed'; classToTarget = '.icon-folder-open'; classToAdd = 'icon-folder-close'; $treeFolderContentFirstChild.hide(); if (!this.options.cacheItems) { $treeFolderContentFirstChild.empty(); } } $parent.find(classToTarget).eq(0) .removeClass('icon-folder-close icon-folder-open') .addClass(classToAdd); this.$element.trigger(eventType, $el.data()); }, selectedItems: function () { var $sel = this.$element.find('.tree-selected'); var data = []; $.each($sel, function (index, value) { data.push($(value).data()); }); return data; }, // collapses open folders collapse: function () { var cacheItems = this.options.cacheItems; // find open folders this.$element.find('.icon-folder-open').each(function () { // update icon class var $this = $(this) .removeClass('icon-folder-close icon-folder-open') .addClass('icon-folder-close'); // "close" or empty folder contents var $parent = $this.parent().parent(); var $folder = $parent.children('.tree-folder-content'); $folder.hide(); if (!cacheItems) { $folder.empty(); } }); } }; // TREE PLUGIN DEFINITION $.fn.tree = function (option, value) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('tree'); var options = typeof option === 'object' && option; if (!data) $this.data('tree', (data = new Tree(this, options))); if (typeof option === 'string') methodReturn = data[option](value); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.tree.defaults = { multiSelect: false, loadingHTML: '<div>Loading...</div>', cacheItems: true }; $.fn.tree.Constructor = Tree; }); /* * Fuel UX Wizard * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/wizard',['require','jquery'],function (require) { var $ = require('jquery'); // WIZARD CONSTRUCTOR AND PROTOTYPE var Wizard = function (element, options) { var kids; this.$element = $(element); this.options = $.extend({}, $.fn.wizard.defaults, options); this.currentStep = this.options.selectedItem.step; this.numSteps = this.$element.find('.steps li').length; this.$prevBtn = this.$element.find('button.btn-prev'); this.$nextBtn = this.$element.find('button.btn-next'); kids = this.$nextBtn.children().detach(); this.nextText = $.trim(this.$nextBtn.text()); this.$nextBtn.append(kids); // handle events this.$prevBtn.on('click', $.proxy(this.previous, this)); this.$nextBtn.on('click', $.proxy(this.next, this)); this.$element.on('click', 'li.complete', $.proxy(this.stepclicked, this)); if(this.currentStep > 1) { this.selectedItem(this.options.selectedItem); } }; Wizard.prototype = { constructor: Wizard, setState: function () { var canMovePrev = (this.currentStep > 1); var firstStep = (this.currentStep === 1); var lastStep = (this.currentStep === this.numSteps); // disable buttons based on current step this.$prevBtn.attr('disabled', (firstStep === true || canMovePrev === false)); // change button text of last step, if specified var data = this.$nextBtn.data(); if (data && data.last) { this.lastText = data.last; if (typeof this.lastText !== 'undefined') { // replace text var text = (lastStep !== true) ? this.nextText : this.lastText; var kids = this.$nextBtn.children().detach(); this.$nextBtn.text(text).append(kids); } } // reset classes for all steps var $steps = this.$element.find('li'); $steps.removeClass('active').removeClass('complete'); $steps.find('span.badge').removeClass('badge-info').removeClass('badge-success'); // set class for all previous steps var prevSelector = 'li:lt(' + (this.currentStep - 1) + ')'; var $prevSteps = this.$element.find(prevSelector); $prevSteps.addClass('complete'); $prevSteps.find('span.badge').addClass('badge-success'); // set class for current step var currentSelector = 'li:eq(' + (this.currentStep - 1) + ')'; var $currentStep = this.$element.find(currentSelector); $currentStep.addClass('active'); $currentStep.find('span.badge').addClass('badge-info'); // set display of target element var target = $currentStep.data().target; $('.step-pane').removeClass('active'); $(target).addClass('active'); // reset the wizard position to the left $('.wizard .steps').attr('style','margin-left: 0'); // check if the steps are wider than the container div var totalWidth = 0; $('.wizard .steps > li').each(function () { totalWidth += $(this).outerWidth(); }); var containerWidth = 0; if ($('.wizard .actions').length) { containerWidth = $('.wizard').width() - $('.wizard .actions').outerWidth(); } else { containerWidth = $('.wizard').width(); } if (totalWidth > containerWidth) { // set the position so that the last step is on the right var newMargin = totalWidth - containerWidth; $('.wizard .steps').attr('style','margin-left: -' + newMargin + 'px'); // set the position so that the active step is in a good // position if it has been moved out of view if ($('.wizard li.active').position().left < 200) { newMargin += $('.wizard li.active').position().left - 200; if (newMargin < 1) { $('.wizard .steps').attr('style','margin-left: 0'); } else { $('.wizard .steps').attr('style','margin-left: -' + newMargin + 'px'); } } } this.$element.trigger('changed'); }, stepclicked: function (e) { var li = $(e.currentTarget); var index = $('.steps li').index(li); var evt = $.Event('stepclick'); this.$element.trigger(evt, {step: index + 1}); if (evt.isDefaultPrevented()) return; this.currentStep = (index + 1); this.setState(); }, previous: function () { var canMovePrev = (this.currentStep > 1); if (canMovePrev) { var e = $.Event('change'); this.$element.trigger(e, {step: this.currentStep, direction: 'previous'}); if (e.isDefaultPrevented()) return; this.currentStep -= 1; this.setState(); } }, next: function () { var canMoveNext = (this.currentStep + 1 <= this.numSteps); var lastStep = (this.currentStep === this.numSteps); if (canMoveNext) { var e = $.Event('change'); this.$element.trigger(e, {step: this.currentStep, direction: 'next'}); if (e.isDefaultPrevented()) return; this.currentStep += 1; this.setState(); } else if (lastStep) { this.$element.trigger('finished'); } }, selectedItem: function (selectedItem) { var retVal, step; if(selectedItem) { step = selectedItem.step || -1; if(step >= 1 && step <= this.numSteps) { this.currentStep = step; this.setState(); } retVal = this; } else { retVal = { step: this.currentStep }; } return retVal; } }; // WIZARD PLUGIN DEFINITION $.fn.wizard = function (option, value) { var methodReturn; var $set = this.each(function () { var $this = $(this); var data = $this.data('wizard'); var options = typeof option === 'object' && option; if (!data) $this.data('wizard', (data = new Wizard(this, options))); if (typeof option === 'string') methodReturn = data[option](value); }); return (methodReturn === undefined) ? $set : methodReturn; }; $.fn.wizard.defaults = { selectedItem: {step:1} }; $.fn.wizard.Constructor = Wizard; // WIZARD DATA-API $(function () { $('body').on('mousedown.wizard.data-api', '.wizard', function () { var $this = $(this); if ($this.data('wizard')) return; $this.wizard($this.data()); }); }); }); /* * Fuel UX * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ define('fuelux/all',['require','jquery','bootstrap/bootstrap-affix','bootstrap/bootstrap-alert','bootstrap/bootstrap-button','bootstrap/bootstrap-carousel','bootstrap/bootstrap-collapse','bootstrap/bootstrap-dropdown','bootstrap/bootstrap-modal','bootstrap/bootstrap-popover','bootstrap/bootstrap-scrollspy','bootstrap/bootstrap-tab','bootstrap/bootstrap-tooltip','bootstrap/bootstrap-transition','bootstrap/bootstrap-typeahead','fuelux/checkbox','fuelux/combobox','fuelux/datagrid','fuelux/intelligent-dropdown','fuelux/pillbox','fuelux/radio','fuelux/search','fuelux/spinner','fuelux/select','fuelux/tree','fuelux/wizard'],function (require) { require('jquery'); require('bootstrap/bootstrap-affix'); require('bootstrap/bootstrap-alert'); require('bootstrap/bootstrap-button'); require('bootstrap/bootstrap-carousel'); require('bootstrap/bootstrap-collapse'); require('bootstrap/bootstrap-dropdown'); require('bootstrap/bootstrap-modal'); require('bootstrap/bootstrap-popover'); require('bootstrap/bootstrap-scrollspy'); require('bootstrap/bootstrap-tab'); require('bootstrap/bootstrap-tooltip'); require('bootstrap/bootstrap-transition'); require('bootstrap/bootstrap-typeahead'); require('fuelux/checkbox'); require('fuelux/combobox'); require('fuelux/datagrid'); require('fuelux/intelligent-dropdown'); require('fuelux/pillbox'); require('fuelux/radio'); require('fuelux/search'); require('fuelux/spinner'); require('fuelux/select'); require('fuelux/tree'); require('fuelux/wizard'); }); }());
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u1796\u17d2\u179a\u17b9\u1780", "\u179b\u17d2\u1784\u17b6\u1785" ], "DAY": [ "\u17a2\u17b6\u1791\u17b7\u178f\u17d2\u1799", "\u1785\u1793\u17d2\u1791", "\u17a2\u1784\u17d2\u1782\u17b6\u179a", "\u1796\u17bb\u1792", "\u1796\u17d2\u179a\u17a0\u179f\u17d2\u1794\u178f\u17b7\u17cd", "\u179f\u17bb\u1780\u17d2\u179a", "\u179f\u17c5\u179a\u17cd" ], "ERANAMES": [ "\u1798\u17bb\u1793\u200b\u1782\u17d2\u179a\u17b7\u179f\u17d2\u178f\u179f\u1780\u179a\u17b6\u1787", "\u1782\u17d2\u179a\u17b7\u179f\u17d2\u178f\u179f\u1780\u179a\u17b6\u1787" ], "ERAS": [ "\u1798\u17bb\u1793 \u1782.\u179f.", "\u1782.\u179f." ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "\u1798\u1780\u179a\u17b6", "\u1780\u17bb\u1798\u17d2\u1797\u17c8", "\u1798\u17b8\u1793\u17b6", "\u1798\u17c1\u179f\u17b6", "\u17a7\u179f\u1797\u17b6", "\u1798\u17b7\u1790\u17bb\u1793\u17b6", "\u1780\u1780\u17d2\u1780\u178a\u17b6", "\u179f\u17b8\u17a0\u17b6", "\u1780\u1789\u17d2\u1789\u17b6", "\u178f\u17bb\u179b\u17b6", "\u179c\u17b7\u1785\u17d2\u1786\u17b7\u1780\u17b6", "\u1792\u17d2\u1793\u17bc" ], "SHORTDAY": [ "\u17a2\u17b6\u1791\u17b7\u178f\u17d2\u1799", "\u1785\u1793\u17d2\u1791", "\u17a2\u1784\u17d2\u1782\u17b6\u179a", "\u1796\u17bb\u1792", "\u1796\u17d2\u179a\u17a0\u179f\u17d2\u1794\u178f\u17b7\u17cd", "\u179f\u17bb\u1780\u17d2\u179a", "\u179f\u17c5\u179a\u17cd" ], "SHORTMONTH": [ "\u1798\u1780\u179a\u17b6", "\u1780\u17bb\u1798\u17d2\u1797\u17c8", "\u1798\u17b8\u1793\u17b6", "\u1798\u17c1\u179f\u17b6", "\u17a7\u179f\u1797\u17b6", "\u1798\u17b7\u1790\u17bb\u1793\u17b6", "\u1780\u1780\u17d2\u1780\u178a\u17b6", "\u179f\u17b8\u17a0\u17b6", "\u1780\u1789\u17d2\u1789\u17b6", "\u178f\u17bb\u179b\u17b6", "\u179c\u17b7\u1785\u17d2\u1786\u17b7\u1780\u17b6", "\u1792\u17d2\u1793\u17bc" ], "STANDALONEMONTH": [ "\u1798\u1780\u179a\u17b6", "\u1780\u17bb\u1798\u17d2\u1797\u17c8", "\u1798\u17b8\u1793\u17b6", "\u1798\u17c1\u179f\u17b6", "\u17a7\u179f\u1797\u17b6", "\u1798\u17b7\u1790\u17bb\u1793\u17b6", "\u1780\u1780\u17d2\u1780\u178a\u17b6", "\u179f\u17b8\u17a0\u17b6", "\u1780\u1789\u17d2\u1789\u17b6", "\u178f\u17bb\u179b\u17b6", "\u179c\u17b7\u1785\u17d2\u1786\u17b7\u1780\u17b6", "\u1792\u17d2\u1793\u17bc" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "d/M/yy h:mm a", "shortDate": "d/M/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Riel", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "km-kh", "pluralCat": function(n, opt_precision) { return PLURAL_CATEGORY.OTHER;} }); }]);
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'table', 'gu', { border: 'કોઠાની બાજુ(બોર્ડર) સાઇઝ', caption: 'મથાળું/કૅપ્શન ', cell: { menu: 'કોષના ખાના', insertBefore: 'પહેલાં કોષ ઉમેરવો', insertAfter: 'પછી કોષ ઉમેરવો', deleteCell: 'કોષ ડિલીટ/કાઢી નાખવો', merge: 'કોષ ભેગા કરવા', mergeRight: 'જમણી બાજુ ભેગા કરવા', mergeDown: 'નીચે ભેગા કરવા', splitHorizontal: 'કોષને સમસ્તરીય વિભાજન કરવું', splitVertical: 'કોષને સીધું ને ઊભું વિભાજન કરવું', title: 'સેલના ગુણ', cellType: 'સેલનો પ્રકાર', rowSpan: 'આડી કટારની જગ્યા', colSpan: 'ઊભી કતારની જગ્યા', wordWrap: 'વર્ડ રેપ', hAlign: 'સપાટ લાઈનદોરી', vAlign: 'ઊભી લાઈનદોરી', alignBaseline: 'બસે લાઈન', bgColor: 'પાછાળનો રંગ', borderColor: 'બોર્ડેર રંગ', data: 'સ્વીકૃત માહિતી', header: 'મથાળું', yes: 'હા', no: 'ના', invalidWidth: 'સેલની પોહલાઈ આંકડો હોવો જોઈએ.', invalidHeight: 'સેલની ઊંચાઈ આંકડો હોવો જોઈએ.', invalidRowSpan: 'રો સ્પાન આંકડો હોવો જોઈએ.', invalidColSpan: 'કોલમ સ્પાન આંકડો હોવો જોઈએ.', chooseColor: 'પસંદ કરવું' }, cellPad: 'સેલ પૅડિંગ', cellSpace: 'સેલ અંતર', column: { menu: 'કૉલમ/ઊભી કટાર', insertBefore: 'પહેલાં કૉલમ/ઊભી કટાર ઉમેરવી', insertAfter: 'પછી કૉલમ/ઊભી કટાર ઉમેરવી', deleteColumn: 'કૉલમ/ઊભી કટાર ડિલીટ/કાઢી નાખવી' }, columns: 'કૉલમ/ઊભી કટાર', deleteTable: 'કોઠો ડિલીટ/કાઢી નાખવું', headers: 'મથાળા', headersBoth: 'બેવું', headersColumn: 'પહેલી ઊભી કટાર', headersNone: 'નથી ', headersRow: 'પહેલી કટાર', invalidBorder: 'બોર્ડર એક આંકડો હોવો જોઈએ', invalidCellPadding: 'સેલની અંદરની જગ્યા સુન્ય કરતા વધારે હોવી જોઈએ.', invalidCellSpacing: 'સેલ વચ્ચેની જગ્યા સુન્ય કરતા વધારે હોવી જોઈએ.', invalidCols: 'ઉભી કટાર, 0 કરતા વધારે હોવી જોઈએ.', invalidHeight: 'ટેબલની ઊંચાઈ આંકડો હોવો જોઈએ.', invalidRows: 'આડી કટાર, 0 કરતા વધારે હોવી જોઈએ.', invalidWidth: 'ટેબલની પોહલાઈ આંકડો હોવો જોઈએ.', menu: 'ટેબલ, કોઠાનું મથાળું', row: { menu: 'પંક્તિના ખાના', insertBefore: 'પહેલાં પંક્તિ ઉમેરવી', insertAfter: 'પછી પંક્તિ ઉમેરવી', deleteRow: 'પંક્તિઓ ડિલીટ/કાઢી નાખવી' }, rows: 'પંક્તિના ખાના', summary: 'ટૂંકો એહેવાલ', title: 'ટેબલ, કોઠાનું મથાળું', toolbar: 'ટેબલ, કોઠો', widthPc: 'પ્રતિશત', widthPx: 'પિકસલ', widthUnit: 'પોહાલાઈ એકમ' });
/*! elasticsearch - v6.1.0 - 2015-08-18 * http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html * Copyright (c) 2015 Elasticsearch BV; Licensed Apache-2.0 */ ;(function () { /* prevent lodash from detecting external amd loaders */var define; ;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ },{}],2:[function(require,module,exports){ // // The shims in this file are not fully implemented shims for the ES5 // features, but do work for the particular usecases there is in // the other modules. // var toString = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; // Array.isArray is supported in IE9 function isArray(xs) { return toString.call(xs) === '[object Array]'; } exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray; // Array.prototype.indexOf is supported in IE9 exports.indexOf = function indexOf(xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0; i < xs.length; i++) { if (x === xs[i]) return i; } return -1; }; // Array.prototype.filter is supported in IE9 exports.filter = function filter(xs, fn) { if (xs.filter) return xs.filter(fn); var res = []; for (var i = 0; i < xs.length; i++) { if (fn(xs[i], i, xs)) res.push(xs[i]); } return res; }; // Array.prototype.forEach is supported in IE9 exports.forEach = function forEach(xs, fn, self) { if (xs.forEach) return xs.forEach(fn, self); for (var i = 0; i < xs.length; i++) { fn.call(self, xs[i], i, xs); } }; // Array.prototype.map is supported in IE9 exports.map = function map(xs, fn) { if (xs.map) return xs.map(fn); var out = new Array(xs.length); for (var i = 0; i < xs.length; i++) { out[i] = fn(xs[i], i, xs); } return out; }; // Array.prototype.reduce is supported in IE9 exports.reduce = function reduce(array, callback, opt_initialValue) { if (array.reduce) return array.reduce(callback, opt_initialValue); var value, isValueSet = false; if (2 < arguments.length) { value = opt_initialValue; isValueSet = true; } for (var i = 0, l = array.length; l > i; ++i) { if (array.hasOwnProperty(i)) { if (isValueSet) { value = callback(value, array[i], i, array); } else { value = array[i]; isValueSet = true; } } } return value; }; // String.prototype.substr - negative index don't work in IE8 if ('ab'.substr(-1) !== 'b') { exports.substr = function (str, start, length) { // did we get a negative start, calculate how much it is from the beginning of the string if (start < 0) start = str.length + start; // call the original function return str.substr(start, length); }; } else { exports.substr = function (str, start, length) { return str.substr(start, length); }; } // String.prototype.trim is supported in IE9 exports.trim = function (str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); }; // Function.prototype.bind is supported in IE9 exports.bind = function () { var args = Array.prototype.slice.call(arguments); var fn = args.shift(); if (fn.bind) return fn.bind.apply(fn, args); var self = args.shift(); return function () { fn.apply(self, args.concat([Array.prototype.slice.call(arguments)])); }; }; // Object.create is supported in IE9 function create(prototype, properties) { var object; if (prototype === null) { object = { '__proto__' : null }; } else { if (typeof prototype !== 'object') { throw new TypeError( 'typeof prototype[' + (typeof prototype) + '] != \'object\'' ); } var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (typeof properties !== 'undefined' && Object.defineProperties) { Object.defineProperties(object, properties); } return object; } exports.create = typeof Object.create === 'function' ? Object.create : create; // Object.keys and Object.getOwnPropertyNames is supported in IE9 however // they do show a description and number property on Error objects function notObject(object) { return ((typeof object != "object" && typeof object != "function") || object === null); } function keysShim(object) { if (notObject(object)) { throw new TypeError("Object.keys called on a non-object"); } var result = []; for (var name in object) { if (hasOwnProperty.call(object, name)) { result.push(name); } } return result; } // getOwnPropertyNames is almost the same as Object.keys one key feature // is that it returns hidden properties, since that can't be implemented, // this feature gets reduced so it just shows the length property on arrays function propertyShim(object) { if (notObject(object)) { throw new TypeError("Object.getOwnPropertyNames called on a non-object"); } var result = keysShim(object); if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { result.push('length'); } return result; } var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? Object.getOwnPropertyNames : propertyShim; if (new Error().hasOwnProperty('description')) { var ERROR_PROPERTY_FILTER = function (obj, array) { if (toString.call(obj) === '[object Error]') { array = exports.filter(array, function (name) { return name !== 'description' && name !== 'number' && name !== 'message'; }); } return array; }; exports.keys = function (object) { return ERROR_PROPERTY_FILTER(object, keys(object)); }; exports.getOwnPropertyNames = function (object) { return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object)); }; } else { exports.keys = keys; exports.getOwnPropertyNames = getOwnPropertyNames; } // Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements function valueObject(value, key) { return { value: value[key] }; } if (typeof Object.getOwnPropertyDescriptor === 'function') { try { Object.getOwnPropertyDescriptor({'a': 1}, 'a'); exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; } catch (e) { // IE8 dom element issue - use a try catch and default to valueObject exports.getOwnPropertyDescriptor = function (value, key) { try { return Object.getOwnPropertyDescriptor(value, key); } catch (e) { return valueObject(value, key); } }; } } else { exports.getOwnPropertyDescriptor = valueObject; } },{}],3:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // UTILITY var util = require('util'); var shims = require('_shims'); var pSlice = Array.prototype.slice; // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; this.message = options.message || getMessage(this); }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (util.isUndefined(value)) { return '' + value; } if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; } function truncate(s, n) { if (util.isString(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (util.isBuffer(actual) && util.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (!util.isObject(actual) && !util.isObject(expected)) { return actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try { var ka = shims.keys(a), kb = shims.keys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (util.isString(expected)) { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; },{"_shims":2,"util":8}],4:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!util.isNumber(n) || n < 0) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (util.isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (util.isUndefined(handler)) return false; if (util.isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (util.isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!util.isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, util.isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (util.isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (util.isObject(this._events[type]) && !this._events[type].warned) { var m; if (!util.isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!util.isFunction(listener)) throw TypeError('listener must be a function'); function g() { this.removeListener(type, g); listener.apply(this, arguments); } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!util.isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (util.isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (util.isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (util.isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (util.isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (util.isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; },{"util":8}],5:[function(require,module,exports){ var process=require("__browserify_process");// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); var shims = require('_shims'); // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (!util.isString(path)) { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(shims.filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = shims.substr(path, -1) === '/'; // Normalize the path path = normalizeArray(shims.filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(shims.filter(paths, function(p, index) { if (!util.isString(p)) { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; },{"__browserify_process":13,"_shims":2,"util":8}],6:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Query String Utilities var QueryString = exports; var util = require('util'); var shims = require('_shims'); var Buffer = require('buffer').Buffer; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function charCode(c) { return c.charCodeAt(0); } // a safe fast alternative to decodeURIComponent QueryString.unescapeBuffer = function(s, decodeSpaces) { var out = new Buffer(s.length); var state = 'CHAR'; // states: CHAR, HEX0, HEX1 var n, m, hexchar; for (var inIndex = 0, outIndex = 0; inIndex <= s.length; inIndex++) { var c = s.charCodeAt(inIndex); switch (state) { case 'CHAR': switch (c) { case charCode('%'): n = 0; m = 0; state = 'HEX0'; break; case charCode('+'): if (decodeSpaces) c = charCode(' '); // pass thru default: out[outIndex++] = c; break; } break; case 'HEX0': state = 'HEX1'; hexchar = c; if (charCode('0') <= c && c <= charCode('9')) { n = c - charCode('0'); } else if (charCode('a') <= c && c <= charCode('f')) { n = c - charCode('a') + 10; } else if (charCode('A') <= c && c <= charCode('F')) { n = c - charCode('A') + 10; } else { out[outIndex++] = charCode('%'); out[outIndex++] = c; state = 'CHAR'; break; } break; case 'HEX1': state = 'CHAR'; if (charCode('0') <= c && c <= charCode('9')) { m = c - charCode('0'); } else if (charCode('a') <= c && c <= charCode('f')) { m = c - charCode('a') + 10; } else if (charCode('A') <= c && c <= charCode('F')) { m = c - charCode('A') + 10; } else { out[outIndex++] = charCode('%'); out[outIndex++] = hexchar; out[outIndex++] = c; break; } out[outIndex++] = 16 * n + m; break; } } // TODO support returning arbitrary buffers. return out.slice(0, outIndex - 1); }; QueryString.unescape = function(s, decodeSpaces) { return QueryString.unescapeBuffer(s, decodeSpaces).toString(); }; QueryString.escape = function(str) { return encodeURIComponent(str); }; var stringifyPrimitive = function(v) { if (util.isString(v)) return v; if (util.isBoolean(v)) return v ? 'true' : 'false'; if (util.isNumber(v)) return isFinite(v) ? v : ''; return ''; }; QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (util.isNull(obj)) { obj = undefined; } if (util.isObject(obj)) { return shims.map(shims.keys(obj), function(k) { var ks = QueryString.escape(stringifyPrimitive(k)) + eq; if (util.isArray(obj[k])) { return shims.map(obj[k], function(v) { return ks + QueryString.escape(stringifyPrimitive(v)); }).join(sep); } else { return ks + QueryString.escape(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return QueryString.escape(stringifyPrimitive(name)) + eq + QueryString.escape(stringifyPrimitive(obj)); }; // Parse a key=val string. QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (!util.isString(qs) || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && util.isNumber(options.maxKeys)) { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } try { k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); } catch (e) { k = QueryString.unescape(kstr, true); v = QueryString.unescape(vstr, true); } if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (util.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; },{"_shims":2,"buffer":10,"util":8}],7:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var punycode = { encode : function (s) { return s } }; var util = require('util'); var shims = require('_shims'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = shims.trim(rest); var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a puny coded representation of "domain". // It only converts the part of the domain name that // has non ASCII characters. I.e. it dosent matter if // you call it with a domain that already is in ASCII. var domainArray = this.hostname.split('.'); var newOut = []; for (var i = 0; i < domainArray.length; ++i) { var s = domainArray[i]; newOut.push(s.match(/[^A-Za-z0-9_-]/) ? 'xn--' + punycode.encode(s) : s); } this.hostname = newOut.join('.'); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && shims.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && shims.substr(protocol, -1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); shims.forEach(shims.keys(this), function(k) { result[k] = this[k]; }, this); // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative shims.forEach(shims.keys(relative), function(k) { if (k !== 'protocol') result[k] = relative[k]; }); //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { shims.forEach(shims.keys(relative), function(k) { result[k] = relative[k]; }); result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last == '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (shims.substr(srcPath.join('/'), -1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; },{"_shims":2,"querystring":6,"util":8}],8:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var shims = require('_shims'); var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; shims.forEach(array, function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = shims.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = shims.getOwnPropertyNames(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } shims.forEach(keys, function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (shims.indexOf(ctx.seen, desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = shims.reduce(output, function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return shims.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && objectToString(e) === '[object Error]'; } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.binarySlice === 'function' ; } exports.isBuffer = isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = shims.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = shims.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } },{"_shims":2}],9:[function(require,module,exports){ exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isBE ? 0 : (nBytes - 1), d = isBE ? 1 : -1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isBE ? (nBytes - 1) : 0, d = isBE ? -1 : 1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],10:[function(require,module,exports){ var assert; exports.Buffer = Buffer; exports.SlowBuffer = Buffer; Buffer.poolSize = 8192; exports.INSPECT_MAX_BYTES = 50; function stringtrim(str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); } function Buffer(subject, encoding, offset) { if(!assert) assert= require('assert'); if (!(this instanceof Buffer)) { return new Buffer(subject, encoding, offset); } this.parent = this; this.offset = 0; // Work-around: node's base64 implementation // allows for non-padded strings while base64-js // does not.. if (encoding == "base64" && typeof subject == "string") { subject = stringtrim(subject); while (subject.length % 4 != 0) { subject = subject + "="; } } var type; // Are we slicing? if (typeof offset === 'number') { this.length = coerce(encoding); // slicing works, with limitations (no parent tracking/update) // check https://github.com/toots/buffer-browserify/issues/19 for (var i = 0; i < this.length; i++) { this[i] = subject.get(i+offset); } } else { // Find the length switch (type = typeof subject) { case 'number': this.length = coerce(subject); break; case 'string': this.length = Buffer.byteLength(subject, encoding); break; case 'object': // Assume object is an array this.length = coerce(subject.length); break; default: throw new TypeError('First argument needs to be a number, ' + 'array or string.'); } // Treat array-ish objects as a byte array. if (isArrayIsh(subject)) { for (var i = 0; i < this.length; i++) { if (subject instanceof Buffer) { this[i] = subject.readUInt8(i); } else { // Round-up subject[i] to a UInt8. // e.g.: ((-432 % 256) + 256) % 256 = (-176 + 256) % 256 // = 80 this[i] = ((subject[i] % 256) + 256) % 256; } } } else if (type == 'string') { // We are a string this.length = this.write(subject, 0, encoding); } else if (type === 'number') { for (var i = 0; i < this.length; i++) { this[i] = 0; } } } } Buffer.prototype.get = function get(i) { if (i < 0 || i >= this.length) throw new Error('oob'); return this[i]; }; Buffer.prototype.set = function set(i, v) { if (i < 0 || i >= this.length) throw new Error('oob'); return this[i] = v; }; Buffer.byteLength = function (str, encoding) { switch (encoding || "utf8") { case 'hex': return str.length / 2; case 'utf8': case 'utf-8': return utf8ToBytes(str).length; case 'ascii': case 'binary': return str.length; case 'base64': return base64ToBytes(str).length; default: throw new Error('Unknown encoding'); } }; Buffer.prototype.utf8Write = function (string, offset, length) { var bytes, pos; return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length); }; Buffer.prototype.asciiWrite = function (string, offset, length) { var bytes, pos; return Buffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length); }; Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite; Buffer.prototype.base64Write = function (string, offset, length) { var bytes, pos; return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length); }; Buffer.prototype.base64Slice = function (start, end) { var bytes = Array.prototype.slice.apply(this, arguments) return require("base64-js").fromByteArray(bytes); }; Buffer.prototype.utf8Slice = function () { var bytes = Array.prototype.slice.apply(this, arguments); var res = ""; var tmp = ""; var i = 0; while (i < bytes.length) { if (bytes[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]); tmp = ""; } else tmp += "%" + bytes[i].toString(16); i++; } return res + decodeUtf8Char(tmp); } Buffer.prototype.asciiSlice = function () { var bytes = Array.prototype.slice.apply(this, arguments); var ret = ""; for (var i = 0; i < bytes.length; i++) ret += String.fromCharCode(bytes[i]); return ret; } Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice; Buffer.prototype.inspect = function() { var out = [], len = this.length; for (var i = 0; i < len; i++) { out[i] = toHex(this[i]); if (i == exports.INSPECT_MAX_BYTES) { out[i + 1] = '...'; break; } } return '<Buffer ' + out.join(' ') + '>'; }; Buffer.prototype.hexSlice = function(start, end) { var len = this.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; i++) { out += toHex(this[i]); } return out; }; Buffer.prototype.toString = function(encoding, start, end) { encoding = String(encoding || 'utf8').toLowerCase(); start = +start || 0; if (typeof end == 'undefined') end = this.length; // Fastpath empty strings if (+end == start) { return ''; } switch (encoding) { case 'hex': return this.hexSlice(start, end); case 'utf8': case 'utf-8': return this.utf8Slice(start, end); case 'ascii': return this.asciiSlice(start, end); case 'binary': return this.binarySlice(start, end); case 'base64': return this.base64Slice(start, end); case 'ucs2': case 'ucs-2': return this.ucs2Slice(start, end); default: throw new Error('Unknown encoding'); } }; Buffer.prototype.hexWrite = function(string, offset, length) { offset = +offset || 0; var remaining = this.length - offset; if (!length) { length = remaining; } else { length = +length; if (length > remaining) { length = remaining; } } // must be an even number of digits var strLen = string.length; if (strLen % 2) { throw new Error('Invalid hex string'); } if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; i++) { var b = parseInt(string.substr(i * 2, 2), 16); if (isNaN(b)) throw new Error('Invalid hex string'); this[offset + i] = b; } Buffer._charsWritten = i * 2; return i; }; Buffer.prototype.write = function(string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length; length = undefined; } } else { // legacy var swap = encoding; encoding = offset; offset = length; length = swap; } offset = +offset || 0; var remaining = this.length - offset; if (!length) { length = remaining; } else { length = +length; if (length > remaining) { length = remaining; } } encoding = String(encoding || 'utf8').toLowerCase(); switch (encoding) { case 'hex': return this.hexWrite(string, offset, length); case 'utf8': case 'utf-8': return this.utf8Write(string, offset, length); case 'ascii': return this.asciiWrite(string, offset, length); case 'binary': return this.binaryWrite(string, offset, length); case 'base64': return this.base64Write(string, offset, length); case 'ucs2': case 'ucs-2': return this.ucs2Write(string, offset, length); default: throw new Error('Unknown encoding'); } }; // slice(start, end) function clamp(index, len, defaultValue) { if (typeof index !== 'number') return defaultValue; index = ~~index; // Coerce to integer. if (index >= len) return len; if (index >= 0) return index; index += len; if (index >= 0) return index; return 0; } Buffer.prototype.slice = function(start, end) { var len = this.length; start = clamp(start, len, 0); end = clamp(end, len, len); return new Buffer(this, end - start, +start); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function(target, target_start, start, end) { var source = this; start || (start = 0); if (end === undefined || isNaN(end)) { end = this.length; } target_start || (target_start = 0); if (end < start) throw new Error('sourceEnd < sourceStart'); // Copy 0 bytes; we're done if (end === start) return 0; if (target.length == 0 || source.length == 0) return 0; if (target_start < 0 || target_start >= target.length) { throw new Error('targetStart out of bounds'); } if (start < 0 || start >= source.length) { throw new Error('sourceStart out of bounds'); } if (end < 0 || end > source.length) { throw new Error('sourceEnd out of bounds'); } // Are we oob? if (end > this.length) { end = this.length; } if (target.length - target_start < end - start) { end = target.length - target_start + start; } var temp = []; for (var i=start; i<end; i++) { assert.ok(typeof this[i] !== 'undefined', "copying undefined buffer bytes!"); temp.push(this[i]); } for (var i=target_start; i<target_start+temp.length; i++) { target[i] = temp[i-target_start]; } }; // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function fill(value, start, end) { value || (value = 0); start || (start = 0); end || (end = this.length); if (typeof value === 'string') { value = value.charCodeAt(0); } if (!(typeof value === 'number') || isNaN(value)) { throw new Error('value is not a number'); } if (end < start) throw new Error('end < start'); // Fill 0 bytes; we're done if (end === start) return 0; if (this.length == 0) return 0; if (start < 0 || start >= this.length) { throw new Error('start out of bounds'); } if (end < 0 || end > this.length) { throw new Error('end out of bounds'); } for (var i = start; i < end; i++) { this[i] = value; } } // Static methods Buffer.isBuffer = function isBuffer(b) { return b instanceof Buffer; }; Buffer.concat = function (list, totalLength) { if (!isArray(list)) { throw new Error("Usage: Buffer.concat(list, [totalLength])\n \ list should be an Array."); } if (list.length === 0) { return new Buffer(0); } else if (list.length === 1) { return list[0]; } if (typeof totalLength !== 'number') { totalLength = 0; for (var i = 0; i < list.length; i++) { var buf = list[i]; totalLength += buf.length; } } var buffer = new Buffer(totalLength); var pos = 0; for (var i = 0; i < list.length; i++) { var buf = list[i]; buf.copy(buffer, pos); pos += buf.length; } return buffer; }; Buffer.isEncoding = function(encoding) { switch ((encoding + '').toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; default: return false; } }; // helpers function coerce(length) { // Coerce length to a number (possibly NaN), round up // in case it's fractional (e.g. 123.456) then do a // double negate to coerce a NaN to 0. Easy, right? length = ~~Math.ceil(+length); return length < 0 ? 0 : length; } function isArray(subject) { return (Array.isArray || function(subject){ return {}.toString.apply(subject) == '[object Array]' }) (subject) } function isArrayIsh(subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number'; } function toHex(n) { if (n < 16) return '0' + n.toString(16); return n.toString(16); } function utf8ToBytes(str) { var byteArray = []; for (var i = 0; i < str.length; i++) if (str.charCodeAt(i) <= 0x7F) byteArray.push(str.charCodeAt(i)); else { var h = encodeURIComponent(str.charAt(i)).substr(1).split('%'); for (var j = 0; j < h.length; j++) byteArray.push(parseInt(h[j], 16)); } return byteArray; } function asciiToBytes(str) { var byteArray = [] for (var i = 0; i < str.length; i++ ) // Node's code seems to be doing this and not & 0x7F.. byteArray.push( str.charCodeAt(i) & 0xFF ); return byteArray; } function base64ToBytes(str) { return require("base64-js").toByteArray(str); } function blitBuffer(src, dst, offset, length) { var pos, i = 0; while (i < length) { if ((i+offset >= dst.length) || (i >= src.length)) break; dst[i + offset] = src[i]; i++; } return i; } function decodeUtf8Char(str) { try { return decodeURIComponent(str); } catch (err) { return String.fromCharCode(0xFFFD); // UTF 8 invalid char } } // read/write bit-twiddling Buffer.prototype.readUInt8 = function(offset, noAssert) { var buffer = this; if (!noAssert) { assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset < buffer.length, 'Trying to read beyond buffer length'); } if (offset >= buffer.length) return; return buffer[offset]; }; function readUInt16(buffer, offset, isBigEndian, noAssert) { var val = 0; if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 1 < buffer.length, 'Trying to read beyond buffer length'); } if (offset >= buffer.length) return 0; if (isBigEndian) { val = buffer[offset] << 8; if (offset + 1 < buffer.length) { val |= buffer[offset + 1]; } } else { val = buffer[offset]; if (offset + 1 < buffer.length) { val |= buffer[offset + 1] << 8; } } return val; } Buffer.prototype.readUInt16LE = function(offset, noAssert) { return readUInt16(this, offset, false, noAssert); }; Buffer.prototype.readUInt16BE = function(offset, noAssert) { return readUInt16(this, offset, true, noAssert); }; function readUInt32(buffer, offset, isBigEndian, noAssert) { var val = 0; if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'Trying to read beyond buffer length'); } if (offset >= buffer.length) return 0; if (isBigEndian) { if (offset + 1 < buffer.length) val = buffer[offset + 1] << 16; if (offset + 2 < buffer.length) val |= buffer[offset + 2] << 8; if (offset + 3 < buffer.length) val |= buffer[offset + 3]; val = val + (buffer[offset] << 24 >>> 0); } else { if (offset + 2 < buffer.length) val = buffer[offset + 2] << 16; if (offset + 1 < buffer.length) val |= buffer[offset + 1] << 8; val |= buffer[offset]; if (offset + 3 < buffer.length) val = val + (buffer[offset + 3] << 24 >>> 0); } return val; } Buffer.prototype.readUInt32LE = function(offset, noAssert) { return readUInt32(this, offset, false, noAssert); }; Buffer.prototype.readUInt32BE = function(offset, noAssert) { return readUInt32(this, offset, true, noAssert); }; /* * Signed integer types, yay team! A reminder on how two's complement actually * works. The first bit is the signed bit, i.e. tells us whether or not the * number should be positive or negative. If the two's complement value is * positive, then we're done, as it's equivalent to the unsigned representation. * * Now if the number is positive, you're pretty much done, you can just leverage * the unsigned translations and return those. Unfortunately, negative numbers * aren't quite that straightforward. * * At first glance, one might be inclined to use the traditional formula to * translate binary numbers between the positive and negative values in two's * complement. (Though it doesn't quite work for the most negative value) * Mainly: * - invert all the bits * - add one to the result * * Of course, this doesn't quite work in Javascript. Take for example the value * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of * course, Javascript will do the following: * * > ~0xff80 * -65409 * * Whoh there, Javascript, that's not quite right. But wait, according to * Javascript that's perfectly correct. When Javascript ends up seeing the * constant 0xff80, it has no notion that it is actually a signed number. It * assumes that we've input the unsigned value 0xff80. Thus, when it does the * binary negation, it casts it into a signed value, (positive 0xff80). Then * when you perform binary negation on that, it turns it into a negative number. * * Instead, we're going to have to use the following general formula, that works * in a rather Javascript friendly way. I'm glad we don't support this kind of * weird numbering scheme in the kernel. * * (BIT-MAX - (unsigned)val + 1) * -1 * * The astute observer, may think that this doesn't make sense for 8-bit numbers * (really it isn't necessary for them). However, when you get 16-bit numbers, * you do. Let's go back to our prior example and see how this will look: * * (0xffff - 0xff80 + 1) * -1 * (0x007f + 1) * -1 * (0x0080) * -1 */ Buffer.prototype.readInt8 = function(offset, noAssert) { var buffer = this; var neg; if (!noAssert) { assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset < buffer.length, 'Trying to read beyond buffer length'); } if (offset >= buffer.length) return; neg = buffer[offset] & 0x80; if (!neg) { return (buffer[offset]); } return ((0xff - buffer[offset] + 1) * -1); }; function readInt16(buffer, offset, isBigEndian, noAssert) { var neg, val; if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 1 < buffer.length, 'Trying to read beyond buffer length'); } val = readUInt16(buffer, offset, isBigEndian, noAssert); neg = val & 0x8000; if (!neg) { return val; } return (0xffff - val + 1) * -1; } Buffer.prototype.readInt16LE = function(offset, noAssert) { return readInt16(this, offset, false, noAssert); }; Buffer.prototype.readInt16BE = function(offset, noAssert) { return readInt16(this, offset, true, noAssert); }; function readInt32(buffer, offset, isBigEndian, noAssert) { var neg, val; if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'Trying to read beyond buffer length'); } val = readUInt32(buffer, offset, isBigEndian, noAssert); neg = val & 0x80000000; if (!neg) { return (val); } return (0xffffffff - val + 1) * -1; } Buffer.prototype.readInt32LE = function(offset, noAssert) { return readInt32(this, offset, false, noAssert); }; Buffer.prototype.readInt32BE = function(offset, noAssert) { return readInt32(this, offset, true, noAssert); }; function readFloat(buffer, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset + 3 < buffer.length, 'Trying to read beyond buffer length'); } return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, 23, 4); } Buffer.prototype.readFloatLE = function(offset, noAssert) { return readFloat(this, offset, false, noAssert); }; Buffer.prototype.readFloatBE = function(offset, noAssert) { return readFloat(this, offset, true, noAssert); }; function readDouble(buffer, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset + 7 < buffer.length, 'Trying to read beyond buffer length'); } return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, 52, 8); } Buffer.prototype.readDoubleLE = function(offset, noAssert) { return readDouble(this, offset, false, noAssert); }; Buffer.prototype.readDoubleBE = function(offset, noAssert) { return readDouble(this, offset, true, noAssert); }; /* * We have to make sure that the value is a valid integer. This means that it is * non-negative. It has no fractional component and that it does not exceed the * maximum allowed value. * * value The number to check for validity * * max The maximum value */ function verifuint(value, max) { assert.ok(typeof (value) == 'number', 'cannot write a non-number as a number'); assert.ok(value >= 0, 'specified a negative value for writing an unsigned value'); assert.ok(value <= max, 'value is larger than maximum value for type'); assert.ok(Math.floor(value) === value, 'value has a fractional component'); } Buffer.prototype.writeUInt8 = function(value, offset, noAssert) { var buffer = this; if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset < buffer.length, 'trying to write beyond buffer length'); verifuint(value, 0xff); } if (offset < buffer.length) { buffer[offset] = value; } }; function writeUInt16(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 1 < buffer.length, 'trying to write beyond buffer length'); verifuint(value, 0xffff); } for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) { buffer[offset + i] = (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>> (isBigEndian ? 1 - i : i) * 8; } } Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) { writeUInt16(this, value, offset, false, noAssert); }; Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) { writeUInt16(this, value, offset, true, noAssert); }; function writeUInt32(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'trying to write beyond buffer length'); verifuint(value, 0xffffffff); } for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) { buffer[offset + i] = (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff; } } Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) { writeUInt32(this, value, offset, false, noAssert); }; Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) { writeUInt32(this, value, offset, true, noAssert); }; /* * We now move onto our friends in the signed number category. Unlike unsigned * numbers, we're going to have to worry a bit more about how we put values into * arrays. Since we are only worrying about signed 32-bit values, we're in * slightly better shape. Unfortunately, we really can't do our favorite binary * & in this system. It really seems to do the wrong thing. For example: * * > -32 & 0xff * 224 * * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of * this aren't treated as a signed number. Ultimately a bad thing. * * What we're going to want to do is basically create the unsigned equivalent of * our representation and pass that off to the wuint* functions. To do that * we're going to do the following: * * - if the value is positive * we can pass it directly off to the equivalent wuint * - if the value is negative * we do the following computation: * mb + val + 1, where * mb is the maximum unsigned value in that byte size * val is the Javascript negative integer * * * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If * you do out the computations: * * 0xffff - 128 + 1 * 0xffff - 127 * 0xff80 * * You can then encode this value as the signed version. This is really rather * hacky, but it should work and get the job done which is our goal here. */ /* * A series of checks to make sure we actually have a signed 32-bit number */ function verifsint(value, max, min) { assert.ok(typeof (value) == 'number', 'cannot write a non-number as a number'); assert.ok(value <= max, 'value larger than maximum allowed value'); assert.ok(value >= min, 'value smaller than minimum allowed value'); assert.ok(Math.floor(value) === value, 'value has a fractional component'); } function verifIEEE754(value, max, min) { assert.ok(typeof (value) == 'number', 'cannot write a non-number as a number'); assert.ok(value <= max, 'value larger than maximum allowed value'); assert.ok(value >= min, 'value smaller than minimum allowed value'); } Buffer.prototype.writeInt8 = function(value, offset, noAssert) { var buffer = this; if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset < buffer.length, 'Trying to write beyond buffer length'); verifsint(value, 0x7f, -0x80); } if (value >= 0) { buffer.writeUInt8(value, offset, noAssert); } else { buffer.writeUInt8(0xff + value + 1, offset, noAssert); } }; function writeInt16(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 1 < buffer.length, 'Trying to write beyond buffer length'); verifsint(value, 0x7fff, -0x8000); } if (value >= 0) { writeUInt16(buffer, value, offset, isBigEndian, noAssert); } else { writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert); } } Buffer.prototype.writeInt16LE = function(value, offset, noAssert) { writeInt16(this, value, offset, false, noAssert); }; Buffer.prototype.writeInt16BE = function(value, offset, noAssert) { writeInt16(this, value, offset, true, noAssert); }; function writeInt32(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'Trying to write beyond buffer length'); verifsint(value, 0x7fffffff, -0x80000000); } if (value >= 0) { writeUInt32(buffer, value, offset, isBigEndian, noAssert); } else { writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert); } } Buffer.prototype.writeInt32LE = function(value, offset, noAssert) { writeInt32(this, value, offset, false, noAssert); }; Buffer.prototype.writeInt32BE = function(value, offset, noAssert) { writeInt32(this, value, offset, true, noAssert); }; function writeFloat(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'Trying to write beyond buffer length'); verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38); } require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, 23, 4); } Buffer.prototype.writeFloatLE = function(value, offset, noAssert) { writeFloat(this, value, offset, false, noAssert); }; Buffer.prototype.writeFloatBE = function(value, offset, noAssert) { writeFloat(this, value, offset, true, noAssert); }; function writeDouble(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 7 < buffer.length, 'Trying to write beyond buffer length'); verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308); } require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, 52, 8); } Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { writeDouble(this, value, offset, false, noAssert); }; Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { writeDouble(this, value, offset, true, noAssert); }; },{"./buffer_ieee754":9,"assert":3,"base64-js":11}],11:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) var PLUS_URL_SAFE = '-'.charCodeAt(0) var SLASH_URL_SAFE = '_'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+' if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],12:[function(require,module,exports){ require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isBE ? 0 : (nBytes - 1), d = isBE ? 1 : -1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isBE ? (nBytes - 1) : 0, d = isBE ? -1 : 1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],"q9TxCC":[function(require,module,exports){ var assert; exports.Buffer = Buffer; exports.SlowBuffer = Buffer; Buffer.poolSize = 8192; exports.INSPECT_MAX_BYTES = 50; function stringtrim(str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); } function Buffer(subject, encoding, offset) { if(!assert) assert= require('assert'); if (!(this instanceof Buffer)) { return new Buffer(subject, encoding, offset); } this.parent = this; this.offset = 0; // Work-around: node's base64 implementation // allows for non-padded strings while base64-js // does not.. if (encoding == "base64" && typeof subject == "string") { subject = stringtrim(subject); while (subject.length % 4 != 0) { subject = subject + "="; } } var type; // Are we slicing? if (typeof offset === 'number') { this.length = coerce(encoding); // slicing works, with limitations (no parent tracking/update) // check https://github.com/toots/buffer-browserify/issues/19 for (var i = 0; i < this.length; i++) { this[i] = subject.get(i+offset); } } else { // Find the length switch (type = typeof subject) { case 'number': this.length = coerce(subject); break; case 'string': this.length = Buffer.byteLength(subject, encoding); break; case 'object': // Assume object is an array this.length = coerce(subject.length); break; default: throw new Error('First argument needs to be a number, ' + 'array or string.'); } // Treat array-ish objects as a byte array. if (isArrayIsh(subject)) { for (var i = 0; i < this.length; i++) { if (subject instanceof Buffer) { this[i] = subject.readUInt8(i); } else { this[i] = subject[i]; } } } else if (type == 'string') { // We are a string this.length = this.write(subject, 0, encoding); } else if (type === 'number') { for (var i = 0; i < this.length; i++) { this[i] = 0; } } } } Buffer.prototype.get = function get(i) { if (i < 0 || i >= this.length) throw new Error('oob'); return this[i]; }; Buffer.prototype.set = function set(i, v) { if (i < 0 || i >= this.length) throw new Error('oob'); return this[i] = v; }; Buffer.byteLength = function (str, encoding) { switch (encoding || "utf8") { case 'hex': return str.length / 2; case 'utf8': case 'utf-8': return utf8ToBytes(str).length; case 'ascii': case 'binary': return str.length; case 'base64': return base64ToBytes(str).length; default: throw new Error('Unknown encoding'); } }; Buffer.prototype.utf8Write = function (string, offset, length) { var bytes, pos; return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length); }; Buffer.prototype.asciiWrite = function (string, offset, length) { var bytes, pos; return Buffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length); }; Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite; Buffer.prototype.base64Write = function (string, offset, length) { var bytes, pos; return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length); }; Buffer.prototype.base64Slice = function (start, end) { var bytes = Array.prototype.slice.apply(this, arguments) return require("base64-js").fromByteArray(bytes); }; Buffer.prototype.utf8Slice = function () { var bytes = Array.prototype.slice.apply(this, arguments); var res = ""; var tmp = ""; var i = 0; while (i < bytes.length) { if (bytes[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]); tmp = ""; } else tmp += "%" + bytes[i].toString(16); i++; } return res + decodeUtf8Char(tmp); } Buffer.prototype.asciiSlice = function () { var bytes = Array.prototype.slice.apply(this, arguments); var ret = ""; for (var i = 0; i < bytes.length; i++) ret += String.fromCharCode(bytes[i]); return ret; } Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice; Buffer.prototype.inspect = function() { var out = [], len = this.length; for (var i = 0; i < len; i++) { out[i] = toHex(this[i]); if (i == exports.INSPECT_MAX_BYTES) { out[i + 1] = '...'; break; } } return '<Buffer ' + out.join(' ') + '>'; }; Buffer.prototype.hexSlice = function(start, end) { var len = this.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; i++) { out += toHex(this[i]); } return out; }; Buffer.prototype.toString = function(encoding, start, end) { encoding = String(encoding || 'utf8').toLowerCase(); start = +start || 0; if (typeof end == 'undefined') end = this.length; // Fastpath empty strings if (+end == start) { return ''; } switch (encoding) { case 'hex': return this.hexSlice(start, end); case 'utf8': case 'utf-8': return this.utf8Slice(start, end); case 'ascii': return this.asciiSlice(start, end); case 'binary': return this.binarySlice(start, end); case 'base64': return this.base64Slice(start, end); case 'ucs2': case 'ucs-2': return this.ucs2Slice(start, end); default: throw new Error('Unknown encoding'); } }; Buffer.prototype.hexWrite = function(string, offset, length) { offset = +offset || 0; var remaining = this.length - offset; if (!length) { length = remaining; } else { length = +length; if (length > remaining) { length = remaining; } } // must be an even number of digits var strLen = string.length; if (strLen % 2) { throw new Error('Invalid hex string'); } if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16); if (isNaN(byte)) throw new Error('Invalid hex string'); this[offset + i] = byte; } Buffer._charsWritten = i * 2; return i; }; Buffer.prototype.write = function(string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length; length = undefined; } } else { // legacy var swap = encoding; encoding = offset; offset = length; length = swap; } offset = +offset || 0; var remaining = this.length - offset; if (!length) { length = remaining; } else { length = +length; if (length > remaining) { length = remaining; } } encoding = String(encoding || 'utf8').toLowerCase(); switch (encoding) { case 'hex': return this.hexWrite(string, offset, length); case 'utf8': case 'utf-8': return this.utf8Write(string, offset, length); case 'ascii': return this.asciiWrite(string, offset, length); case 'binary': return this.binaryWrite(string, offset, length); case 'base64': return this.base64Write(string, offset, length); case 'ucs2': case 'ucs-2': return this.ucs2Write(string, offset, length); default: throw new Error('Unknown encoding'); } }; // slice(start, end) function clamp(index, len, defaultValue) { if (typeof index !== 'number') return defaultValue; index = ~~index; // Coerce to integer. if (index >= len) return len; if (index >= 0) return index; index += len; if (index >= 0) return index; return 0; } Buffer.prototype.slice = function(start, end) { var len = this.length; start = clamp(start, len, 0); end = clamp(end, len, len); return new Buffer(this, end - start, +start); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function(target, target_start, start, end) { var source = this; start || (start = 0); if (end === undefined || isNaN(end)) { end = this.length; } target_start || (target_start = 0); if (end < start) throw new Error('sourceEnd < sourceStart'); // Copy 0 bytes; we're done if (end === start) return 0; if (target.length == 0 || source.length == 0) return 0; if (target_start < 0 || target_start >= target.length) { throw new Error('targetStart out of bounds'); } if (start < 0 || start >= source.length) { throw new Error('sourceStart out of bounds'); } if (end < 0 || end > source.length) { throw new Error('sourceEnd out of bounds'); } // Are we oob? if (end > this.length) { end = this.length; } if (target.length - target_start < end - start) { end = target.length - target_start + start; } var temp = []; for (var i=start; i<end; i++) { assert.ok(typeof this[i] !== 'undefined', "copying undefined buffer bytes!"); temp.push(this[i]); } for (var i=target_start; i<target_start+temp.length; i++) { target[i] = temp[i-target_start]; } }; // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function fill(value, start, end) { value || (value = 0); start || (start = 0); end || (end = this.length); if (typeof value === 'string') { value = value.charCodeAt(0); } if (!(typeof value === 'number') || isNaN(value)) { throw new Error('value is not a number'); } if (end < start) throw new Error('end < start'); // Fill 0 bytes; we're done if (end === start) return 0; if (this.length == 0) return 0; if (start < 0 || start >= this.length) { throw new Error('start out of bounds'); } if (end < 0 || end > this.length) { throw new Error('end out of bounds'); } for (var i = start; i < end; i++) { this[i] = value; } } // Static methods Buffer.isBuffer = function isBuffer(b) { return b instanceof Buffer || b instanceof Buffer; }; Buffer.concat = function (list, totalLength) { if (!isArray(list)) { throw new Error("Usage: Buffer.concat(list, [totalLength])\n \ list should be an Array."); } if (list.length === 0) { return new Buffer(0); } else if (list.length === 1) { return list[0]; } if (typeof totalLength !== 'number') { totalLength = 0; for (var i = 0; i < list.length; i++) { var buf = list[i]; totalLength += buf.length; } } var buffer = new Buffer(totalLength); var pos = 0; for (var i = 0; i < list.length; i++) { var buf = list[i]; buf.copy(buffer, pos); pos += buf.length; } return buffer; }; Buffer.isEncoding = function(encoding) { switch ((encoding + '').toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; default: return false; } }; // helpers function coerce(length) { // Coerce length to a number (possibly NaN), round up // in case it's fractional (e.g. 123.456) then do a // double negate to coerce a NaN to 0. Easy, right? length = ~~Math.ceil(+length); return length < 0 ? 0 : length; } function isArray(subject) { return (Array.isArray || function(subject){ return {}.toString.apply(subject) == '[object Array]' }) (subject) } function isArrayIsh(subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number'; } function toHex(n) { if (n < 16) return '0' + n.toString(16); return n.toString(16); } function utf8ToBytes(str) { var byteArray = []; for (var i = 0; i < str.length; i++) if (str.charCodeAt(i) <= 0x7F) byteArray.push(str.charCodeAt(i)); else { var h = encodeURIComponent(str.charAt(i)).substr(1).split('%'); for (var j = 0; j < h.length; j++) byteArray.push(parseInt(h[j], 16)); } return byteArray; } function asciiToBytes(str) { var byteArray = [] for (var i = 0; i < str.length; i++ ) // Node's code seems to be doing this and not & 0x7F.. byteArray.push( str.charCodeAt(i) & 0xFF ); return byteArray; } function base64ToBytes(str) { return require("base64-js").toByteArray(str); } function blitBuffer(src, dst, offset, length) { var pos, i = 0; while (i < length) { if ((i+offset >= dst.length) || (i >= src.length)) break; dst[i + offset] = src[i]; i++; } return i; } function decodeUtf8Char(str) { try { return decodeURIComponent(str); } catch (err) { return String.fromCharCode(0xFFFD); // UTF 8 invalid char } } // read/write bit-twiddling Buffer.prototype.readUInt8 = function(offset, noAssert) { var buffer = this; if (!noAssert) { assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset < buffer.length, 'Trying to read beyond buffer length'); } if (offset >= buffer.length) return; return buffer[offset]; }; function readUInt16(buffer, offset, isBigEndian, noAssert) { var val = 0; if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 1 < buffer.length, 'Trying to read beyond buffer length'); } if (offset >= buffer.length) return 0; if (isBigEndian) { val = buffer[offset] << 8; if (offset + 1 < buffer.length) { val |= buffer[offset + 1]; } } else { val = buffer[offset]; if (offset + 1 < buffer.length) { val |= buffer[offset + 1] << 8; } } return val; } Buffer.prototype.readUInt16LE = function(offset, noAssert) { return readUInt16(this, offset, false, noAssert); }; Buffer.prototype.readUInt16BE = function(offset, noAssert) { return readUInt16(this, offset, true, noAssert); }; function readUInt32(buffer, offset, isBigEndian, noAssert) { var val = 0; if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'Trying to read beyond buffer length'); } if (offset >= buffer.length) return 0; if (isBigEndian) { if (offset + 1 < buffer.length) val = buffer[offset + 1] << 16; if (offset + 2 < buffer.length) val |= buffer[offset + 2] << 8; if (offset + 3 < buffer.length) val |= buffer[offset + 3]; val = val + (buffer[offset] << 24 >>> 0); } else { if (offset + 2 < buffer.length) val = buffer[offset + 2] << 16; if (offset + 1 < buffer.length) val |= buffer[offset + 1] << 8; val |= buffer[offset]; if (offset + 3 < buffer.length) val = val + (buffer[offset + 3] << 24 >>> 0); } return val; } Buffer.prototype.readUInt32LE = function(offset, noAssert) { return readUInt32(this, offset, false, noAssert); }; Buffer.prototype.readUInt32BE = function(offset, noAssert) { return readUInt32(this, offset, true, noAssert); }; /* * Signed integer types, yay team! A reminder on how two's complement actually * works. The first bit is the signed bit, i.e. tells us whether or not the * number should be positive or negative. If the two's complement value is * positive, then we're done, as it's equivalent to the unsigned representation. * * Now if the number is positive, you're pretty much done, you can just leverage * the unsigned translations and return those. Unfortunately, negative numbers * aren't quite that straightforward. * * At first glance, one might be inclined to use the traditional formula to * translate binary numbers between the positive and negative values in two's * complement. (Though it doesn't quite work for the most negative value) * Mainly: * - invert all the bits * - add one to the result * * Of course, this doesn't quite work in Javascript. Take for example the value * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of * course, Javascript will do the following: * * > ~0xff80 * -65409 * * Whoh there, Javascript, that's not quite right. But wait, according to * Javascript that's perfectly correct. When Javascript ends up seeing the * constant 0xff80, it has no notion that it is actually a signed number. It * assumes that we've input the unsigned value 0xff80. Thus, when it does the * binary negation, it casts it into a signed value, (positive 0xff80). Then * when you perform binary negation on that, it turns it into a negative number. * * Instead, we're going to have to use the following general formula, that works * in a rather Javascript friendly way. I'm glad we don't support this kind of * weird numbering scheme in the kernel. * * (BIT-MAX - (unsigned)val + 1) * -1 * * The astute observer, may think that this doesn't make sense for 8-bit numbers * (really it isn't necessary for them). However, when you get 16-bit numbers, * you do. Let's go back to our prior example and see how this will look: * * (0xffff - 0xff80 + 1) * -1 * (0x007f + 1) * -1 * (0x0080) * -1 */ Buffer.prototype.readInt8 = function(offset, noAssert) { var buffer = this; var neg; if (!noAssert) { assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset < buffer.length, 'Trying to read beyond buffer length'); } if (offset >= buffer.length) return; neg = buffer[offset] & 0x80; if (!neg) { return (buffer[offset]); } return ((0xff - buffer[offset] + 1) * -1); }; function readInt16(buffer, offset, isBigEndian, noAssert) { var neg, val; if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 1 < buffer.length, 'Trying to read beyond buffer length'); } val = readUInt16(buffer, offset, isBigEndian, noAssert); neg = val & 0x8000; if (!neg) { return val; } return (0xffff - val + 1) * -1; } Buffer.prototype.readInt16LE = function(offset, noAssert) { return readInt16(this, offset, false, noAssert); }; Buffer.prototype.readInt16BE = function(offset, noAssert) { return readInt16(this, offset, true, noAssert); }; function readInt32(buffer, offset, isBigEndian, noAssert) { var neg, val; if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'Trying to read beyond buffer length'); } val = readUInt32(buffer, offset, isBigEndian, noAssert); neg = val & 0x80000000; if (!neg) { return (val); } return (0xffffffff - val + 1) * -1; } Buffer.prototype.readInt32LE = function(offset, noAssert) { return readInt32(this, offset, false, noAssert); }; Buffer.prototype.readInt32BE = function(offset, noAssert) { return readInt32(this, offset, true, noAssert); }; function readFloat(buffer, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset + 3 < buffer.length, 'Trying to read beyond buffer length'); } return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, 23, 4); } Buffer.prototype.readFloatLE = function(offset, noAssert) { return readFloat(this, offset, false, noAssert); }; Buffer.prototype.readFloatBE = function(offset, noAssert) { return readFloat(this, offset, true, noAssert); }; function readDouble(buffer, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset + 7 < buffer.length, 'Trying to read beyond buffer length'); } return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, 52, 8); } Buffer.prototype.readDoubleLE = function(offset, noAssert) { return readDouble(this, offset, false, noAssert); }; Buffer.prototype.readDoubleBE = function(offset, noAssert) { return readDouble(this, offset, true, noAssert); }; /* * We have to make sure that the value is a valid integer. This means that it is * non-negative. It has no fractional component and that it does not exceed the * maximum allowed value. * * value The number to check for validity * * max The maximum value */ function verifuint(value, max) { assert.ok(typeof (value) == 'number', 'cannot write a non-number as a number'); assert.ok(value >= 0, 'specified a negative value for writing an unsigned value'); assert.ok(value <= max, 'value is larger than maximum value for type'); assert.ok(Math.floor(value) === value, 'value has a fractional component'); } Buffer.prototype.writeUInt8 = function(value, offset, noAssert) { var buffer = this; if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset < buffer.length, 'trying to write beyond buffer length'); verifuint(value, 0xff); } if (offset < buffer.length) { buffer[offset] = value; } }; function writeUInt16(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 1 < buffer.length, 'trying to write beyond buffer length'); verifuint(value, 0xffff); } for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) { buffer[offset + i] = (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>> (isBigEndian ? 1 - i : i) * 8; } } Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) { writeUInt16(this, value, offset, false, noAssert); }; Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) { writeUInt16(this, value, offset, true, noAssert); }; function writeUInt32(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'trying to write beyond buffer length'); verifuint(value, 0xffffffff); } for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) { buffer[offset + i] = (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff; } } Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) { writeUInt32(this, value, offset, false, noAssert); }; Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) { writeUInt32(this, value, offset, true, noAssert); }; /* * We now move onto our friends in the signed number category. Unlike unsigned * numbers, we're going to have to worry a bit more about how we put values into * arrays. Since we are only worrying about signed 32-bit values, we're in * slightly better shape. Unfortunately, we really can't do our favorite binary * & in this system. It really seems to do the wrong thing. For example: * * > -32 & 0xff * 224 * * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of * this aren't treated as a signed number. Ultimately a bad thing. * * What we're going to want to do is basically create the unsigned equivalent of * our representation and pass that off to the wuint* functions. To do that * we're going to do the following: * * - if the value is positive * we can pass it directly off to the equivalent wuint * - if the value is negative * we do the following computation: * mb + val + 1, where * mb is the maximum unsigned value in that byte size * val is the Javascript negative integer * * * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If * you do out the computations: * * 0xffff - 128 + 1 * 0xffff - 127 * 0xff80 * * You can then encode this value as the signed version. This is really rather * hacky, but it should work and get the job done which is our goal here. */ /* * A series of checks to make sure we actually have a signed 32-bit number */ function verifsint(value, max, min) { assert.ok(typeof (value) == 'number', 'cannot write a non-number as a number'); assert.ok(value <= max, 'value larger than maximum allowed value'); assert.ok(value >= min, 'value smaller than minimum allowed value'); assert.ok(Math.floor(value) === value, 'value has a fractional component'); } function verifIEEE754(value, max, min) { assert.ok(typeof (value) == 'number', 'cannot write a non-number as a number'); assert.ok(value <= max, 'value larger than maximum allowed value'); assert.ok(value >= min, 'value smaller than minimum allowed value'); } Buffer.prototype.writeInt8 = function(value, offset, noAssert) { var buffer = this; if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset < buffer.length, 'Trying to write beyond buffer length'); verifsint(value, 0x7f, -0x80); } if (value >= 0) { buffer.writeUInt8(value, offset, noAssert); } else { buffer.writeUInt8(0xff + value + 1, offset, noAssert); } }; function writeInt16(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 1 < buffer.length, 'Trying to write beyond buffer length'); verifsint(value, 0x7fff, -0x8000); } if (value >= 0) { writeUInt16(buffer, value, offset, isBigEndian, noAssert); } else { writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert); } } Buffer.prototype.writeInt16LE = function(value, offset, noAssert) { writeInt16(this, value, offset, false, noAssert); }; Buffer.prototype.writeInt16BE = function(value, offset, noAssert) { writeInt16(this, value, offset, true, noAssert); }; function writeInt32(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'Trying to write beyond buffer length'); verifsint(value, 0x7fffffff, -0x80000000); } if (value >= 0) { writeUInt32(buffer, value, offset, isBigEndian, noAssert); } else { writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert); } } Buffer.prototype.writeInt32LE = function(value, offset, noAssert) { writeInt32(this, value, offset, false, noAssert); }; Buffer.prototype.writeInt32BE = function(value, offset, noAssert) { writeInt32(this, value, offset, true, noAssert); }; function writeFloat(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 3 < buffer.length, 'Trying to write beyond buffer length'); verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38); } require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, 23, 4); } Buffer.prototype.writeFloatLE = function(value, offset, noAssert) { writeFloat(this, value, offset, false, noAssert); }; Buffer.prototype.writeFloatBE = function(value, offset, noAssert) { writeFloat(this, value, offset, true, noAssert); }; function writeDouble(buffer, value, offset, isBigEndian, noAssert) { if (!noAssert) { assert.ok(value !== undefined && value !== null, 'missing value'); assert.ok(typeof (isBigEndian) === 'boolean', 'missing or invalid endian'); assert.ok(offset !== undefined && offset !== null, 'missing offset'); assert.ok(offset + 7 < buffer.length, 'Trying to write beyond buffer length'); verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308); } require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, 52, 8); } Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { writeDouble(this, value, offset, false, noAssert); }; Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { writeDouble(this, value, offset, true, noAssert); }; },{"./buffer_ieee754":1,"assert":6,"base64-js":4}],"buffer-browserify":[function(require,module,exports){ module.exports=require('q9TxCC'); },{}],4:[function(require,module,exports){ (function (exports) { 'use strict'; var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function b64ToByteArray(b64) { var i, j, l, tmp, placeHolders, arr; if (b64.length % 4 > 0) { throw 'Invalid string. Length must be a multiple of 4'; } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice placeHolders = b64.indexOf('='); placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0; // base64 is 4/3 + up to two characters of the original data arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length; for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]); arr.push((tmp & 0xFF0000) >> 16); arr.push((tmp & 0xFF00) >> 8); arr.push(tmp & 0xFF); } if (placeHolders === 2) { tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4); arr.push(tmp & 0xFF); } else if (placeHolders === 1) { tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2); arr.push((tmp >> 8) & 0xFF); arr.push(tmp & 0xFF); } return arr; } function uint8ToBase64(uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length; function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; }; // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); output += tripletToBase64(temp); } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1]; output += lookup[temp >> 2]; output += lookup[(temp << 4) & 0x3F]; output += '=='; break; case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]); output += lookup[temp >> 10]; output += lookup[(temp >> 4) & 0x3F]; output += lookup[(temp << 2) & 0x3F]; output += '='; break; } return output; } module.exports.toByteArray = b64ToByteArray; module.exports.fromByteArray = uint8ToBase64; }()); },{}],5:[function(require,module,exports){ // // The shims in this file are not fully implemented shims for the ES5 // features, but do work for the particular usecases there is in // the other modules. // var toString = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; // Array.isArray is supported in IE9 function isArray(xs) { return toString.call(xs) === '[object Array]'; } exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray; // Array.prototype.indexOf is supported in IE9 exports.indexOf = function indexOf(xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0; i < xs.length; i++) { if (x === xs[i]) return i; } return -1; }; // Array.prototype.filter is supported in IE9 exports.filter = function filter(xs, fn) { if (xs.filter) return xs.filter(fn); var res = []; for (var i = 0; i < xs.length; i++) { if (fn(xs[i], i, xs)) res.push(xs[i]); } return res; }; // Array.prototype.forEach is supported in IE9 exports.forEach = function forEach(xs, fn, self) { if (xs.forEach) return xs.forEach(fn, self); for (var i = 0; i < xs.length; i++) { fn.call(self, xs[i], i, xs); } }; // Array.prototype.map is supported in IE9 exports.map = function map(xs, fn) { if (xs.map) return xs.map(fn); var out = new Array(xs.length); for (var i = 0; i < xs.length; i++) { out[i] = fn(xs[i], i, xs); } return out; }; // Array.prototype.reduce is supported in IE9 exports.reduce = function reduce(array, callback, opt_initialValue) { if (array.reduce) return array.reduce(callback, opt_initialValue); var value, isValueSet = false; if (2 < arguments.length) { value = opt_initialValue; isValueSet = true; } for (var i = 0, l = array.length; l > i; ++i) { if (array.hasOwnProperty(i)) { if (isValueSet) { value = callback(value, array[i], i, array); } else { value = array[i]; isValueSet = true; } } } return value; }; // String.prototype.substr - negative index don't work in IE8 if ('ab'.substr(-1) !== 'b') { exports.substr = function (str, start, length) { // did we get a negative start, calculate how much it is from the beginning of the string if (start < 0) start = str.length + start; // call the original function return str.substr(start, length); }; } else { exports.substr = function (str, start, length) { return str.substr(start, length); }; } // String.prototype.trim is supported in IE9 exports.trim = function (str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); }; // Function.prototype.bind is supported in IE9 exports.bind = function () { var args = Array.prototype.slice.call(arguments); var fn = args.shift(); if (fn.bind) return fn.bind.apply(fn, args); var self = args.shift(); return function () { fn.apply(self, args.concat([Array.prototype.slice.call(arguments)])); }; }; // Object.create is supported in IE9 function create(prototype, properties) { var object; if (prototype === null) { object = { '__proto__' : null }; } else { if (typeof prototype !== 'object') { throw new TypeError( 'typeof prototype[' + (typeof prototype) + '] != \'object\'' ); } var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (typeof properties !== 'undefined' && Object.defineProperties) { Object.defineProperties(object, properties); } return object; } exports.create = typeof Object.create === 'function' ? Object.create : create; // Object.keys and Object.getOwnPropertyNames is supported in IE9 however // they do show a description and number property on Error objects function notObject(object) { return ((typeof object != "object" && typeof object != "function") || object === null); } function keysShim(object) { if (notObject(object)) { throw new TypeError("Object.keys called on a non-object"); } var result = []; for (var name in object) { if (hasOwnProperty.call(object, name)) { result.push(name); } } return result; } // getOwnPropertyNames is almost the same as Object.keys one key feature // is that it returns hidden properties, since that can't be implemented, // this feature gets reduced so it just shows the length property on arrays function propertyShim(object) { if (notObject(object)) { throw new TypeError("Object.getOwnPropertyNames called on a non-object"); } var result = keysShim(object); if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { result.push('length'); } return result; } var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? Object.getOwnPropertyNames : propertyShim; if (new Error().hasOwnProperty('description')) { var ERROR_PROPERTY_FILTER = function (obj, array) { if (toString.call(obj) === '[object Error]') { array = exports.filter(array, function (name) { return name !== 'description' && name !== 'number' && name !== 'message'; }); } return array; }; exports.keys = function (object) { return ERROR_PROPERTY_FILTER(object, keys(object)); }; exports.getOwnPropertyNames = function (object) { return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object)); }; } else { exports.keys = keys; exports.getOwnPropertyNames = getOwnPropertyNames; } // Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements function valueObject(value, key) { return { value: value[key] }; } if (typeof Object.getOwnPropertyDescriptor === 'function') { try { Object.getOwnPropertyDescriptor({'a': 1}, 'a'); exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; } catch (e) { // IE8 dom element issue - use a try catch and default to valueObject exports.getOwnPropertyDescriptor = function (value, key) { try { return Object.getOwnPropertyDescriptor(value, key); } catch (e) { return valueObject(value, key); } }; } } else { exports.getOwnPropertyDescriptor = valueObject; } },{}],6:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // UTILITY var util = require('util'); var shims = require('_shims'); var pSlice = Array.prototype.slice; // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; this.message = options.message || getMessage(this); }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (util.isUndefined(value)) { return '' + value; } if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; } function truncate(s, n) { if (util.isString(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (util.isBuffer(actual) && util.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (!util.isObject(actual) && !util.isObject(expected)) { return actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try { var ka = shims.keys(a), kb = shims.keys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (util.isString(expected)) { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; },{"_shims":5,"util":7}],7:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var shims = require('_shims'); var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; shims.forEach(array, function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = shims.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = shims.getOwnPropertyNames(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } shims.forEach(keys, function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (shims.indexOf(ctx.seen, desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = shims.reduce(output, function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return shims.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && objectToString(e) === '[object Error]'; } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; function isBuffer(arg) { return arg instanceof Buffer; } exports.isBuffer = isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = shims.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = shims.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } },{"_shims":5}]},{},[]) ;;module.exports=require("buffer-browserify") },{}],13:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],14:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** * @license * lodash 3.9.3 (Custom Build) <https://lodash.com/> * Build: `lodash compat -d -o ./index.js` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '3.9.3'; /** Used to compose bitmasks for wrapper metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, CURRY_RIGHT_FLAG = 16, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64, ARY_FLAG = 128, REARG_FLAG = 256; /** Used as default options for `_.trunc`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect when a function becomes hot. */ var HOT_COUNT = 150, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_DROP_WHILE_FLAG = 0, LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, reUnescapedHtml = /[&<>"'`]/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */ var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect hexadecimal string values. */ var reHasHexPrefix = /^0[xX]/; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to match words to create compound words. */ var reWords = (function() { var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]', lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+'; return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g'); }()); /** Used to detect and test for whitespace. */ var whitespace = ( // Basic whitespace characters. ' \t\x0b\f\xa0\ufeff' + // Line terminators. '\n\r\u2028\u2029' + // Unicode category "Zs" space separators. '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' ); /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number', 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'document', 'isFinite', 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', 'window' ]; /** Used to fix the JScript `[[DontEnum]]` bug. */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[stringTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[mapTag] = cloneableTags[setTag] = cloneableTags[weakMapTag] = false; /** Used as an internal `_.debounce` options object by `_.throttle`. */ var debounceOptions = { 'leading': false, 'maxWait': 0, 'trailing': false }; /** Used to map latin-1 supplementary letters to basic latin letters. */ var deburredLetters = { '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '`': '&#96;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", '&#96;': '`' }; /** Used to determine if values are of the language type `Object`. */ var objectTypes = { 'function': true, 'object': true }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Detect free variable `exports`. */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect free variable `global` from Node.js. */ var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; /** Detect free variable `self`. */ var freeSelf = objectTypes[typeof self] && self && self.Object && self; /** Detect free variable `window`. */ var freeWindow = objectTypes[typeof window] && window && window.Object && window; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** * Used as a reference to the global object. * * The `this` value is used if it's the global object to avoid Greasemonkey's * restricted `window` object, otherwise the `window` object is used. */ var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this; /*--------------------------------------------------------------------------*/ /** * The base implementation of `compareAscending` which compares values and * sorts them in ascending order without guaranteeing a stable sort. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function baseCompareAscending(value, other) { if (value !== other) { var valIsNull = value === null, valIsUndef = value === undefined, valIsReflexive = value === value; var othIsNull = other === null, othIsUndef = other === undefined, othIsReflexive = other === other; if ((value > other && !othIsNull) || !valIsReflexive || (valIsNull && !othIsUndef && othIsReflexive) || (valIsUndef && othIsReflexive)) { return 1; } if ((value < other && !valIsNull) || !othIsReflexive || (othIsNull && !valIsUndef && valIsReflexive) || (othIsUndef && valIsReflexive)) { return -1; } } return 0; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for callback shorthands and `this` binding. * * @private * @param {Array} array The array to search. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without support for binary searches. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { if (value !== value) { return indexOfNaN(array, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * The base implementation of `_.isFunction` without support for environments * with incorrect `typeof` results. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. */ function baseIsFunction(value) { // Avoid a Chakra JIT bug in compatibility modes of IE 11. // See https://github.com/jashkenas/underscore/issues/1621 for more details. return typeof value == 'function' || false; } /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * Used by `_.trim` and `_.trimLeft` to get the index of the first character * of `string` that is not found in `chars`. * * @private * @param {string} string The string to inspect. * @param {string} chars The characters to find. * @returns {number} Returns the index of the first character not found in `chars`. */ function charsLeftIndex(string, chars) { var index = -1, length = string.length; while (++index < length && chars.indexOf(string.charAt(index)) > -1) {} return index; } /** * Used by `_.trim` and `_.trimRight` to get the index of the last character * of `string` that is not found in `chars`. * * @private * @param {string} string The string to inspect. * @param {string} chars The characters to find. * @returns {number} Returns the index of the last character not found in `chars`. */ function charsRightIndex(string, chars) { var index = string.length; while (index-- && chars.indexOf(string.charAt(index)) > -1) {} return index; } /** * Used by `_.sortBy` to compare transformed elements of a collection and stable * sort them in ascending order. * * @private * @param {Object} object The object to compare to `other`. * @param {Object} other The object to compare to `object`. * @returns {number} Returns the sort order indicator for `object`. */ function compareAscending(object, other) { return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index); } /** * Used by `_.sortByOrder` to compare multiple properties of each element * in a collection and stable sort them in the following order: * * If `orders` is unspecified, sort in ascending order for all properties. * Otherwise, for each property, sort in ascending order if its corresponding value in * orders is true, and descending order if false. * * @private * @param {Object} object The object to compare to `other`. * @param {Object} other The object to compare to `object`. * @param {boolean[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = baseCompareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } return result * (orders[index] ? 1 : -1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://code.google.com/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ function deburrLetter(letter) { return deburredLetters[letter]; } /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeHtmlChar(chr) { return htmlEscapes[chr]; } /** * Used by `_.template` to escape characters for inclusion in compiled * string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the index at which the first occurrence of `NaN` is found in `array`. * * @private * @param {Array} array The array to search. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched `NaN`, else `-1`. */ function indexOfNaN(array, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 0 : -1); while ((fromRight ? index-- : ++index < length)) { var other = array[index]; if (other !== other) { return index; } } return -1; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { // IE < 9 presents many host objects as `Object` objects that can coerce // to strings despite having improperly defined `toString` methods. return typeof value.toString != 'function' && typeof (value + '') == 'string'; }; }()); /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a * character code is whitespace. * * @private * @param {number} charCode The character code to inspect. * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`. */ function isSpace(charCode) { return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 || (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279))); } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { if (array[index] === placeholder) { array[index] = PLACEHOLDER; result[++resIndex] = index; } } return result; } /** * An implementation of `_.uniq` optimized for sorted arrays without support * for callback shorthands and `this` binding. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The function invoked per iteration. * @returns {Array} Returns the new duplicate-value-free array. */ function sortedUniq(array, iteratee) { var seen, index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value, index, array) : value; if (!index || seen !== computed) { seen = computed; result[++resIndex] = value; } } return result; } /** * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the first non-whitespace character. */ function trimmedLeftIndex(string) { var index = -1, length = string.length; while (++index < length && isSpace(string.charCodeAt(index))) {} return index; } /** * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedRightIndex(string) { var index = string.length; while (index-- && isSpace(string.charCodeAt(index))) {} return index; } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ function unescapeHtmlChar(chr) { return htmlUnescapes[chr]; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the given `context` object. * * @static * @memberOf _ * @category Utility * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // using `context` to mock `Date#getTime` use in `_.now` * var mock = _.runInContext({ * 'Date': function() { * return { 'getTime': getTimeMock }; * } * }); * * // or creating a suped-up `defer` in Node.js * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ function runInContext(context) { // Avoid issues with some ES3 environments that attempt to use values, named // after built-in constructors like `Object`, for the creation of literals. // ES5 clears this up by stating that literals must use built-in constructors. // See https://es5.github.io/#x11.1.5 for more details. context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; /** Native constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Number = context.Number, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to detect DOM support. */ var document = (document = context.window) ? document.document : null; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = context._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Native method references. */ var ArrayBuffer = getNative(context, 'ArrayBuffer'), bufferSlice = getNative(ArrayBuffer && new ArrayBuffer(0), 'slice'), ceil = Math.ceil, clearTimeout = context.clearTimeout, floor = Math.floor, getPrototypeOf = getNative(Object, 'getPrototypeOf'), parseFloat = context.parseFloat, push = arrayProto.push, propertyIsEnumerable = objectProto.propertyIsEnumerable, Set = getNative(context, 'Set'), setTimeout = context.setTimeout, splice = arrayProto.splice, Uint8Array = getNative(context, 'Uint8Array'), WeakMap = getNative(context, 'WeakMap'); /** Used to clone array buffers. */ var Float64Array = (function() { // Safari 5 errors when using an array buffer to initialize a typed array // where the array buffer's `byteLength` is not a multiple of the typed // array's `BYTES_PER_ELEMENT`. try { var func = getNative(context, 'Float64Array'), result = new func(new ArrayBuffer(10), 0, 1) && func; } catch(e) {} return result || null; }()); /* Native method references for those with the same name as other `lodash` methods. */ var nativeCreate = getNative(Object, 'create'), nativeIsArray = getNative(Array, 'isArray'), nativeIsFinite = context.isFinite, nativeKeys = getNative(Object, 'keys'), nativeMax = Math.max, nativeMin = Math.min, nativeNow = getNative(Date, 'now'), nativeNumIsFinite = getNative(Number, 'isFinite'), nativeParseInt = context.parseInt, nativeRandom = Math.random; /** Used as references for `-Infinity` and `Infinity`. */ var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY, POSITIVE_INFINITY = Number.POSITIVE_INFINITY; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used as the size, in bytes, of each `Float64Array` element. */ var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to lookup a type array constructors by `toStringTag`. */ var ctorByTag = {}; ctorByTag[float32Tag] = context.Float32Array; ctorByTag[float64Tag] = context.Float64Array; ctorByTag[int8Tag] = context.Int8Array; ctorByTag[int16Tag] = context.Int16Array; ctorByTag[int32Tag] = context.Int32Array; ctorByTag[uint8Tag] = context.Uint8Array; ctorByTag[uint8ClampedTag] = context.Uint8ClampedArray; ctorByTag[uint16Tag] = context.Uint16Array; ctorByTag[uint32Tag] = context.Uint32Array; /** Used to avoid iterating over non-enumerable properties in IE < 9. */ var nonEnumProps = {}; nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; nonEnumProps[objectTag] = { 'constructor': true }; arrayEach(shadowProps, function(key) { for (var tag in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, tag)) { var props = nonEnumProps[tag]; props[key] = hasOwnProperty.call(props, key); } } }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit chaining. * Methods that operate on and return arrays, collections, and functions can * be chained together. Methods that return a boolean or single value will * automatically end the chain returning the unwrapped value. Explicit chaining * may be enabled using `_.chain`. The execution of chained methods is lazy, * that is, execution is deferred until `_#value` is implicitly or explicitly * called. * * Lazy evaluation allows several methods to support shortcut fusion. Shortcut * fusion is an optimization that merges iteratees to avoid creating intermediate * arrays and reduce the number of iteratee executions. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, * `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, * and `where` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`, * `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`, * `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`, * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`, * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`, * `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `method`, `methodOf`, `mixin`, `negate`, `omit`, `once`, * `pairs`, `partial`, `partialRight`, `partition`, `pick`, `plant`, `pluck`, * `property`, `propertyOf`, `pull`, `pullAt`, `push`, `range`, `rearg`, * `reject`, `remove`, `rest`, `restParam`, `reverse`, `set`, `shuffle`, * `slice`, `sort`, `sortBy`, `sortByAll`, `sortByOrder`, `splice`, `spread`, * `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, `throttle`, * `thru`, `times`, `toArray`, `toPlainObject`, `transform`, `union`, `uniq`, * `unshift`, `unzip`, `unzipWith`, `values`, `valuesIn`, `where`, `without`, * `wrap`, `xor`, `zip`, `zipObject`, `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`, * `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, * `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `get`, * `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`, `inRange`, `isArguments`, * `isArray`, `isBoolean`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, * `isFinite` `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`, * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, * `isTypedArray`, `join`, `kebabCase`, `last`, `lastIndexOf`, `lt`, `lte`, * `max`, `min`, `noConflict`, `noop`, `now`, `pad`, `padLeft`, `padRight`, * `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, `repeat`, `result`, * `runInContext`, `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, * `sortedLastIndex`, `startCase`, `startsWith`, `sum`, `template`, `trim`, * `trimLeft`, `trimRight`, `trunc`, `unescape`, `uniqueId`, `value`, and `words` * * The wrapper method `sample` will return a wrapped value when `n` is provided, * otherwise an unwrapped value is returned. * * @name _ * @constructor * @category Chain * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(total, n) { * return total + n; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(n) { * return n * n; * }); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The function whose prototype all chaining wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable chaining for all wrapper methods. * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value. */ function LodashWrapper(value, chainAll, actions) { this.__wrapped__ = value; this.__actions__ = actions || []; this.__chain__ = !!chainAll; } /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = lodash.support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if the `toStringTag` of `arguments` objects is resolvable * (all but Firefox < 4, IE < 9). * * @memberOf _.support * @type boolean */ support.argsTag = objToString.call(arguments) == argsTag; /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default (IE < 9, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly set the `[[Enumerable]]` value of a function's `prototype` * property to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); /** * Detect if the `toStringTag` of DOM nodes is resolvable (all but IE < 9). * * @memberOf _.support * @type boolean */ support.nodeTag = objToString.call(document) != objectTag; /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an object's own properties, shadowing non-enumerable ones, * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects * correctly. * * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array * `shift()` and `splice()` functions that fail to remove the last element, * `value[0]`, of array-like objects even though the "length" property is * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, * while `splice()` is buggy regardless of mode in IE < 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index. IE 8 can only access characters * by index on string literals, not string objects. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; /** * Detect if the DOM is supported. * * @memberOf _.support * @type boolean */ try { support.dom = document.createDocumentFragment().nodeType === 11; } catch(e) { support.dom = false; } }(1, 0)); /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB). Change the following template settings to use * alternative delimiters. * * @static * @memberOf _ * @type Object */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type RegExp */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type RegExp */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type RegExp */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type string */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type Object */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type Function */ '_': lodash } }; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = null; this.__dir__ = 1; this.__dropCount__ = 0; this.__filtered__ = false; this.__iteratees__ = null; this.__takeCount__ = POSITIVE_INFINITY; this.__views__ = null; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var actions = this.__actions__, iteratees = this.__iteratees__, views = this.__views__, result = new LazyWrapper(this.__wrapped__); result.__actions__ = actions ? arrayCopy(actions) : null; result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = iteratees ? arrayCopy(iteratees) : null; result.__takeCount__ = this.__takeCount__; result.__views__ = views ? arrayCopy(views) : null; return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(); if (!isArray(array)) { return baseWrapperValue(array, this.__actions__); } var dir = this.__dir__, isRight = dir < 0, view = getView(0, array.length, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), takeCount = nativeMin(length, this.__takeCount__), iteratees = this.__iteratees__, iterLength = iteratees ? iteratees.length : 0, resIndex = 0, result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type; if (type == LAZY_DROP_WHILE_FLAG) { if (data.done && (isRight ? (index > data.index) : (index < data.index))) { data.count = 0; data.done = false; } data.index = index; if (!data.done) { var limit = data.limit; if (!(data.done = limit > -1 ? (data.count++ >= limit) : !iteratee(value))) { continue outer; } } } else { var computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } } result[resIndex++] = value; } return result; } /*------------------------------------------------------------------------*/ /** * Creates a cache object to store key/value pairs. * * @private * @static * @name Cache * @memberOf _.memoize */ function MapCache() { this.__data__ = {}; } /** * Removes `key` and its value from the cache. * * @private * @name delete * @memberOf _.memoize.Cache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`. */ function mapDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the cached value for `key`. * * @private * @name get * @memberOf _.memoize.Cache * @param {string} key The key of the value to get. * @returns {*} Returns the cached value. */ function mapGet(key) { return key == '__proto__' ? undefined : this.__data__[key]; } /** * Checks if a cached value for `key` exists. * * @private * @name has * @memberOf _.memoize.Cache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapHas(key) { return key != '__proto__' && hasOwnProperty.call(this.__data__, key); } /** * Sets `value` to `key` of the cache. * * @private * @name set * @memberOf _.memoize.Cache * @param {string} key The key of the value to cache. * @param {*} value The value to cache. * @returns {Object} Returns the cache object. */ function mapSet(key, value) { if (key != '__proto__') { this.__data__[key] = value; } return this; } /*------------------------------------------------------------------------*/ /** * * Creates a cache object to store unique values. * * @private * @param {Array} [values] The values to cache. */ function SetCache(values) { var length = values ? values.length : 0; this.data = { 'hash': nativeCreate(null), 'set': new Set }; while (length--) { this.push(values[length]); } } /** * Checks if `value` is in `cache` mimicking the return signature of * `_.indexOf` by returning `0` if the value is found, else `-1`. * * @private * @param {Object} cache The cache to search. * @param {*} value The value to search for. * @returns {number} Returns `0` if `value` is found, else `-1`. */ function cacheIndexOf(cache, value) { var data = cache.data, result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; return result ? 0 : -1; } /** * Adds `value` to the cache. * * @private * @name push * @memberOf SetCache * @param {*} value The value to cache. */ function cachePush(value) { var data = this.data; if (typeof value == 'string' || isObject(value)) { data.set.add(value); } else { data.hash[value] = true; } } /*------------------------------------------------------------------------*/ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * callback shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `baseExtremum` for arrays which invokes `iteratee` * with one argument: (value). * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} comparator The function used to compare values. * @param {*} exValue The initial extremum value. * @returns {*} Returns the extremum value. */ function arrayExtremum(array, iteratee, comparator, exValue) { var index = -1, length = array.length, computed = exValue, result = computed; while (++index < length) { var value = array[index], current = +iteratee(value); if (comparator(current, computed)) { computed = current; result = value; } } return result; } /** * A specialized version of `_.filter` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[++resIndex] = value; } } return result; } /** * A specialized version of `_.map` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * A specialized version of `_.reduce` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initFromArray] Specify using the first element of `array` * as the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initFromArray) { var index = -1, length = array.length; if (initFromArray && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * callback shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initFromArray] Specify using the last element of `array` * as the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initFromArray) { var length = array.length; if (initFromArray && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * A specialized version of `_.sum` for arrays without support for iteratees. * * @private * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. */ function arraySum(array) { var length = array.length, result = 0; while (length--) { result += +array[length] || 0; } return result; } /** * Used by `_.defaults` to customize its `_.assign` use. * * @private * @param {*} objectValue The destination object property value. * @param {*} sourceValue The source object property value. * @returns {*} Returns the value to assign to the destination object. */ function assignDefaults(objectValue, sourceValue) { return objectValue === undefined ? sourceValue : objectValue; } /** * Used by `_.template` to customize its `_.assign` use. * * **Note:** This function is like `assignDefaults` except that it ignores * inherited property values when checking if a property is `undefined`. * * @private * @param {*} objectValue The destination object property value. * @param {*} sourceValue The source object property value. * @param {string} key The key associated with the object and source values. * @param {Object} object The destination object. * @returns {*} Returns the value to assign to the destination object. */ function assignOwnDefaults(objectValue, sourceValue, key, object) { return (objectValue === undefined || !hasOwnProperty.call(object, key)) ? sourceValue : objectValue; } /** * A specialized version of `_.assign` for customizing assigned values without * support for argument juggling, multiple sources, and `this` binding `customizer` * functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. */ function assignWith(object, source, customizer) { var index = -1, props = keys(source), length = props.length; while (++index < length) { var key = props[index], value = object[key], result = customizer(value, source[key], key, object, source); if ((result === result ? (result !== value) : (value === value)) || (value === undefined && !(key in object))) { object[key] = result; } } return object; } /** * The base implementation of `_.assign` without support for argument juggling, * multiple sources, and `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return source == null ? object : baseCopy(source, keys(source), object); } /** * The base implementation of `_.at` without support for string collections * and individual key arguments. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {number[]|string[]} props The property names or indexes of elements to pick. * @returns {Array} Returns the new array of picked elements. */ function baseAt(collection, props) { var index = -1, isNil = collection == null, isArr = !isNil && isArrayLike(collection), length = isArr ? collection.length : 0, propsLength = props.length, result = Array(propsLength); while(++index < propsLength) { var key = props[index]; if (isArr) { result[index] = isIndex(key, length) ? collection[key] : undefined; } else { result[index] = isNil ? undefined : collection[key]; } } return result; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } /** * The base implementation of `_.callback` which supports specifying the * number of arguments to provide to `func`. * * @private * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } /** * The base implementation of `_.clone` without support for argument juggling * and `this` binding `customizer` functions. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {Function} [customizer] The function to customize cloning values. * @param {string} [key] The key of `value`. * @param {Object} [object] The object `value` belongs to. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates clones with source counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { var result; if (customizer) { result = object ? customizer(value, key, object) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return arrayCopy(value, result); } } else { var tag = objToString.call(value), isFunc = tag == funcTag; if (tag == objectTag || tag == argsTag || (isFunc && !object)) { if (isHostObject(value)) { return object ? value : {}; } result = initCloneObject(isFunc ? {} : value); if (!isDeep) { return baseAssign(result, value); } } else { return cloneableTags[tag] ? initCloneByTag(value, tag, isDeep) : (object ? value : {}); } } // Check for circular references and return corresponding clone. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } // Add the source value to the stack of traversed objects and associate it with its clone. stackA.push(value); stackB.push(result); // Recursively populate clone (susceptible to call stack limits). (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); }); return result; } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(prototype) { if (isObject(prototype)) { object.prototype = prototype; var result = new object; object.prototype = null; } return result || {}; }; }()); /** * The base implementation of `_.delay` and `_.defer` which accepts an index * of where to slice the arguments to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Object} args The arguments provide to `func`. * @returns {number} Returns the timer id. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of `_.difference` which accepts a single array * of values to exclude. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values) { var length = array ? array.length : 0, result = []; if (!length) { return result; } var index = -1, indexOf = getIndexOf(), isCommon = indexOf == baseIndexOf, cache = (isCommon && values.length >= 200) ? createCache(values) : null, valuesLength = values.length; if (cache) { indexOf = cacheIndexOf; isCommon = false; values = cache; } outer: while (++index < length) { var value = array[index]; if (isCommon && value === value) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === value) { continue outer; } } result.push(value); } else if (indexOf(values, value, 0) < 0) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * Gets the extremum value of `collection` invoking `iteratee` for each value * in `collection` to generate the criterion by which the value is ranked. * The `iteratee` is invoked with three arguments: (value, index|key, collection). * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} comparator The function used to compare values. * @param {*} exValue The initial extremum value. * @returns {*} Returns the extremum value. */ function baseExtremum(collection, iteratee, comparator, exValue) { var computed = exValue, result = computed; baseEach(collection, function(value, index, collection) { var current = +iteratee(value, index, collection); if (comparator(current, computed) || (current === exValue && current === result)) { computed = current; result = value; } }); return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : (end >>> 0); start >>>= 0; while (start < length) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`, * without support for callback shorthands and `this` binding, which iterates * over `collection` using the provided `eachFunc`. * * @private * @param {Array|Object|string} collection The collection to search. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @param {boolean} [retKey] Specify returning the key of the found element * instead of the element itself. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFind(collection, predicate, eachFunc, retKey) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = retKey ? key : value; return false; } }); return result; } /** * The base implementation of `_.flatten` with added support for restricting * flattening and specifying the start index. * * @private * @param {Array} array The array to flatten. * @param {boolean} [isDeep] Specify a deep flatten. * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, isDeep, isStrict) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (isObjectLike(value) && isArrayLike(value) && (isStrict || isArray(value) || isArguments(value))) { if (isDeep) { // Recursively flatten arrays (susceptible to call stack limits). value = baseFlatten(value, isDeep, isStrict); } var valIndex = -1, valLength = value.length; while (++valIndex < valLength) { result[++resIndex] = value[valIndex]; } } else if (!isStrict) { result[++resIndex] = value; } } return result; } /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } /** * The base implementation of `_.forOwn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from those provided. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the new array of filtered property names. */ function baseFunctions(object, props) { var index = -1, length = props.length, resIndex = -1, result = []; while (++index < length) { var key = props[index]; if (isFunction(object[key])) { result[++resIndex] = key; } } return result; } /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } object = toObject(object); if (pathKey !== undefined && pathKey in object) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = toObject(object)[path[index++]]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing objects. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `value` objects. * @param {Array} [stackB=[]] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } /** * The base implementation of `_.isMatch` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to inspect. * @param {Array} matchData The propery names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparing objects. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = toObject(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var result = customizer ? customizer(objValue, srcValue, key) : undefined; if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { return false; } } } return true; } /** * The base implementation of `_.map` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which does not clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { var key = matchData[0][0], value = matchData[0][1]; return function(object) { if (object == null) { return false; } object = toObject(object); return object[key] === value && (value !== undefined || (key in object)); }; } return function(object) { return baseIsMatch(object, matchData); }; } /** * The base implementation of `_.matchesProperty` which does not clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to compare. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, srcValue) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(srcValue), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === srcValue ? (srcValue !== undefined || (key in object)) : baseIsEqual(srcValue, object[key], undefined, true); }; } /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? null : keys(source); arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((result !== undefined || (isSrcArr && !(key in object))) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (isArrayLike(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : toObject(object)[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } /** * The base implementation of `_.pullAt` without support for individual * index arguments and capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0; while (length--) { var index = indexes[length]; if (index != previous && isIndex(index)) { var previous = index; splice.call(array, index, 1); } } return array; } /** * The base implementation of `_.random` without support for argument juggling * and returning floating-point numbers. * * @private * @param {number} min The minimum possible value. * @param {number} max The maximum possible value. * @returns {number} Returns the random number. */ function baseRandom(min, max) { return min + floor(nativeRandom() * (max - min + 1)); } /** * The base implementation of `_.reduce` and `_.reduceRight` without support * for callback shorthands and `this` binding, which iterates over `collection` * using the provided `eachFunc`. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initFromCollection Specify using the first or last element * of `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initFromCollection ? (initFromCollection = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `setData` without support for hot loop detection. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortBy` which uses `comparer` to define * the sort order of `array` and replaces criteria objects with their * corresponding values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sortByOrder` without param guards. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {boolean[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseSortByOrder(collection, iteratees, orders) { var callback = getCallback(), index = -1; iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); }); var result = baseMap(collection, function(value) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.sum` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(collection, iteratee) { var result = 0; baseEach(collection, function(value, index, collection) { result += +iteratee(value, index, collection) || 0; }); return result; } /** * The base implementation of `_.uniq` without support for callback shorthands * and `this` binding. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The function invoked per iteration. * @returns {Array} Returns the new duplicate-value-free array. */ function baseUniq(array, iteratee) { var index = -1, indexOf = getIndexOf(), length = array.length, isCommon = indexOf == baseIndexOf, isLarge = isCommon && length >= 200, seen = isLarge ? createCache() : null, result = []; if (seen) { indexOf = cacheIndexOf; isCommon = false; } else { isLarge = false; seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value, index, array) : value; if (isCommon && value === value) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (indexOf(seen, computed, 0) < 0) { if (iteratee || isLarge) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { var index = -1, length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } /** * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`, * and `_.takeWhile` without support for callback shorthands and `this` binding. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to peform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } var index = -1, length = actions.length; while (++index < length) { var args = [result], action = actions[index]; push.apply(args, action.args); result = action.func.apply(action.thisArg, args); } return result; } /** * Performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function binaryIndex(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) { low = mid + 1; } else { high = mid; } } return high; } return binaryIndexBy(array, value, identity, retHighest); } /** * This function is like `binaryIndex` except that it invokes `iteratee` for * `value` and each element of `array` to compute their sort ranking. The * iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The function invoked per iteration. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function binaryIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, valIsNull = value === null, valIsUndef = value === undefined; while (low < high) { var mid = floor((low + high) / 2), computed = iteratee(array[mid]), isDef = computed !== undefined, isReflexive = computed === computed; if (valIsNaN) { var setLow = isReflexive || retHighest; } else if (valIsNull) { setLow = isReflexive && isDef && (retHighest || computed != null); } else if (valIsUndef) { setLow = isReflexive && (retHighest || isDef); } else if (computed == null) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } /** * Creates a clone of the given array buffer. * * @private * @param {ArrayBuffer} buffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function bufferClone(buffer) { return bufferSlice.call(buffer, 0); } if (!bufferSlice) { // PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`. bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function(buffer) { var byteLength = buffer.byteLength, floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0, offset = floatLength * FLOAT64_BYTES_PER_ELEMENT, result = new ArrayBuffer(byteLength); if (floatLength) { var view = new Float64Array(result, 0, floatLength); view.set(new Float64Array(buffer, 0, floatLength)); } if (byteLength != offset) { view = new Uint8Array(result, offset); view.set(new Uint8Array(buffer, offset)); } return result; }; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array|Object} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders) { var holdersLength = holders.length, argsIndex = -1, argsLength = nativeMax(args.length - holdersLength, 0), leftIndex = -1, leftLength = partials.length, result = Array(argsLength + leftLength); while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { result[holders[argsIndex]] = args[argsIndex]; } while (argsLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array|Object} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders) { var holdersIndex = -1, holdersLength = holders.length, argsIndex = -1, argsLength = nativeMax(args.length - holdersLength, 0), rightIndex = -1, rightLength = partials.length, result = Array(argsLength + rightLength); while (++argsIndex < argsLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } return result; } /** * Creates a function that aggregates a collection, creating an accumulator * object composed from the results of running each element in the collection * through an iteratee. * * **Note:** This function is used to create `_.countBy`, `_.groupBy`, `_.indexBy`, * and `_.partition`. * * @private * @param {Function} setter The function to set keys and values of the accumulator object. * @param {Function} [initializer] The function to initialize the accumulator object. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee, thisArg) { var result = initializer ? initializer() : {}; iteratee = getCallback(iteratee, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; setter(result, value, iteratee(value, index, collection), collection); } } else { baseEach(collection, function(value, key, collection) { setter(result, value, iteratee(value, key, collection), collection); }); } return result; }; } /** * Creates a function that assigns properties of source object(s) to a given * destination object. * * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : undefined; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` and invokes it with the `this` * binding of `thisArg`. * * @private * @param {Function} func The function to bind. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new bound function. */ function createBindWrapper(func, thisArg) { var Ctor = createCtorWrapper(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(thisArg, arguments); } return wrapper; } /** * Creates a `Set` cache object to optimize linear searches of large arrays. * * @private * @param {Array} [values] The values to cache. * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. */ var createCache = !(nativeCreate && Set) ? constant(null) : function(values) { return new SetCache(values); }; /** * Creates a function that produces compound words out of the words in a * given string. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { var index = -1, array = words(deburr(string)), length = array.length, result = ''; while (++index < length) { result = callback(result, array[index], index); } return result; }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtorWrapper(Ctor) { return function() { // Use a `switch` statement to work with class constructors. // See https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a `_.curry` or `_.curryRight` function. * * @private * @param {boolean} flag The curry bit flag. * @returns {Function} Returns the new curry function. */ function createCurry(flag) { function curryFunc(func, arity, guard) { if (guard && isIterateeCall(func, arity, guard)) { arity = null; } var result = createWrapper(func, flag, null, null, null, null, null, arity); result.placeholder = curryFunc.placeholder; return result; } return curryFunc; } /** * Creates a `_.max` or `_.min` function. * * @private * @param {Function} comparator The function used to compare values. * @param {*} exValue The initial extremum value. * @returns {Function} Returns the new extremum function. */ function createExtremum(comparator, exValue) { return function(collection, iteratee, thisArg) { if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } iteratee = getCallback(iteratee, thisArg, 3); if (iteratee.length == 1) { collection = toIterable(collection); var result = arrayExtremum(collection, iteratee, comparator, exValue); if (!(collection.length && result === exValue)) { return result; } } return baseExtremum(collection, iteratee, comparator, exValue); }; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new find function. */ function createFind(eachFunc, fromRight) { return function(collection, predicate, thisArg) { predicate = getCallback(predicate, thisArg, 3); if (isArray(collection)) { var index = baseFindIndex(collection, predicate, fromRight); return index > -1 ? collection[index] : undefined; } return baseFind(collection, predicate, eachFunc); }; } /** * Creates a `_.findIndex` or `_.findLastIndex` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new find function. */ function createFindIndex(fromRight) { return function(array, predicate, thisArg) { if (!(array && array.length)) { return -1; } predicate = getCallback(predicate, thisArg, 3); return baseFindIndex(array, predicate, fromRight); }; } /** * Creates a `_.findKey` or `_.findLastKey` function. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new find function. */ function createFindKey(objectFunc) { return function(object, predicate, thisArg) { predicate = getCallback(predicate, thisArg, 3); return baseFind(object, predicate, objectFunc, true); }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return function() { var wrapper, length = arguments.length, index = fromRight ? length : -1, leftIndex = 0, funcs = Array(length); while ((fromRight ? index-- : ++index < length)) { var func = funcs[leftIndex++] = arguments[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') { wrapper = new LodashWrapper([]); } } index = wrapper ? -1 : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : null; if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments; if (wrapper && args.length == 1 && isArray(args[0])) { return wrapper.plant(args[0]).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : args[0]; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }; } /** * Creates a function for `_.forEach` or `_.forEachRight`. * * @private * @param {Function} arrayFunc The function to iterate over an array. * @param {Function} eachFunc The function to iterate over a collection. * @returns {Function} Returns the new each function. */ function createForEach(arrayFunc, eachFunc) { return function(collection, iteratee, thisArg) { return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee) : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); }; } /** * Creates a function for `_.forIn` or `_.forInRight`. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new each function. */ function createForIn(objectFunc) { return function(object, iteratee, thisArg) { if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee, keysIn); }; } /** * Creates a function for `_.forOwn` or `_.forOwnRight`. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new each function. */ function createForOwn(objectFunc) { return function(object, iteratee, thisArg) { if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee); }; } /** * Creates a function for `_.mapKeys` or `_.mapValues`. * * @private * @param {boolean} [isMapKeys] Specify mapping keys instead of values. * @returns {Function} Returns the new map function. */ function createObjectMapper(isMapKeys) { return function(object, iteratee, thisArg) { var result = {}; iteratee = getCallback(iteratee, thisArg, 3); baseForOwn(object, function(value, key, object) { var mapped = iteratee(value, key, object); key = isMapKeys ? mapped : key; value = isMapKeys ? value : mapped; result[key] = value; }); return result; }; } /** * Creates a function for `_.padLeft` or `_.padRight`. * * @private * @param {boolean} [fromRight] Specify padding from the right. * @returns {Function} Returns the new pad function. */ function createPadDir(fromRight) { return function(string, length, chars) { string = baseToString(string); return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string); }; } /** * Creates a `_.partial` or `_.partialRight` function. * * @private * @param {boolean} flag The partial bit flag. * @returns {Function} Returns the new partial function. */ function createPartial(flag) { var partialFunc = restParam(function(func, partials) { var holders = replaceHolders(partials, partialFunc.placeholder); return createWrapper(func, flag, null, partials, holders); }); return partialFunc; } /** * Creates a function for `_.reduce` or `_.reduceRight`. * * @private * @param {Function} arrayFunc The function to iterate over an array. * @param {Function} eachFunc The function to iterate over a collection. * @returns {Function} Returns the new each function. */ function createReduce(arrayFunc, eachFunc) { return function(collection, iteratee, accumulator, thisArg) { var initFromArray = arguments.length < 3; return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee, accumulator, initFromArray) : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc); }; } /** * Creates a function that wraps `func` and invokes it with optional `this` * binding of, partial application, and currying. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurry = bitmask & CURRY_FLAG, isCurryBound = bitmask & CURRY_BOUND_FLAG, isCurryRight = bitmask & CURRY_RIGHT_FLAG, Ctor = isBindKey ? null : createCtorWrapper(func); function wrapper() { // Avoid `arguments` object use disqualifying optimizations by // converting it to an array before providing it to other functions. var length = arguments.length, index = length, args = Array(length); while (index--) { args[index] = arguments[index]; } if (partials) { args = composeArgs(args, partials, holders); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight); } if (isCurry || isCurryRight) { var placeholder = wrapper.placeholder, argsHolders = replaceHolders(args, placeholder); length -= argsHolders.length; if (length < arity) { var newArgPos = argPos ? arrayCopy(argPos) : null, newArity = nativeMax(arity - length, 0), newsHolders = isCurry ? argsHolders : null, newHoldersRight = isCurry ? null : argsHolders, newPartials = isCurry ? args : null, newPartialsRight = isCurry ? null : args; bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); if (!isCurryBound) { bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); } var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity], result = createHybridWrapper.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return result; } } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; if (argPos) { args = reorder(args, argPos); } if (isAry && ary < args.length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtorWrapper(func); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates the padding required for `string` based on the given `length`. * The `chars` string is truncated if the number of characters exceeds `length`. * * @private * @param {string} string The string to create padding for. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the pad for `string`. */ function createPadding(string, length, chars) { var strLength = string.length; length = +length; if (strLength >= length || !nativeIsFinite(length)) { return ''; } var padLength = length - strLength; chars = chars == null ? ' ' : (chars + ''); return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength); } /** * Creates a function that wraps `func` and invokes it with the optional `this` * binding of `thisArg` and the `partials` prepended to those provided to * the wrapper. * * @private * @param {Function} func The function to partially apply arguments to. * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to the new function. * @returns {Function} Returns the new bound function. */ function createPartialWrapper(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtorWrapper(func); function wrapper() { // Avoid `arguments` object use disqualifying optimizations by // converting it to an array before providing it `func`. var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(argsLength + leftLength); while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.sortedIndex` or `_.sortedLastIndex` function. * * @private * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {Function} Returns the new index function. */ function createSortedIndex(retHighest) { return function(array, value, iteratee, thisArg) { var callback = getCallback(iteratee); return (iteratee == null && callback === baseCallback) ? binaryIndex(array, value, retHighest) : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of flags. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); partials = holders = null; } length -= (holders ? holders.length : 0); if (bitmask & PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = null; } var data = isBindKey ? null : getData(func), newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; if (data) { mergeData(newData, data); bitmask = newData[1]; arity = newData[9]; } newData[9] = arity == null ? (isBindKey ? 0 : func.length) : (nativeMax(arity - length, 0) || 0); if (bitmask == BIND_FLAG) { var result = createBindWrapper(newData[0], newData[2]); } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { result = createPartialWrapper.apply(undefined, newData); } else { result = createHybridWrapper.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setter(result, newData); } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing arrays. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index], result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; if (result !== undefined) { if (result) { continue; } return false; } // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); })) { return false; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { return false; } } return true; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} value The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: // Coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. return +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { return false; } } var skipCtor = isLoose; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key], result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; // Recursively compare objects (susceptible to call stack limits). if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } /** * Gets the appropriate "callback" function. If the `_.callback` method is * customized this function returns the custom method, otherwise it returns * the `baseCallback` function. If arguments are provided the chosen function * is invoked with them and its result is returned. * * @private * @returns {Function} Returns the chosen function or its result. */ function getCallback(func, thisArg, argCount) { var result = lodash.callback || callback; result = result === callback ? baseCallback : result; return argCount ? result(func, thisArg, argCount) : result; } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = func.name, array = realNames[result], length = array ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the appropriate "indexOf" function. If the `_.indexOf` method is * customized this function returns the custom method, otherwise it returns * the `baseIndexOf` function. If arguments are provided the chosen function * is invoked with them and its result is returned. * * @private * @returns {Function|number} Returns the chosen function or its result. */ function getIndexOf(collection, target, fromIndex) { var result = lodash.indexOf || indexOf; result = result === indexOf ? baseIndexOf : result; return collection ? result(collection, target, fromIndex) : result; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Gets the propery names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = pairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} [transforms] The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms ? transforms.length : 0; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add array properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { var Ctor = object.constructor; if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { Ctor = Object; } return new Ctor; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return bufferClone(object); case boolTag: case dateTag: return new Ctor(+object); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: // Safari 5 mobile incorrectly has `Object` as the constructor of typed arrays. if (Ctor instanceof Ctor) { Ctor = ctorByTag[tag]; } var buffer = object.buffer; return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); case numberTag: case stringTag: return new Ctor(object); case regexpTag: var result = new Ctor(object.source, reFlags.exec(object)); result.lastIndex = object.lastIndex; } return result; } /** * Invokes the method at `path` on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function invokePath(object, path, args) { if (object != null && !isKey(path, object)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); path = last(path); } var func = object == null ? object : object[path]; return func == null ? undefined : func.apply(object, args); } /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if the provided arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object)) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`. */ function isLaziable(func) { var funcName = getFuncName(func); if (!(funcName in LazyWrapper.prototype)) { return false; } var other = lodash[funcName]; if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers required to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg` * augment function arguments, making the order in which they are executed important, * preventing the merging of metadata. However, we make an exception for a safe * common case where curried functions have `_.ary` and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < ARY_FLAG; var isCombo = (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) || (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) || (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value); data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]); } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value); data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]); } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = arrayCopy(value); } // Use source `ary` if it's smaller. if (srcBitmask & ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * A specialized version of `_.pick` which picks `object` properties specified * by `props`. * * @private * @param {Object} object The source object. * @param {string[]} props The property names to pick. * @returns {Object} Returns the new object. */ function pickByArray(object, props) { object = toObject(object); var index = -1, length = props.length, result = {}; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } return result; } /** * A specialized version of `_.pick` which picks `object` properties `predicate` * returns truthy for. * * @private * @param {Object} object The source object. * @param {Function} predicate The function invoked per iteration. * @returns {Object} Returns the new object. */ function pickByCallback(object, predicate) { var result = {}; baseForIn(object, function(value, key, object) { if (predicate(value, key, object)) { result[key] = value; } }); return result; } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = arrayCopy(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity function * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = (function() { var count = 0, lastCalled = 0; return function(key, value) { var stamp = now(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return key; } } else { count = 0; } return baseSetData(key, value); }; }()); /** * A fallback implementation of `_.isPlainObject` which checks if `value` * is an object created by the `Object` constructor or has a `[[Prototype]]` * of `null`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { var Ctor, support = lodash.support; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value)) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor))) || (!support.argsTag && isArguments(value))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; if (support.ownLast) { baseForIn(value, function(subValue, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result !== false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } /** * Converts `value` to an array-like object if it's not one. * * @private * @param {*} value The value to process. * @returns {Array|Object} Returns the array-like object. */ function toIterable(value) { if (value == null) { return []; } if (!isArrayLike(value)) { return values(value); } if (lodash.support.unindexedChars && isString(value)) { return value.split(''); } return isObject(value) ? value : Object(value); } /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { if (lodash.support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); } /** * Converts `value` to property path array if it's not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { return wrapper instanceof LazyWrapper ? wrapper.clone() : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__)); } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `collection` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the new array containing chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if (guard ? isIterateeCall(array, size, guard) : size == null) { size = 1; } else { size = nativeMax(+size || 1, 1); } var index = 0, length = array ? array.length : 0, resIndex = -1, result = Array(ceil(length / size)); while (index < length) { result[++resIndex] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (value) { result[++resIndex] = value; } } return result; } /** * Creates an array of unique `array` values not included in the other * provided arrays using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The arrays of values to exclude. * @returns {Array} Returns the new array of filtered values. * @example * * _.difference([1, 2, 3], [4, 2]); * // => [1, 3] */ var difference = restParam(function(array, values) { return isArrayLike(array) ? baseDifference(array, baseFlatten(values, false, true)) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } if (guard ? isIterateeCall(array, n, guard) : n == null) { n = 1; } return baseSlice(array, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } if (guard ? isIterateeCall(array, n, guard) : n == null) { n = 1; } n = length - (+n || 0); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * bound to `thisArg` and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that match the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRightWhile([1, 2, 3], function(n) { * return n > 1; * }); * // => [1] * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); * // => ['barney', 'fred'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.dropRightWhile(users, 'active', false), 'user'); * // => ['barney'] * * // using the `_.property` callback shorthand * _.pluck(_.dropRightWhile(users, 'active'), 'user'); * // => ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate, thisArg) { return (array && array.length) ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * bound to `thisArg` and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropWhile([1, 2, 3], function(n) { * return n < 3; * }); * // => [3] * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user'); * // => ['fred', 'pebbles'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.dropWhile(users, 'active', false), 'user'); * // => ['pebbles'] * * // using the `_.property` callback shorthand * _.pluck(_.dropWhile(users, 'active'), 'user'); * // => ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate, thisArg) { return (array && array.length) ? baseWhile(array, getCallback(predicate, thisArg, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8], '*', 1, 2); * // => [4, '*', 8] */ function fill(array, value, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(chr) { * return chr.user == 'barney'; * }); * // => 0 * * // using the `_.matches` callback shorthand * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // using the `_.matchesProperty` callback shorthand * _.findIndex(users, 'active', false); * // => 0 * * // using the `_.property` callback shorthand * _.findIndex(users, 'active'); * // => 2 */ var findIndex = createFindIndex(); /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(chr) { * return chr.user == 'pebbles'; * }); * // => 2 * * // using the `_.matches` callback shorthand * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // using the `_.matchesProperty` callback shorthand * _.findLastIndex(users, 'active', false); * // => 2 * * // using the `_.property` callback shorthand * _.findLastIndex(users, 'active'); * // => 0 */ var findLastIndex = createFindIndex(true); /** * Gets the first element of `array`. * * @static * @memberOf _ * @alias head * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.first([1, 2, 3]); * // => 1 * * _.first([]); * // => undefined */ function first(array) { return array ? array[0] : undefined; } /** * Flattens a nested array. If `isDeep` is `true` the array is recursively * flattened, otherwise it is only flattened a single level. * * @static * @memberOf _ * @category Array * @param {Array} array The array to flatten. * @param {boolean} [isDeep] Specify a deep flatten. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, 3, [4]]]); * // => [1, 2, 3, [4]] * * // using `isDeep` * _.flatten([1, [2, 3, [4]]], true); * // => [1, 2, 3, 4] */ function flatten(array, isDeep, guard) { var length = array ? array.length : 0; if (guard && isIterateeCall(array, isDeep, guard)) { isDeep = false; } return length ? baseFlatten(array, isDeep) : []; } /** * Recursively flattens a nested array. * * @static * @memberOf _ * @category Array * @param {Array} array The array to recursively flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, 3, [4]]]); * // => [1, 2, 3, 4] */ function flattenDeep(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, true) : []; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it is used as the offset * from the end of `array`. If `array` is sorted providing `true` for `fromIndex` * performs a faster binary search. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {boolean|number} [fromIndex=0] The index to search from or `true` * to perform a binary search on a sorted array. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // using `fromIndex` * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 * * // performing a binary search * _.indexOf([1, 1, 2, 2], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } if (typeof fromIndex == 'number') { fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; } else if (fromIndex) { var index = binaryIndex(array, value), other = array[index]; if (value === value ? (value === other) : (other !== other)) { return index; } return -1; } return baseIndexOf(array, value, fromIndex || 0); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { return dropRight(array, 1); } /** * Creates an array of unique values that are included in all of the provided * arrays using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of shared values. * @example * _.intersection([1, 2], [4, 2], [2, 1]); * // => [2] */ var intersection = restParam(function(arrays) { var othLength = arrays.length, othIndex = othLength, caches = Array(length), indexOf = getIndexOf(), isCommon = indexOf == baseIndexOf, result = []; while (othIndex--) { var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : []; caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null; } var array = arrays[0], index = -1, length = array ? array.length : 0, seen = caches[0]; outer: while (++index < length) { value = array[index]; if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) { var othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) { continue outer; } } if (seen) { seen.push(value); } result.push(value); } } return result; }); /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {boolean|number} [fromIndex=array.length-1] The index to search from * or `true` to perform a binary search on a sorted array. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // using `fromIndex` * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 * * // performing a binary search * _.lastIndexOf([1, 1, 2, 2], 2, true); * // => 3 */ function lastIndexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = length; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1; } else if (fromIndex) { index = binaryIndex(array, value, true) - 1; var other = array[index]; if (value === value ? (value === other) : (other !== other)) { return index; } return -1; } if (value !== value) { return indexOfNaN(array, index, true); } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Removes all provided values from `array` using * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * * _.pull(array, 2, 3); * console.log(array); * // => [1, 1] */ function pull() { var args = arguments, array = args[0]; if (!(array && array.length)) { return array; } var index = 0, indexOf = getIndexOf(), length = args.length; while (++index < length) { var fromIndex = 0, value = args[index]; while ((fromIndex = indexOf(array, value, fromIndex)) > -1) { splice.call(array, fromIndex, 1); } } return array; } /** * Removes elements from `array` corresponding to the given indexes and returns * an array of the removed elements. Indexes may be specified as an array of * indexes or as individual arguments. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove, * specified as individual indexes or arrays of indexes. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [5, 10, 15, 20]; * var evens = _.pullAt(array, 1, 3); * * console.log(array); * // => [5, 15] * * console.log(evens); * // => [10, 20] */ var pullAt = restParam(function(array, indexes) { indexes = baseFlatten(indexes); var result = baseAt(array, indexes); basePullAt(array, indexes.sort(baseCompareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is bound to * `thisArg` and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * **Note:** Unlike `_.filter`, this method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate, thisArg) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getCallback(predicate, thisArg, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @alias tail * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] */ function rest(array) { return drop(array, 1); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of `Array#slice` to support node * lists in IE < 9 and to ensure dense arrays are returned. * * @static * @memberOf _ * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` should * be inserted into `array` in order to maintain its sort order. If an iteratee * function is provided it is invoked for `value` and each element of `array` * to compute their sort ranking. The iteratee is bound to `thisArg` and * invoked with one argument; (value). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 * * _.sortedIndex([4, 4, 5, 5], 5); * // => 2 * * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; * * // using an iteratee function * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { * return this.data[word]; * }, dict); * // => 1 * * // using the `_.property` callback shorthand * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 1 */ var sortedIndex = createSortedIndex(); /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 4, 5, 5], 5); * // => 4 */ var sortedLastIndex = createSortedIndex(true); /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } if (guard ? isIterateeCall(array, n, guard) : n == null) { n = 1; } return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } if (guard ? isIterateeCall(array, n, guard) : n == null) { n = 1; } n = length - (+n || 0); return baseSlice(array, n < 0 ? 0 : n); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is bound to `thisArg` * and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRightWhile([1, 2, 3], function(n) { * return n > 1; * }); * // => [2, 3] * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); * // => ['pebbles'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.takeRightWhile(users, 'active', false), 'user'); * // => ['fred', 'pebbles'] * * // using the `_.property` callback shorthand * _.pluck(_.takeRightWhile(users, 'active'), 'user'); * // => [] */ function takeRightWhile(array, predicate, thisArg) { return (array && array.length) ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is bound to * `thisArg` and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeWhile([1, 2, 3], function(n) { * return n < 3; * }); * // => [1, 2] * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false}, * { 'user': 'pebbles', 'active': true } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user'); * // => ['barney'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.takeWhile(users, 'active', false), 'user'); * // => ['barney', 'fred'] * * // using the `_.property` callback shorthand * _.pluck(_.takeWhile(users, 'active'), 'user'); * // => [] */ function takeWhile(array, predicate, thisArg) { return (array && array.length) ? baseWhile(array, getCallback(predicate, thisArg, 3)) : []; } /** * Creates an array of unique values, in order, from all of the provided arrays * using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([1, 2], [4, 2], [2, 1]); * // => [1, 2, 4] */ var union = restParam(function(arrays) { return baseUniq(baseFlatten(arrays, false, true)); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * for equality comparisons, in which only the first occurence of each element * is kept. Providing `true` for `isSorted` performs a faster search algorithm * for sorted arrays. If an iteratee function is provided it is invoked for * each element in the array to generate the criterion by which uniqueness * is computed. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index, array). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias unique * @category Array * @param {Array} array The array to inspect. * @param {boolean} [isSorted] Specify the array is sorted. * @param {Function|Object|string} [iteratee] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new duplicate-value-free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] * * // using `isSorted` * _.uniq([1, 1, 2], true); * // => [1, 2] * * // using an iteratee function * _.uniq([1, 2.5, 1.5, 2], function(n) { * return this.floor(n); * }, Math); * // => [1, 2.5] * * // using the `_.property` callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniq(array, isSorted, iteratee, thisArg) { var length = array ? array.length : 0; if (!length) { return []; } if (isSorted != null && typeof isSorted != 'boolean') { thisArg = iteratee; iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted; isSorted = false; } var callback = getCallback(); if (!(iteratee == null && callback === baseCallback)) { iteratee = callback(iteratee, thisArg, 3); } return (isSorted && getIndexOf() == baseIndexOf) ? sortedUniq(array, iteratee) : baseUniq(array, iteratee); } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] * * _.unzip(zipped); * // => [['fred', 'barney'], [30, 40], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var index = -1, length = 0; array = arrayFilter(array, function(group) { if (isArrayLike(group)) { length = nativeMax(group.length, length); return true; } }); var result = Array(length); while (++index < length) { result[index] = arrayMap(array, baseProperty(index)); } return result; } /** * This method is like `_.unzip` except that it accepts an iteratee to specify * how regrouped values should be combined. The `iteratee` is bound to `thisArg` * and invoked with four arguments: (accumulator, value, index, group). * * @static * @memberOf _ * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee] The function to combine regrouped values. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee, thisArg) { var length = array ? array.length : 0; if (!length) { return []; } var result = unzip(array); if (iteratee == null) { return result; } iteratee = bindCallback(iteratee, thisArg, 4); return arrayMap(result, function(group) { return arrayReduce(group, iteratee, undefined, true); }); } /** * Creates an array excluding all provided values using * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @category Array * @param {Array} array The array to filter. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @example * * _.without([1, 2, 1, 3], 1, 2); * // => [3] */ var without = restParam(function(array, values) { return isArrayLike(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the provided arrays. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of values. * @example * * _.xor([1, 2], [4, 2]); * // => [1, 4] */ function xor() { var index = -1, length = arguments.length; while (++index < length) { var array = arguments[index]; if (isArrayLike(array)) { var result = result ? baseDifference(result, array).concat(baseDifference(array, result)) : array; } } return result ? baseUniq(result) : []; } /** * Creates an array of grouped elements, the first of which contains the first * elements of the given arrays, the second of which contains the second elements * of the given arrays, and so on. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] */ var zip = restParam(unzip); /** * The inverse of `_.pairs`; this method returns an object composed from arrays * of property names and values. Provide either a single two dimensional array, * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names * and one of corresponding values. * * @static * @memberOf _ * @alias object * @category Array * @param {Array} props The property names. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject([['fred', 30], ['barney', 40]]); * // => { 'fred': 30, 'barney': 40 } * * _.zipObject(['fred', 'barney'], [30, 40]); * // => { 'fred': 30, 'barney': 40 } */ function zipObject(props, values) { var index = -1, length = props ? props.length : 0, result = {}; if (length && !values && !isArray(props[0])) { values = []; } while (++index < length) { var key = props[index]; if (values) { result[key] = values[index]; } else if (key) { result[key[0]] = key[1]; } } return result; } /** * This method is like `_.zip` except that it accepts an iteratee to specify * how grouped values should be combined. The `iteratee` is bound to `thisArg` * and invoked with four arguments: (accumulator, value, index, group). * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee] The function to combine grouped values. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], _.add); * // => [111, 222] */ var zipWith = restParam(function(arrays) { var length = arrays.length, iteratee = length > 2 ? arrays[length - 2] : undefined, thisArg = length > 1 ? arrays[length - 1] : undefined; if (length > 2 && typeof iteratee == 'function') { length -= 2; } else { iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined; thisArg = undefined; } arrays.length = length; return unzipWith(arrays, iteratee, thisArg); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object that wraps `value` with explicit method * chaining enabled. * * @static * @memberOf _ * @category Chain * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _.chain(users) * .sortBy('age') * .map(function(chr) { * return chr.user + ' is ' + chr.age; * }) * .first() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor is * bound to `thisArg` and invoked with one argument; (value). The purpose of * this method is to "tap into" a method chain in order to perform operations * on intermediate results within the chain. * * @static * @memberOf _ * @category Chain * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @param {*} [thisArg] The `this` binding of `interceptor`. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor, thisArg) { interceptor.call(thisArg, value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * * @static * @memberOf _ * @category Chain * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @param {*} [thisArg] The `this` binding of `interceptor`. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor, thisArg) { return interceptor.call(thisArg, value); } /** * Enables explicit method chaining on the wrapper object. * * @name chain * @memberOf _ * @category Chain * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // without explicit chaining * _(users).first(); * // => { 'user': 'barney', 'age': 36 } * * // with explicit chaining * _(users).chain() * .first() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chained sequence and returns the wrapped result. * * @name commit * @memberOf _ * @category Chain * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapper = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapper = wrapper.commit(); * console.log(array); * // => [1, 2, 3] * * wrapper.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Creates a clone of the chained sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @category Chain * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapper = _(array).map(function(value) { * return Math.pow(value, 2); * }); * * var other = [3, 4]; * var otherWrapper = wrapper.plant(other); * * otherWrapper.value(); * // => [9, 16] * * wrapper.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * Reverses the wrapped array so the first element becomes the last, the * second element becomes the second to last, and so on. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @category Chain * @returns {Object} Returns the new reversed `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { if (this.__actions__.length) { value = new LazyWrapper(this); } return new LodashWrapper(value.reverse(), this.__chain__); } return this.thru(function(value) { return value.reverse(); }); } /** * Produces the result of coercing the unwrapped value to a string. * * @name toString * @memberOf _ * @category Chain * @returns {string} Returns the coerced string value. * @example * * _([1, 2, 3]).toString(); * // => '1,2,3' */ function wrapperToString() { return (this.value() + ''); } /** * Executes the chained sequence to extract the unwrapped value. * * @name value * @memberOf _ * @alias run, toJSON, valueOf * @category Chain * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an array of elements corresponding to the given keys, or indexes, * of `collection`. Keys may be specified as individual arguments or as arrays * of keys. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {...(number|number[]|string|string[])} [props] The property names * or indexes of elements to pick, specified individually or in arrays. * @returns {Array} Returns the new array of picked elements. * @example * * _.at(['a', 'b', 'c'], [0, 2]); * // => ['a', 'c'] * * _.at(['barney', 'fred', 'pebbles'], 0, 2); * // => ['barney', 'pebbles'] */ var at = restParam(function(collection, props) { if (isArrayLike(collection)) { collection = toIterable(collection); } return baseAt(collection, baseFlatten(props)); }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` through `iteratee`. The corresponding value * of each key is the number of times the key was returned by `iteratee`. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(n) { * return Math.floor(n); * }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(n) { * return this.floor(n); * }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * The predicate is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias all * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // using the `_.matchesProperty` callback shorthand * _.every(users, 'active', false); * // => true * * // using the `_.property` callback shorthand * _.every(users, 'active'); * // => false */ function every(collection, predicate, thisArg) { var func = isArray(collection) ? arrayEvery : baseEvery; if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } if (typeof predicate != 'function' || thisArg !== undefined) { predicate = getCallback(predicate, thisArg, 3); } return func(collection, predicate); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is bound to `thisArg` and * invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias select * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the new filtered array. * @example * * _.filter([4, 5, 6], function(n) { * return n % 2 == 0; * }); * // => [4, 6] * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); * // => ['barney'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.filter(users, 'active', false), 'user'); * // => ['fred'] * * // using the `_.property` callback shorthand * _.pluck(_.filter(users, 'active'), 'user'); * // => ['barney'] */ function filter(collection, predicate, thisArg) { var func = isArray(collection) ? arrayFilter : baseFilter; predicate = getCallback(predicate, thisArg, 3); return func(collection, predicate); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is bound to `thisArg` and * invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias detect * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.result(_.find(users, function(chr) { * return chr.age < 40; * }), 'user'); * // => 'barney' * * // using the `_.matches` callback shorthand * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); * // => 'pebbles' * * // using the `_.matchesProperty` callback shorthand * _.result(_.find(users, 'active', false), 'user'); * // => 'fred' * * // using the `_.property` callback shorthand * _.result(_.find(users, 'active'), 'user'); * // => 'barney' */ var find = createFind(baseEach); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(baseEachRight, true); /** * Performs a deep comparison between each element in `collection` and the * source object, returning the first element that has equivalent property * values. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. For comparing a single * own or inherited property value see `_.matchesProperty`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Object} source The object of property values to match. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user'); * // => 'barney' * * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user'); * // => 'fred' */ function findWhere(collection, source) { return find(collection, baseMatches(source)); } /** * Iterates over elements of `collection` invoking `iteratee` for each element. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). Iteratee functions may exit iteration early * by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" property * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` * may be used for object iteration. * * @static * @memberOf _ * @alias each * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2]).forEach(function(n) { * console.log(n); * }).value(); * // => logs each value from left to right and returns the array * * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { * console.log(n, key); * }); * // => logs each value-key pair and returns the object (iteration order is not guaranteed) */ var forEach = createForEach(arrayEach, baseEach); /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @alias eachRight * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2]).forEachRight(function(n) { * console.log(n); * }).value(); * // => logs each value from right to left and returns the array */ var forEachRight = createForEach(arrayEachRight, baseEachRight); /** * Creates an object composed of keys generated from the results of running * each element of `collection` through `iteratee`. The corresponding value * of each key is an array of the elements responsible for generating the key. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([4.2, 6.1, 6.4], function(n) { * return Math.floor(n); * }); * // => { '4': [4.2], '6': [6.1, 6.4] } * * _.groupBy([4.2, 6.1, 6.4], function(n) { * return this.floor(n); * }, Math); * // => { '4': [4.2], '6': [6.1, 6.4] } * * // using the `_.property` callback shorthand * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { result[key] = [value]; } }); /** * Checks if `value` is in `collection` using * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it is used as the offset * from the end of `collection`. * * @static * @memberOf _ * @alias contains, include * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {*} target The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. * @returns {boolean} Returns `true` if a matching element is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); * // => true * * _.includes('pebbles', 'eb'); * // => true */ function includes(collection, target, fromIndex, guard) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { collection = values(collection); length = collection.length; } if (!length) { return false; } if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { fromIndex = 0; } else { fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); } return (typeof collection == 'string' || !isArray(collection) && isString(collection)) ? (fromIndex < length && collection.indexOf(target, fromIndex) > -1) : (getIndexOf(collection, target, fromIndex) > -1); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` through `iteratee`. The corresponding value * of each key is the last element responsible for generating the key. The * iteratee function is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the composed aggregate object. * @example * * var keyData = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.indexBy(keyData, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keyData, function(object) { * return String.fromCharCode(object.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keyData, function(object) { * return this.fromCharCode(object.code); * }, String); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } */ var indexBy = createAggregator(function(result, value, key) { result[key] = value; }); /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `methodName` is a function it is * invoked for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke the method with. * @returns {Array} Returns the array of results. * @example * * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invoke = restParam(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', isProp = isKey(path), result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { var func = isFunc ? path : ((isProp && value != null) ? value[path] : null); result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); }); return result; }); /** * Creates an array of values by running each element in `collection` through * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, * `sum`, `uniq`, and `words` * * @static * @memberOf _ * @alias collect * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new mapped array. * @example * * function timesThree(n) { * return n * 3; * } * * _.map([1, 2], timesThree); * // => [3, 6] * * _.map({ 'a': 1, 'b': 2 }, timesThree); * // => [3, 6] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // using the `_.property` callback shorthand * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee, thisArg) { var func = isArray(collection) ? arrayMap : baseMap; iteratee = getCallback(iteratee, thisArg, 3); return func(collection, iteratee); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, while the second of which * contains elements `predicate` returns falsey for. The predicate is bound * to `thisArg` and invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the array of grouped elements. * @example * * _.partition([1, 2, 3], function(n) { * return n % 2; * }); * // => [[1, 3], [2]] * * _.partition([1.2, 2.3, 3.4], function(n) { * return this.floor(n) % 2; * }, Math); * // => [[1.2, 3.4], [2.3]] * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * var mapper = function(array) { * return _.pluck(array, 'user'); * }; * * // using the `_.matches` callback shorthand * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper); * // => [['pebbles'], ['barney', 'fred']] * * // using the `_.matchesProperty` callback shorthand * _.map(_.partition(users, 'active', false), mapper); * // => [['barney', 'pebbles'], ['fred']] * * // using the `_.property` callback shorthand * _.map(_.partition(users, 'active'), mapper); * // => [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Gets the property value of `path` from all elements in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|string} path The path of the property to pluck. * @returns {Array} Returns the property values. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * _.pluck(users, 'user'); * // => ['barney', 'fred'] * * var userIndex = _.indexBy(users, 'user'); * _.pluck(userIndex, 'age'); * // => [36, 40] (iteration order is not guaranteed) */ function pluck(collection, path) { return map(collection, property(path)); } /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` through `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not provided the first element of `collection` is used as the initial * value. The `iteratee` is bound to `thisArg` and invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `includes`, `merge`, `sortByAll`, and `sortByOrder` * * @static * @memberOf _ * @alias foldl, inject * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the accumulated value. * @example * * _.reduce([1, 2], function(total, n) { * return total + n; * }); * // => 3 * * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { * result[key] = n * 3; * return result; * }, {}); * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed) */ var reduce = createReduce(arrayReduce, baseEach); /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the accumulated value. * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ var reduceRight = createReduce(arrayReduceRight, baseEachRight); /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the new filtered array. * @example * * _.reject([1, 2, 3, 4], function(n) { * return n % 2 == 0; * }); * // => [1, 3] * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user'); * // => ['barney'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.reject(users, 'active', false), 'user'); * // => ['fred'] * * // using the `_.property` callback shorthand * _.pluck(_.reject(users, 'active'), 'user'); * // => ['barney'] */ function reject(collection, predicate, thisArg) { var func = isArray(collection) ? arrayFilter : baseFilter; predicate = getCallback(predicate, thisArg, 3); return func(collection, function(value, index, collection) { return !predicate(value, index, collection); }); } /** * Gets a random element or `n` random elements from a collection. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to sample. * @param {number} [n] The number of elements to sample. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {*} Returns the random sample(s). * @example * * _.sample([1, 2, 3, 4]); * // => 2 * * _.sample([1, 2, 3, 4], 2); * // => [3, 1] */ function sample(collection, n, guard) { if (guard ? isIterateeCall(collection, n, guard) : n == null) { collection = toIterable(collection); var length = collection.length; return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; } var index = -1, result = toArray(collection), length = result.length, lastIndex = length - 1; n = nativeMin(n < 0 ? 0 : (+n || 0), length); while (++index < n) { var rand = baseRandom(index, lastIndex), value = result[rand]; result[rand] = result[index]; result[index] = value; } result.length = n; return result; } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { return sample(collection, POSITIVE_INFINITY); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the size of `collection`. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { var length = collection ? getLength(collection) : 0; return isLength(length) ? length : keys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * The function returns as soon as it finds a passing value and does not iterate * over the entire collection. The predicate is bound to `thisArg` and invoked * with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias any * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // using the `_.matchesProperty` callback shorthand * _.some(users, 'active', false); * // => true * * // using the `_.property` callback shorthand * _.some(users, 'active'); * // => true */ function some(collection, predicate, thisArg) { var func = isArray(collection) ? arraySome : baseSome; if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } if (typeof predicate != 'function' || thisArg !== undefined) { predicate = getCallback(predicate, thisArg, 3); } return func(collection, predicate); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through `iteratee`. This method performs * a stable sort, that is, it preserves the original sort order of equal elements. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new sorted array. * @example * * _.sortBy([1, 2, 3], function(n) { * return Math.sin(n); * }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(n) { * return this.sin(n); * }, Math); * // => [3, 1, 2] * * var users = [ * { 'user': 'fred' }, * { 'user': 'pebbles' }, * { 'user': 'barney' } * ]; * * // using the `_.property` callback shorthand * _.pluck(_.sortBy(users, 'user'), 'user'); * // => ['barney', 'fred', 'pebbles'] */ function sortBy(collection, iteratee, thisArg) { if (collection == null) { return []; } if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } var index = -1; iteratee = getCallback(iteratee, thisArg, 3); var result = baseMap(collection, function(value, key, collection) { return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; }); return baseSortBy(result, compareAscending); } /** * This method is like `_.sortBy` except that it can sort by multiple iteratees * or property names. * * If a property name is provided for an iteratee the created `_.property` * style callback returns the property value of the given element. * * If an object is provided for an iteratee the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees * The iteratees to sort by, specified as individual values or arrays of values. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 42 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.map(_.sortByAll(users, ['user', 'age']), _.values); * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] * * _.map(_.sortByAll(users, 'user', function(chr) { * return Math.floor(chr.age / 10); * }), _.values); * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ var sortByAll = restParam(function(collection, iteratees) { if (collection == null) { return []; } var guard = iteratees[2]; if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { iteratees.length = 1; } return baseSortByOrder(collection, baseFlatten(iteratees), []); }); /** * This method is like `_.sortByAll` except that it allows specifying the * sort orders of the iteratees to sort by. A truthy value in `orders` will * sort the corresponding property name in ascending order while a falsey * value will sort it in descending order. * * If a property name is provided for an iteratee the created `_.property` * style callback returns the property value of the given element. * * If an object is provided for an iteratee the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {boolean[]} orders The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 42 }, * { 'user': 'barney', 'age': 36 } * ]; * * // sort by `user` in ascending order and by `age` in descending order * _.map(_.sortByOrder(users, ['user', 'age'], [true, false]), _.values); * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ function sortByOrder(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (guard && isIterateeCall(iteratees, orders, guard)) { orders = null; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseSortByOrder(collection, iteratees, orders); } /** * Performs a deep comparison between each element in `collection` and the * source object, returning an array of all elements that have equivalent * property values. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. For comparing a single * own or inherited property value see `_.matchesProperty`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Object} source The object of property values to match. * @returns {Array} Returns the new filtered array. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] } * ]; * * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user'); * // => ['barney'] * * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user'); * // => ['fred'] */ function where(collection, source) { return filter(collection, baseMatches(source)); } /*------------------------------------------------------------------------*/ /** * Gets the number of milliseconds that have elapsed since the Unix epoch * (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @category Date * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => logs the number of milliseconds it took for the deferred function to be invoked */ var now = nativeNow || function() { return new Date().getTime(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it is called `n` or more times. * * @static * @memberOf _ * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => logs 'done saving!' after the two async saves have completed */ function after(n, func) { if (typeof func != 'function') { if (typeof n == 'function') { var temp = n; n = func; func = temp; } else { throw new TypeError(FUNC_ERROR_TEXT); } } n = nativeIsFinite(n = +n) ? n : 0; return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that accepts up to `n` arguments ignoring any * additional arguments. * * @static * @memberOf _ * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Function} Returns the new function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { if (guard && isIterateeCall(func, n, guard)) { n = null; } n = (func && n == null) ? func.length : nativeMax(+n || 0, 0); return createWrapper(func, ARY_FLAG, null, null, null, null, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it is called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery('#add').on('click', _.before(5, addContactToList)); * // => allows adding up to 4 contacts to the list */ function before(n, func) { var result; if (typeof func != 'function') { if (typeof n == 'function') { var temp = n; n = func; func = temp; } else { throw new TypeError(FUNC_ERROR_TEXT); } } return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = null; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and prepends any additional `_.bind` arguments to those provided to the * bound function. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind` this method does not set the "length" * property of bound functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var greet = function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * }; * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // using placeholders * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = restParam(function(func, thisArg, partials) { var bitmask = BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, bind.placeholder); bitmask |= PARTIAL_FLAG; } return createWrapper(func, bitmask, thisArg, partials, holders); }); /** * Binds methods of an object to the object itself, overwriting the existing * method. Method names may be specified as individual arguments or as arrays * of method names. If no method names are provided all enumerable function * properties, own and inherited, of `object` are bound. * * **Note:** This method does not set the "length" property of bound functions. * * @static * @memberOf _ * @category Function * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} [methodNames] The object method names to bind, * specified as individual method names or arrays of method names. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'onClick': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view); * jQuery('#docs').on('click', view.onClick); * // => logs 'clicked docs' when the element is clicked */ var bindAll = restParam(function(object, methodNames) { methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object); var index = -1, length = methodNames.length; while (++index < length) { var key = methodNames[index]; object[key] = createWrapper(object[key], BIND_FLAG, object); } return object; }); /** * Creates a function that invokes the method at `object[key]` and prepends * any additional `_.bindKey` arguments to those provided to the bound function. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @category Function * @param {Object} object The object the method belongs to. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // using placeholders * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = restParam(function(object, key, partials) { var bitmask = BIND_FLAG | BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, bindKey.placeholder); bitmask |= PARTIAL_FLAG; } return createWrapper(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts one or more arguments of `func` that when * called either invokes `func` returning its result, if all `func` arguments * have been provided, or returns a function that accepts one or more of the * remaining `func` arguments, and so on. The arity of `func` may be specified * if `func.length` is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method does not set the "length" property of curried functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // using placeholders * curried(1)(_, 3)(2); * // => [1, 2, 3] */ var curry = createCurry(CURRY_FLAG); /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method does not set the "length" property of curried functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // using placeholders * curried(3)(1, _)(2); * // => [1, 2, 3] */ var curryRight = createCurry(CURRY_RIGHT_FLAG); /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed invocations. Provide an options object to indicate that `func` * should be invoked on the leading and/or trailing edge of the `wait` timeout. * Subsequent calls to the debounced function return the result of the last * `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the debounced function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options] The options object. * @param {boolean} [options.leading=false] Specify invoking on the leading * edge of the timeout. * @param {number} [options.maxWait] The maximum time `func` is allowed to be * delayed before it is invoked. * @param {boolean} [options.trailing=true] Specify invoking on the trailing * edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // avoid costly calculations while the window size is in flux * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // invoke `sendMail` when the click event is fired, debouncing subsequent calls * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // ensure `batchLog` is invoked once after 1 second of debounced calls * var source = new EventSource('/stream'); * jQuery(source).on('message', _.debounce(batchLog, 250, { * 'maxWait': 1000 * })); * * // cancel a debounced call * var todoChanges = _.debounce(batchLog, 1000); * Object.observe(models.todo, todoChanges); * * Object.observe(models, function(changes) { * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { * todoChanges.cancel(); * } * }, ['delete']); * * // ...at some point `models.todo` is changed * models.todo.completed = true; * * // ...before 1 second has passed `models.todo` is deleted * // which cancels the debounced `todoChanges` call * delete models.todo; */ function debounce(func, wait, options) { var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = wait < 0 ? 0 : (+wait || 0); if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = options.leading; maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); trailing = 'trailing' in options ? options.trailing : trailing; } function cancel() { if (timeoutId) { clearTimeout(timeoutId); } if (maxTimeoutId) { clearTimeout(maxTimeoutId); } maxTimeoutId = timeoutId = trailingCall = undefined; } function delayed() { var remaining = wait - (now() - stamp); if (remaining <= 0 || remaining > wait) { if (maxTimeoutId) { clearTimeout(maxTimeoutId); } var isCalled = trailingCall; maxTimeoutId = timeoutId = trailingCall = undefined; if (isCalled) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = null; } } } else { timeoutId = setTimeout(delayed, remaining); } } function maxDelayed() { if (timeoutId) { clearTimeout(timeoutId); } maxTimeoutId = timeoutId = trailingCall = undefined; if (trailing || (maxWait !== wait)) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = null; } } } function debounced() { args = arguments; stamp = now(); thisArg = this; trailingCall = trailing && (timeoutId || !leading); if (maxWait === false) { var leadingCall = leading && !timeoutId; } else { if (!maxTimeoutId && !leading) { lastCalled = stamp; } var remaining = maxWait - (stamp - lastCalled), isCalled = remaining <= 0 || remaining > maxWait; if (isCalled) { if (maxTimeoutId) { maxTimeoutId = clearTimeout(maxTimeoutId); } lastCalled = stamp; result = func.apply(thisArg, args); } else if (!maxTimeoutId) { maxTimeoutId = setTimeout(maxDelayed, remaining); } } if (isCalled && timeoutId) { timeoutId = clearTimeout(timeoutId); } else if (!timeoutId && wait !== maxWait) { timeoutId = setTimeout(delayed, wait); } if (leadingCall) { isCalled = true; result = func.apply(thisArg, args); } if (isCalled && !timeoutId && !maxTimeoutId) { args = thisArg = null; } return result; } debounced.cancel = cancel; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it is invoked. * * @static * @memberOf _ * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // logs 'deferred' after one or more milliseconds */ var defer = restParam(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it is invoked. * * @static * @memberOf _ * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => logs 'later' after one second */ var delay = restParam(function(func, wait, args) { return baseDelay(func, wait, args); }); /** * Creates a function that returns the result of invoking the provided * functions with the `this` binding of the created function, where each * successive invocation is supplied the return value of the previous. * * @static * @memberOf _ * @category Function * @param {...Function} [funcs] Functions to invoke. * @returns {Function} Returns the new function. * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow(_.add, square); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the provided functions from right to left. * * @static * @memberOf _ * @alias backflow, compose * @category Function * @param {...Function} [funcs] Functions to invoke. * @returns {Function} Returns the new function. * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight(square, _.add); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is coerced to a string and used as the * cache key. The `func` is invoked with the `this` binding of the memoized * function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the [`Map`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object) * method interface of `get`, `has`, and `set`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoizing function. * @example * * var upperCase = _.memoize(function(string) { * return string.toUpperCase(); * }); * * upperCase('fred'); * // => 'FRED' * * // modifying the result cache * upperCase.cache.set('fred', 'BARNEY'); * upperCase('fred'); * // => 'BARNEY' * * // replacing `_.memoize.Cache` * var object = { 'user': 'fred' }; * var other = { 'user': 'barney' }; * var identity = _.memoize(_.identity); * * identity(object); * // => { 'user': 'fred' } * identity(other); * // => { 'user': 'fred' } * * _.memoize.Cache = WeakMap; * var identity = _.memoize(_.identity); * * identity(object); * // => { 'user': 'fred' } * identity(other); * // => { 'user': 'barney' } */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result); return result; }; memoized.cache = new memoize.Cache; return memoized; } /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { return !predicate.apply(this, arguments); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first call. The `func` is invoked * with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` invokes `createApplication` once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with `partial` arguments prepended * to those provided to the new function. This method is like `_.bind` except * it does **not** alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method does not set the "length" property of partially * applied functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { * return greeting + ' ' + name; * }; * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // using placeholders * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = createPartial(PARTIAL_FLAG); /** * This method is like `_.partial` except that partially applied arguments * are appended to those provided to the new function. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method does not set the "length" property of partially * applied functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { * return greeting + ' ' + name; * }; * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // using placeholders * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = createPartial(PARTIAL_RIGHT_FLAG); /** * Creates a function that invokes `func` with arguments arranged according * to the specified indexes where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes, * specified as individual indexes or arrays of indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, 2, 0, 1); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] * * var map = _.rearg(_.map, [1, 0]); * map(function(n) { * return n * 3; * }, [1, 2, 3]); * // => [3, 6, 9] */ var rearg = restParam(function(func, indexes) { return createWrapper(func, REARG_FLAG, null, null, null, baseFlatten(indexes)); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } /** * Creates a function that invokes `func` with the `this` binding of the created * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3). * * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). * * @static * @memberOf _ * @category Function * @param {Function} func The function to spread arguments over. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * // with a Promise * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function(array) { return func.apply(this, array); }; } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed invocations. Provide an options object to indicate * that `func` should be invoked on the leading and/or trailing edge of the * `wait` timeout. Subsequent calls to the throttled function return the * result of the last `func` call. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the throttled function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options] The options object. * @param {boolean} [options.leading=true] Specify invoking on the leading * edge of the timeout. * @param {boolean} [options.trailing=true] Specify invoking on the trailing * edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // avoid excessively updating the position while scrolling * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { * 'trailing': false * })); * * // cancel a trailing throttled call * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (options === false) { leading = false; } else if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } debounceOptions.leading = leading; debounceOptions.maxWait = +wait; debounceOptions.trailing = trailing; return debounce(func, wait, debounceOptions); } /** * Creates a function that provides `value` to the wrapper function as its * first argument. Any additional arguments provided to the function are * appended to those provided to the wrapper function. The wrapper is invoked * with the `this` binding of the created function. * * @static * @memberOf _ * @category Function * @param {*} value The value to wrap. * @param {Function} wrapper The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { wrapper = wrapper == null ? identity : wrapper; return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []); } /*------------------------------------------------------------------------*/ /** * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned, * otherwise they are assigned by reference. If `customizer` is provided it is * invoked to produce the cloned values. If `customizer` returns `undefined` * cloning is handled by the method instead. The `customizer` is bound to * `thisArg` and invoked with two argument; (value [, index|key, object]). * * **Note:** This method is loosely based on the * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). * The enumerable properties of `arguments` objects and objects created by * constructors other than `Object` are cloned to plain `Object` objects. An * empty object is returned for uncloneable values such as functions, DOM nodes, * Maps, Sets, and WeakMaps. * * @static * @memberOf _ * @category Lang * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {Function} [customizer] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {*} Returns the cloned value. * @example * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * var shallow = _.clone(users); * shallow[0] === users[0]; * // => true * * var deep = _.clone(users, true); * deep[0] === users[0]; * // => false * * // using a customizer callback * var el = _.clone(document.body, function(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * }); * * el === document.body * // => false * el.nodeName * // => BODY * el.childNodes.length; * // => 0 */ function clone(value, isDeep, customizer, thisArg) { if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) { isDeep = false; } else if (typeof isDeep == 'function') { thisArg = customizer; customizer = isDeep; isDeep = false; } return typeof customizer == 'function' ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1)) : baseClone(value, isDeep); } /** * Creates a deep clone of `value`. If `customizer` is provided it is invoked * to produce the cloned values. If `customizer` returns `undefined` cloning * is handled by the method instead. The `customizer` is bound to `thisArg` * and invoked with two argument; (value [, index|key, object]). * * **Note:** This method is loosely based on the * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). * The enumerable properties of `arguments` objects and objects created by * constructors other than `Object` are cloned to plain `Object` objects. An * empty object is returned for uncloneable values such as functions, DOM nodes, * Maps, Sets, and WeakMaps. * * @static * @memberOf _ * @category Lang * @param {*} value The value to deep clone. * @param {Function} [customizer] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {*} Returns the deep cloned value. * @example * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * var deep = _.cloneDeep(users); * deep[0] === users[0]; * // => false * * // using a customizer callback * var el = _.cloneDeep(document.body, function(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * }); * * el === document.body * // => false * el.nodeName * // => BODY * el.childNodes.length; * // => 20 */ function cloneDeep(value, customizer, thisArg) { return typeof customizer == 'function' ? baseClone(value, true, bindCallback(customizer, thisArg, 1)) : baseClone(value, true); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`. * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ function gt(value, other) { return value > other; } /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`. * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ function gte(value, other) { return value >= other; } /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && objToString.call(value) == argsTag; } // Fallback for environments without a `toStringTag` for `arguments` objects. if (!support.argsTag) { isArguments = function(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag); } /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ function isDate(value) { return isObjectLike(value) && objToString.call(value) == dateTag; } /** * Checks if `value` is a DOM element. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return !!value && value.nodeType === 1 && isObjectLike(value) && (lodash.support.nodeTag ? (objToString.call(value).indexOf('Element') > -1) : isHostObject(value)); } // Fallback for environments without DOM support. if (!support.dom) { isElement = function(value) { return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); }; } /** * Checks if `value` is empty. A value is considered empty unless it is an * `arguments` object, array, string, or jQuery-like collection with a length * greater than `0` or an object with own enumerable properties. * * @static * @memberOf _ * @category Lang * @param {Array|Object|string} value The value to inspect. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) || (isObjectLike(value) && isFunction(value.splice)))) { return !value.length; } return !keys(value).length; } /** * Performs a deep comparison between two values to determine if they are * equivalent. If `customizer` is provided it is invoked to compare values. * If `customizer` returns `undefined` comparisons are handled by the method * instead. The `customizer` is bound to `thisArg` and invoked with three * arguments: (value, other [, index|key]). * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. Functions and DOM nodes * are **not** supported. Provide a customizer function to extend support * for comparing other values. * * @static * @memberOf _ * @alias eq * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize value comparisons. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * object == other; * // => false * * _.isEqual(object, other); * // => true * * // using a customizer callback * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqual(array, other, function(value, other) { * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) { * return true; * } * }); * // => true */ function isEqual(value, other, customizer, thisArg) { customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag; } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on [`Number.isFinite`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite). * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(10); * // => true * * _.isFinite('10'); * // => false * * _.isFinite(true); * // => false * * _.isFinite(Object(10)); * // => false * * _.isFinite(Infinity); * // => false */ var isFinite = nativeNumIsFinite || function(value) { return typeof value == 'number' && nativeIsFinite(value); }; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return objToString.call(value) == funcTag; }; /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Performs a deep comparison between `object` and `source` to determine if * `object` contains equivalent property values. If `customizer` is provided * it is invoked to compare values. If `customizer` returns `undefined` * comparisons are handled by the method instead. The `customizer` is bound * to `thisArg` and invoked with three arguments: (value, other, index|key). * * **Note:** This method supports comparing properties of arrays, booleans, * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions * and DOM nodes are **not** supported. Provide a customizer function to extend * support for comparing other values. * * @static * @memberOf _ * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize value comparisons. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.isMatch(object, { 'age': 40 }); * // => true * * _.isMatch(object, { 'age': 36 }); * // => false * * // using a customizer callback * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatch(object, source, function(value, other) { * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined; * }); * // => true */ function isMatch(object, source, customizer, thisArg) { customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined; return baseIsMatch(object, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4) * which returns `true` for `undefined` and other non-numeric values. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some host objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified * as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isNumber(8.4); * // => true * * _.isNumber(NaN); * // => true * * _.isNumber('8.4'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && objToString.call(value) == objectTag) || (!lodash.support.argsTag && isArguments(value))) { return false; } var valueOf = getNative(value, 'valueOf'), objProto = valueOf && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ function isRegExp(value) { return isObject(value) && objToString.call(value) == regexpTag; } /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`. * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ function lt(value, other) { return value < other; } /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`. * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ function lte(value, other) { return value <= other; } /** * Converts `value` to an array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * (function() { * return _.toArray(arguments).slice(1); * }(1, 2, 3)); * // => [2, 3] */ function toArray(value) { var length = value ? getLength(value) : 0; if (!isLength(length)) { return values(value); } if (!length) { return []; } return (lodash.support.unindexedChars && isString(value)) ? value.split('') : arrayCopy(value); } /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources overwrite property assignments of previous sources. * If `customizer` is provided it is invoked to produce the assigned values. * The `customizer` is bound to `thisArg` and invoked with five arguments: * (objectValue, sourceValue, key, object, source). * * **Note:** This method mutates `object` and is based on * [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). * * @static * @memberOf _ * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); * // => { 'user': 'fred', 'age': 40 } * * // using a customizer callback * var defaults = _.partialRight(_.assign, function(value, other) { * return _.isUndefined(value) ? other : value; * }); * * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var assign = createAssigner(function(object, source, customizer) { return customizer ? assignWith(object, source, customizer) : baseAssign(object, source); }); /** * Creates an object that inherits from the given `prototype` object. If a * `properties` object is provided its own enumerable properties are assigned * to the created object. * * @static * @memberOf _ * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties, guard) { var result = baseCreate(prototype); if (guard && isIterateeCall(prototype, properties, guard)) { properties = null; } return properties ? baseAssign(result, properties) : result; } /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var defaults = restParam(function(args) { var object = args[0]; if (object == null) { return object; } args.push(assignDefaults); return assign.apply(undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {string|undefined} Returns the key of the matched element, else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(chr) { * return chr.age < 40; * }); * // => 'barney' (iteration order is not guaranteed) * * // using the `_.matches` callback shorthand * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // using the `_.matchesProperty` callback shorthand * _.findKey(users, 'active', false); * // => 'fred' * * // using the `_.property` callback shorthand * _.findKey(users, 'active'); * // => 'barney' */ var findKey = createFindKey(baseForOwn); /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {string|undefined} Returns the key of the matched element, else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(chr) { * return chr.age < 40; * }); * // => returns `pebbles` assuming `_.findKey` returns `barney` * * // using the `_.matches` callback shorthand * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // using the `_.matchesProperty` callback shorthand * _.findLastKey(users, 'active', false); * // => 'fred' * * // using the `_.property` callback shorthand * _.findLastKey(users, 'active'); * // => 'pebbles' */ var findLastKey = createFindKey(baseForOwnRight); /** * Iterates over own and inherited enumerable properties of an object invoking * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed) */ var forIn = createForIn(baseFor); /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c' */ var forInRight = createForIn(baseForRight); /** * Iterates over own enumerable properties of an object invoking `iteratee` * for each property. The `iteratee` is bound to `thisArg` and invoked with * three arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'a' and 'b' (iteration order is not guaranteed) */ var forOwn = createForOwn(baseForOwn); /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b' */ var forOwnRight = createForOwn(baseForOwnRight); /** * Creates an array of function property names from all enumerable properties, * own and inherited, of `object`. * * @static * @memberOf _ * @alias methods * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the new array of property names. * @example * * _.functions(_); * // => ['after', 'ary', 'assign', ...] */ function functions(object) { return baseFunctions(object, keysIn(object)); } /** * Gets the property value at `path` of `object`. If the resolved value is * `undefined` the `defaultValue` is used in its place. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, toPath(path), path + ''); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` is a direct property, else `false`. * @example * * var object = { 'a': { 'b': { 'c': 3 } } }; * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b.c'); * // => true * * _.has(object, ['a', 'b', 'c']); * // => true */ function has(object, path) { if (object == null) { return false; } var result = hasOwnProperty.call(object, path); if (!result && !isKey(path)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } path = last(path); result = hasOwnProperty.call(object, path); } return result || (isLength(object.length) && isIndex(path, object.length) && (isArray(object) || isArguments(object) || isString(object))); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite property * assignments of previous values unless `multiValue` is `true`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to invert. * @param {boolean} [multiValue] Allow multiple values per key. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } * * // with `multiValue` * _.invert(object, true); * // => { '1': ['a', 'c'], '2': ['b'] } */ function invert(object, multiValue, guard) { if (guard && isIterateeCall(object, multiValue, guard)) { multiValue = null; } var index = -1, props = keys(object), length = props.length, result = {}; while (++index < length) { var key = props[index], value = object[key]; if (multiValue) { if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } } else { result[value] = key; } } return result; } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? null : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object == 'function' ? lodash.support.enumPrototypes : isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length, support = lodash.support; length = (length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)) && length) || 0; var Ctor = object.constructor, index = -1, proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, isProto = proto === object, result = Array(length), skipIndexes = length > 0, skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), skipProto = support.enumPrototypes && isFunction(object); while (++index < length) { result[index] = (index + ''); } // lodash skips the `constructor` property when it infers it is iterating // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` // attribute of an existing property and the `constructor` property of a // prototype defaults to non-enumerable. for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name')) && !(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; if (tag == objectTag) { proto = objectProto; } length = shadowProps.length; while (length--) { key = shadowProps[length]; var nonEnum = nonEnums[key]; if (!(isProto && nonEnum) && (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { result.push(key); } } } return result; } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * property of `object` through `iteratee`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the new mapped object. * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ var mapKeys = createObjectMapper(true); /** * Creates an object with the same keys as `object` and values generated by * running each own enumerable property of `object` through `iteratee`. The * iteratee function is bound to `thisArg` and invoked with three arguments: * (value, key, object). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the new mapped object. * @example * * _.mapValues({ 'a': 1, 'b': 2 }, function(n) { * return n * 3; * }); * // => { 'a': 3, 'b': 6 } * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * // using the `_.property` callback shorthand * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ var mapValues = createObjectMapper(); /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it is invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable properties of `object` that are not omitted. * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|...(string|string[])} [predicate] The function invoked per * iteration or property names to omit, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Object} Returns the new object. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.omit(object, 'age'); * // => { 'user': 'fred' } * * _.omit(object, _.isNumber); * // => { 'user': 'fred' } */ var omit = restParam(function(object, props) { if (object == null) { return {}; } if (typeof props[0] != 'function') { var props = arrayMap(baseFlatten(props), String); return pickByArray(object, baseDifference(keysIn(object), props)); } var predicate = bindCallback(props[0], props[1], 3); return pickByCallback(object, function(value, key, object) { return !predicate(value, key, object); }); }); /** * Creates a two dimensional array of the key-value pairs for `object`, * e.g. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) */ function pairs(object) { object = toObject(object); var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } /** * Creates an object composed of the picked `object` properties. Property * names may be specified as individual arguments or as arrays of property * names. If `predicate` is provided it is invoked for each property of `object` * picking the properties `predicate` returns truthy for. The predicate is * bound to `thisArg` and invoked with three arguments: (value, key, object). * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|...(string|string[])} [predicate] The function invoked per * iteration or property names to pick, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Object} Returns the new object. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.pick(object, 'user'); * // => { 'user': 'fred' } * * _.pick(object, _.isString); * // => { 'user': 'fred' } */ var pick = restParam(function(object, props) { if (object == null) { return {}; } return typeof props[0] == 'function' ? pickByCallback(object, bindCallback(props[0], props[1], 3)) : pickByArray(object, baseFlatten(props)); }); /** * This method is like `_.get` except that if the resolved value is a function * it is invoked with the `this` binding of its parent object and its result * is returned. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a.b.c', 'default'); * // => 'default' * * _.result(object, 'a.b.c', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { var result = object == null ? undefined : toObject(object)[path]; if (result === undefined) { if (object != null && !isKey(path, object)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); result = object == null ? undefined : toObject(object)[last(path)]; } result = result === undefined ? defaultValue : result; } return isFunction(result) ? result.call(object) : result; } /** * Sets the property value of `path` on `object`. If a portion of `path` * does not exist it is created. * * @static * @memberOf _ * @category Object * @param {Object} object The object to augment. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, 'x[0].y.z', 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { if (object == null) { return object; } var pathKey = (path + ''); path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = path[index]; if (isObject(nested)) { if (index == lastIndex) { nested[key] = value; } else if (nested[key] == null) { nested[key] = isIndex(path[index + 1]) ? [] : {}; } } nested = nested[key]; } return object; } /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own enumerable * properties through `iteratee`, with each invocation potentially mutating * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked * with four arguments: (accumulator, value, key, object). Iteratee functions * may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Array|Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) { * result[key] = n * 3; * }); * // => { 'a': 3, 'b': 6 } */ function transform(object, iteratee, accumulator, thisArg) { var isArr = isArray(object) || isTypedArray(object); iteratee = getCallback(iteratee, thisArg, 4); if (accumulator == null) { if (isArr || isObject(object)) { var Ctor = object.constructor; if (isArr) { accumulator = isArray(object) ? new Ctor : []; } else { accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : null); } } else { accumulator = {}; } } (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Creates an array of the own enumerable property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable property values * of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Checks if `n` is between `start` and up to but not including, `end`. If * `end` is not specified it is set to `start` with `start` then set to `0`. * * @static * @memberOf _ * @category Number * @param {number} n The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `n` is in the range, else `false`. * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false */ function inRange(value, start, end) { start = +start || 0; if (typeof end === 'undefined') { end = start; start = 0; } else { end = +end || 0; } return value >= nativeMin(start, end) && value < nativeMax(start, end); } /** * Produces a random number between `min` and `max` (inclusive). If only one * argument is provided a number between `0` and the given number is returned. * If `floating` is `true`, or either `min` or `max` are floats, a floating-point * number is returned instead of an integer. * * @static * @memberOf _ * @category Number * @param {number} [min=0] The minimum possible value. * @param {number} [max=1] The maximum possible value. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(min, max, floating) { if (floating && isIterateeCall(min, max, floating)) { max = floating = null; } var noMin = min == null, noMax = max == null; if (floating == null) { if (noMax && typeof min == 'boolean') { floating = min; min = 1; } else if (typeof max == 'boolean') { floating = max; noMax = true; } } if (noMin && noMax) { max = 1; noMax = false; } min = +min || 0; if (noMax) { max = min; min = 0; } else { max = +max || 0; } if (floating || min % 1 || max % 1) { var rand = nativeRandom(); return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); } return baseRandom(min, max); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar'); * // => 'fooBar' * * _.camelCase('__foo_bar__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word); }); /** * Capitalizes the first character of `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('fred'); * // => 'Fred' */ function capitalize(string) { string = baseToString(string); return string && (string.charAt(0).toUpperCase() + string.slice(1)); } /** * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = baseToString(string); return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to search. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search from. * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = baseToString(string); target = (target + ''); var length = string.length; position = position === undefined ? length : nativeMin(position < 0 ? 0 : (+position || 0), length); position -= target.length; return position >= 0 && string.indexOf(target, position) == position; } /** * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to * their corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional characters * use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * Backticks are escaped because in Internet Explorer < 9, they can break out * of attribute values or HTML comments. See [#59](https://html5sec.org/#59), * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/) * for more details. * * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping) * to reduce XSS vectors. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { // Reset `lastIndex` because in IE < 9 `String#replace` does not. string = baseToString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } /** * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__foo_bar__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = baseToString(string); length = +length; var strLength = string.length; if (strLength >= length || !nativeIsFinite(length)) { return string; } var mid = (length - strLength) / 2, leftLength = floor(mid), rightLength = ceil(mid); chars = createPadding('', rightLength, chars); return chars.slice(0, leftLength) + string + chars; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padLeft('abc', 6); * // => ' abc' * * _.padLeft('abc', 6, '_-'); * // => '_-_abc' * * _.padLeft('abc', 3); * // => 'abc' */ var padLeft = createPadDir(); /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padRight('abc', 6); * // => 'abc ' * * _.padRight('abc', 6, '_-'); * // => 'abc_-_' * * _.padRight('abc', 3); * // => 'abc' */ var padRight = createPadDir(true); /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal, * in which case a `radix` of `16` is used. * * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E) * of `parseInt`. * * @static * @memberOf _ * @category String * @param {string} string The string to convert. * @param {number} [radix] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard && isIterateeCall(string, radix, guard)) { radix = 0; } return nativeParseInt(string, radix); } // Fallback for environments with pre-ES5 implementations. if (nativeParseInt(whitespace + '08') != 8) { parseInt = function(string, radix, guard) { // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`. // Chrome fails to trim leading <BOM> whitespace characters. // See https://code.google.com/p/v8/issues/detail?id=3109 for more details. if (guard ? isIterateeCall(string, radix, guard) : radix == null) { radix = 0; } else if (radix) { radix = +radix; } string = trim(string); return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); }; } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=0] The number of times to repeat the string. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n) { var result = ''; string = baseToString(string); n = +n; if (n < 1 || !string || !nativeIsFinite(n)) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = floor(n / 2); string += string; } while (n); return result; } /** * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--foo-bar'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__foo_bar__'); * // => 'Foo Bar' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1)); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to search. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = baseToString(string); position = position == null ? 0 : nativeMin(position < 0 ? 0 : (+position || 0), string.length); return string.lastIndexOf(target, position) == position; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is provided it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options] The options object. * @param {RegExp} [options.escape] The HTML "escape" delimiter. * @param {RegExp} [options.evaluate] The "evaluate" delimiter. * @param {Object} [options.imports] An object to import into the template as free variables. * @param {RegExp} [options.interpolate] The "interpolate" delimiter. * @param {string} [options.sourceURL] The sourceURL of the template's compiled source. * @param {string} [options.variable] The data object variable name. * @param- {Object} [otherOptions] Enables the legacy `options` param signature. * @returns {Function} Returns the compiled template function. * @example * * // using the "interpolate" delimiter to create a compiled template * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // using the HTML "escape" delimiter to escape data property values * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // using the "evaluate" delimiter to execute JavaScript and generate HTML * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // using the internal `print` function in "evaluate" delimiters * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // using the ES delimiter as an alternative to the default "interpolate" delimiter * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // using custom template delimiters * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // using backslashes to treat delimiters as plain text * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // using the `imports` option to import `jQuery` as `jq` * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // using the `sourceURL` option to specify a custom sourceURL for the template * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector * * // using the `variable` option to ensure a with-statement isn't used in the compiled template * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // using the `source` property to inline compiled templates for meaningful * // line numbers in error messages and a stack trace * fs.writeFileSync(path.join(cwd, 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, otherOptions) { // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (otherOptions && isIterateeCall(string, options, otherOptions)) { options = otherOptions = null; } string = baseToString(string); options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults); var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { var value = string; string = baseToString(string); if (!string) { return string; } if (guard ? isIterateeCall(value, chars, guard) : chars == null) { return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1); } chars = (chars + ''); return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimLeft(' abc '); * // => 'abc ' * * _.trimLeft('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimLeft(string, chars, guard) { var value = string; string = baseToString(string); if (!string) { return string; } if (guard ? isIterateeCall(value, chars, guard) : chars == null) { return string.slice(trimmedLeftIndex(string)); } return string.slice(charsLeftIndex(string, (chars + ''))); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimRight(' abc '); * // => ' abc' * * _.trimRight('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimRight(string, chars, guard) { var value = string; string = baseToString(string); if (!string) { return string; } if (guard ? isIterateeCall(value, chars, guard) : chars == null) { return string.slice(0, trimmedRightIndex(string) + 1); } return string.slice(0, charsRightIndex(string, (chars + '')) + 1); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to truncate. * @param {Object|number} [options] The options object or maximum string length. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {string} Returns the truncated string. * @example * * _.trunc('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.trunc('hi-diddly-ho there, neighborino', 24); * // => 'hi-diddly-ho there, n...' * * _.trunc('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.trunc('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.trunc('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function trunc(string, options, guard) { if (guard && isIterateeCall(string, options, guard)) { options = null; } var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (options != null) { if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? (+options.length || 0) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } else { length = +options || 0; } } string = baseToString(string); if (length >= string.length) { return string; } var end = length - omission.length; if (end < 1) { return omission; } var result = string.slice(0, end); if (separator == null) { return result + omission; } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, newEnd, substring = string.slice(0, end); if (!separator.global) { separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { newEnd = match.index; } result = result.slice(0, newEnd == null ? end : newEnd); } } else if (string.indexOf(separator, end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their * corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional HTML * entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = baseToString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { if (guard && isIterateeCall(string, pattern, guard)) { pattern = null; } string = baseToString(string); return string.match(pattern || reWords) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it is invoked. * * @static * @memberOf _ * @category Utility * @param {Function} func The function to attempt. * @returns {*} Returns the `func` result or error object. * @example * * // avoid throwing errors for invalid selectors * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = restParam(function(func, args) { try { return func.apply(undefined, args); } catch(e) { return isError(e) ? e : new Error(e); } }); /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and arguments of the created function. If `func` is a property name the * created callback returns the property value for a given element. If `func` * is an object the created callback returns `true` for elements that contain * the equivalent object properties, otherwise it returns `false`. * * @static * @memberOf _ * @alias iteratee * @category Utility * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // wrap to create custom callback shorthands * _.callback = _.wrap(_.callback, function(callback, func, thisArg) { * var match = /^(.+?)__([gl]t)(.+)$/.exec(func); * if (!match) { * return callback(func, thisArg); * } * return function(object) { * return match[2] == 'gt' * ? object[match[1]] > match[3] * : object[match[1]] < match[3]; * }; * }); * * _.filter(users, 'age__gt36'); * // => [{ 'user': 'fred', 'age': 40 }] */ function callback(func, thisArg, guard) { if (guard && isIterateeCall(func, thisArg, guard)) { thisArg = null; } return isObjectLike(func) ? matches(func) : baseCallback(func, thisArg); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @category Utility * @param {*} value The value to return from the new function. * @returns {Function} Returns the new function. * @example * * var object = { 'user': 'fred' }; * var getter = _.constant(object); * * getter() === object; * // => true */ function constant(value) { return function() { return value; }; } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } /** * Creates a function that performs a deep comparison between a given object * and `source`, returning `true` if the given object has equivalent property * values, else `false`. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. For comparing a single * own or inherited property value see `_.matchesProperty`. * * @static * @memberOf _ * @category Utility * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, _.matches({ 'age': 40, 'active': false })); * // => [{ 'user': 'fred', 'age': 40, 'active': false }] */ function matches(source) { return baseMatches(baseClone(source, true)); } /** * Creates a function that compares the property value of `path` on a given * object to `value`. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new function. * @example * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * _.find(users, _.matchesProperty('user', 'fred')); * // => { 'user': 'fred' } */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, true)); } /** * Creates a function that invokes the method at `path` on a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': _.constant(2) } } }, * { 'a': { 'b': { 'c': _.constant(1) } } } * ]; * * _.map(objects, _.method('a.b.c')); * // => [2, 1] * * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ var method = restParam(function(path, args) { return function(object) { return invokePath(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path on `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @category Utility * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = restParam(function(object, args) { return function(path) { return invokePath(object, path, args); }; }); /** * Adds all own enumerable function properties of a source object to the * destination object. If `object` is a function then methods are added to * its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @memberOf _ * @category Utility * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options] The options object. * @param {boolean} [options.chain=true] Specify whether the functions added * are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { if (options == null) { var isObj = isObject(source), props = isObj ? keys(source) : null, methodNames = (props && props.length) ? baseFunctions(source, props) : null; if (!(methodNames ? methodNames.length : isObj)) { methodNames = false; options = source; source = object; object = this; } } if (!methodNames) { methodNames = baseFunctions(source, keys(source)); } var chain = true, index = -1, isFunc = isFunction(object), length = methodNames.length; if (options === false) { chain = false; } else if (isObject(options) && 'chain' in options) { chain = options.chain; } while (++index < length) { var methodName = methodNames[index], func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = (function(func) { return function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = arrayCopy(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } var args = [this.value()]; push.apply(args, arguments); return func.apply(object, args); }; }(func)); } } return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @memberOf _ * @category Utility * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { context._ = oldDash; return this; } /** * A no-operation function that returns `undefined` regardless of the * arguments it receives. * * @static * @memberOf _ * @category Utility * @example * * var object = { 'user': 'fred' }; * * _.noop(object) === undefined; * // => true */ function noop() { // No operation performed. } /** * Creates a function that returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the property value at a given path on `object`. * * @static * @memberOf _ * @category Utility * @param {Object} object The object to query. * @returns {Function} Returns the new function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return baseGet(object, toPath(path), path + ''); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. If `end` is not specified it is * set to `start` with `start` then set to `0`. If `end` is less than `start` * a zero-length range is created unless a negative `step` is specified. * * @static * @memberOf _ * @category Utility * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the new array of numbers. * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ function range(start, end, step) { if (step && isIterateeCall(start, end, step)) { end = step = null; } start = +start || 0; step = step == null ? 1 : (+step || 0); if (end == null) { end = start; start = 0; } else { end = +end || 0; } // Use `Array(length)` so engines like Chakra and V8 avoid slower modes. // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details. var index = -1, length = nativeMax(ceil((end - start) / (step || 1)), 0), result = Array(length); while (++index < length) { result[index] = start; start += step; } return result; } /** * Invokes the iteratee function `n` times, returning an array of the results * of each invocation. The `iteratee` is bound to `thisArg` and invoked with * one argument; (index). * * @static * @memberOf _ * @category Utility * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the array of results. * @example * * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false)); * // => [3, 6, 4] * * _.times(3, function(n) { * mage.castSpell(n); * }); * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` * * _.times(3, function(n) { * this.cast(n); * }, mage); * // => also invokes `mage.castSpell(n)` three times */ function times(n, iteratee, thisArg) { n = floor(n); // Exit early to avoid a JSC JIT bug in Safari 8 // where `Array(0)` is treated as `Array(1)`. if (n < 1 || !nativeIsFinite(n)) { return []; } var index = -1, result = Array(nativeMin(n, MAX_ARRAY_LENGTH)); iteratee = bindCallback(iteratee, thisArg, 1); while (++index < n) { if (index < MAX_ARRAY_LENGTH) { result[index] = iteratee(index); } else { iteratee(index); } } return result; } /** * Generates a unique ID. If `prefix` is provided the ID is appended to it. * * @static * @memberOf _ * @category Utility * @param {string} [prefix] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return baseToString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @category Math * @param {number} augend The first number to add. * @param {number} addend The second number to add. * @returns {number} Returns the sum. * @example * * _.add(6, 4); * // => 10 */ function add(augend, addend) { return (+augend || 0) + (+addend || 0); } /** * Gets the maximum value of `collection`. If `collection` is empty or falsey * `-Infinity` is returned. If an iteratee function is provided it is invoked * for each value in `collection` to generate the criterion by which the value * is ranked. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Math * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => -Infinity * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * _.max(users, function(chr) { * return chr.age; * }); * // => { 'user': 'fred', 'age': 40 } * * // using the `_.property` callback shorthand * _.max(users, 'age'); * // => { 'user': 'fred', 'age': 40 } */ var max = createExtremum(gt, NEGATIVE_INFINITY); /** * Gets the minimum value of `collection`. If `collection` is empty or falsey * `Infinity` is returned. If an iteratee function is provided it is invoked * for each value in `collection` to generate the criterion by which the value * is ranked. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Math * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => Infinity * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * _.min(users, function(chr) { * return chr.age; * }); * // => { 'user': 'barney', 'age': 36 } * * // using the `_.property` callback shorthand * _.min(users, 'age'); * // => { 'user': 'barney', 'age': 36 } */ var min = createExtremum(lt, POSITIVE_INFINITY); /** * Gets the sum of the values in `collection`. * * @static * @memberOf _ * @category Math * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {number} Returns the sum. * @example * * _.sum([4, 6]); * // => 10 * * _.sum({ 'a': 4, 'b': 6 }); * // => 10 * * var objects = [ * { 'n': 4 }, * { 'n': 6 } * ]; * * _.sum(objects, function(object) { * return object.n; * }); * // => 10 * * // using the `_.property` callback shorthand * _.sum(objects, 'n'); * // => 10 */ function sum(collection, iteratee, thisArg) { if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } var callback = getCallback(), noIteratee = iteratee == null; if (!(noIteratee && callback === baseCallback)) { noIteratee = false; iteratee = callback(iteratee, thisArg, 3); } return noIteratee ? arraySum(isArray(collection) ? collection : toIterable(collection)) : baseSum(collection, iteratee); } /*------------------------------------------------------------------------*/ // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; // Add functions to the `Map` cache. MapCache.prototype['delete'] = mapDelete; MapCache.prototype.get = mapGet; MapCache.prototype.has = mapHas; MapCache.prototype.set = mapSet; // Add functions to the `Set` cache. SetCache.prototype.push = cachePush; // Assign cache to `_.memoize`. memoize.Cache = MapCache; // Add functions that return wrapped values when chaining. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.callback = callback; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flow = flow; lodash.flowRight = flowRight; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.functions = functions; lodash.groupBy = groupBy; lodash.indexBy = indexBy; lodash.initial = initial; lodash.intersection = intersection; lodash.invert = invert; lodash.invoke = invoke; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.omit = omit; lodash.once = once; lodash.pairs = pairs; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pluck = pluck; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAt = pullAt; lodash.range = range; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.restParam = restParam; lodash.set = set; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortByAll = sortByAll; lodash.sortByOrder = sortByOrder; lodash.spread = spread; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.times = times; lodash.toArray = toArray; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.union = union; lodash.uniq = uniq; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.where = where; lodash.without = without; lodash.wrap = wrap; lodash.xor = xor; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipWith = zipWith; // Add aliases. lodash.backflow = flowRight; lodash.collect = map; lodash.compose = flowRight; lodash.each = forEach; lodash.eachRight = forEachRight; lodash.extend = assign; lodash.iteratee = callback; lodash.methods = functions; lodash.object = zipObject; lodash.select = filter; lodash.tail = rest; lodash.unique = uniq; // Add functions to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add functions that return unwrapped values when chaining. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.deburr = deburr; lodash.endsWith = endsWith; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.findWhere = findWhere; lodash.first = first; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isBoolean = isBoolean; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isMatch = isMatch; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isString = isString; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.min = min; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padLeft = padLeft; lodash.padRight = padRight; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.result = result; lodash.runInContext = runInContext; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedLastIndex = sortedLastIndex; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.sum = sum; lodash.template = template; lodash.trim = trim; lodash.trimLeft = trimLeft; lodash.trimRight = trimRight; lodash.trunc = trunc; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.words = words; // Add aliases. lodash.all = every; lodash.any = some; lodash.contains = includes; lodash.eq = isEqual; lodash.detect = find; lodash.foldl = reduce; lodash.foldr = reduceRight; lodash.head = first; lodash.include = includes; lodash.inject = reduce; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!lodash.prototype[methodName]) { source[methodName] = func; } }); return source; }()), false); /*------------------------------------------------------------------------*/ // Add functions capable of returning wrapped and unwrapped values when chaining. lodash.sample = sample; lodash.prototype.sample = function(n) { if (!this.__chain__ && n == null) { return sample(this.value()); } return this.thru(function(value) { return sample(value, n); }); }; /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type string */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['dropWhile', 'filter', 'map', 'takeWhile'], function(methodName, type) { var isFilter = type != LAZY_MAP_FLAG, isDropWhile = type == LAZY_DROP_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee, thisArg) { var filtered = this.__filtered__, result = (filtered && isDropWhile) ? new LazyWrapper(this) : this.clone(), iteratees = result.__iteratees__ || (result.__iteratees__ = []); iteratees.push({ 'done': false, 'count': 0, 'index': 0, 'iteratee': getCallback(iteratee, thisArg, 1), 'limit': -1, 'type': type }); result.__filtered__ = filtered || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { var whileName = methodName + 'While'; LazyWrapper.prototype[methodName] = function(n) { var filtered = this.__filtered__, result = (filtered && !index) ? this.dropWhile() : this.clone(); n = n == null ? 1 : nativeMax(floor(n) || 0, 0); if (filtered) { if (index) { result.__takeCount__ = nativeMin(result.__takeCount__, n); } else { last(result.__iteratees__).limit = n; } } else { var views = result.__views__ || (result.__views__ = []); views.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; LazyWrapper.prototype[methodName + 'RightWhile'] = function(predicate, thisArg) { return this.reverse()[whileName](predicate, thisArg).reverse(); }; }); // Add `LazyWrapper` methods for `_.first` and `_.last`. arrayEach(['first', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.rest`. arrayEach(['initial', 'rest'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this[dropName](1); }; }); // Add `LazyWrapper` methods for `_.pluck` and `_.where`. arrayEach(['pluck', 'where'], function(methodName, index) { var operationName = index ? 'filter' : 'map', createCallback = index ? baseMatches : property; LazyWrapper.prototype[methodName] = function(value) { return this[operationName](createCallback(value)); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.reject = function(predicate, thisArg) { predicate = getCallback(predicate, thisArg, 1); return this.filter(function(value) { return !predicate(value); }); }; LazyWrapper.prototype.slice = function(start, end) { start = start == null ? 0 : (+start || 0); var result = this; if (start < 0) { result = this.takeRight(-start); } else if (start) { result = this.drop(start); } if (end !== undefined) { end = (+end || 0); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.toArray = function() { return this.drop(0); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (!lodashFunc) { return; } var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName), retUnwrapped = /^(?:first|last)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments, chainAll = this.__chain__, value = this.__wrapped__, isHybrid = !!this.__actions__.length, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // avoid lazy use if the iteratee has a "length" value other than `1` isLazy = useLazy = false; } var onlyLazy = isLazy && !isHybrid; if (retUnwrapped && !chainAll) { return onlyLazy ? func.call(value) : lodashFunc.call(lodash, this.value()); } var interceptor = function(value) { var otherArgs = [value]; push.apply(otherArgs, args); return lodashFunc.apply(lodash, otherArgs); }; if (useLazy) { var wrapper = onlyLazy ? value : new LazyWrapper(this), result = func.apply(wrapper, args); if (!retUnwrapped && (isHybrid || result.__actions__)) { var actions = result.__actions__ || (result.__actions__ = []); actions.push({ 'func': thru, 'args': [interceptor], 'thisArg': lodash }); } return new LodashWrapper(result, chainAll); } return this.thru(interceptor); }; }); // Add `Array` and `String` methods to `lodash.prototype`. arrayEach(['concat', 'join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) { var protoFunc = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', fixObjects = !support.spliceObjects && /^(?:pop|shift|splice)$/.test(methodName), retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName); // Avoid array-like object bugs with `Array#shift` and `Array#splice` in // IE < 9, Firefox < 10, and RingoJS. var func = !fixObjects ? protoFunc : function() { var result = protoFunc.apply(this, arguments); if (this.length === 0) { delete this[0]; } return result; }; lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { return func.apply(this.value(), args); } return this[chainName](function(value) { return func.apply(value, args); }); }; }); // Map minified function names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name, names = realNames[key] || (realNames[key] = []); names.push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybridWrapper(null, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': null }]; // Add functions to the lazy wrapper. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chaining functions to the `lodash` wrapper. lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toString = wrapperToString; lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add function aliases to the `lodash` wrapper. lodash.prototype.collect = lodash.prototype.map; lodash.prototype.head = lodash.prototype.first; lodash.prototype.select = lodash.prototype.filter; lodash.prototype.tail = lodash.prototype.rest; return lodash; } /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers like r.js check for condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose lodash to the global object when an AMD loader is present to avoid // errors in cases where lodash is loaded by a script tag and not intended // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for // more details. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. define(function() { return _; }); } // Check for `exports` after `define` in case a build optimizer adds an `exports` object. else if (freeExports && freeModule) { // Export for Node.js or RingoJS. if (moduleExports) { (freeModule.exports = _)._ = _; } // Export for Rhino with CommonJS support. else { freeExports._ = _; } } else { // Export for a browser or Rhino. root._ = _; } }.call(this)); },{}],15:[function(require,module,exports){ var process=require("__browserify_process");/* global jQuery */ (function ($) { process.jquery_build = true; var es = require('./elasticsearch'); function defer() { var def = $.Deferred(); // def.promise is usually a property (in normal implementations) // we override the promise to keep things working def.promise = def.promise(); return def; } $.es = $.extend({}, es); $.es.Client = function (config) { config = config || {}; config.defer = defer; config.$ = $; return new es.Client(config); }; }(jQuery)); },{"./elasticsearch":16,"__browserify_process":13}],16:[function(require,module,exports){ // In order to help people who were accidentally upgraded to this ES client, // throw an error when they try to instanciate the exported function. // previous "elasticsearch" module -> https://github.com/ncb000gt/node-es function es() { throw new Error('Looks like you are expecting the previous "elasticsearch" module. ' + 'It is now the "es" module. To create a client with this module use ' + '`new es.Client(params)`.'); } es.Client = require('./lib/client'); es.ConnectionPool = require('./lib/connection_pool'); es.Transport = require('./lib/transport'); es.errors = require('./lib/errors'); module.exports = es; },{"./lib/client":21,"./lib/connection_pool":24,"./lib/errors":27,"./lib/transport":40}],17:[function(require,module,exports){ /* jshint maxlen: false */ var ca = require('../client_action').factory; var namespace = require('../client_action').namespaceFactory; var api = module.exports = {}; api._namespaces = ['cat', 'cluster', 'indices', 'nodes', 'snapshot']; /** * Perform a [bulk](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-bulk.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Explicitely set the replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String} params.type - Default document type for items which don't provide one * @param {String} params.index - Default index for items which don't provide one */ api.bulk = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, type: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_bulk', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_bulk', req: { index: { type: 'string' } } }, { fmt: '/_bulk' } ], needBody: true, bulkBody: true, method: 'POST' }); api.cat = namespace(); /** * Perform a [cat.aliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.cat.prototype.aliases = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/aliases/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_cat/aliases' } ] }); /** * Perform a [cat.allocation](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-allocation.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information */ api.cat.prototype.allocation = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/allocation/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_cat/allocation' } ] }); /** * Perform a [cat.count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-count.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.count = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/count/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/count' } ] }); /** * Perform a [cat.fielddata](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-fielddata.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return the fielddata size */ api.cat.prototype.fielddata = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false }, fields: { type: 'list' } }, urls: [ { fmt: '/_cat/fielddata/<%=fields%>', req: { fields: { type: 'list' } } }, { fmt: '/_cat/fielddata' } ] }); /** * Perform a [cat.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-health.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} [params.ts=true] - Set to false to disable timestamping * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.health = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, ts: { type: 'boolean', 'default': true }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/health' } }); /** * Perform a [cat.help](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.help - Return help information */ api.cat.prototype.help = ca({ params: { help: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat' } }); /** * Perform a [cat.indices](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-indices.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.pri - Set to true to return stats only for primary shards * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.indices = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, pri: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/indices/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/indices' } ] }); /** * Perform a [cat.master](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-master.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.master = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/master' } }); /** * Perform a [cat.nodes](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-nodes.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.nodes = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/nodes' } }); /** * Perform a [cat.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-pending-tasks.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.pendingTasks = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/pending_tasks' } }); /** * Perform a [cat.plugins](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-plugins.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.plugins = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/plugins' } }); /** * Perform a [cat.recovery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-recovery.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.recovery = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/recovery/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/recovery' } ] }); /** * Perform a [cat.segments](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-segments.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} [params.v=true] - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.segments = ca({ params: { h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': true } }, urls: [ { fmt: '/_cat/segments/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/segments' } ] }); /** * Perform a [cat.shards](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-shards.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.shards = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/shards/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/shards' } ] }); /** * Perform a [cat.threadPool](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-thread-pool.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {Boolean} params.fullId - Enables displaying the complete node ids */ api.cat.prototype.threadPool = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false }, fullId: { type: 'boolean', 'default': false, name: 'full_id' } }, url: { fmt: '/_cat/thread_pool' } }); /** * Perform a [clearScroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-scroll.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.scrollId - A comma-separated list of scroll IDs to clear */ api.clearScroll = ca({ urls: [ { fmt: '/_search/scroll/<%=scrollId%>', req: { scrollId: { type: 'list' } } }, { fmt: '/_search/scroll' } ], method: 'DELETE' }); api.cluster = namespace(); /** * Perform a [cluster.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout */ api.cluster.prototype.getSettings = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_cluster/settings' } }); /** * Perform a [cluster.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-health.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} [params.level=cluster] - Specify the level of detail for returned information * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Number} params.waitForActiveShards - Wait until the specified number of shards is active * @param {String} params.waitForNodes - Wait until the specified number of nodes is available * @param {Number} params.waitForRelocatingShards - Wait until the specified number of relocating shards is finished * @param {String} params.waitForStatus - Wait until cluster is in a specific state * @param {String} params.index - Limit the information returned to a specific index */ api.cluster.prototype.health = ca({ params: { level: { type: 'enum', 'default': 'cluster', options: [ 'cluster', 'indices', 'shards' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' }, waitForActiveShards: { type: 'number', name: 'wait_for_active_shards' }, waitForNodes: { type: 'string', name: 'wait_for_nodes' }, waitForRelocatingShards: { type: 'number', name: 'wait_for_relocating_shards' }, waitForStatus: { type: 'enum', 'default': null, options: [ 'green', 'yellow', 'red' ], name: 'wait_for_status' } }, urls: [ { fmt: '/_cluster/health/<%=index%>', req: { index: { type: 'string' } } }, { fmt: '/_cluster/health' } ] }); /** * Perform a [cluster.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-pending.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master */ api.cluster.prototype.pendingTasks = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_cluster/pending_tasks' } }); /** * Perform a [cluster.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout */ api.cluster.prototype.putSettings = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_cluster/settings' }, method: 'PUT' }); /** * Perform a [cluster.reroute](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-reroute.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.dryRun - Simulate the operation only and return the resulting state * @param {Boolean} params.explain - Return an explanation of why the commands can or cannot be executed * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics. Defaults to all but metadata * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout */ api.cluster.prototype.reroute = ca({ params: { dryRun: { type: 'boolean', name: 'dry_run' }, explain: { type: 'boolean' }, metric: { type: 'list', options: [ '_all', 'blocks', 'metadata', 'nodes', 'routing_table', 'master_node', 'version' ] }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_cluster/reroute' }, method: 'POST' }); /** * Perform a [cluster.state](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-state.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics */ api.cluster.prototype.state = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, flatSettings: { type: 'boolean', name: 'flat_settings' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/_cluster/state/<%=metric%>/<%=index%>', req: { metric: { type: 'list', options: [ '_all', 'blocks', 'metadata', 'nodes', 'routing_table', 'master_node', 'version' ] }, index: { type: 'list' } } }, { fmt: '/_cluster/state/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'blocks', 'metadata', 'nodes', 'routing_table', 'master_node', 'version' ] } } }, { fmt: '/_cluster/state' } ] }); /** * Perform a [cluster.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.cluster.prototype.stats = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cluster/stats/nodes/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_cluster/stats' } ] }); /** * Perform a [count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-count.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Number} params.minScore - Include only documents with a specific `_score` value in the result * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the results * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the results */ api.count = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, minScore: { type: 'number', name: 'min_score' }, preference: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_count', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_count', req: { index: { type: 'list' } } }, { fmt: '/_count' } ], method: 'POST' }); /** * Perform a [countPercolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.percolateIndex - The index to count percolate the document into. Defaults to index. * @param {String} params.percolateType - The type to count percolate document into. Defaults to type. * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.index - The index of the document being count percolated. * @param {String} params.type - The type of the document being count percolated. * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster. */ api.countPercolate = ca({ params: { source: { type: 'string' }, routing: { type: 'list' }, preference: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, percolateIndex: { type: 'string', name: 'percolate_index' }, percolateType: { type: 'string', name: 'percolate_type' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate/count', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>/_percolate/count', req: { index: { type: 'string' }, type: { type: 'string' } } } ], method: 'POST' }); /** * Perform a [delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-delete.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Specific write consistency setting for the operation * @param {String} params.parent - ID of parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api['delete'] = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [deleteByQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-delete-by-query.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.analyzer - The analyzer to use for the query string * @param {String} params.consistency - Specific write consistency setting for the operation * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the operation; use `_all` to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the operation */ api.deleteByQuery = ca({ params: { analyzer: { type: 'string' }, consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, q: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' }, timeout: { type: 'time' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_query', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_query', req: { index: { type: 'list' } } } ], method: 'DELETE' }); /** * Perform a [deleteScript](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.deleteScript = ca({ params: { version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [deleteTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Template ID */ api.deleteTemplate = ca({ params: { version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.exists = ca({ params: { parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'HEAD' }); /** * Perform a [explain](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-explain.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.analyzeWildcard - Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false) * @param {String} params.analyzer - The analyzer for the query string query * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The default field for query string query (default: _all) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.explain = ca({ params: { analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, analyzer: { type: 'string' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, fields: { type: 'list' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' }, parent: { type: 'string' }, preference: { type: 'string' }, q: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_explain', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.get = ca({ params: { fields: { type: 'list' }, parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getScript](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.getScript = ca({ params: { version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getSource](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document; use `_all` to fetch the first document matching the ID across all types */ api.getSource = ca({ params: { parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_source', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Template ID */ api.getTemplate = ca({ params: { version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } } }); /** * Perform a [index](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-index_.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String} params.parent - ID of the parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.index = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, opType: { type: 'enum', 'default': 'index', options: [ 'index', 'create' ], name: 'op_type' }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, timestamp: { type: 'time' }, ttl: { type: 'duration' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>', req: { index: { type: 'string' }, type: { type: 'string' } } } ], needBody: true, method: 'POST' }); api.indices = namespace(); /** * Perform a [indices.analyze](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-analyze.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {String} params.analyzer - The name of the analyzer to use * @param {String, String[], Boolean} params.charFilters - A comma-separated list of character filters to use for the analysis * @param {String} params.field - Use the analyzer configured for this field (instead of passing the analyzer name) * @param {String, String[], Boolean} params.filters - A comma-separated list of filters to use for the analysis * @param {String} params.index - The name of the index to scope the operation * @param {Boolean} params.preferLocal - With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true) * @param {String} params.text - The text on which the analysis should be performed (when request body is not used) * @param {String} params.tokenizer - The name of the tokenizer to use for the analysis * @param {String} [params.format=detailed] - Format of the output */ api.indices.prototype.analyze = ca({ params: { source: { type: 'string' }, analyzer: { type: 'string' }, charFilters: { type: 'list', name: 'char_filters' }, field: { type: 'string' }, filters: { type: 'list' }, index: { type: 'string' }, preferLocal: { type: 'boolean', name: 'prefer_local' }, text: { type: 'string' }, tokenizer: { type: 'string' }, format: { type: 'enum', 'default': 'detailed', options: [ 'detailed', 'text' ] } }, urls: [ { fmt: '/<%=index%>/_analyze', req: { index: { type: 'string' } } }, { fmt: '/_analyze' } ], method: 'POST' }); /** * Perform a [indices.clearCache](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-clearcache.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.fieldData - Clear field data * @param {Boolean} params.fielddata - Clear field data * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to clear when using the `field_data` parameter (default: all) * @param {Boolean} params.filter - Clear filter caches * @param {Boolean} params.filterCache - Clear filter caches * @param {Boolean} params.filterKeys - A comma-separated list of keys to clear when using the `filter_cache` parameter (default: all) * @param {Boolean} params.id - Clear ID caches for parent/child * @param {Boolean} params.idCache - Clear ID caches for parent/child * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index name to limit the operation * @param {Boolean} params.recycler - Clear the recycler cache * @param {Boolean} params.queryCache - Clear query cache */ api.indices.prototype.clearCache = ca({ params: { fieldData: { type: 'boolean', name: 'field_data' }, fielddata: { type: 'boolean' }, fields: { type: 'list' }, filter: { type: 'boolean' }, filterCache: { type: 'boolean', name: 'filter_cache' }, filterKeys: { type: 'boolean', name: 'filter_keys' }, id: { type: 'boolean' }, idCache: { type: 'boolean', name: 'id_cache' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, index: { type: 'list' }, recycler: { type: 'boolean' }, queryCache: { type: 'boolean', name: 'query_cache' } }, urls: [ { fmt: '/<%=index%>/_cache/clear', req: { index: { type: 'list' } } }, { fmt: '/_cache/clear' } ], method: 'POST' }); /** * Perform a [indices.close](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-open-close.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index */ api.indices.prototype.close = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, url: { fmt: '/<%=index%>/_close', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-create-index.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String} params.index - The name of the index */ api.indices.prototype.create = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-delete-index.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of indices to delete; use `_all` or `*` string to delete all indices */ api.indices.prototype['delete'] = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit timestamp for the document * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices * @param {String, String[], Boolean} params.name - A comma-separated list of aliases to delete (supports wildcards); use `_all` to delete all aliases for the specified indices. */ api.indices.prototype.deleteAlias = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-delete-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to delete (supports wildcards); use `_all` to delete all document types in the specified indices. */ api.indices.prototype.deleteMapping = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>/<%=type%>/_mapping', req: { index: { type: 'list' }, type: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String} params.name - The name of the template */ api.indices.prototype.deleteTemplate = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.name - A comma-separated list of warmer names to delete (supports wildcards); use `_all` to delete all warmers in the specified indices. You must specify a name either in the uri or in the parameters. * @param {String, String[], Boolean} params.index - A comma-separated list of index names to delete warmers from (supports wildcards); use `_all` to perform the operation on all indices. */ api.indices.prototype.deleteWarmer = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, name: { type: 'list' } }, url: { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-exists.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of indices to check */ api.indices.prototype.exists = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'list' } } }, method: 'HEAD' }); /** * Perform a [indices.existsAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.indices.prototype.existsAlias = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': [ 'open', 'closed' ], options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/_alias/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/<%=index%>/_alias', req: { index: { type: 'list' } } } ], method: 'HEAD' }); /** * Perform a [indices.existsTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.existsTemplate = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, local: { type: 'boolean' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, method: 'HEAD' }); /** * Perform a [indices.existsType](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-types-exists.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` to check the types across all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to check */ api.indices.prototype.existsType = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, url: { fmt: '/<%=index%>/<%=type%>', req: { index: { type: 'list' }, type: { type: 'list' } } }, method: 'HEAD' }); /** * Perform a [indices.flush](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-flush.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.force - Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal) * @param {Boolean} params.waitIfOngoing - If set to true the flush operation will block until the flush can be executed if another flush operation is already executing. The default is false and will cause an exception to be thrown on the shard level if another flush operation is already running. * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices */ api.indices.prototype.flush = ca({ params: { force: { type: 'boolean' }, waitIfOngoing: { type: 'boolean', name: 'wait_if_ongoing' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/_flush', req: { index: { type: 'list' } } }, { fmt: '/_flush' } ], method: 'POST' }); /** * Perform a [indices.get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-index.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Boolean} params.ignoreUnavailable - Ignore unavailable indexes (default: false) * @param {Boolean} params.allowNoIndices - Ignore if a wildcard expression resolves to no concrete indices (default: false) * @param {String} [params.expandWildcards=open] - Whether wildcard expressions should get expanded to open or closed indices (default: open) * @param {String, String[], Boolean} params.index - A comma-separated list of index names * @param {String, String[], Boolean} params.feature - A comma-separated list of features */ api.indices.prototype.get = ca({ params: { local: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=feature%>', req: { index: { type: 'list' }, feature: { type: 'list' } } }, { fmt: '/<%=index%>', req: { index: { type: 'list' } } } ] }); /** * Perform a [indices.getAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.indices.prototype.getAlias = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/_alias/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/<%=index%>/_alias', req: { index: { type: 'list' } } }, { fmt: '/_alias' } ] }); /** * Perform a [indices.getAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to filter */ api.indices.prototype.getAliases = ca({ params: { timeout: { type: 'time' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_aliases/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_aliases', req: { index: { type: 'list' } } }, { fmt: '/_aliases/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_aliases' } ] }); /** * Perform a [indices.getFieldMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-field-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.includeDefaults - Whether the default mapping values should be returned as well * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names * @param {String, String[], Boolean} params.type - A comma-separated list of document types * @param {String, String[], Boolean} params.field - A comma-separated list of fields */ api.indices.prototype.getFieldMapping = ca({ params: { includeDefaults: { type: 'boolean', name: 'include_defaults' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>/field/<%=field%>', req: { index: { type: 'list' }, type: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/<%=index%>/_mapping/field/<%=field%>', req: { index: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/_mapping/<%=type%>/field/<%=field%>', req: { type: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/_mapping/field/<%=field%>', req: { field: { type: 'list' } } } ] }); /** * Perform a [indices.getMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names * @param {String, String[], Boolean} params.type - A comma-separated list of document types */ api.indices.prototype.getMapping = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_mapping', req: { index: { type: 'list' } } }, { fmt: '/_mapping/<%=type%>', req: { type: { type: 'list' } } }, { fmt: '/_mapping' } ] }); /** * Perform a [indices.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.name - The name of the settings that should be included */ api.indices.prototype.getSettings = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': [ 'open', 'closed' ], options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, flatSettings: { type: 'boolean', name: 'flat_settings' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_settings/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_settings', req: { index: { type: 'list' } } }, { fmt: '/_settings/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_settings' } ] }); /** * Perform a [indices.getTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.getTemplate = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, masterTimeout: { type: 'time', name: 'master_timeout' }, local: { type: 'boolean' } }, urls: [ { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, { fmt: '/_template' } ] }); /** * Perform a [indices.getUpgrade](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-upgrade.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.getUpgrade = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/<%=index%>/_upgrade', req: { index: { type: 'list' } } }, { fmt: '/_upgrade' } ] }); /** * Perform a [indices.getWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` to perform the operation on all indices * @param {String, String[], Boolean} params.name - The name of the warmer (supports wildcards); leave empty to get all warmers * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types */ api.indices.prototype.getWarmer = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>', req: { index: { type: 'list' }, type: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_warmer', req: { index: { type: 'list' } } }, { fmt: '/_warmer/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_warmer' } ] }); /** * Perform a [indices.open](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-open-close.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index */ api.indices.prototype.open = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'closed', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, url: { fmt: '/<%=index%>/_open', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.optimize](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-optimize.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flush - Specify whether the index should be flushed after performing the operation (default: true) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Number} params.maxNumSegments - The number of segments the index should be merged into (default: dynamic) * @param {Boolean} params.onlyExpungeDeletes - Specify whether the operation should only expunge deleted documents * @param {Anything} params.operationThreading - TODO: ? * @param {Boolean} params.waitForMerge - Specify whether the request should block until the merge process is finished (default: true) * @param {Boolean} params.force - Force a merge operation to run, even if there is a single segment in the index (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.optimize = ca({ params: { flush: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, maxNumSegments: { type: 'number', name: 'max_num_segments' }, onlyExpungeDeletes: { type: 'boolean', name: 'only_expunge_deletes' }, operationThreading: { name: 'operation_threading' }, waitForMerge: { type: 'boolean', name: 'wait_for_merge' }, force: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_optimize', req: { index: { type: 'list' } } }, { fmt: '/_optimize' } ], method: 'POST' }); /** * Perform a [indices.putAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit timestamp for the document * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names the alias should point to (supports wildcards); use `_all` to perform the operation on all indices. * @param {String} params.name - The name of the alias to be created or updated */ api.indices.prototype.putAlias = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'string' } } }, method: 'PUT' }); /** * Perform a [indices.putMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-put-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreConflicts - Specify whether to ignore conflicts while updating the mapping (default: false) * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices. * @param {String} params.type - The name of the document type */ api.indices.prototype.putMapping = ca({ params: { ignoreConflicts: { type: 'boolean', name: 'ignore_conflicts' }, timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>', req: { index: { type: 'list' }, type: { type: 'string' } } }, { fmt: '/_mapping/<%=type%>', req: { type: { type: 'string' } } } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.putSettings = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, flatSettings: { type: 'boolean', name: 'flat_settings' } }, urls: [ { fmt: '/<%=index%>/_settings', req: { index: { type: 'list' } } }, { fmt: '/_settings' } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.putTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.order - The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers) * @param {Boolean} params.create - Whether the index template should only be added if new or can also replace an existing one * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.putTemplate = ca({ params: { order: { type: 'number' }, create: { type: 'boolean', 'default': false }, timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, flatSettings: { type: 'boolean', name: 'flat_settings' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [indices.putWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) in the search request to warm * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices in the search request to warm. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both, in the search request to warm. * @param {String, String[], Boolean} params.index - A comma-separated list of index names to register the warmer for; use `_all` or omit to perform the operation on all indices * @param {String} params.name - The name of the warmer * @param {String, String[], Boolean} params.type - A comma-separated list of document types to register the warmer for; leave empty to perform the operation on all types */ api.indices.prototype.putWarmer = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>', req: { index: { type: 'list' }, type: { type: 'list' }, name: { type: 'string' } } }, { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'string' } } }, { fmt: '/_warmer/<%=name%>', req: { name: { type: 'string' } } } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.recovery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-recovery.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.detailed - Whether to display detailed information about shard recovery * @param {Boolean} params.activeOnly - Display only those recoveries that are currently on-going * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.recovery = ca({ params: { detailed: { type: 'boolean', 'default': false }, activeOnly: { type: 'boolean', 'default': false, name: 'active_only' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/<%=index%>/_recovery', req: { index: { type: 'list' } } }, { fmt: '/_recovery' } ] }); /** * Perform a [indices.refresh](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-refresh.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.force - Force a refresh even if not required * @param {Anything} params.operationThreading - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.refresh = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, force: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' } }, urls: [ { fmt: '/<%=index%>/_refresh', req: { index: { type: 'list' } } }, { fmt: '/_refresh' } ], method: 'POST' }); /** * Perform a [indices.segments](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-segments.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {Anything} params.operationThreading - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.segments = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, human: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' } }, urls: [ { fmt: '/<%=index%>/_segments', req: { index: { type: 'list' } } }, { fmt: '/_segments' } ] }); /** * Perform a [indices.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) * @param {String, String[], Boolean} params.groups - A comma-separated list of search groups for `search` index metric * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String} [params.level=indices] - Return stats aggregated at cluster, index or shard level * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.metric - Limit the information returned the specific metrics. */ api.indices.prototype.stats = ca({ params: { completionFields: { type: 'list', name: 'completion_fields' }, fielddataFields: { type: 'list', name: 'fielddata_fields' }, fields: { type: 'list' }, groups: { type: 'list' }, human: { type: 'boolean', 'default': false }, level: { type: 'enum', 'default': 'indices', options: [ 'cluster', 'indices', 'shards' ] }, types: { type: 'list' } }, urls: [ { fmt: '/<%=index%>/_stats/<%=metric%>', req: { index: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'query_cache', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_stats/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'query_cache', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/<%=index%>/_stats', req: { index: { type: 'list' } } }, { fmt: '/_stats' } ] }); /** * Perform a [indices.status](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-status.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {Anything} params.operationThreading - TODO: ? * @param {Boolean} params.recovery - Return information about shard recovery * @param {Boolean} params.snapshot - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.status = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, human: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' }, recovery: { type: 'boolean' }, snapshot: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_status', req: { index: { type: 'list' } } }, { fmt: '/_status' } ] }); /** * Perform a [indices.updateAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Request timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master */ api.indices.prototype.updateAliases = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_aliases' }, needBody: true, method: 'POST' }); /** * Perform a [indices.upgrade](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-upgrade.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.waitForCompletion - Specify whether the request should block until the all segments are upgraded (default: true) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.upgrade = ca({ params: { allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, waitForCompletion: { type: 'boolean', name: 'wait_for_completion' } }, urls: [ { fmt: '/<%=index%>/_upgrade', req: { index: { type: 'list' } } }, { fmt: '/_upgrade' } ], method: 'POST' }); /** * Perform a [indices.validateQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-validate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.explain - Return detailed information about the error * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Anything} params.operationThreading - TODO: ? * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {String} params.q - Query in the Lucene query string syntax * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types */ api.indices.prototype.validateQuery = ca({ params: { explain: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, operationThreading: { name: 'operation_threading' }, source: { type: 'string' }, q: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_validate/query', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_validate/query', req: { index: { type: 'list' } } }, { fmt: '/_validate/query' } ], method: 'POST' }); /** * Perform a [info](http://www.elasticsearch.org/guide/) request * * @param {Object} params - An object with parameters used to carry out this action */ api.info = ca({ url: { fmt: '/' } }); /** * Perform a [mget](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-multi-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.mget = ca({ params: { source: { type: 'string' }, fields: { type: 'list' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mget', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mget', req: { index: { type: 'string' } } }, { fmt: '/_mget' } ], needBody: true, method: 'POST' }); /** * Perform a [mlt](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-more-like-this.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {Number} params.boostTerms - The boost factor * @param {Number} params.maxDocFreq - The word occurrence frequency as count: words with higher occurrence in the corpus will be ignored * @param {Number} params.maxQueryTerms - The maximum query terms to be included in the generated query * @param {Number} params.maxWordLength - The minimum length of the word: longer words will be ignored * @param {Number} params.minDocFreq - The word occurrence frequency as count: words with lower occurrence in the corpus will be ignored * @param {Number} params.minTermFreq - The term frequency as percent: terms with lower occurence in the source document will be ignored * @param {Number} params.minWordLength - The minimum length of the word: shorter words will be ignored * @param {String, String[], Boolean} params.mltFields - Specific fields to perform the query against * @param {Number} params.percentTermsToMatch - How many terms have to match in order to consider the document a match (default: 0.3) * @param {String} params.routing - Specific routing value * @param {Number} params.searchFrom - The offset from which to return results * @param {String, String[], Boolean} params.searchIndices - A comma-separated list of indices to perform the query against (default: the index containing the document) * @param {String} params.searchScroll - A scroll search request definition * @param {Number} params.searchSize - The number of documents to return (default: 10) * @param {String} params.searchSource - A specific search request definition (instead of using the request body) * @param {String} params.searchType - Specific search type (eg. `dfs_then_fetch`, `count`, etc) * @param {String, String[], Boolean} params.searchTypes - A comma-separated list of types to perform the query against (default: the same type as the document) * @param {String, String[], Boolean} params.stopWords - A list of stop words to be ignored * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.mlt = ca({ params: { source: { type: 'string' }, boostTerms: { type: 'number', name: 'boost_terms' }, maxDocFreq: { type: 'number', name: 'max_doc_freq' }, maxQueryTerms: { type: 'number', name: 'max_query_terms' }, maxWordLength: { type: 'number', name: 'max_word_length' }, minDocFreq: { type: 'number', name: 'min_doc_freq' }, minTermFreq: { type: 'number', name: 'min_term_freq' }, minWordLength: { type: 'number', name: 'min_word_length' }, mltFields: { type: 'list', name: 'mlt_fields' }, percentTermsToMatch: { type: 'number', name: 'percent_terms_to_match' }, routing: { type: 'string' }, searchFrom: { type: 'number', name: 'search_from' }, searchIndices: { type: 'list', name: 'search_indices' }, searchScroll: { type: 'string', name: 'search_scroll' }, searchSize: { type: 'number', name: 'search_size' }, searchSource: { type: 'string', name: 'search_source' }, searchType: { type: 'string', name: 'search_type' }, searchTypes: { type: 'list', name: 'search_types' }, stopWords: { type: 'list', name: 'stop_words' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_mlt', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [mpercolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The index of the document being count percolated to use as default * @param {String} params.type - The type of the document being percolated to use as default. */ api.mpercolate = ca({ params: { source: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mpercolate', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mpercolate', req: { index: { type: 'string' } } }, { fmt: '/_mpercolate' } ], needBody: true, bulkBody: true, method: 'POST' }); /** * Perform a [msearch](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-multi-search.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {String} params.searchType - Search operation type * @param {String, String[], Boolean} params.index - A comma-separated list of index names to use as default * @param {String, String[], Boolean} params.type - A comma-separated list of document types to use as default */ api.msearch = ca({ params: { source: { type: 'string' }, searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_msearch', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_msearch', req: { index: { type: 'list' } } }, { fmt: '/_msearch' } ], needBody: true, bulkBody: true, method: 'POST' }); /** * Perform a [mtermvectors](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-multi-termvectors.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {String, String[], Boolean} params.ids - A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.routing - Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.parent - Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} params.realtime - Specifies if requests are real-time as opposed to near-real-time (default: true). * @param {String} params.index - The index in which the document resides. * @param {String} params.type - The type of the document. * @param {String} params.id - The id of the document. */ api.mtermvectors = ca({ params: { source: { type: 'string' }, ids: { type: 'list', required: false }, termStatistics: { type: 'boolean', 'default': false, required: false, name: 'term_statistics' }, fieldStatistics: { type: 'boolean', 'default': true, required: false, name: 'field_statistics' }, fields: { type: 'list', required: false }, offsets: { type: 'boolean', 'default': true, required: false }, positions: { type: 'boolean', 'default': true, required: false }, payloads: { type: 'boolean', 'default': true, required: false }, preference: { type: 'string', required: false }, routing: { type: 'string', required: false }, parent: { type: 'string', required: false }, realtime: { type: 'boolean', required: false } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mtermvectors', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mtermvectors', req: { index: { type: 'string' } } }, { fmt: '/_mtermvectors' } ], method: 'POST' }); api.nodes = namespace(); /** * Perform a [nodes.hotThreads](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-hot-threads.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.interval - The interval for the second sampling of threads * @param {Number} params.snapshots - Number of samples of thread stacktrace (default: 10) * @param {Number} params.threads - Specify the number of threads to provide information for (default: 3) * @param {Boolean} params.ignoreIdleThreads - Don't show threads that are in known-idle places, such as waiting on a socket select or pulling from an empty task queue (default: true) * @param {String} params.type - The type to sample (default: cpu) * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.nodes.prototype.hotThreads = ca({ params: { interval: { type: 'time' }, snapshots: { type: 'number' }, threads: { type: 'number' }, ignoreIdleThreads: { type: 'boolean', name: 'ignore_idle_threads' }, type: { type: 'enum', options: [ 'cpu', 'wait', 'block' ] } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/hotthreads', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/hotthreads' } ] }); /** * Perform a [nodes.info](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-info.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes * @param {String, String[], Boolean} params.metric - A comma-separated list of metrics you wish returned. Leave empty to return all. */ api.nodes.prototype.info = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/<%=metric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ 'settings', 'os', 'process', 'jvm', 'thread_pool', 'network', 'transport', 'http', 'plugins' ] } } }, { fmt: '/_nodes/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/<%=metric%>', req: { metric: { type: 'list', options: [ 'settings', 'os', 'process', 'jvm', 'thread_pool', 'network', 'transport', 'http', 'plugins' ] } } }, { fmt: '/_nodes' } ] }); /** * Perform a [nodes.shutdown](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-shutdown.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.delay - Set the delay for the operation (default: 1s) * @param {Boolean} params.exit - Exit the JVM as well (default: true) * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to perform the operation on; use `_local` to perform the operation on the node you're connected to, leave empty to perform the operation on all nodes */ api.nodes.prototype.shutdown = ca({ params: { delay: { type: 'time' }, exit: { type: 'boolean' } }, urls: [ { fmt: '/_cluster/nodes/<%=nodeId%>/_shutdown', req: { nodeId: { type: 'list' } } }, { fmt: '/_shutdown' } ], method: 'POST' }); /** * Perform a [nodes.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) * @param {Boolean} params.groups - A comma-separated list of search groups for `search` index metric * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String} [params.level=node] - Return indices stats aggregated at node, index or shard level * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics * @param {String, String[], Boolean} params.indexMetric - Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.nodes.prototype.stats = ca({ params: { completionFields: { type: 'list', name: 'completion_fields' }, fielddataFields: { type: 'list', name: 'fielddata_fields' }, fields: { type: 'list' }, groups: { type: 'boolean' }, human: { type: 'boolean', 'default': false }, level: { type: 'enum', 'default': 'node', options: [ 'node', 'indices', 'shards' ] }, types: { type: 'list' } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] }, indexMetric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'query_cache', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] } } }, { fmt: '/_nodes/stats/<%=metric%>/<%=indexMetric%>', req: { metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] }, indexMetric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'query_cache', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_nodes/<%=nodeId%>/stats', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/stats/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] } } }, { fmt: '/_nodes/stats' } ] }); /** * Perform a [percolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.percolateFormat - Return an array of matching query IDs instead of objects * @param {String} params.percolateIndex - The index to percolate the document into. Defaults to index. * @param {String} params.percolateType - The type to percolate document into. Defaults to type. * @param {String} params.percolateRouting - The routing value to use when percolating the existing document. * @param {String} params.percolatePreference - Which shard to prefer when executing the percolate request. * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.index - The index of the document being percolated. * @param {String} params.type - The type of the document being percolated. * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster. */ api.percolate = ca({ params: { source: { type: 'string' }, routing: { type: 'list' }, preference: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, percolateFormat: { type: 'enum', options: [ 'ids' ], name: 'percolate_format' }, percolateIndex: { type: 'string', name: 'percolate_index' }, percolateType: { type: 'string', name: 'percolate_type' }, percolateRouting: { type: 'string', name: 'percolate_routing' }, percolatePreference: { type: 'string', name: 'percolate_preference' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>/_percolate', req: { index: { type: 'string' }, type: { type: 'string' } } } ], method: 'POST' }); /** * Perform a [ping](http://www.elasticsearch.org/guide/) request * * @param {Object} params - An object with parameters used to carry out this action */ api.ping = ca({ url: { fmt: '/' }, requestTimeout: 3000, method: 'HEAD' }); /** * Perform a [putScript](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} [params.opType=index] - Explicit operation type * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.putScript = ca({ params: { opType: { type: 'enum', 'default': 'index', options: [ 'index', 'create' ], name: 'op_type' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [putTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} [params.opType=index] - Explicit operation type * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Template ID */ api.putTemplate = ca({ params: { opType: { type: 'enum', 'default': 'index', options: [ 'index', 'create' ], name: 'op_type' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [scroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-scroll.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.scrollId - The scroll ID */ api.scroll = ca({ params: { source: { type: 'string' }, scroll: { type: 'duration' }, scrollId: { type: 'string', name: 'scroll_id' } }, urls: [ { fmt: '/_search/scroll/<%=scrollId%>', req: { scrollId: { type: 'string' } } }, { fmt: '/_search/scroll' } ], paramAsBody: 'scrollId', method: 'POST' }); /** * Perform a [search](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-search.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.analyzer - The analyzer to use for the query string * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false) * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.explain - Specify whether to return detailed information about score computation as part of a hit * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return as part of a hit * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields to return as the field data representation of a field for each hit * @param {Number} params.from - Starting offset (default: 0) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.indicesBoost - Comma-separated list of index boosts * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.q - Query in the Lucene query string syntax * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.searchType - Search operation type * @param {Number} params.size - Number of hits to return (default: 10) * @param {String, String[], Boolean} params.sort - A comma-separated list of <field>:<direction> pairs * @param {String} params.source - The URL-encoded request definition using the Query DSL (instead of using request body) * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String, String[], Boolean} params.stats - Specific 'tag' of the request for logging and statistical purposes * @param {String} params.suggestField - Specify which field to use for suggestions * @param {String} [params.suggestMode=missing] - Specify suggest mode * @param {Number} params.suggestSize - How many suggestions to return in response * @param {Text} params.suggestText - The source text for which the suggestions should be returned * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Boolean} params.trackScores - Whether to calculate and return scores even if they are not used for sorting * @param {Boolean} params.version - Specify whether to return document version as part of a hit * @param {Boolean} params.queryCache - Specify if query cache should be used for this request or not, defaults to index level setting * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types */ api.search = ca({ params: { analyzer: { type: 'string' }, analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, explain: { type: 'boolean' }, fields: { type: 'list' }, fielddataFields: { type: 'list', name: 'fielddata_fields' }, from: { type: 'number' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, indicesBoost: { type: 'list', name: 'indices_boost' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' }, preference: { type: 'string' }, q: { type: 'string' }, routing: { type: 'list' }, scroll: { type: 'duration' }, searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' }, size: { type: 'number' }, sort: { type: 'list' }, source: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, stats: { type: 'list' }, suggestField: { type: 'string', name: 'suggest_field' }, suggestMode: { type: 'enum', 'default': 'missing', options: [ 'missing', 'popular', 'always' ], name: 'suggest_mode' }, suggestSize: { type: 'number', name: 'suggest_size' }, suggestText: { type: 'text', name: 'suggest_text' }, timeout: { type: 'time' }, trackScores: { type: 'boolean', name: 'track_scores' }, version: { type: 'boolean' }, queryCache: { type: 'boolean', name: 'query_cache' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_search', req: { index: { type: 'list' } } }, { fmt: '/_search' } ], method: 'POST' }); /** * Perform a [searchExists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-exists.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Number} params.minScore - Include only documents with a specific `_score` value in the result * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the results * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the results */ api.searchExists = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, minScore: { type: 'number', name: 'min_score' }, preference: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search/exists', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_search/exists', req: { index: { type: 'list' } } }, { fmt: '/_search/exists' } ], method: 'POST' }); /** * Perform a [searchShards](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-shards.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.searchShards = ca({ params: { preference: { type: 'string' }, routing: { type: 'string' }, local: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search_shards', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_search_shards', req: { index: { type: 'string' } } }, { fmt: '/_search_shards' } ], method: 'POST' }); /** * Perform a [searchTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.searchType - Search operation type * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types */ api.searchTemplate = ca({ params: { source: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, preference: { type: 'string' }, routing: { type: 'list' }, scroll: { type: 'duration' }, searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search/template', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_search/template', req: { index: { type: 'list' } } }, { fmt: '/_search/template' } ], method: 'POST' }); api.snapshot = namespace(); /** * Perform a [snapshot.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype.create = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, waitForCompletion: { type: 'boolean', 'default': false, name: 'wait_for_completion' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_create', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'POST' }); /** * Perform a [snapshot.createRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Boolean} params.verify - Whether to verify the repository after creation * @param {String} params.repository - A repository name */ api.snapshot.prototype.createRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' }, verify: { type: 'boolean' } }, url: { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'string' } } }, needBody: true, method: 'POST' }); /** * Perform a [snapshot.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype['delete'] = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [snapshot.deleteRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names */ api.snapshot.prototype.deleteRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [snapshot.get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names */ api.snapshot.prototype.get = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>', req: { repository: { type: 'string' }, snapshot: { type: 'list' } } } }); /** * Perform a [snapshot.getRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names */ api.snapshot.prototype.getRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, local: { type: 'boolean' } }, urls: [ { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'list' } } }, { fmt: '/_snapshot' } ] }); /** * Perform a [snapshot.restore](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype.restore = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, waitForCompletion: { type: 'boolean', 'default': false, name: 'wait_for_completion' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_restore', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'POST' }); /** * Perform a [snapshot.status](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names */ api.snapshot.prototype.status = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, urls: [ { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_status', req: { repository: { type: 'string' }, snapshot: { type: 'list' } } }, { fmt: '/_snapshot/<%=repository%>/_status', req: { repository: { type: 'string' } } }, { fmt: '/_snapshot/_status' } ] }); /** * Perform a [snapshot.verifyRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String} params.repository - A repository name */ api.snapshot.prototype.verifyRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_snapshot/<%=repository%>/_verify', req: { repository: { type: 'string' } } }, method: 'POST' }); /** * Perform a [suggest](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-suggesters.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded request definition (instead of using request body) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices */ api.suggest = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, preference: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/_suggest', req: { index: { type: 'list' } } }, { fmt: '/_suggest' } ], needBody: true, method: 'POST' }); /** * Perform a [termvector](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-termvectors.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.source - The URL-encoded request definition * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned. * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return. * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned. * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned. * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random). * @param {String} params.routing - Specific routing value. * @param {String} params.parent - Parent id of documents. * @param {Boolean} params.realtime - Specifies if request is real-time as opposed to near-real-time (default: true). * @param {String} params.index - The index in which the document resides. * @param {String} params.type - The type of the document. * @param {String} params.id - The id of the document. */ api.termvector = ca({ params: { source: { type: 'string' }, termStatistics: { type: 'boolean', 'default': false, required: false, name: 'term_statistics' }, fieldStatistics: { type: 'boolean', 'default': true, required: false, name: 'field_statistics' }, fields: { type: 'list', required: false }, offsets: { type: 'boolean', 'default': true, required: false }, positions: { type: 'boolean', 'default': true, required: false }, payloads: { type: 'boolean', 'default': true, required: false }, preference: { type: 'string', required: false }, routing: { type: 'string', required: false }, parent: { type: 'string', required: false }, realtime: { type: 'boolean', required: false } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/_termvector', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>/_termvector', req: { index: { type: 'string' }, type: { type: 'string' } } } ], method: 'POST' }); /** * Perform a [update](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-update.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.lang - The script language (default: groovy) * @param {String} params.parent - ID of the parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {Number} params.retryOnConflict - Specify how many times should the operation be retried when a conflict occurs (default: 0) * @param {String} params.routing - Specific routing value * @param {Anything} params.script - The URL-encoded script definition (instead of using request body) * @param {Anything} params.scriptId - The id of a stored script * @param {Boolean} params.scriptedUpsert - True if the script referenced in script or script_id should be called to perform inserts - defaults to false * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.update = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, fields: { type: 'list' }, lang: { type: 'string' }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, retryOnConflict: { type: 'number', name: 'retry_on_conflict' }, routing: { type: 'string' }, script: {}, scriptId: { name: 'script_id' }, scriptedUpsert: { type: 'boolean', name: 'scripted_upsert' }, timeout: { type: 'time' }, timestamp: { type: 'time' }, ttl: { type: 'duration' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_update', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-index_.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String} params.parent - ID of the parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.create = ca.proxy(api.index, { transform: function (params) { params.op_type = 'create'; } }); },{"../client_action":22}],18:[function(require,module,exports){ /* jshint maxlen: false */ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { return require('../utils').merge(spec, { params: { filterPath: { type: 'list', name: 'filter_path' } } }); }); var namespace = require('../client_action').namespaceFactory; var api = module.exports = {}; api._namespaces = ['cat', 'cluster', 'indices', 'nodes', 'snapshot']; /** * Perform a [bulk](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-bulk.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Explicitely set the replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String} params.type - Default document type for items which don't provide one * @param {String} params.index - Default index for items which don't provide one */ api.bulk = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, type: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_bulk', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_bulk', req: { index: { type: 'string' } } }, { fmt: '/_bulk' } ], needBody: true, bulkBody: true, method: 'POST' }); api.cat = namespace(); /** * Perform a [cat.aliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.cat.prototype.aliases = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/aliases/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_cat/aliases' } ] }); /** * Perform a [cat.allocation](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-allocation.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information */ api.cat.prototype.allocation = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/allocation/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_cat/allocation' } ] }); /** * Perform a [cat.count](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-count.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.count = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/count/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/count' } ] }); /** * Perform a [cat.fielddata](http://www.elastic.co/guide/en/elasticsearch/reference/master/cat-fielddata.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return the fielddata size */ api.cat.prototype.fielddata = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false }, fields: { type: 'list' } }, urls: [ { fmt: '/_cat/fielddata/<%=fields%>', req: { fields: { type: 'list' } } }, { fmt: '/_cat/fielddata' } ] }); /** * Perform a [cat.health](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-health.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} [params.ts=true] - Set to false to disable timestamping * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.health = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, ts: { type: 'boolean', 'default': true }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/health' } }); /** * Perform a [cat.help](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.help - Return help information */ api.cat.prototype.help = ca({ params: { help: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat' } }); /** * Perform a [cat.indices](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-indices.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.pri - Set to true to return stats only for primary shards * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.indices = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, pri: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/indices/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/indices' } ] }); /** * Perform a [cat.master](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-master.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.master = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/master' } }); /** * Perform a [cat.nodes](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-nodes.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.nodes = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/nodes' } }); /** * Perform a [cat.pendingTasks](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-pending-tasks.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.pendingTasks = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/pending_tasks' } }); /** * Perform a [cat.plugins](http://www.elastic.co/guide/en/elasticsearch/reference/master/cat-plugins.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.plugins = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/plugins' } }); /** * Perform a [cat.recovery](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-recovery.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.recovery = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/recovery/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/recovery' } ] }); /** * Perform a [cat.segments](http://www.elastic.co/guide/en/elasticsearch/reference/master/cat-segments.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} [params.v=true] - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.segments = ca({ params: { h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': true } }, urls: [ { fmt: '/_cat/segments/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/segments' } ] }); /** * Perform a [cat.shards](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cat-shards.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.shards = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/shards/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/shards' } ] }); /** * Perform a [cat.threadPool](http://www.elastic.co/guide/en/elasticsearch/reference/master/cat-thread-pool.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {Boolean} params.fullId - Enables displaying the complete node ids */ api.cat.prototype.threadPool = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false }, fullId: { type: 'boolean', 'default': false, name: 'full_id' } }, url: { fmt: '/_cat/thread_pool' } }); /** * Perform a [clearScroll](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-request-scroll.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.scrollId - A comma-separated list of scroll IDs to clear */ api.clearScroll = ca({ urls: [ { fmt: '/_search/scroll/<%=scrollId%>', req: { scrollId: { type: 'list' } } }, { fmt: '/_search/scroll' } ], method: 'DELETE' }); api.cluster = namespace(); /** * Perform a [cluster.getSettings](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout */ api.cluster.prototype.getSettings = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_cluster/settings' } }); /** * Perform a [cluster.health](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-health.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} [params.level=cluster] - Specify the level of detail for returned information * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Number} params.waitForActiveShards - Wait until the specified number of shards is active * @param {String} params.waitForNodes - Wait until the specified number of nodes is available * @param {Number} params.waitForRelocatingShards - Wait until the specified number of relocating shards is finished * @param {String} params.waitForStatus - Wait until cluster is in a specific state * @param {String} params.index - Limit the information returned to a specific index */ api.cluster.prototype.health = ca({ params: { level: { type: 'enum', 'default': 'cluster', options: [ 'cluster', 'indices', 'shards' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' }, waitForActiveShards: { type: 'number', name: 'wait_for_active_shards' }, waitForNodes: { type: 'string', name: 'wait_for_nodes' }, waitForRelocatingShards: { type: 'number', name: 'wait_for_relocating_shards' }, waitForStatus: { type: 'enum', 'default': null, options: [ 'green', 'yellow', 'red' ], name: 'wait_for_status' } }, urls: [ { fmt: '/_cluster/health/<%=index%>', req: { index: { type: 'string' } } }, { fmt: '/_cluster/health' } ] }); /** * Perform a [cluster.pendingTasks](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-pending.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master */ api.cluster.prototype.pendingTasks = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_cluster/pending_tasks' } }); /** * Perform a [cluster.putSettings](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout */ api.cluster.prototype.putSettings = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_cluster/settings' }, method: 'PUT' }); /** * Perform a [cluster.reroute](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-reroute.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.dryRun - Simulate the operation only and return the resulting state * @param {Boolean} params.explain - Return an explanation of why the commands can or cannot be executed * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics. Defaults to all but metadata * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout */ api.cluster.prototype.reroute = ca({ params: { dryRun: { type: 'boolean', name: 'dry_run' }, explain: { type: 'boolean' }, metric: { type: 'list', options: [ '_all', 'blocks', 'metadata', 'nodes', 'routing_table', 'master_node', 'version' ] }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_cluster/reroute' }, method: 'POST' }); /** * Perform a [cluster.state](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-state.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics */ api.cluster.prototype.state = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, flatSettings: { type: 'boolean', name: 'flat_settings' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/_cluster/state/<%=metric%>/<%=index%>', req: { metric: { type: 'list', options: [ '_all', 'blocks', 'metadata', 'nodes', 'routing_table', 'routing_nodes', 'master_node', 'version' ] }, index: { type: 'list' } } }, { fmt: '/_cluster/state/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'blocks', 'metadata', 'nodes', 'routing_table', 'routing_nodes', 'master_node', 'version' ] } } }, { fmt: '/_cluster/state' } ] }); /** * Perform a [cluster.stats](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.cluster.prototype.stats = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cluster/stats/nodes/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_cluster/stats' } ] }); /** * Perform a [count](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-count.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Number} params.minScore - Include only documents with a specific `_score` value in the result * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.analyzer - The analyzer to use for the query string * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false) * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the results * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the results */ api.count = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, minScore: { type: 'number', name: 'min_score' }, preference: { type: 'string' }, routing: { type: 'string' }, q: { type: 'string' }, analyzer: { type: 'string' }, analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_count', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_count', req: { index: { type: 'list' } } }, { fmt: '/_count' } ], method: 'POST' }); /** * Perform a [countPercolate](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.percolateIndex - The index to count percolate the document into. Defaults to index. * @param {String} params.percolateType - The type to count percolate document into. Defaults to type. * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.index - The index of the document being count percolated. * @param {String} params.type - The type of the document being count percolated. * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster. */ api.countPercolate = ca({ params: { routing: { type: 'list' }, preference: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, percolateIndex: { type: 'string', name: 'percolate_index' }, percolateType: { type: 'string', name: 'percolate_type' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate/count', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>/_percolate/count', req: { index: { type: 'string' }, type: { type: 'string' } } } ], method: 'POST' }); /** * Perform a [delete](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-delete.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Specific write consistency setting for the operation * @param {String} params.parent - ID of parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api['delete'] = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [deleteByQuery](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-delete-by-query.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.analyzer - The analyzer to use for the query string * @param {String} params.consistency - Specific write consistency setting for the operation * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the operation; use `_all` to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the operation */ api.deleteByQuery = ca({ params: { analyzer: { type: 'string' }, consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, q: { type: 'string' }, routing: { type: 'string' }, timeout: { type: 'time' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_query', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_query', req: { index: { type: 'list' } } } ], method: 'DELETE' }); /** * Perform a [deleteScript](http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.deleteScript = ca({ params: { version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [deleteTemplate](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Template ID */ api.deleteTemplate = ca({ params: { version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [exists](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.exists = ca({ params: { parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'HEAD' }); /** * Perform a [explain](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-explain.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.analyzeWildcard - Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false) * @param {String} params.analyzer - The analyzer for the query string query * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The default field for query string query (default: _all) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.routing - Specific routing value * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.explain = ca({ params: { analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, analyzer: { type: 'string' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, fields: { type: 'list' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' }, parent: { type: 'string' }, preference: { type: 'string' }, q: { type: 'string' }, routing: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_explain', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [fieldStats](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-field-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for to get field statistics for (min value, max value, and more) * @param {String} [params.level=cluster] - Defines if field stats should be returned on a per index level or on a cluster wide level * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.fieldStats = ca({ params: { fields: { type: 'list' }, level: { type: 'enum', 'default': 'cluster', options: [ 'indices', 'cluster' ] }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/_field_stats', req: { index: { type: 'list' } } }, { fmt: '/_field_stats' } ], method: 'POST' }); /** * Perform a [get](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.get = ca({ params: { fields: { type: 'list' }, parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getScript](http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.getScript = ca({ params: { version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getSource](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document; use `_all` to fetch the first document matching the ID across all types */ api.getSource = ca({ params: { parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_source', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getTemplate](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Template ID */ api.getTemplate = ca({ params: { version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } } }); /** * Perform a [index](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-index_.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String} params.parent - ID of the parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.index = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, opType: { type: 'enum', 'default': 'index', options: [ 'index', 'create' ], name: 'op_type' }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, timestamp: { type: 'time' }, ttl: { type: 'duration' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>', req: { index: { type: 'string' }, type: { type: 'string' } } } ], needBody: true, method: 'POST' }); api.indices = namespace(); /** * Perform a [indices.analyze](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-analyze.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.analyzer - The name of the analyzer to use * @param {String, String[], Boolean} params.charFilters - A comma-separated list of character filters to use for the analysis * @param {String} params.field - Use the analyzer configured for this field (instead of passing the analyzer name) * @param {String, String[], Boolean} params.filters - A comma-separated list of filters to use for the analysis * @param {String} params.index - The name of the index to scope the operation * @param {Boolean} params.preferLocal - With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true) * @param {String} params.text - The text on which the analysis should be performed (when request body is not used) * @param {String} params.tokenizer - The name of the tokenizer to use for the analysis * @param {String} [params.format=detailed] - Format of the output */ api.indices.prototype.analyze = ca({ params: { analyzer: { type: 'string' }, charFilters: { type: 'list', name: 'char_filters' }, field: { type: 'string' }, filters: { type: 'list' }, index: { type: 'string' }, preferLocal: { type: 'boolean', name: 'prefer_local' }, text: { type: 'string' }, tokenizer: { type: 'string' }, format: { type: 'enum', 'default': 'detailed', options: [ 'detailed', 'text' ] } }, urls: [ { fmt: '/<%=index%>/_analyze', req: { index: { type: 'string' } } }, { fmt: '/_analyze' } ], method: 'POST' }); /** * Perform a [indices.clearCache](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-clearcache.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.fieldData - Clear field data * @param {Boolean} params.fielddata - Clear field data * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to clear when using the `field_data` parameter (default: all) * @param {Boolean} params.filter - Clear filter caches * @param {Boolean} params.filterCache - Clear filter caches * @param {Boolean} params.filterKeys - A comma-separated list of keys to clear when using the `filter_cache` parameter (default: all) * @param {Boolean} params.id - Clear ID caches for parent/child * @param {Boolean} params.idCache - Clear ID caches for parent/child * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index name to limit the operation * @param {Boolean} params.recycler - Clear the recycler cache * @param {Boolean} params.queryCache - Clear query cache */ api.indices.prototype.clearCache = ca({ params: { fieldData: { type: 'boolean', name: 'field_data' }, fielddata: { type: 'boolean' }, fields: { type: 'list' }, filter: { type: 'boolean' }, filterCache: { type: 'boolean', name: 'filter_cache' }, filterKeys: { type: 'boolean', name: 'filter_keys' }, id: { type: 'boolean' }, idCache: { type: 'boolean', name: 'id_cache' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, index: { type: 'list' }, recycler: { type: 'boolean' }, queryCache: { type: 'boolean', name: 'query_cache' } }, urls: [ { fmt: '/<%=index%>/_cache/clear', req: { index: { type: 'list' } } }, { fmt: '/_cache/clear' } ], method: 'POST' }); /** * Perform a [indices.close](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-open-close.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index */ api.indices.prototype.close = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, url: { fmt: '/<%=index%>/_close', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.create](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-create-index.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String} params.index - The name of the index */ api.indices.prototype.create = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.delete](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-delete-index.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of indices to delete; use `_all` or `*` string to delete all indices */ api.indices.prototype['delete'] = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteAlias](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit timestamp for the document * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices * @param {String, String[], Boolean} params.name - A comma-separated list of aliases to delete (supports wildcards); use `_all` to delete all aliases for the specified indices. */ api.indices.prototype.deleteAlias = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteMapping](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-delete-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to delete (supports wildcards); use `_all` to delete all document types in the specified indices. */ api.indices.prototype.deleteMapping = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>/<%=type%>/_mapping', req: { index: { type: 'list' }, type: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteTemplate](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String} params.name - The name of the template */ api.indices.prototype.deleteTemplate = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteWarmer](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.name - A comma-separated list of warmer names to delete (supports wildcards); use `_all` to delete all warmers in the specified indices. You must specify a name either in the uri or in the parameters. * @param {String, String[], Boolean} params.index - A comma-separated list of index names to delete warmers from (supports wildcards); use `_all` to perform the operation on all indices. */ api.indices.prototype.deleteWarmer = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, name: { type: 'list' } }, url: { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.exists](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-exists.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of indices to check */ api.indices.prototype.exists = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'list' } } }, method: 'HEAD' }); /** * Perform a [indices.existsAlias](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.indices.prototype.existsAlias = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': [ 'open', 'closed' ], options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/_alias/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/<%=index%>/_alias', req: { index: { type: 'list' } } } ], method: 'HEAD' }); /** * Perform a [indices.existsTemplate](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.existsTemplate = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, local: { type: 'boolean' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, method: 'HEAD' }); /** * Perform a [indices.existsType](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-types-exists.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` to check the types across all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to check */ api.indices.prototype.existsType = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, url: { fmt: '/<%=index%>/<%=type%>', req: { index: { type: 'list' }, type: { type: 'list' } } }, method: 'HEAD' }); /** * Perform a [indices.flush](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-flush.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.force - Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal) * @param {Boolean} params.waitIfOngoing - If set to true the flush operation will block until the flush can be executed if another flush operation is already executing. The default is false and will cause an exception to be thrown on the shard level if another flush operation is already running. * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices */ api.indices.prototype.flush = ca({ params: { force: { type: 'boolean' }, waitIfOngoing: { type: 'boolean', name: 'wait_if_ongoing' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/_flush', req: { index: { type: 'list' } } }, { fmt: '/_flush' } ], method: 'POST' }); /** * Perform a [indices.flushSynced](http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-synced-flush.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. */ api.indices.prototype.flushSynced = ca({ urls: [ { fmt: '/<%=index%>/_flush/synced', req: { index: { type: 'list' } } }, { fmt: '/_flush/synced' } ], method: 'POST' }); /** * Perform a [indices.get](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-get-index.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Boolean} params.ignoreUnavailable - Ignore unavailable indexes (default: false) * @param {Boolean} params.allowNoIndices - Ignore if a wildcard expression resolves to no concrete indices (default: false) * @param {String} [params.expandWildcards=open] - Whether wildcard expressions should get expanded to open or closed indices (default: open) * @param {String, String[], Boolean} params.index - A comma-separated list of index names * @param {String, String[], Boolean} params.feature - A comma-separated list of features */ api.indices.prototype.get = ca({ params: { local: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=feature%>', req: { index: { type: 'list' }, feature: { type: 'list' } } }, { fmt: '/<%=index%>', req: { index: { type: 'list' } } } ] }); /** * Perform a [indices.getAlias](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.indices.prototype.getAlias = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/_alias/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/<%=index%>/_alias', req: { index: { type: 'list' } } }, { fmt: '/_alias' } ] }); /** * Perform a [indices.getAliases](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to filter */ api.indices.prototype.getAliases = ca({ params: { timeout: { type: 'time' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_aliases/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_aliases', req: { index: { type: 'list' } } }, { fmt: '/_aliases/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_aliases' } ] }); /** * Perform a [indices.getFieldMapping](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-get-field-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.includeDefaults - Whether the default mapping values should be returned as well * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names * @param {String, String[], Boolean} params.type - A comma-separated list of document types * @param {String, String[], Boolean} params.field - A comma-separated list of fields */ api.indices.prototype.getFieldMapping = ca({ params: { includeDefaults: { type: 'boolean', name: 'include_defaults' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>/field/<%=field%>', req: { index: { type: 'list' }, type: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/<%=index%>/_mapping/field/<%=field%>', req: { index: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/_mapping/<%=type%>/field/<%=field%>', req: { type: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/_mapping/field/<%=field%>', req: { field: { type: 'list' } } } ] }); /** * Perform a [indices.getMapping](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-get-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names * @param {String, String[], Boolean} params.type - A comma-separated list of document types */ api.indices.prototype.getMapping = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_mapping', req: { index: { type: 'list' } } }, { fmt: '/_mapping/<%=type%>', req: { type: { type: 'list' } } }, { fmt: '/_mapping' } ] }); /** * Perform a [indices.getSettings](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-get-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.name - The name of the settings that should be included */ api.indices.prototype.getSettings = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': [ 'open', 'closed' ], options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, flatSettings: { type: 'boolean', name: 'flat_settings' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_settings/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_settings', req: { index: { type: 'list' } } }, { fmt: '/_settings/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_settings' } ] }); /** * Perform a [indices.getTemplate](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.getTemplate = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, masterTimeout: { type: 'time', name: 'master_timeout' }, local: { type: 'boolean' } }, urls: [ { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, { fmt: '/_template' } ] }); /** * Perform a [indices.getUpgrade](http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-upgrade.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.getUpgrade = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/<%=index%>/_upgrade', req: { index: { type: 'list' } } }, { fmt: '/_upgrade' } ] }); /** * Perform a [indices.getWarmer](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` to perform the operation on all indices * @param {String, String[], Boolean} params.name - The name of the warmer (supports wildcards); leave empty to get all warmers * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types */ api.indices.prototype.getWarmer = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>', req: { index: { type: 'list' }, type: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_warmer', req: { index: { type: 'list' } } }, { fmt: '/_warmer/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_warmer' } ] }); /** * Perform a [indices.open](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-open-close.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index */ api.indices.prototype.open = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'closed', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, url: { fmt: '/<%=index%>/_open', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.optimize](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-optimize.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flush - Specify whether the index should be flushed after performing the operation (default: true) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Number} params.maxNumSegments - The number of segments the index should be merged into (default: dynamic) * @param {Boolean} params.onlyExpungeDeletes - Specify whether the operation should only expunge deleted documents * @param {Anything} params.operationThreading - TODO: ? * @param {Boolean} params.waitForMerge - Specify whether the request should block until the merge process is finished (default: true) * @param {Boolean} params.force - Force a merge operation to run, even if there is a single segment in the index (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.optimize = ca({ params: { flush: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, maxNumSegments: { type: 'number', name: 'max_num_segments' }, onlyExpungeDeletes: { type: 'boolean', name: 'only_expunge_deletes' }, operationThreading: { name: 'operation_threading' }, waitForMerge: { type: 'boolean', name: 'wait_for_merge' }, force: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_optimize', req: { index: { type: 'list' } } }, { fmt: '/_optimize' } ], method: 'POST' }); /** * Perform a [indices.putAlias](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit timestamp for the document * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names the alias should point to (supports wildcards); use `_all` to perform the operation on all indices. * @param {String} params.name - The name of the alias to be created or updated */ api.indices.prototype.putAlias = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'string' } } }, method: 'PUT' }); /** * Perform a [indices.putMapping](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-put-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreConflicts - Specify whether to ignore conflicts while updating the mapping (default: false) * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices. * @param {String} params.type - The name of the document type */ api.indices.prototype.putMapping = ca({ params: { ignoreConflicts: { type: 'boolean', name: 'ignore_conflicts' }, timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>', req: { index: { type: 'list' }, type: { type: 'string' } } }, { fmt: '/_mapping/<%=type%>', req: { type: { type: 'string' } } } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.putSettings](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.putSettings = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, flatSettings: { type: 'boolean', name: 'flat_settings' } }, urls: [ { fmt: '/<%=index%>/_settings', req: { index: { type: 'list' } } }, { fmt: '/_settings' } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.putTemplate](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.order - The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers) * @param {Boolean} params.create - Whether the index template should only be added if new or can also replace an existing one * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.putTemplate = ca({ params: { order: { type: 'number' }, create: { type: 'boolean', 'default': false }, timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, flatSettings: { type: 'boolean', name: 'flat_settings' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [indices.putWarmer](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) in the search request to warm * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices in the search request to warm. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both, in the search request to warm. * @param {String, String[], Boolean} params.index - A comma-separated list of index names to register the warmer for; use `_all` or omit to perform the operation on all indices * @param {String} params.name - The name of the warmer * @param {String, String[], Boolean} params.type - A comma-separated list of document types to register the warmer for; leave empty to perform the operation on all types */ api.indices.prototype.putWarmer = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>', req: { index: { type: 'list' }, type: { type: 'list' }, name: { type: 'string' } } }, { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'string' } } }, { fmt: '/_warmer/<%=name%>', req: { name: { type: 'string' } } } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.recovery](http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-recovery.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.detailed - Whether to display detailed information about shard recovery * @param {Boolean} params.activeOnly - Display only those recoveries that are currently on-going * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.recovery = ca({ params: { detailed: { type: 'boolean', 'default': false }, activeOnly: { type: 'boolean', 'default': false, name: 'active_only' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/<%=index%>/_recovery', req: { index: { type: 'list' } } }, { fmt: '/_recovery' } ] }); /** * Perform a [indices.refresh](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-refresh.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.force - Force a refresh even if not required * @param {Anything} params.operationThreading - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.refresh = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, force: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' } }, urls: [ { fmt: '/<%=index%>/_refresh', req: { index: { type: 'list' } } }, { fmt: '/_refresh' } ], method: 'POST' }); /** * Perform a [indices.segments](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-segments.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {Anything} params.operationThreading - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.segments = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, human: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' } }, urls: [ { fmt: '/<%=index%>/_segments', req: { index: { type: 'list' } } }, { fmt: '/_segments' } ] }); /** * Perform a [indices.stats](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) * @param {String, String[], Boolean} params.groups - A comma-separated list of search groups for `search` index metric * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String} [params.level=indices] - Return stats aggregated at cluster, index or shard level * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.metric - Limit the information returned the specific metrics. */ api.indices.prototype.stats = ca({ params: { completionFields: { type: 'list', name: 'completion_fields' }, fielddataFields: { type: 'list', name: 'fielddata_fields' }, fields: { type: 'list' }, groups: { type: 'list' }, human: { type: 'boolean', 'default': false }, level: { type: 'enum', 'default': 'indices', options: [ 'cluster', 'indices', 'shards' ] }, types: { type: 'list' } }, urls: [ { fmt: '/<%=index%>/_stats/<%=metric%>', req: { index: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'query_cache', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_stats/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'query_cache', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/<%=index%>/_stats', req: { index: { type: 'list' } } }, { fmt: '/_stats' } ] }); /** * Perform a [indices.status](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-status.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {Anything} params.operationThreading - TODO: ? * @param {Boolean} params.recovery - Return information about shard recovery * @param {Boolean} params.snapshot - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.status = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, human: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' }, recovery: { type: 'boolean' }, snapshot: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_status', req: { index: { type: 'list' } } }, { fmt: '/_status' } ] }); /** * Perform a [indices.updateAliases](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Request timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master */ api.indices.prototype.updateAliases = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_aliases' }, needBody: true, method: 'POST' }); /** * Perform a [indices.upgrade](http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-upgrade.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.waitForCompletion - Specify whether the request should block until the all segments are upgraded (default: true) * @param {Boolean} params.onlyAncientSegments - If true, only ancient (an older Lucene major release) segments will be upgraded * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.upgrade = ca({ params: { allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, waitForCompletion: { type: 'boolean', name: 'wait_for_completion' }, onlyAncientSegments: { type: 'boolean', name: 'only_ancient_segments' } }, urls: [ { fmt: '/<%=index%>/_upgrade', req: { index: { type: 'list' } } }, { fmt: '/_upgrade' } ], method: 'POST' }); /** * Perform a [indices.validateQuery](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-validate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.explain - Return detailed information about the error * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Anything} params.operationThreading - TODO: ? * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.analyzer - The analyzer to use for the query string * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false) * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {Boolean} params.rewrite - Provide a more detailed explanation showing the actual Lucene query that will be executed. * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types */ api.indices.prototype.validateQuery = ca({ params: { explain: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, operationThreading: { name: 'operation_threading' }, q: { type: 'string' }, analyzer: { type: 'string' }, analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' }, rewrite: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_validate/query', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_validate/query', req: { index: { type: 'list' } } }, { fmt: '/_validate/query' } ], method: 'POST' }); /** * Perform a [info](http://www.elastic.co/guide/) request * * @param {Object} params - An object with parameters used to carry out this action */ api.info = ca({ url: { fmt: '/' } }); /** * Perform a [mget](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-multi-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.mget = ca({ params: { fields: { type: 'list' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mget', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mget', req: { index: { type: 'string' } } }, { fmt: '/_mget' } ], needBody: true, method: 'POST' }); /** * Perform a [mlt](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-more-like-this.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.boostTerms - The boost factor * @param {Number} params.maxDocFreq - The word occurrence frequency as count: words with higher occurrence in the corpus will be ignored * @param {Number} params.maxQueryTerms - The maximum query terms to be included in the generated query * @param {Number} params.maxWordLength - The minimum length of the word: longer words will be ignored * @param {Number} params.minDocFreq - The word occurrence frequency as count: words with lower occurrence in the corpus will be ignored * @param {Number} params.minTermFreq - The term frequency as percent: terms with lower occurence in the source document will be ignored * @param {Number} params.minWordLength - The minimum length of the word: shorter words will be ignored * @param {String, String[], Boolean} params.mltFields - Specific fields to perform the query against * @param {Number} params.percentTermsToMatch - How many terms have to match in order to consider the document a match (default: 0.3) * @param {String} params.routing - Specific routing value * @param {Number} params.searchFrom - The offset from which to return results * @param {String, String[], Boolean} params.searchIndices - A comma-separated list of indices to perform the query against (default: the index containing the document) * @param {String} params.searchScroll - A scroll search request definition * @param {Number} params.searchSize - The number of documents to return (default: 10) * @param {String} params.searchSource - A specific search request definition (instead of using the request body) * @param {String} params.searchType - Specific search type (eg. `dfs_then_fetch`, `count`, etc) * @param {String, String[], Boolean} params.searchTypes - A comma-separated list of types to perform the query against (default: the same type as the document) * @param {String, String[], Boolean} params.stopWords - A list of stop words to be ignored * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.mlt = ca({ params: { boostTerms: { type: 'number', name: 'boost_terms' }, maxDocFreq: { type: 'number', name: 'max_doc_freq' }, maxQueryTerms: { type: 'number', name: 'max_query_terms' }, maxWordLength: { type: 'number', name: 'max_word_length' }, minDocFreq: { type: 'number', name: 'min_doc_freq' }, minTermFreq: { type: 'number', name: 'min_term_freq' }, minWordLength: { type: 'number', name: 'min_word_length' }, mltFields: { type: 'list', name: 'mlt_fields' }, percentTermsToMatch: { type: 'number', name: 'percent_terms_to_match' }, routing: { type: 'string' }, searchFrom: { type: 'number', name: 'search_from' }, searchIndices: { type: 'list', name: 'search_indices' }, searchScroll: { type: 'string', name: 'search_scroll' }, searchSize: { type: 'number', name: 'search_size' }, searchSource: { type: 'string', name: 'search_source' }, searchType: { type: 'string', name: 'search_type' }, searchTypes: { type: 'list', name: 'search_types' }, stopWords: { type: 'list', name: 'stop_words' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_mlt', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [mpercolate](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The index of the document being count percolated to use as default * @param {String} params.type - The type of the document being percolated to use as default. */ api.mpercolate = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mpercolate', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mpercolate', req: { index: { type: 'string' } } }, { fmt: '/_mpercolate' } ], needBody: true, bulkBody: true, method: 'POST' }); /** * Perform a [msearch](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-multi-search.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.searchType - Search operation type * @param {String, String[], Boolean} params.index - A comma-separated list of index names to use as default * @param {String, String[], Boolean} params.type - A comma-separated list of document types to use as default */ api.msearch = ca({ params: { searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_msearch', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_msearch', req: { index: { type: 'list' } } }, { fmt: '/_msearch' } ], needBody: true, bulkBody: true, method: 'POST' }); /** * Perform a [mtermvectors](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-multi-termvectors.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.ids - A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.routing - Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.parent - Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} params.realtime - Specifies if requests are real-time as opposed to near-real-time (default: true). * @param {String} params.index - The index in which the document resides. * @param {String} params.type - The type of the document. * @param {String} params.id - The id of the document. */ api.mtermvectors = ca({ params: { ids: { type: 'list', required: false }, termStatistics: { type: 'boolean', 'default': false, required: false, name: 'term_statistics' }, fieldStatistics: { type: 'boolean', 'default': true, required: false, name: 'field_statistics' }, fields: { type: 'list', required: false }, offsets: { type: 'boolean', 'default': true, required: false }, positions: { type: 'boolean', 'default': true, required: false }, payloads: { type: 'boolean', 'default': true, required: false }, preference: { type: 'string', required: false }, routing: { type: 'string', required: false }, parent: { type: 'string', required: false }, realtime: { type: 'boolean', required: false } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mtermvectors', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mtermvectors', req: { index: { type: 'string' } } }, { fmt: '/_mtermvectors' } ], method: 'POST' }); api.nodes = namespace(); /** * Perform a [nodes.hotThreads](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-nodes-hot-threads.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.interval - The interval for the second sampling of threads * @param {Number} params.snapshots - Number of samples of thread stacktrace (default: 10) * @param {Number} params.threads - Specify the number of threads to provide information for (default: 3) * @param {Boolean} params.ignoreIdleThreads - Don't show threads that are in known-idle places, such as waiting on a socket select or pulling from an empty task queue (default: true) * @param {String} params.type - The type to sample (default: cpu) * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.nodes.prototype.hotThreads = ca({ params: { interval: { type: 'time' }, snapshots: { type: 'number' }, threads: { type: 'number' }, ignoreIdleThreads: { type: 'boolean', name: 'ignore_idle_threads' }, type: { type: 'enum', options: [ 'cpu', 'wait', 'block' ] } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/hotthreads', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/hotthreads' } ] }); /** * Perform a [nodes.info](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-nodes-info.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes * @param {String, String[], Boolean} params.metric - A comma-separated list of metrics you wish returned. Leave empty to return all. */ api.nodes.prototype.info = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/<%=metric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ 'settings', 'os', 'process', 'jvm', 'thread_pool', 'network', 'transport', 'http', 'plugins' ] } } }, { fmt: '/_nodes/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/<%=metric%>', req: { metric: { type: 'list', options: [ 'settings', 'os', 'process', 'jvm', 'thread_pool', 'network', 'transport', 'http', 'plugins' ] } } }, { fmt: '/_nodes' } ] }); /** * Perform a [nodes.shutdown](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-nodes-shutdown.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.delay - Set the delay for the operation (default: 1s) * @param {Boolean} params.exit - Exit the JVM as well (default: true) * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to perform the operation on; use `_local` to perform the operation on the node you're connected to, leave empty to perform the operation on all nodes */ api.nodes.prototype.shutdown = ca({ params: { delay: { type: 'time' }, exit: { type: 'boolean' } }, urls: [ { fmt: '/_cluster/nodes/<%=nodeId%>/_shutdown', req: { nodeId: { type: 'list' } } }, { fmt: '/_shutdown' } ], method: 'POST' }); /** * Perform a [nodes.stats](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/cluster-nodes-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) * @param {Boolean} params.groups - A comma-separated list of search groups for `search` index metric * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String} [params.level=node] - Return indices stats aggregated at node, index or shard level * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics * @param {String, String[], Boolean} params.indexMetric - Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.nodes.prototype.stats = ca({ params: { completionFields: { type: 'list', name: 'completion_fields' }, fielddataFields: { type: 'list', name: 'fielddata_fields' }, fields: { type: 'list' }, groups: { type: 'boolean' }, human: { type: 'boolean', 'default': false }, level: { type: 'enum', 'default': 'node', options: [ 'node', 'indices', 'shards' ] }, types: { type: 'list' } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] }, indexMetric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'query_cache', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] } } }, { fmt: '/_nodes/stats/<%=metric%>/<%=indexMetric%>', req: { metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] }, indexMetric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'query_cache', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_nodes/<%=nodeId%>/stats', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/stats/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] } } }, { fmt: '/_nodes/stats' } ] }); /** * Perform a [percolate](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.percolateFormat - Return an array of matching query IDs instead of objects * @param {String} params.percolateIndex - The index to percolate the document into. Defaults to index. * @param {String} params.percolateType - The type to percolate document into. Defaults to type. * @param {String} params.percolateRouting - The routing value to use when percolating the existing document. * @param {String} params.percolatePreference - Which shard to prefer when executing the percolate request. * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.index - The index of the document being percolated. * @param {String} params.type - The type of the document being percolated. * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster. */ api.percolate = ca({ params: { routing: { type: 'list' }, preference: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, percolateFormat: { type: 'enum', options: [ 'ids' ], name: 'percolate_format' }, percolateIndex: { type: 'string', name: 'percolate_index' }, percolateType: { type: 'string', name: 'percolate_type' }, percolateRouting: { type: 'string', name: 'percolate_routing' }, percolatePreference: { type: 'string', name: 'percolate_preference' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>/_percolate', req: { index: { type: 'string' }, type: { type: 'string' } } } ], method: 'POST' }); /** * Perform a [ping](http://www.elastic.co/guide/) request * * @param {Object} params - An object with parameters used to carry out this action */ api.ping = ca({ url: { fmt: '/' }, requestTimeout: 3000, method: 'HEAD' }); /** * Perform a [putScript](http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} [params.opType=index] - Explicit operation type * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.putScript = ca({ params: { opType: { type: 'enum', 'default': 'index', options: [ 'index', 'create' ], name: 'op_type' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [putTemplate](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} [params.opType=index] - Explicit operation type * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Template ID */ api.putTemplate = ca({ params: { opType: { type: 'enum', 'default': 'index', options: [ 'index', 'create' ], name: 'op_type' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [scroll](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-request-scroll.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.scrollId - The scroll ID */ api.scroll = ca({ params: { scroll: { type: 'duration' }, scrollId: { type: 'string', name: 'scroll_id' } }, urls: [ { fmt: '/_search/scroll/<%=scrollId%>', req: { scrollId: { type: 'string' } } }, { fmt: '/_search/scroll' } ], paramAsBody: 'scrollId', method: 'POST' }); /** * Perform a [search](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-search.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.analyzer - The analyzer to use for the query string * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false) * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.explain - Specify whether to return detailed information about score computation as part of a hit * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return as part of a hit * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields to return as the field data representation of a field for each hit * @param {Number} params.from - Starting offset (default: 0) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.q - Query in the Lucene query string syntax * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.searchType - Search operation type * @param {Number} params.size - Number of hits to return (default: 10) * @param {String, String[], Boolean} params.sort - A comma-separated list of <field>:<direction> pairs * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String, String[], Boolean} params.stats - Specific 'tag' of the request for logging and statistical purposes * @param {String} params.suggestField - Specify which field to use for suggestions * @param {String} [params.suggestMode=missing] - Specify suggest mode * @param {Number} params.suggestSize - How many suggestions to return in response * @param {Text} params.suggestText - The source text for which the suggestions should be returned * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Boolean} params.trackScores - Whether to calculate and return scores even if they are not used for sorting * @param {Boolean} params.version - Specify whether to return document version as part of a hit * @param {Boolean} params.queryCache - Specify if query cache should be used for this request or not, defaults to index level setting * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types */ api.search = ca({ params: { analyzer: { type: 'string' }, analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, explain: { type: 'boolean' }, fields: { type: 'list' }, fielddataFields: { type: 'list', name: 'fielddata_fields' }, from: { type: 'number' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' }, preference: { type: 'string' }, q: { type: 'string' }, routing: { type: 'list' }, scroll: { type: 'duration' }, searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' }, size: { type: 'number' }, sort: { type: 'list' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, stats: { type: 'list' }, suggestField: { type: 'string', name: 'suggest_field' }, suggestMode: { type: 'enum', 'default': 'missing', options: [ 'missing', 'popular', 'always' ], name: 'suggest_mode' }, suggestSize: { type: 'number', name: 'suggest_size' }, suggestText: { type: 'text', name: 'suggest_text' }, timeout: { type: 'time' }, trackScores: { type: 'boolean', name: 'track_scores' }, version: { type: 'boolean' }, queryCache: { type: 'boolean', name: 'query_cache' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_search', req: { index: { type: 'list' } } }, { fmt: '/_search' } ], method: 'POST' }); /** * Perform a [searchExists](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-exists.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Number} params.minScore - Include only documents with a specific `_score` value in the result * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.analyzer - The analyzer to use for the query string * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false) * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the results * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the results */ api.searchExists = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, minScore: { type: 'number', name: 'min_score' }, preference: { type: 'string' }, routing: { type: 'string' }, q: { type: 'string' }, analyzer: { type: 'string' }, analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search/exists', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_search/exists', req: { index: { type: 'list' } } }, { fmt: '/_search/exists' } ], method: 'POST' }); /** * Perform a [searchShards](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-shards.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.searchShards = ca({ params: { preference: { type: 'string' }, routing: { type: 'string' }, local: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search_shards', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_search_shards', req: { index: { type: 'string' } } }, { fmt: '/_search_shards' } ], method: 'POST' }); /** * Perform a [searchTemplate](http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.searchType - Search operation type * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types */ api.searchTemplate = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, preference: { type: 'string' }, routing: { type: 'list' }, scroll: { type: 'duration' }, searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search/template', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_search/template', req: { index: { type: 'list' } } }, { fmt: '/_search/template' } ], method: 'POST' }); api.snapshot = namespace(); /** * Perform a [snapshot.create](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype.create = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, waitForCompletion: { type: 'boolean', 'default': false, name: 'wait_for_completion' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'POST' }); /** * Perform a [snapshot.createRepository](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Boolean} params.verify - Whether to verify the repository after creation * @param {String} params.repository - A repository name */ api.snapshot.prototype.createRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' }, verify: { type: 'boolean' } }, url: { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'string' } } }, needBody: true, method: 'POST' }); /** * Perform a [snapshot.delete](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype['delete'] = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [snapshot.deleteRepository](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names */ api.snapshot.prototype.deleteRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [snapshot.get](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names */ api.snapshot.prototype.get = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>', req: { repository: { type: 'string' }, snapshot: { type: 'list' } } } }); /** * Perform a [snapshot.getRepository](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names */ api.snapshot.prototype.getRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, local: { type: 'boolean' } }, urls: [ { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'list' } } }, { fmt: '/_snapshot' } ] }); /** * Perform a [snapshot.restore](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype.restore = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, waitForCompletion: { type: 'boolean', 'default': false, name: 'wait_for_completion' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_restore', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'POST' }); /** * Perform a [snapshot.status](http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names */ api.snapshot.prototype.status = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, urls: [ { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_status', req: { repository: { type: 'string' }, snapshot: { type: 'list' } } }, { fmt: '/_snapshot/<%=repository%>/_status', req: { repository: { type: 'string' } } }, { fmt: '/_snapshot/_status' } ] }); /** * Perform a [snapshot.verifyRepository](http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String} params.repository - A repository name */ api.snapshot.prototype.verifyRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_snapshot/<%=repository%>/_verify', req: { repository: { type: 'string' } } }, method: 'POST' }); /** * Perform a [suggest](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-suggesters.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices */ api.suggest = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed', 'none', 'all' ], name: 'expand_wildcards' }, preference: { type: 'string' }, routing: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/_suggest', req: { index: { type: 'list' } } }, { fmt: '/_suggest' } ], needBody: true, method: 'POST' }); /** * Perform a [termvector](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-termvectors.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned. * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return. * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned. * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned. * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random). * @param {String} params.routing - Specific routing value. * @param {String} params.parent - Parent id of documents. * @param {Boolean} params.realtime - Specifies if request is real-time as opposed to near-real-time (default: true). * @param {String} params.index - The index in which the document resides. * @param {String} params.type - The type of the document. * @param {String} params.id - The id of the document. */ api.termvector = ca({ params: { termStatistics: { type: 'boolean', 'default': false, required: false, name: 'term_statistics' }, fieldStatistics: { type: 'boolean', 'default': true, required: false, name: 'field_statistics' }, fields: { type: 'list', required: false }, offsets: { type: 'boolean', 'default': true, required: false }, positions: { type: 'boolean', 'default': true, required: false }, payloads: { type: 'boolean', 'default': true, required: false }, preference: { type: 'string', required: false }, routing: { type: 'string', required: false }, parent: { type: 'string', required: false }, realtime: { type: 'boolean', required: false } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/_termvector', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>/_termvector', req: { index: { type: 'string' }, type: { type: 'string' } } } ], method: 'POST' }); /** * Perform a [update](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-update.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.lang - The script language (default: groovy) * @param {String} params.parent - ID of the parent document. Is is only used for routing and when for the upsert request * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {Number} params.retryOnConflict - Specify how many times should the operation be retried when a conflict occurs (default: 0) * @param {String} params.routing - Specific routing value * @param {Anything} params.script - The URL-encoded script definition (instead of using request body) * @param {Anything} params.scriptId - The id of a stored script * @param {Boolean} params.scriptedUpsert - True if the script referenced in script or script_id should be called to perform inserts - defaults to false * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.update = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, fields: { type: 'list' }, lang: { type: 'string' }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, retryOnConflict: { type: 'number', name: 'retry_on_conflict' }, routing: { type: 'string' }, script: {}, scriptId: { name: 'script_id' }, scriptedUpsert: { type: 'boolean', name: 'scripted_upsert' }, timeout: { type: 'time' }, timestamp: { type: 'time' }, ttl: { type: 'duration' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_update', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [create](http://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-index_.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String} params.parent - ID of the parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.create = ca.proxy(api.index, { transform: function (params) { params.op_type = 'create'; } }); },{"../client_action":22,"../utils":42}],19:[function(require,module,exports){ module.exports=require(18) },{"../client_action":22,"../utils":42}],20:[function(require,module,exports){ module.exports = { '1.7': require('./1_7'), '1.6': require('./1_6'), '1.5': require('./1_5') }; },{"./1_5":17,"./1_6":18,"./1_7":19}],21:[function(require,module,exports){ /** * A client that makes requests to Elasticsearch via a {{#crossLink "Transport"}}Transport{{/crossLink}} * * Initializing a client might look something like: * * ``` * var client = new es.Client({ * hosts: [ * 'es1.net:9200', * { * host: 'es2.net', * port: 9200 * } * ], * sniffOnStart: true, * log: { * type: 'file', * level: 'warning' * } * }); * ``` * * @class Client * @constructor */ module.exports = Client; var Transport = require('./transport'); var clientAction = require('./client_action'); var _ = require('./utils'); function Client(config) { config = config || {}; if (config.__reused) { throw new Error('Do not reuse objects to configure the elasticsearch Client class: ' + 'https://github.com/elasticsearch/elasticsearch-js/issues/33'); } else { config.__reused = true; } function EsApiClient() { // our client will log minimally by default if (!config.hasOwnProperty('log')) { config.log = 'warning'; } if (!config.hosts && !config.host) { config.host = 'http://localhost:9200'; } this.close = function () { this.transport.close(); }; this.transport = new Transport(config); _.each(EsApiClient.prototype, function (Fn, prop) { if (Fn.prototype instanceof clientAction.ApiNamespace) { this[prop] = new Fn(this.transport); } }, this); delete this._namespaces; } EsApiClient.prototype = _.funcEnum(config, 'apiVersion', Client.apis, '1.7'); if (!config.sniffEndpoint && EsApiClient.prototype === Client.apis['0.90']) { config.sniffEndpoint = '/_cluster/nodes'; } var Constructor = EsApiClient; if (config.plugins) { Constructor.prototype = _.cloneDeep(Constructor.prototype); _.each(config.plugins, function (setup) { Constructor = setup(Constructor, config, { apis: require('./apis'), connectors: require('./connectors'), loggers: require('./loggers'), selectors: require('./selectors'), serializers: require('./serializers'), Client: require('./client'), clientAction: clientAction, Connection: require('./connection'), ConnectionPool: require('./connection_pool'), Errors: require('./errors'), Host: require('./host'), Log: require('./log'), Logger: require('./logger'), NodesToHost: require('./nodes_to_host'), Transport: require('./transport'), utils: require('./utils') }) || Constructor; }); } return new Constructor(); } Client.apis = require('./apis'); },{"./apis":20,"./client":21,"./client_action":22,"./connection":23,"./connection_pool":24,"./connectors":25,"./errors":27,"./host":28,"./log":29,"./logger":30,"./loggers":31,"./nodes_to_host":33,"./selectors":34,"./serializers":38,"./transport":40,"./utils":42}],22:[function(require,module,exports){ var _ = require('./utils'); /** * Constructs a client action factory that uses specific defaults * @type {Function} */ exports.makeFactoryWithModifier = makeFactoryWithModifier; /** * Constructs a function that can be called to make a request to ES * @type {Function} */ exports.factory = makeFactoryWithModifier(); /** * Constructs a proxy to another api method * @type {Function} */ exports.proxyFactory = exports.factory.proxy; // export so that we can test this exports._resolveUrl = resolveUrl; exports.ApiNamespace = function() {}; exports.namespaceFactory = function () { function ClientNamespace(transport) { this.transport = transport; } ClientNamespace.prototype = new exports.ApiNamespace(); return ClientNamespace; }; function makeFactoryWithModifier(modifier) { modifier = modifier || _.identity; var factory = function (spec) { spec = modifier(spec); if (!_.isPlainObject(spec.params)) { spec.params = {}; } if (!spec.method) { spec.method = 'GET'; } function action(params, cb) { if (typeof params === 'function') { cb = params; params = {}; } else { params = params || {}; cb = typeof cb === 'function' ? cb : null; } try { return exec(this.transport, spec, _.clone(params), cb); } catch (e) { if (typeof cb === 'function') { _.nextTick(cb, e); } else { var def = this.transport.defer(); def.reject(e); return def.promise; } } } action.spec = spec; return action; }; factory.proxy = function (fn, spec) { return function (params, cb) { if (typeof params === 'function') { cb = params; params = {}; } else { params = params || {}; cb = typeof cb === 'function' ? cb : null; } if (spec.transform) { spec.transform(params); } return fn.call(this, params, cb); }; }; return factory; } var castType = { 'enum': function validSelection(param, val, name) { if (_.isString(val) && val.indexOf(',') > -1) { val = commaSepList(val); } if (_.isArray(val)) { return val.map(function (v) { return validSelection(param, v, name); }).join(','); } /* jshint eqeqeq: false */ for (var i = 0; i < param.options.length; i++) { if (param.options[i] == val) { return param.options[i]; } } throw new TypeError('Invalid ' + name + ': expected ' + ( param.options.length > 1 ? 'one of ' + param.options.join(',') : param.options[0] )); }, duration: function (param, val, name) { if (_.isNumeric(val) || _.isInterval(val)) { return val; } else { throw new TypeError( 'Invalid ' + name + ': expected a number or interval ' + '(an integer followed by one of M, w, d, h, m, s, y or ms).' ); } }, list: function (param, val, name) { switch (typeof val) { case 'number': case 'boolean': return '' + val; case 'string': val = commaSepList(val); /* falls through */ case 'object': if (_.isArray(val)) { return val.join(','); } /* falls through */ default: throw new TypeError('Invalid ' + name + ': expected be a comma seperated list, array, number or string.'); } }, 'boolean': function (param, val) { val = _.isString(val) ? val.toLowerCase() : val; return (val === 'no' || val === 'off') ? false : !!val; }, number: function (param, val, name) { if (_.isNumeric(val)) { return val * 1; } else { throw new TypeError('Invalid ' + name + ': expected a number.'); } }, string: function (param, val, name) { switch (typeof val) { case 'number': case 'string': return '' + val; default: throw new TypeError('Invalid ' + name + ': expected a string.'); } }, time: function (param, val, name) { if (typeof val === 'string') { return val; } else if (_.isNumeric(val)) { return '' + val; } else if (val instanceof Date) { return '' + val.getTime(); } else { throw new TypeError('Invalid ' + name + ': expected some sort of time.'); } } }; function resolveUrl(url, params) { var vars = {}, i, key; if (url.req) { // url has required params if (!url.reqParamKeys) { // create cached key list on demand url.reqParamKeys = _.keys(url.req); } for (i = 0; i < url.reqParamKeys.length; i ++) { key = url.reqParamKeys[i]; if (!params.hasOwnProperty(key) || params[key] == null) { // missing a required param return false; } else { // cast of copy required param if (castType[url.req[key].type]) { vars[key] = castType[url.req[key].type](url.req[key], params[key], key); } else { vars[key] = params[key]; } } } } if (url.opt) { // url has optional params if (!url.optParamKeys) { url.optParamKeys = _.keys(url.opt); } for (i = 0; i < url.optParamKeys.length; i ++) { key = url.optParamKeys[i]; if (params[key]) { if (castType[url.opt[key].type] || params[key] == null) { vars[key] = castType[url.opt[key].type](url.opt[key], params[key], key); } else { vars[key] = params[key]; } } else { vars[key] = url.opt[key]['default']; } } } if (!url.template) { // compile the template on demand url.template = _.template(url.fmt); } return url.template(_.transform(vars, function (note, val, name) { // encode each value note[name] = encodeURIComponent(val); // remove it from the params so that it isn't sent to the final request delete params[name]; }, {})); } function exec(transport, spec, params, cb) { var request = { method: spec.method }; var query = {}; var i; // pass the timeout from the spec if (spec.requestTimeout) { request.requestTimeout = spec.requestTimeout; } if (!params.body && spec.paramAsBody) { params.body = params[spec.paramAsBody]; delete params[spec.paramAsBody]; } // verify that we have the body if needed if (spec.needsBody && !params.body) { throw new TypeError('A request body is required.'); } // control params if (spec.bulkBody) { request.bulkBody = true; } if (spec.method === 'HEAD') { request.castExists = true; } // pick the url if (spec.url) { // only one url option request.path = resolveUrl(spec.url, params); } else { for (i = 0; i < spec.urls.length; i++) { if (request.path = resolveUrl(spec.urls[i], params)) { break; } } } if (!request.path) { // there must have been some mimimun requirements that were not met var minUrl = spec.url || spec.urls[spec.urls.length - 1]; throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', ')); } // build the query string if (!spec.paramKeys) { // build a key list on demand spec.paramKeys = _.keys(spec.params); spec.requireParamKeys = _.transform(spec.params, function (req, param, key) { if (param.required) { req.push(key); } }, []); } for (var key in params) { if (params.hasOwnProperty(key) && params[key] != null) { switch (key) { case 'body': case 'headers': case 'requestTimeout': case 'maxRetries': request[key] = params[key]; break; case 'ignore': request.ignore = _.isArray(params[key]) ? params[key] : [params[key]]; break; case 'method': request.method = _.toUpperString(params[key]); break; default: var paramSpec = spec.params[key]; if (paramSpec) { // param keys don't always match the param name, in those cases it's stored in the param def as "name" paramSpec.name = paramSpec.name || key; if (params[key] != null) { if (castType[paramSpec.type]) { query[paramSpec.name] = castType[paramSpec.type](paramSpec, params[key], key); } else { query[paramSpec.name] = params[key]; } if (paramSpec['default'] && query[paramSpec.name] === paramSpec['default']) { delete query[paramSpec.name]; } } } else { query[key] = params[key]; } } } } for (i = 0; i < spec.requireParamKeys.length; i ++) { if (!query.hasOwnProperty(spec.requireParamKeys[i])) { throw new TypeError('Missing required parameter ' + spec.requireParamKeys[i]); } } request.query = query; return transport.request(request, cb); } function commaSepList(str) { return str.split(',').map(function (i) { return i.trim(); }); } },{"./utils":42}],23:[function(require,module,exports){ module.exports = ConnectionAbstract; var _ = require('./utils'); var EventEmitter = require('events').EventEmitter; var Log = require('./log'); var Host = require('./host'); var errors = require('./errors'); /** * Abstract class used for Connection classes * @class ConnectionAbstract * @constructor */ function ConnectionAbstract(host, config) { config = config || {}; EventEmitter.call(this); this.log = config.log || new Log(); this.pingTimeout = config.pingTimeout || 3000; if (!host) { throw new TypeError('Missing host'); } else if (host instanceof Host) { this.host = host; } else { throw new TypeError('Invalid host'); } _.makeBoundMethods(this); } _.inherits(ConnectionAbstract, EventEmitter); /** * Make a request using this connection. Must be overridden by Connection classes, which can add whatever keys to * params that they like. These are just the basics. * * @param [params] {Object} - The parameters for the request * @param params.path {String} - The path for which you are requesting * @param params.method {String} - The HTTP method for the request (GET, HEAD, etc.) * @param params.requestTimeout {Integer} - The amount of time in milliseconds that this request should be allowed to run for. * @param cb {Function} - A callback to be called once with `cb(err, responseBody, responseStatus)` */ ConnectionAbstract.prototype.request = function () { throw new Error('Connection#request must be overwritten by the Connector'); }; ConnectionAbstract.prototype.ping = function (params, cb) { if (typeof params === 'function') { cb = params; params = null; } else { cb = typeof cb === 'function' ? cb : null; } var requestTimeout = this.pingTimeout; var requestTimeoutId; var aborted; var abort; if (params && params.hasOwnProperty('requestTimeout')) { requestTimeout = params.requestTimeout; } abort = this.request(_.defaults(params || {}, { path: '/', method: 'HEAD' }), function (err) { if (aborted) { return; } clearTimeout(requestTimeoutId); if (cb) { cb(err); } }); if (requestTimeout) { requestTimeoutId = setTimeout(function () { if (abort) { abort(); } aborted = true; if (cb) { cb(new errors.RequestTimeout('Ping Timeout after ' + requestTimeout + 'ms')); } }, requestTimeout); } }; ConnectionAbstract.prototype.setStatus = function (status) { var origStatus = this.status; this.status = status; this.emit('status set', status, origStatus, this); if (status === 'closed') { this.removeAllListeners(); } }; },{"./errors":27,"./host":28,"./log":29,"./utils":42,"events":4}],24:[function(require,module,exports){ var process=require("__browserify_process");/** * Manager of connections to a node(s), capable of ensuring that connections are clear and living * before providing them to the application * * @class ConnectionPool * @constructor * @param {Object} config - The config object passed to the transport. */ module.exports = ConnectionPool; var _ = require('./utils'); var Log = require('./log'); function ConnectionPool(config) { config = config || {}; _.makeBoundMethods(this); if (!config.log) { this.log = new Log(); config.log = this.log; } else { this.log = config.log; } // we will need this when we create connections down the road this._config = config; // get the selector config var this.selector = _.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector); // get the connection class this.Connection = _.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses, ConnectionPool.defaultConnectionClass); // time that connections will wait before being revived this.deadTimeout = config.hasOwnProperty('deadTimeout') ? config.deadTimeout : 60000; this.maxDeadTimeout = config.hasOwnProperty('maxDeadTimeout') ? config.maxDeadTimeout : 18e5; this.calcDeadTimeout = _.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential'); // a map of connections to their "id" property, used when sniffing this.index = {}; this._conns = { alive: [], dead: [] }; // information about timeouts for dead connections this._timeouts = []; } // selector options ConnectionPool.selectors = require('./selectors'); ConnectionPool.defaultSelector = 'roundRobin'; // get the connection options ConnectionPool.connectionClasses = require('./connectors'); ConnectionPool.defaultConnectionClass = ConnectionPool.connectionClasses._default; delete ConnectionPool.connectionClasses._default; // the function that calculates timeouts based on attempts ConnectionPool.calcDeadTimeoutOptions = { flat: function (attempt, baseTimeout) { return baseTimeout; }, exponential: function (attempt, baseTimeout) { return Math.min(baseTimeout * 2 * Math.pow(2, (attempt * 0.5 - 1)), this.maxDeadTimeout); } }; /** * Selects a connection from the list using the this.selector * Features: * - detects if the selector is async or not * - sync selectors should still return asynchronously * - catches errors in sync selectors * - automatically selects the first dead connection when there no living connections * * @param {Function} cb [description] * @return {[type]} [description] */ ConnectionPool.prototype.select = function (cb) { if (this._conns.alive.length) { if (this.selector.length > 1) { this.selector(this._conns.alive, cb); } else { try { _.nextTick(cb, void 0, this.selector(this._conns.alive)); } catch (e) { cb(e); } } } else if (this._timeouts.length) { this._selectDeadConnection(cb); } else { _.nextTick(cb, void 0); } }; /** * Handler for the "set status" event emitted but the connections. It will move * the connection to it's proper connection list (unless it was closed). * * @param {String} status - the connection's new status * @param {String} oldStatus - the connection's old status * @param {ConnectionAbstract} connection - the connection object itself */ ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, connection) { var index; var died = (status === 'dead'); var wasAlreadyDead = (died && oldStatus === 'dead'); var revived = (!died && oldStatus === 'dead'); var noChange = (oldStatus === status); var from = this._conns[oldStatus]; var to = this._conns[status]; if (noChange && !died) { return true; } if (from !== to) { if (_.isArray(from)) { index = from.indexOf(connection); if (index !== -1) { from.splice(index, 1); } } if (_.isArray(to)) { index = to.indexOf(connection); if (index === -1) { to.push(connection); } } } if (died) { this._onConnectionDied(connection, wasAlreadyDead); } if (revived) { this._onConnectionRevived(connection); } }); /** * Handler used to clear the times created when a connection dies * @param {ConnectionAbstract} connection */ ConnectionPool.prototype._onConnectionRevived = function (connection) { var timeout; for (var i = 0; i < this._timeouts.length; i++) { if (this._timeouts[i].conn === connection) { timeout = this._timeouts[i]; if (timeout.id) { clearTimeout(timeout.id); } this._timeouts.splice(i, 1); break; } } }; /** * Handler used to update or create a timeout for the connection which has died * @param {ConnectionAbstract} connection * @param {Boolean} alreadyWasDead - If the connection was preivously dead this must be set to true */ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDead) { var timeout; if (alreadyWasDead) { for (var i = 0; i < this._timeouts.length; i++) { if (this._timeouts[i].conn === connection) { timeout = this._timeouts[i]; break; } } } else { timeout = { conn: connection, attempt: 0, revive: function (cb) { timeout.attempt++; connection.ping(function (err) { connection.setStatus(err ? 'dead' : 'alive'); if (cb && typeof cb === 'function') { cb(err); } }); } }; this._timeouts.push(timeout); } if (timeout.id) { clearTimeout(timeout.id); } var ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout); timeout.id = setTimeout(timeout.revive, ms); timeout.runAt = _.now() + ms; }; ConnectionPool.prototype._selectDeadConnection = function (cb) { var orderedTimeouts = _.sortBy(this._timeouts, 'runAt'); var log = this.log; process.nextTick(function next() { var timeout = orderedTimeouts.shift(); if (!timeout) { cb(void 0); return; } if (!timeout.conn) { next(); return; } if (timeout.conn.status === 'dead') { timeout.revive(function (err) { if (err) { log.warning('Unable to revive connection: ' + timeout.conn.id); process.nextTick(next); } else { cb(void 0, timeout.conn); } }); } else { cb(void 0, timeout.conn); } }); }; /** * Returns a random list of nodes from the living connections up to the limit. * If there are no living connections it will fall back to the dead connections. * If there are no dead connections it will return nothing. * * This is used for testing (when we just want the one existing node) * and sniffing, where using the selector to get all of the living connections * is not reasonable. * * @param {string} [status] - optional status of the connection to fetch * @param {Number} [limit] - optional limit on the number of connections to return */ ConnectionPool.prototype.getConnections = function (status, limit) { var list; if (status) { list = this._conns[status]; } else { list = this._conns[this._conns.alive.length ? 'alive' : 'dead']; } if (limit == null) { return list.slice(0); } else { return _.shuffle(list).slice(0, limit); } }; /** * Add a single connection to the pool and change it's status to "alive". * The connection should inherit from ConnectionAbstract * * @param {ConnectionAbstract} connection - The connection to add */ ConnectionPool.prototype.addConnection = function (connection) { if (!connection.id) { connection.id = connection.host.toString(); } if (!this.index[connection.id]) { this.log.info('Adding connection to', connection.id); this.index[connection.id] = connection; connection.on('status set', this.bound.onStatusSet); connection.setStatus('alive'); } }; /** * Remove a connection from the pool, and set it's status to "closed". * * @param {ConnectionAbstract} connection - The connection to remove/close */ ConnectionPool.prototype.removeConnection = function (connection) { if (!connection.id) { connection.id = connection.host.toString(); } if (this.index[connection.id]) { delete this.index[connection.id]; connection.setStatus('closed'); connection.removeListener('status set', this.bound.onStatusSet); } }; /** * Override the internal node list. All connections that are not in the new host * list are closed and removed. Non-unique hosts are ignored. * * @param {Host[]} hosts - An array of Host instances. */ ConnectionPool.prototype.setHosts = function (hosts) { var connection; var i; var id; var host; var toRemove = _.clone(this.index); for (i = 0; i < hosts.length; i++) { host = hosts[i]; id = host.toString(); if (this.index[id]) { delete toRemove[id]; } else { connection = new this.Connection(host, this._config); connection.id = id; this.addConnection(connection); } } var removeIds = _.keys(toRemove); for (i = 0; i < removeIds.length; i++) { this.removeConnection(this.index[removeIds[i]]); } }; /** * Close the conncetion pool, as well as all of it's connections */ ConnectionPool.prototype.close = function () { this.setHosts([]); }; ConnectionPool.prototype.empty = ConnectionPool.prototype.close; },{"./connectors":25,"./log":29,"./selectors":34,"./utils":42,"__browserify_process":13}],25:[function(require,module,exports){ var opts = { xhr: require('./xhr'), jquery: require('./jquery'), angular: require('./angular') }; var _ = require('../utils'); // remove modules that have been ignored by browserify _.each(opts, function (conn, name) { if (typeof conn !== 'function') { delete opts[name]; } }); // custom _default specification if (opts.xhr) { opts._default = 'xhr'; } else if (opts.angular) { opts._default = 'angular'; } else { opts._default = 'jquery'; } module.exports = opts; },{"../utils":42,"./angular":1,"./jquery":26,"./xhr":1}],26:[function(require,module,exports){ /* jshint browser: true, jquery: true */ /** * Simple connection class for using the XHR object in browsers * * @class {XhrConnection} */ module.exports = JqueryConnector; var _ = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; function JqueryConnector(host, config) { ConnectionAbstract.call(this, host, config); } _.inherits(JqueryConnector, ConnectionAbstract); JqueryConnector.prototype.request = function (params, cb) { var ajax = { url: this.host.makeUrl(params), data: params.body, type: params.method, dataType: 'text', headers: this.host.getHeaders(params.headers), done: cb }; var jqXHR = jQuery.ajax(ajax) .done(function (data, textStatus, jqXHR) { cb(null, data, jqXHR.statusCode(), { 'content-type': jqXHR.getResponseHeader('content-type') }); }) .fail(function (jqXHR, textStatus, err) { cb(new ConnectionFault(err && err.message)); }); return function () { jqXHR.abort(); }; }; },{"../connection":23,"../errors":27,"../utils":42}],27:[function(require,module,exports){ var _ = require('./utils'); var errors = module.exports; var canCapture = (typeof Error.captureStackTrace === 'function'); var canStack = !!(new Error()).stack; function ErrorAbstract(msg, constructor, metadata) { this.message = msg; Error.call(this, this.message); if (canCapture) { Error.captureStackTrace(this, constructor); } else if (canStack) { this.stack = (new Error()).stack; } else { this.stack = ''; } if (metadata) { _.assign(this, metadata); this.toString = function () { return msg + ' :: ' + JSON.stringify(metadata); }; this.toJSON = function () { return _.assign({ msg: msg }, metadata); }; } } errors._Abstract = ErrorAbstract; _.inherits(ErrorAbstract, Error); /** * Connection Error * @param {String} [msg] - An error message that will probably end up in a log. */ errors.ConnectionFault = function ConnectionFault(msg) { ErrorAbstract.call(this, msg || 'Connection Failure', errors.ConnectionFault); }; _.inherits(errors.ConnectionFault, ErrorAbstract); /** * No Living Connections * @param {String} [msg] - An error message that will probably end up in a log. */ errors.NoConnections = function NoConnections(msg) { ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections); }; _.inherits(errors.NoConnections, ErrorAbstract); /** * Generic Error * @param {String} [msg] - An error message that will probably end up in a log. */ errors.Generic = function Generic(msg, metadata) { ErrorAbstract.call(this, msg || 'Generic Error', errors.Generic, metadata); }; _.inherits(errors.Generic, ErrorAbstract); /** * Request Timeout Error * @param {String} [msg] - An error message that will probably end up in a log. */ errors.RequestTimeout = function RequestTimeout(msg) { ErrorAbstract.call(this, msg || 'Request Timeout', errors.RequestTimeout); }; _.inherits(errors.RequestTimeout, ErrorAbstract); /** * Request Body could not be parsed * @param {String} [msg] - An error message that will probably end up in a log. */ errors.Serialization = function Serialization(msg) { ErrorAbstract.call(this, msg || 'Unable to parse/serialize body', errors.Serialization); }; _.inherits(errors.Serialization, ErrorAbstract); /** * Thrown when a browser compatability issue is detected (cough, IE, cough) */ errors.RequestTypeError = function RequestTypeError(feature) { ErrorAbstract.call(this, 'Cross-domain AJAX requests ' + feature + ' are not supported', errors.RequestTypeError); }; _.inherits(errors.RequestTypeError, ErrorAbstract); var statusCodes = { 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 308: 'Permanent Redirect', 400: 'Bad Request', 401: 'Authentication Exception', 402: 'Payment Required', 403: 'Authorization Exception', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request URIToo Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 418: 'Im ATeapot', 421: 'Too Many Connections From This IP', 426: 'Upgrade Required', 429: 'Too Many Requests', 450: 'Blocked By Windows Parental Controls', 494: 'Request Header Too Large', 497: 'HTTPTo HTTPS', 499: 'Client Closed Request', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTPVersion Not Supported', 506: 'Variant Also Negotiates', 510: 'Not Extended' }; _.each(statusCodes, function (name, status) { var className = _.studlyCase(name); function StatusCodeError(msg, metadata) { this.status = status; var esErrObject = null; if (_.isPlainObject(msg)) { esErrObject = msg; msg = null; } if (!esErrObject) { // errors from es now come in two forms, an error string < 2.0 and // an object >= 2.0 // TODO: remove after dropping support for < 2.0 ErrorAbstract.call(this, msg || name, StatusCodeError); return this; } msg = [].concat(esErrObject.root_cause || []).reduce(function (memo, cause) { if (memo) memo += ' (and) '; memo += '[' + cause.type + '] ' + cause.reason; var extraData = _.omit(cause, ['type', 'reason']); if (_.size(extraData)) { memo += ', with: ' + JSON.stringify(extraData); } return memo; }, ''); if (!msg) { if (esErrObject.type) msg += '[' + esErrObject.type + '] '; if (esErrObject.reason) msg += esErrObject.reason; } ErrorAbstract.call(this, msg || name, StatusCodeError, metadata); return this; } _.inherits(StatusCodeError, ErrorAbstract); errors[className] = StatusCodeError; errors[status] = StatusCodeError; }); },{"./utils":42}],28:[function(require,module,exports){ var Buffer=require("__browserify_Buffer").Buffer;/** * Class to wrap URLS, formatting them and maintaining their separate details * @type {[type]} */ module.exports = Host; var url = require('url'); var qs = require('querystring'); var _ = require('./utils'); var startsWithProtocolRE = /^([a-z]+:)?\/\//; var defaultProto = 'http:'; var btoa; /* jshint ignore:start */ if (typeof window !== 'undefined') { defaultProto = window.location.protocol; btoa = window.btoa; } /* jshint ignore:end */ btoa = btoa || function (data) { return (new Buffer(data, 'utf8')).toString('base64'); }; var urlParseFields = [ 'protocol', 'hostname', 'pathname', 'port', 'auth', 'query' ]; var simplify = ['host', 'path']; var sslDefaults = { pfx: null, key: null, passphrase: null, cert: null, ca: null, ciphers: null, rejectUnauthorized: false, secureProtocol: null }; // simple reference used when formatting as a url // and defines when parsing from a string Host.defaultPorts = { http: 80, https: 443 }; function Host(config, globalConfig) { config = _.clone(config || {}); globalConfig = globalConfig || {}; // defaults this.protocol = 'http'; this.host = 'localhost'; this.path = ''; this.port = 9200; this.query = null; this.headers = null; this.suggestCompression = !!globalConfig.suggestCompression; this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults); if (typeof config === 'string') { var firstColon = config.indexOf(':'); var firstSlash = config.indexOf('/'); var noSlash = firstSlash === -1; var portNoPath = firstColon > -1 && noSlash; var portWithPath = !portNoPath && firstColon < firstSlash; if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) { config = defaultProto + '//' + config; } config = _.pick(url.parse(config, false, true), urlParseFields); // default logic for the port is to use 9200 for the default. When a string is specified though, // we will use the default from the protocol of the string. if (!config.port) { var proto = config.protocol || 'http'; if (proto.charAt(proto.length - 1) === ':') { proto = proto.substring(0, proto.length - 1); } if (Host.defaultPorts[proto]) { config.port = Host.defaultPorts[proto]; } } } if (_.isObject(config)) { // move hostname/portname to host/port semi-intelligently. _.each(simplify, function (to) { var from = to + 'name'; if (config[from] && config[to]) { if (config[to].indexOf(config[from]) === 0) { config[to] = config[from]; } } else if (config[from]) { config[to] = config[from]; } delete config[from]; }); } else { config = {}; } if (config.auth) { config.headers = config.headers || {}; config.headers.Authorization = 'Basic ' + btoa(config.auth); delete config.auth; } _.forOwn(config, function (val, prop) { if (val != null) this[prop] = _.clone(val); }, this); // make sure the query string is parsed if (this.query === null) { // majority case this.query = {}; } else if (!_.isPlainObject(this.query)) { this.query = qs.parse(this.query); } // make sure that the port is a number if (_.isNumeric(this.port)) { this.port = parseInt(this.port, 10); } else { this.port = 9200; } // make sure the path starts with a leading slash if (this.path === '/') { this.path = ''; } else if (this.path && this.path.charAt(0) !== '/') { this.path = '/' + (this.path || ''); } // strip trailing ':' on the protocol (when config comes from url.parse) if (this.protocol.substr(-1) === ':') { this.protocol = this.protocol.substring(0, this.protocol.length - 1); } } Host.prototype.makeUrl = function (params) { params = params || {}; // build the port var port = ''; if (this.port !== Host.defaultPorts[this.protocol]) { // add an actual port port = ':' + this.port; } // build the path var path = '' + (this.path || '') + (params.path || ''); // if path doesn't start with '/' add it. if (path.charAt(0) !== '/') { path = '/' + path; } // build the query string var query = qs.stringify(this.getQuery(params.query)); if (this.host) { return this.protocol + '://' + this.host + port + path + (query ? '?' + query : ''); } else { return path + (query ? '?' + query : ''); } }; function objectPropertyGetter(prop, preOverride) { return function (overrides) { if (preOverride) { overrides = preOverride.call(this, overrides); } var obj = this[prop]; if (!obj && !overrides) { return null; } if (overrides) { obj = _.assign({}, obj, overrides); } return _.size(obj) ? obj : null; }; } Host.prototype.getHeaders = objectPropertyGetter('headers', function (overrides) { if (!this.suggestCompression) { return overrides; } return _.defaults(overrides || {}, { 'Accept-Encoding': 'gzip,deflate' }); }); Host.prototype.getQuery = objectPropertyGetter('query', function (query) { return typeof query === 'string' ? qs.parse(query) : query; }); Host.prototype.toString = function () { return this.makeUrl(); }; },{"./utils":42,"__browserify_Buffer":12,"querystring":6,"url":7}],29:[function(require,module,exports){ var process=require("__browserify_process");var _ = require('./utils'); var url = require('url'); var EventEmitter = require('events').EventEmitter; /** * Log bridge, which is an [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter) * that sends events to one or more outputs/loggers. Setup these loggers by * specifying their config as the first argument, or by passing it to addOutput(). * * @class Log * @uses Loggers.Stdio * @constructor * @param {string|Object|ArrayOfStrings|ArrayOfObjects} output - Either the level * to setup a single logger, a full config object for alogger, or an array of * config objects to use for creating log outputs. * @param {string} output.level - One of the keys in Log.levels (error, warning, etc.) * @param {string} output.type - The name of the logger to use for this output */ function Log(config) { config = config || {}; var i; var outputs; if (config.log) { if (_.isArrayOfStrings(config.log)) { outputs = [{ levels: config.log }]; } else { outputs = _.createArray(config.log, function (val) { if (_.isPlainObject(val)) { return val; } if (typeof val === 'string') { return { level: val }; } }); } if (!outputs) { throw new TypeError('Invalid logging output config. Expected either a log level, array of log levels, ' + 'a logger config object, or an array of logger config objects.'); } for (i = 0; i < outputs.length; i++) { this.addOutput(outputs[i]); } } } _.inherits(Log, EventEmitter); Log.loggers = require('./loggers'); Log.prototype.close = function () { this.emit('closing'); if (this.listenerCount()) { console.error('Something is still listening for log events, but the logger is closing.'); this.clearAllListeners(); } }; Log.prototype.listenerCount = function (event) { // compatability for node < 0.10 if (EventEmitter.listenerCount) { return EventEmitter.listenerCount(this, event); } else { return this.listeners(event).length; } }; /** * Levels observed by the loggers, ordered by rank * * @property levels * @type Array * @static */ Log.levels = [ /** * Event fired for error level log entries * @event error * @param {Error} error - The error object to log */ 'error', /** * Event fired for "warning" level log entries, which usually represent things * like correctly formatted error responses from ES (400, ...) and recoverable * errors (one node unresponsive) * * @event warning * @param {String} message - A message to be logged */ 'warning', /** * Event fired for "info" level log entries, which usually describe what a * client is doing (sniffing etc) * * @event info * @param {String} message - A message to be logged */ 'info', /** * Event fired for "debug" level log entries, which will describe requests sent, * including their url (no data, response codes, or exec times) * * @event debug * @param {String} message - A message to be logged */ 'debug', /** * Event fired for "trace" level log entries, which provide detailed information * about each request made from a client, including reponse codes, execution times, * and a full curl command that can be copied and pasted into a terminal * * @event trace * @param {String} method method, , body, responseStatus, responseBody * @param {String} url - The url the request was made to * @param {String} body - The body of the request * @param {Integer} responseStatus - The status code returned from the response * @param {String} responseBody - The body of the response */ 'trace' ]; /** * Converts a log config value (string or array) to an array of level names which * it represents * * @method parseLevels * @static * @private * @param {String|ArrayOfStrings} input - Cound be a string to specify the max * level, or an array of exact levels * @return {Array} - */ Log.parseLevels = function (input) { switch (typeof input) { case 'string': var i = _.indexOf(Log.levels, input); if (i >= 0) { return Log.levels.slice(0, i + 1); } /* fall through */ case 'object': if (_.isArray(input)) { var valid = _.intersection(input, Log.levels); if (valid.length === input.length) { return valid; } } /* fall through */ default: throw new TypeError('invalid logging level ' + input + '. Expected zero or more of these options: ' + Log.levels.join(', ')); } }; /** * Combine the array-like param into a simple string * * @method join * @static * @private * @param {*} arrayish - An array like object that can be itterated by _.each * @return {String} - The final string. */ Log.join = function (arrayish) { return _.map(arrayish, function (item) { if (_.isPlainObject(item)) { return _.inspect(item) + '\n'; } else { return item.toString(); } }).join(' '); }; /** * Create a new logger, based on the config. * * @method addOutput * @param {object} config - An object with config options for the logger. * @param {String} [config.type=stdio] - The name of an output/logger. Options * can be found in the `src/loggers` directory. * @param {String|ArrayOfStrings} [config.levels=warning] - The levels to output * to this logger, when an array is specified no levels other than the ones * specified will be listened to. When a string is specified, that and all lower * levels will be logged. * @return {Logger} */ Log.prototype.addOutput = function (config) { config = config || {}; // force "levels" key config.levels = Log.parseLevels(config.levels || config.level || 'warning'); delete config.level; var Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio'); return new Logger(this, config); }; /** * Log an error * * @method error * @param {Error|String} error The Error to log * @return {Boolean} - True if any outputs accepted the message */ Log.prototype.error = function (e) { if (this.listenerCount('error')) { return this.emit('error', e instanceof Error ? e : new Error(e)); } }; /** * Log a warning message * * @method warning * @param {*} msg* - Any amount of messages that will be joined before logged * @return {Boolean} - True if any outputs accepted the message */ Log.prototype.warning = function (/* ...msg */) { if (this.listenerCount('warning')) { return this.emit('warning', Log.join(arguments)); } }; /** * Log useful info about what's going on * * @method info * @param {*} msg* - Any amount of messages that will be joined before logged * @return {Boolean} - True if any outputs accepted the message */ Log.prototype.info = function (/* ...msg */) { if (this.listenerCount('info')) { return this.emit('info', Log.join(arguments)); } }; /** * Log a debug level message * * @method debug * @param {*} msg* - Any amount of messages that will be joined before logged * @return {Boolean} - True if any outputs accepted the message */ Log.prototype.debug = function (/* ...msg */) { if (this.listenerCount('debug')) { return this.emit('debug', Log.join(arguments)); } }; /** * Log a trace level message * * @method trace * @param {String} method - HTTP request method * @param {String|Object} requestUrl - URL requested. If the value is an object, * it is expected to be the return value of Node's url.parse() * @param {String} body - The request's body * @param {String} responseBody - body returned from ES * @param {String} responseStatus - HTTP status code * @return {Boolean} - True if any outputs accepted the message */ Log.prototype.trace = function (method, requestUrl, body, responseBody, responseStatus) { if (this.listenerCount('trace')) { return this.emit('trace', Log.normalizeTraceArgs(method, requestUrl, body, responseBody, responseStatus)); } }; Log.normalizeTraceArgs = function (method, requestUrl, body, responseBody, responseStatus) { if (typeof requestUrl === 'string') { requestUrl = url.parse(requestUrl, true, true); } else { requestUrl = _.clone(requestUrl); if (requestUrl.path) { requestUrl.query = url.parse(requestUrl.path, true, false).query; } if (!requestUrl.pathname && requestUrl.path) { requestUrl.pathname = requestUrl.path.split('?').shift(); } } delete requestUrl.auth; return { method: method, url: url.format(requestUrl), body: body, status: responseStatus, response: responseBody }; }; module.exports = Log; },{"./loggers":31,"./utils":42,"__browserify_process":13,"events":4,"url":7}],30:[function(require,module,exports){ var _ = require('./utils'); /** * Abstract class providing common functionality to loggers * @param {[type]} log [description] * @param {[type]} config [description] */ function LoggerAbstract(log, config) { this.log = log; this.listeningLevels = []; _.makeBoundMethods(this); // when the log closes, remove our event listeners this.log.once('closing', this.bound.cleanUpListeners); this.setupListeners(config.levels); } function padNumToTen(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } /** * Create a timestamp string used in the format function. Defers to Log.timestamp if it is defined, * Also, feel free to override this at the logger level. * @return {String} - Timestamp in ISO 8601 UTC */ LoggerAbstract.prototype.timestamp = function () { var d = new Date(); return d.getUTCFullYear() + '-' + padNumToTen(d.getUTCMonth() + 1) + '-' + padNumToTen(d.getUTCDate()) + 'T' + padNumToTen(d.getUTCHours()) + ':' + padNumToTen(d.getUTCMinutes()) + ':' + padNumToTen(d.getUTCSeconds()) + 'Z'; }; function indent(text, spaces) { var space = _.repeat(' ', spaces || 2); return (text || '').split(/\r?\n/).map(function (line) { return space + line; }).join('\n'); } LoggerAbstract.prototype.format = function (label, message) { return label + ': ' + this.timestamp() + '\n' + indent(message) + '\n\n'; }; LoggerAbstract.prototype.write = function () { throw new Error('This should be overwritten by the logger'); }; /** * Clear the current event listeners and then re-listen for events based on the level specified * * @method setupListeners * @private * @param {Integer} level - The max log level that this logger should listen to * @return {undefined} */ LoggerAbstract.prototype.setupListeners = function (levels) { this.cleanUpListeners(); this.listeningLevels = []; _.each(levels, function (level) { var fnName = 'on' + _.ucfirst(level); if (this.bound[fnName]) { this.listeningLevels.push(level); this.log.on(level, this.bound[fnName]); } else { throw new Error('Unable to listen for level "' + level + '"'); } }, this); }; /** * Clear the current event listeners * * @method cleanUpListeners * @private * @return {undefined} */ LoggerAbstract.prototype.cleanUpListeners = _.handler(function () { _.each(this.listeningLevels, function (level) { this.log.removeListener(level, this.bound['on' + _.ucfirst(level)]); }, this); }); /** * Handler for the logs "error" event * * @method onError * @private * @param {Error} e - The Error object to log * @return {undefined} */ LoggerAbstract.prototype.onError = _.handler(function (e) { this.write((e.name === 'Error' ? 'ERROR' : e.name), e.stack); }); /** * Handler for the logs "warning" event * * @method onWarning * @private * @param {String} msg - The message to be logged * @return {undefined} */ LoggerAbstract.prototype.onWarning = _.handler(function (msg) { this.write('WARNING', msg); }); /** * Handler for the logs "info" event * * @method onInfo * @private * @param {String} msg - The message to be logged * @return {undefined} */ LoggerAbstract.prototype.onInfo = _.handler(function (msg) { this.write('INFO', msg); }); /** * Handler for the logs "debug" event * * @method onDebug * @private * @param {String} msg - The message to be logged * @return {undefined} */ LoggerAbstract.prototype.onDebug = _.handler(function (msg) { this.write('DEBUG', msg); }); /** * Handler for the logs "trace" event * * @method onTrace * @private * @param {String} msg - The message to be logged * @return {undefined} */ LoggerAbstract.prototype.onTrace = _.handler(function (requestDetails) { this.write('TRACE', this._formatTraceMessage(requestDetails)); }); LoggerAbstract.prototype._formatTraceMessage = function (req) { return '-> ' + req.method + ' ' + req.url + '\n' + this._prettyJson(req.body) + '\n' + '<- ' + req.status + '\n' + this._prettyJson(req.response); /* -> GET https://sldfkjsdlfksjdf:9200/slsdkfjlxckvxhclks?sdlkj=sdlfkje { asdflksjdf } <- 502 { sldfksjdlf } */ }; LoggerAbstract.prototype._prettyJson = function (body) { try { if (typeof body === 'string') { body = JSON.parse(body); } return JSON.stringify(body, null, ' ').replace(/'/g, '\\u0027'); } catch (e) { return typeof body === 'string' ? body : ''; } }; module.exports = LoggerAbstract; },{"./utils":42}],31:[function(require,module,exports){ module.exports = { console: require('./console') }; },{"./console":32}],32:[function(require,module,exports){ /** * Special version of the Stream logger, which logs errors and warnings to stderr and all other * levels to stdout. * * @class Loggers.Console * @extends LoggerAbstract * @constructor * @param {Object} config - The configuration for the Logger * @param {string} config.level - The highest log level for this logger to output. * @param {Log} bridge - The object that triggers logging events, which we will record */ module.exports = Console; var LoggerAbstract = require('../logger'); var _ = require('../utils'); function Console(log, config) { LoggerAbstract.call(this, log, config); // config/state this.color = _.has(config, 'color') ? !!config.color : true; } _.inherits(Console, LoggerAbstract); /** * Override the LoggerAbstract's setup listeners to do a little extra setup * * @param {Array} levels - The levels that we should be listeneing for */ Console.prototype.setupListeners = function (levels) { // call the super method LoggerAbstract.prototype.setupListeners.call(this, levels); }; Console.prototype.write = function (label, message, to) { if (console[to]) { console[to](this.format(label, message)); } }; /** * Handler for the bridges "error" event * * @method onError * @private * @param {Error} e - The Error object to log * @return {undefined} */ Console.prototype.onError = _.handler(function (e) { var to = console.error ? 'error' : 'log'; this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to); }); /** * Handler for the bridges "warning" event * * @method onWarning * @private * @param {String} msg - The message to be logged * @return {undefined} */ Console.prototype.onWarning = _.handler(function (msg) { this.write('WARNING', msg, console.warn ? 'warn' : 'log'); }); /** * Handler for the bridges "info" event * * @method onInfo * @private * @param {String} msg - The message to be logged * @return {undefined} */ Console.prototype.onInfo = _.handler(function (msg) { this.write('INFO', msg, console.info ? 'info' : 'log'); }); /** * Handler for the bridges "debug" event * * @method onDebug * @private * @param {String} msg - The message to be logged * @return {undefined} */ Console.prototype.onDebug = _.handler(function (msg) { this.write('DEBUG', msg, console.debug ? 'debug' : 'log'); }); /** * Handler for the bridges "trace" event * * @method onTrace * @private * @return {undefined} */ Console.prototype.onTrace = _.handler(function (msg) { this.write('TRACE', this._formatTraceMessage(msg), 'log'); }); },{"../logger":30,"../utils":42}],33:[function(require,module,exports){ var _ = require('./utils'); var extractHostPartsRE = /\[\/*([^:]+):(\d+)\]/; function makeNodeParser(hostProp) { return function (nodes) { return _.transform(nodes, function (hosts, node, id) { if (!node[hostProp]) { return; } var hostnameMatches = extractHostPartsRE.exec(node[hostProp]); if (!hostnameMatches) { throw new Error('node\'s ' + hostProp + ' property (' + JSON.stringify(node[hostProp]) + ') does not match the expected pattern ' + extractHostPartsRE + '.'); } hosts.push({ host: hostnameMatches[1], port: parseInt(hostnameMatches[2], 10), _meta: { id: id, name: node.name, hostname: node.hostname, version: node.version } }); }, []); }; } module.exports = makeNodeParser('http_address'); module.exports.thrift = makeNodeParser('transport_address'); },{"./utils":42}],34:[function(require,module,exports){ module.exports = { random: require('./random'), roundRobin: require('./round_robin') }; },{"./random":35,"./round_robin":36}],35:[function(require,module,exports){ /** * Selects a connection randomly * * @module selectors * @type {Function} * @param {Array} connection - The list of connections to choose from * @return {Connection} - The selected connection */ module.exports = function RandomSelector(connections) { return connections[Math.floor(Math.random() * connections.length)]; }; },{}],36:[function(require,module,exports){ /** * Selects a connection the simplest way possible, Round Robin * * @module selectors * @type {Function} * @param {Array} connections - The list of connections that this selector needs to choose from * @return {Connection} - The selected connection */ module.exports = function (connections) { var connection = connections[0]; connections.push(connections.shift()); return connection; }; },{}],37:[function(require,module,exports){ /* global angular */ var _ = require('../utils'); var JsonSerializer = require('../serializers/json'); function AngularSerializer() {} _.inherits(AngularSerializer, JsonSerializer); // mimic the JsonSerializer's encode method, but use angular's toJson instead AngularSerializer.prototype.encode = function (val) { switch (typeof val) { case 'string': return val; case 'object': if (val) return angular.toJson(val); /* falls through */ default: return; } }; module.exports = AngularSerializer; },{"../serializers/json":39,"../utils":42}],38:[function(require,module,exports){ module.exports = { angular: require('./angular'), json: require('./json') }; },{"./angular":37,"./json":39}],39:[function(require,module,exports){ /** * Simple JSON serializer * @type {[type]} */ module.exports = Json; var _ = require('../utils'); function Json() {} /** * Converts a value into a string, or an error * @param {*} val - Any value, methods are stripped and * see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify about other params * @return {String|Error} - A string is always returned, unless an error occured. then it will be that error. */ Json.prototype.serialize = function (val, replacer, spaces) { switch (typeof val) { case 'string': return val; case 'object': if (val) { return JSON.stringify(val, replacer, spaces); } /* falls through */ default: return; } }; /** * Parse a JSON string, if it is already parsed it is ignored * @param {String} str - the string to parse * @return {[type]} */ Json.prototype.deserialize = function (str) { if (typeof str === 'string') { try { return JSON.parse(str); } catch (e) {} } }; Json.prototype.bulkBody = function (val) { var body = '', i; if (_.isArray(val)) { for (i = 0; i < val.length; i++) { body += this.serialize(val[i]) + '\n'; } } else if (typeof val === 'string') { // make sure the string ends in a new line body = val + (val[val.length - 1] === '\n' ? '' : '\n'); } else { throw new TypeError('Bulk body should either be an Array of commands/string, or a String'); } return body; }; },{"../utils":42}],40:[function(require,module,exports){ /** * Class that manages making request, called by all of the API methods. * @type {[type]} */ module.exports = Transport; var _ = require('./utils'); var errors = require('./errors'); var Host = require('./host'); var Promise = require('bluebird'); var patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault'); function Transport(config) { var self = this; config = self._config = config || {}; var LogClass = (typeof config.log === 'function') ? config.log : require('./log'); config.log = self.log = new LogClass(config); // setup the connection pool var ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); self.connectionPool = new ConnectionPool(config); // setup the serializer var Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json'); self.serializer = new Serializer(config); // setup the nodesToHostCallback self.nodesToHostCallback = _.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); // setup max retries self.maxRetries = config.hasOwnProperty('maxRetries') ? config.maxRetries : 3; // setup endpoint to use for sniffing self.sniffEndpoint = config.hasOwnProperty('sniffEndpoint') ? config.sniffEndpoint : '/_nodes/_all/clear'; // setup requestTimeout default self.requestTimeout = config.hasOwnProperty('requestTimeout') ? config.requestTimeout : 30000; if (config.hasOwnProperty('defer')) { self.defer = config.defer; } // randomizeHosts option var randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true; if (config.host) { config.hosts = config.host; } if (config.hosts) { var hostsConfig = _.createArray(config.hosts, function (val) { if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) { return val; } }); if (!hostsConfig) { throw new TypeError('Invalid hosts config. Expected a URL, an array of urls, a host config object, ' + 'or an array of host config objects.'); } var hosts = _.map(hostsConfig, function (conf) { return (conf instanceof Host) ? conf : new Host(conf, self._config); }); if (randomizeHosts) { hosts = _.shuffle(hosts); } self.connectionPool.setHosts(hosts); } if (config.sniffOnStart) { self.sniff(); } if (config.sniffInterval) { self._timeout(function doSniff() { self.sniff(); self._timeout(doSniff, config.sniffInterval); }, config.sniffInterval); } if (config.sniffOnConnectionFault) { patchSniffOnConnectionFault(self); } } Transport.connectionPools = { main: require('./connection_pool') }; Transport.serializers = require('./serializers'); Transport.nodesToHostCallbacks = { main: require('./nodes_to_host') }; Transport.prototype.defer = function () { return Promise.defer(); }; /** * Perform a request with the client's transport * * @method request * @todo async body writing * @todo abort * @todo access to custom headers, modifying of request in general * @param {object} params * @param {Number} params.requestTimeout - timeout for the entire request (inculding all retries) * @param {Number} params.maxRetries - number of times the request will be re-run in * the original node chosen can not be connected to. * @param {String} params.url - The url for the request * @param {String} params.method - The HTTP method for the request * @param {String} params.body - The body of the HTTP request * @param {Function} cb - A function to call back with (error, responseBody, responseStatus) */ Transport.prototype.request = function (params, cb) { var self = this; var remainingRetries = this.maxRetries; var requestTimeout = this.requestTimeout; var connection; // set in sendReqWithConnection var aborted = false; // several connector will respond with an error when the request is aborted var requestAborter; // an abort function, returned by connection#request() var requestTimeoutId; // the id of the ^timeout var ret; // the object returned to the user, might be a promise var defer; // the defer object, will be set when we are using promises. self.log.debug('starting request', params); if (params.body && params.method === 'GET') { _.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); return; } // serialize the body if (params.body) { params.body = self.serializer[params.bulkBody ? 'bulkBody' : 'serialize'](params.body); } if (params.hasOwnProperty('maxRetries')) { remainingRetries = params.maxRetries; } if (params.hasOwnProperty('requestTimeout')) { requestTimeout = params.requestTimeout; } params.req = { method: params.method, path: params.path || '/', query: params.query, body: params.body, headers: params.headers }; function sendReqWithConnection(err, _connection) { if (aborted) { return; } if (err) { respond(err); } else if (_connection) { connection = _connection; requestAborter = connection.request(params.req, checkRespForFailure); } else { self.log.warning('No living connections'); respond(new errors.NoConnections()); } } function checkRespForFailure(err, body, status, headers) { if (aborted) { return; } requestAborter = void 0; if (err instanceof errors.RequestTypeError) { self.log.error('Connection refused to execute the request', err); respond(err, body, status, headers); return; } if (err) { connection.setStatus('dead'); if (remainingRetries) { remainingRetries--; self.log.error('Request error, retrying' + (err.message ? ' -- ' + err.message : '')); self.connectionPool.select(sendReqWithConnection); } else { self.log.error('Request complete with error' + (err.message ? ' -- ' + err.message : '')); respond(new errors.ConnectionFault(err)); } } else { self.log.debug('Request complete'); respond(void 0, body, status, headers); } } function respond(err, body, status, headers) { if (aborted) { return; } self._timeout(requestTimeoutId); var parsedBody; var isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json')); if (!err && body) { if (isJson) { parsedBody = self.serializer.deserialize(body); if (parsedBody == null) { err = new errors.Serialization(); parsedBody = body; } } else { parsedBody = body; } } // does the response represent an error? if ( (!err || err instanceof errors.Serialization) && (status < 200 || status >= 300) && (!params.ignore || !_.contains(params.ignore, status)) ) { var errorMetadata = _.pick(params.req, ['path', 'query', 'body']); errorMetadata.statusCode = status; errorMetadata.response = body; if (errors[status]) { err = new errors[status](parsedBody && parsedBody.error, errorMetadata); } else { err = new errors.Generic('unknown error', errorMetadata); } } // can we cast notfound to false? if (params.castExists) { if (err && err instanceof errors.NotFound) { parsedBody = false; err = void 0; } else { parsedBody = !err; } } // how do we send the response? if (typeof cb === 'function') { if (err) { cb(err, parsedBody, status); } else { cb(void 0, parsedBody, status); } } else if (err) { err.body = parsedBody; err.status = status; defer.reject(err); } else { defer.resolve(parsedBody); } } function abortRequest() { if (aborted) { return; } aborted = true; remainingRetries = 0; self._timeout(requestTimeoutId); if (typeof requestAborter === 'function') { requestAborter(); } } if (requestTimeout && requestTimeout !== Infinity) { requestTimeoutId = this._timeout(function () { respond(new errors.RequestTimeout('Request Timeout after ' + requestTimeout + 'ms')); abortRequest(); }, requestTimeout); } // determine the response based on the presense of a callback if (typeof cb === 'function') { ret = { abort: abortRequest }; } else { defer = this.defer(); ret = defer.promise; ret.abort = abortRequest; } if (connection) { sendReqWithConnection(void 0, connection); } else { self.connectionPool.select(sendReqWithConnection); } return ret; }; Transport.prototype._timeout = function (cb, delay) { this._timers = this._timers || []; var id; if ('function' !== typeof cb) { id = cb; cb = void 0; } if (cb) { // set the timer id = setTimeout(cb, delay); this._timers.push(id); return id; } if (id) { clearTimeout(id); var i = this._timers.indexOf(id); if (i !== -1) { this._timers.splice(i, 1); } } }; /** * Ask an ES node for a list of all the nodes, add/remove nodes from the connection * pool as appropriate * * @param {Function} cb - Function to call back once complete */ Transport.prototype.sniff = function (cb) { var connectionPool = this.connectionPool; var nodesToHostCallback = this.nodesToHostCallback; var log = this.log; var globalConfig = this._config; // make cb a function if it isn't cb = typeof cb === 'function' ? cb : _.noop; this.request({ path: this.sniffEndpoint, method: 'GET' }, function (err, resp, status) { if (!err && resp && resp.nodes) { var hostsConfigs; try { hostsConfigs = nodesToHostCallback(resp.nodes); } catch (e) { log.error(new Error('Unable to convert node list from ' + this.sniffEndpoint + ' to hosts durring sniff. Encountered error:\n' + (e.stack || e.message))); return; } connectionPool.setHosts(_.map(hostsConfigs, function (hostConfig) { return new Host(hostConfig, globalConfig); })); } cb(err, resp, status); }); }; /** * Close the Transport, which closes the logs and connection pool * @return {[type]} [description] */ Transport.prototype.close = function () { this.log.close(); _.each(this._timers, clearTimeout); this.connectionPool.close(); }; },{"./connection_pool":24,"./errors":27,"./host":28,"./log":29,"./nodes_to_host":33,"./serializers":38,"./transport/sniff_on_connection_fault":41,"./utils":42,"bluebird":1}],41:[function(require,module,exports){ var _ = require('../utils'); /** * Patch the transport's connection pool to schedule a sniff after a connection fails. * When a connection fails for the first time it will schedule a sniff 1 second in the * future, and increase the timeout based on the deadTimeout algorithm chosen by the * connectionPool, and the number of times the sniff has failed. * * @param {Transport} transport - the transport that will be using this behavior * @return {undefined} */ module.exports = function setupSniffOnConnectionFault(transport) { var failures = 0; var pool = transport.connectionPool; var originalOnDied = pool._onConnectionDied; // do the actual sniff, if the sniff is unable to // connect to a node this function will be called again by the connectionPool var work = function () { work.timerId = transport._timeout(work.timerId); transport.sniff(); }; // create a function that will count down to a // point n milliseconds into the future var countdownTo = function (ms) { var start = _.now(); return function () { return start - ms; }; }; // overwrite the function, but still call it pool._onConnectionDied = function (connection, wasAlreadyDead) { var ret = originalOnDied.call(pool, connection, wasAlreadyDead); // clear the failures if this is the first failure we have seen failures = work.timerId ? failures + 1 : 0; var ms = pool.calcDeadTimeout(failures, 1000); if (work.timerId && ms < work.timerId && work.countdown()) { // clear the timer work.timerId = transport._timeout(work.timerId); } if (!work.timerId) { work.timerId = transport._timeout(work, ms); work.countdown = countdownTo(ms); } return ret; }; pool._onConnectionDied.restore = function () { pool._onConnectionDied = originalOnDied; }; }; },{"../utils":42}],42:[function(require,module,exports){ var process=require("__browserify_process"),Buffer=require("__browserify_Buffer").Buffer;var path = require('path'); var _ = require('lodash'); var nodeUtils = require('util'); /** * Custom utils library, basically a modified version of [lodash](http://lodash.com/docs) + * [node.utils](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent * confusion when requiring lodash itself. * * @class utils * @static */ var utils = _.extend({}, _, nodeUtils); _ = utils; /** * Link to [path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2) * * @method utils.joinPath * @type {function} */ utils.joinPath = path.join; /** * Recursively merge two objects, walking into each object and concating arrays. If both to and from have a value at a * key, but the values' types don't match to's value is left unmodified. Only Array and Object values are merged - that * it to say values with a typeof "object" * * @param {Object} to - Object to merge into (no cloning, the original object * is modified) * @param {Object} from - Object to pull changed from * @return {Object} - returns the modified to value */ utils.deepMerge = function (to, from) { _.each(from, function (fromVal, key) { switch (typeof to[key]) { case 'undefined': to[key] = from[key]; break; case 'object': if (_.isArray(to[key]) && _.isArray(from[key])) { to[key] = to[key].concat(from[key]); } else if (_.isPlainObject(to[key]) && _.isPlainObject(from[key])) { utils.deepMerge(to[key], from[key]); } } }); return to; }; /** * Test if a value is an array and it's contents are of a specific type * * @method isArrayOf<Strings|Object|Array|Finite|Function|RegExp>s * @param {Array} arr - An array to check * @return {Boolean} */ _.each([ 'String', 'Object', 'PlainObject', 'Array', 'Finite', 'Function', 'RegExp' ], function (type) { var check = _['is' + type]; utils['isArrayOf' + type + 's'] = function (arr) { // quick shallow check of arrays return _.isArray(arr) && _.every(arr.slice(0, 10), check); }; }); /** * Capitalize the first letter of a word * * @method ucfirst * @param {string} word - The word to transform * @return {string} */ utils.ucfirst = function (word) { return word[0].toUpperCase() + word.substring(1).toLowerCase(); }; /** * Base algo for studlyCase and camelCase * @param {boolean} firstWordCap - Should the first character of the first word be capitalized * @return {Function} */ function adjustWordCase(firstWordCap, otherWordsCap, sep) { return function (string) { var i = 0; var words = []; var word = ''; var code, c, upper, lower; for (; i < string.length; i++) { code = string.charCodeAt(i); c = string.charAt(i); lower = (code >= 97 && code <= 122) || (code >= 48 && code <= 57); upper = code >= 65 && code <= 90; if (upper || !lower) { // new word if (word.length) { words.push(word); } word = ''; } if (upper || lower) { if (lower && word.length) { word += c; } else { if ((!words.length && firstWordCap) || (words.length && otherWordsCap)) { word = c.toUpperCase(); } else { word = c.toLowerCase(); } } } } if (word.length) { words.push(word); } // add the leading underscore back to strings the had it originally if (words.length && string.charAt(0) === '_') { words[0] = '_' + words[0]; } return words.join(sep); }; } /** * Transform a string into StudlyCase * * @method studlyCase * @param {String} string * @return {String} */ utils.studlyCase = adjustWordCase(true, true, ''); /** * Transform a string into camelCase * * @method camelCase * @param {String} string * @return {String} */ utils.camelCase = adjustWordCase(false, true, ''); /** * Transform a string into snakeCase * * @method snakeCase * @param {String} string * @return {String} */ utils.snakeCase = adjustWordCase(false, false, '_'); /** * Lower-case a string, and return an empty string if any is not a string * * @param any {*} - Something or nothing * @returns {string} */ utils.toLowerString = function (any) { if (any) { if (typeof any !== 'string') { any = any.toString(); } } else { any = ''; } return any.toLowerCase(); }; /** * Upper-case the string, return an empty string if any is not a string * * @param any {*} - Something or nothing * @returns {string} */ utils.toUpperString = function (any) { if (any) { if (typeof any !== 'string') { any = any.toString(); } } else { any = ''; } return any.toUpperCase(); }; /** * Test if a value is "numeric" meaning that it can be transformed into something besides NaN * * @method isNumeric * @param {*} val * @return {Boolean} */ utils.isNumeric = function (val) { return typeof val !== 'object' && val - parseFloat(val) >= 0; }; // regexp to test for intervals var intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/; /** * Test if a string represents an interval (eg. 1m, 2Y) * * @method isInterval * @param {String} val * @return {Boolean} */ utils.isInterval = function (val) { return !!(val.match && val.match(intervalRE)); }; /** * Repeat a string n times * * @todo TestPerformance * @method repeat * @param {String} what - The string to repeat * @param {Number} times - Times the string should be repeated * @return {String} */ utils.repeat = function (what, times) { return (new Array(times + 1)).join(what); }; /** * Call a function, applying the arguments object to it in an optimized way, rather than always turning it into an array * * @param func {Function} - The function to execute * @param context {*} - The context the function will be executed with * @param args {Arguments} - The arguments to send to func * @param [sliceIndex=0] {Integer} - The index that args should be sliced at, before feeding args to func * @returns {*} - the return value of func */ utils.applyArgs = function (func, context, args, sliceIndex) { sliceIndex = sliceIndex || 0; switch (args.length - sliceIndex) { case 0: return func.call(context); case 1: return func.call(context, args[0 + sliceIndex]); case 2: return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex]); case 3: return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex]); case 4: return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex], args[3 + sliceIndex]); case 5: return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex], args[3 + sliceIndex], args[4 + sliceIndex]); default: return func.apply(context, Array.prototype.slice.call(args, sliceIndex)); } }; /** * Schedule a function to be called on the next tick, and supply it with these arguments * when it is called. * @return {[type]} [description] */ _.nextTick = function (cb) { // bind the function and schedule it process.nextTick(_.bindKey(_, 'applyArgs', cb, null, arguments, 1)); }; /** * Marks a method as a handler. Currently this just makes a property on the method * flagging it to be bound to the object at object creation when "makeBoundMethods" is called * * ``` * ClassName.prototype.methodName = _.handler(function () { * // this will always be bound when called via classInstance.bound.methodName * this === classInstance * }); * ``` * * @alias _.scheduled * @param {Function} func - The method that is being defined * @return {Function} */ _.handler = function (func) { func._provideBound = true; return func; }; _.scheduled = _.handler; /** * Creates an "bound" property on an object, which all or a subset of methods from * the object which are bound to the original object. * * ``` * var obj = { * onEvent: function () {} * }; * * _.makeBoundMethods(obj); * * obj.bound.onEvent() // is bound to obj, and can safely be used as an event handler. * ``` * * @param {Object} obj - The object to bind the methods to */ _.makeBoundMethods = function (obj) { obj.bound = {}; for (var prop in obj) { // dearest maintainer, we want to look through the prototype if (typeof obj[prop] === 'function' && obj[prop]._provideBound === true) { obj.bound[prop] = _.bind(obj[prop], obj); } } }; _.noop = function () {}; /** * Implements the standard "string or constructor" check that I was copy/pasting everywhere * @param {String|Function} val - the value that the user passed in * @param {Object} opts - a map of the options * @return {Function|undefined} - If a valid option was specified, then the constructor is returned */ _.funcEnum = function (config, name, opts, def) { var val = config[name]; switch (typeof val) { case 'undefined': return opts[def]; case 'function': return val; case 'string': if (opts.hasOwnProperty(val)) { return opts[val]; } /* falls through */ default: var err = 'Invalid ' + name + ' "' + val + '", expected a function'; switch (_.size(opts)) { case 0: break; case 1: err += ' or ' + _.keys(opts)[0]; break; default: err += ' or one of ' + _.keys(opts).join(', '); break; } throw new TypeError(err); } }; /** * Accepts any object and attempts to convert it into an array. If the object passed in is not * an array it will be wrapped in one. Then the transform/map function will be called for each element * and create a new array that is returned. If the map function fails to return something, the loop is * halted and false is returned instead of an array. * * @param {*} input - The value to convert * @param {Function} transform - A function called for each element of the resulting array * @return {Array|false} - an array on success, or false on failure. */ _.createArray = function (input, transform) { transform = typeof transform === 'function' ? transform : _.identity; var output = []; var item; var i; if (!_.isArray(input)) { input = [input]; } for (i = 0; i < input.length; i++) { item = transform(input[i]); if (item === void 0) { return false; } else { output.push(item); } } return output; }; /** * Takes a WritableStream, and returns the chunks that have not successfully written, returning them as a string. * * ONLY WORKS FOR TEXT STREAMS * * @param {WritableStream} stream - an instance of stream.Writable * @return {string} - the remaining test to be written to the stream */ _.getUnwrittenFromStream = function (stream) { var writeBuffer = _.getStreamWriteBuffer(stream); if (!writeBuffer) return; // flush the write buffer var out = ''; if (!writeBuffer.length) return out; _.each(writeBuffer, function (writeReq) { if (writeReq.chunk) { // 0.9.12+ uses WriteReq objects with a chunk prop out += '' + writeReq.chunk; } else if (_.isArray(writeReq) && (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))) { // 0.9.4 - 0.9.9 buffers are arrays of arrays like [[chunk, cb], [chunk, undef], ...]. out += '' + writeReq[0]; } else { return false; } }); return out; }; _.getStreamWriteBuffer = function (stream) { if (!stream || !stream._writableState) return; var writeState = stream._writableState; if (writeState.getBuffer) { return writeState.getBuffer(); } else if (writeState.buffer) { return writeState.buffer; } }; _.clearWriteStreamBuffer = function (stream) { var buffer = _.getStreamWriteBuffer(stream); return buffer && buffer.splice(0); }; /** * return the current time in milliseconds since epoch */ _.now = function () { return (typeof Date.now === 'function') ? Date.now() : (new Date()).getTime(); }; module.exports = utils; },{"__browserify_Buffer":12,"__browserify_process":13,"lodash":14,"path":5,"util":8}]},{},[15]) ; }());
describe('Exceptions:', function() { var env; beforeEach(function() { env = new jasmine.Env(); env.updateInterval = 0; }); it('jasmine.formatException formats Firefox exception messages as expected', function() { var sampleFirefoxException = { fileName: 'foo.js', line: '1978', message: 'you got your foo in my bar', name: 'A Classic Mistake' }; var expected = 'A Classic Mistake: you got your foo in my bar in foo.js (line 1978)'; expect(jasmine.util.formatException(sampleFirefoxException)).toEqual(expected); }); it('jasmine.formatException formats Webkit exception messages as expected', function() { var sampleWebkitException = { sourceURL: 'foo.js', lineNumber: '1978', message: 'you got your foo in my bar', name: 'A Classic Mistake' }; var expected = 'A Classic Mistake: you got your foo in my bar in foo.js (line 1978)'; expect(jasmine.util.formatException(sampleWebkitException)).toEqual(expected); }); describe('with break on exception', function() { it('should not catch the exception', function() { var suite = env.describe('suite for break on exceptions', function() { env.it('should break when an exception is thrown', function() { throw new Error('I should hit a breakpoint!'); }); }); var runner = env.currentRunner(); var dont_change = 'I will never change!'; var oldCatch = jasmine.CATCH_EXCEPTIONS; jasmine.CATCH_EXCEPTIONS = false; try { suite.execute(); dont_change = 'oops I changed'; } catch (e) {} finally { jasmine.CATCH_EXCEPTIONS = oldCatch; } expect(dont_change).toEqual('I will never change!'); }); }); describe("with catch on exception", function() { it('should handle exceptions thrown, but continue', function() { var fakeTimer = new jasmine.FakeTimer(); env.setTimeout = fakeTimer.setTimeout; env.clearTimeout = fakeTimer.clearTimeout; env.setInterval = fakeTimer.setInterval; env.clearInterval = fakeTimer.clearInterval; //we run two exception tests to make sure we continue after throwing an exception var suite = env.describe('Suite for handles exceptions', function () { env.it('should be a test that fails because it throws an exception', function() { throw new Error('fake error 1'); }); env.it('should be another test that fails because it throws an exception', function() { this.runs(function () { throw new Error('fake error 2'); }); this.runs(function () { this.expect(true).toEqual(true); }); }); env.it('should be a passing test that runs after exceptions are thrown', function() { this.expect(true).toEqual(true); }); env.it('should be another test that fails because it throws an exception after a wait', function() { this.runs(function () { var foo = 'foo'; }); this.waits(250); this.runs(function () { throw new Error('fake error 3'); }); }); env.it('should be a passing test that runs after exceptions are thrown from a async test', function() { this.expect(true).toEqual(true); }); }); var runner = env.currentRunner(); suite.execute(); fakeTimer.tick(2500); var suiteResults = suite.results(); var specResults = suiteResults.getItems(); expect(suiteResults.passed()).toEqual(false); // expect(specResults.length).toEqual(5); expect(specResults[0].passed()).toMatch(false); var blockResults = specResults[0].getItems(); expect(blockResults[0].passed()).toEqual(false); expect(blockResults[0].message).toMatch(/fake error 1/); expect(specResults[1].passed()).toEqual(false); blockResults = specResults[1].getItems(); expect(blockResults[0].passed()).toEqual(false); expect(blockResults[0].message).toMatch(/fake error 2/); expect(blockResults[1].passed()).toEqual(true); expect(specResults[2].passed()).toEqual(true); expect(specResults[3].passed()).toEqual(false); blockResults = specResults[3].getItems(); expect(blockResults[0].message).toMatch(/fake error 3/); expect(specResults[4].passed()).toEqual(true); }); it("should handle exceptions thrown directly in top-level describe blocks and continue", function () { var suite = env.describe("a top level describe block that throws an exception", function () { env.it("is a test that should pass", function () { this.expect(true).toEqual(true); }); throw new Error("top level error"); }); suite.execute(); var suiteResults = suite.results(); var specResults = suiteResults.getItems(); expect(suiteResults.passed()).toEqual(false); expect(specResults.length).toEqual(2); expect(specResults[1].description).toMatch(/encountered a declaration exception/); }); it("should handle exceptions thrown directly in nested describe blocks and continue", function () { var suite = env.describe("a top level describe", function () { env.describe("a mid-level describe that throws an exception", function () { env.it("is a test that should pass", function () { this.expect(true).toEqual(true); }); throw new Error("a mid-level error"); }); }); suite.execute(); var suiteResults = suite.results(); var specResults = suiteResults.getItems(); expect(suiteResults.passed()).toEqual(false); expect(specResults.length).toEqual(1); var nestedSpecResults = specResults[0].getItems(); expect(nestedSpecResults.length).toEqual(2); expect(nestedSpecResults[1].description).toMatch(/encountered a declaration exception/); }); }); });
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("panel",function(e,t){var n=e.ClassNameManager.getClassName;e.Panel=e.Base.create("panel",e.Widget,[e.WidgetPosition,e.WidgetStdMod,e.WidgetAutohide,e.WidgetButtons,e.WidgetModality,e.WidgetPositionAlign,e.WidgetPositionConstrain,e.WidgetStack],{BUTTONS:{close:{label:"Close",action:"hide",section:"header",template:'<button type="button" />',classNames:n("button","close")}}},{ATTRS:{buttons:{value:["close"]}}})},"3.16.0",{requires:["widget","widget-autohide","widget-buttons","widget-modality","widget-position","widget-position-align","widget-position-constrain","widget-stack","widget-stdmod"],skinnable:!0});
"format global"; export var p = 'value';
/* svg.js v0.11-7-g7b0ba31 - svg regex default color viewbox bbox element container fx event group arrange defs mask clip pattern gradient doc shape rect ellipse line poly path plotable image text nested sugar - svgjs.com/license */ ;(function() { this.SVG = function(element) { if (SVG.supported) return new SVG.Doc(element) } // DEPRECATED!!! Use SVG() instead this.svg = function(element) { console.warn('WARNING: svg() is deprecated, please use SVG() instead.') return SVG(element) } // Default namespaces SVG.ns = 'http://www.w3.org/2000/svg' SVG.xlink = 'http://www.w3.org/1999/xlink' // Element id sequence SVG.did = 1000 // Get next named element id SVG.eid = function(name) { return 'Svgjs' + name.charAt(0).toUpperCase() + name.slice(1) + (SVG.did++) } // Method for element creation SVG.create = function(name) { /* create element */ var element = document.createElementNS(this.ns, name) /* apply unique id */ element.setAttribute('id', this.eid(name)) return element } // Method for extending objects SVG.extend = function() { var modules, methods, key, i /* get list of modules */ modules = [].slice.call(arguments) /* get object with extensions */ methods = modules.pop() for (i = modules.length - 1; i >= 0; i--) if (modules[i]) for (key in methods) modules[i].prototype[key] = methods[key] } // Method for getting an eleemnt by id SVG.get = function(id) { var node = document.getElementById(id) if (node) return node.instance } // svg support test SVG.supported = (function() { return !! document.createElementNS && !! document.createElementNS(SVG.ns,'svg').createSVGRect })() if (!SVG.supported) return false SVG.regex = { /* test a given value */ test: function(value, test) { return this[test].test(value) } /* parse unit value */ , unit: /^([\d\.]+)([a-z%]{0,2})$/ /* parse hex value */ , hex: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i /* parse rgb value */ , rgb: /rgb\((\d+),(\d+),(\d+),([\d\.]+)\)/ /* parse hsb value */ , hsb: /hsb\((\d+),(\d+),(\d+),([\d\.]+)\)/ /* test hex value */ , isHex: /^#[a-f0-9]{3,6}$/i /* test rgb value */ , isRgb: /^rgb\(/ /* test hsb value */ , isHsb: /^hsb\(/ /* test css declaration */ , isCss: /[^:]+:[^;]+;?/ /* test css property */ , isStyle: /^font|text|leading|cursor/ /* test for blank string */ , isBlank: /^(\s+)?$/ /* test for numeric string */ , isNumber: /^-?[\d\.]+$/ } SVG.default = { // Default matrix matrix: '1,0,0,1,0,0' // Default attribute values , attrs: { /* fill and stroke */ 'fill-opacity': 1 , 'stroke-opacity': 1 , 'stroke-width': 0 , fill: '#000' , stroke: '#000' , opacity: 1 /* position */ , x: 0 , y: 0 , cx: 0 , cy: 0 /* size */ , width: 0 , height: 0 /* radius */ , r: 0 , rx: 0 , ry: 0 /* gradient */ , offset: 0 } // Default transformation values , trans: function() { return { /* translate */ x: 0 , y: 0 /* scale */ , scaleX: 1 , scaleY: 1 /* rotate */ , rotation: 0 /* skew */ , skewX: 0 , skewY: 0 /* matrix */ , matrix: this.matrix , a: 1 , b: 0 , c: 0 , d: 1 , e: 0 , f: 0 } } } SVG.Color = function(color) { var match /* initialize defaults */ this.r = 0 this.g = 0 this.b = 0 /* parse color */ if (typeof color == 'string') { if (SVG.regex.isRgb.test(color)) { /* get rgb values */ match = SVG.regex.rgb.exec(color.replace(/\s/g,'')) /* parse numeric values */ this.r = parseInt(m[1]) this.g = parseInt(m[2]) this.b = parseInt(m[3]) } else if (SVG.regex.isHex.test(color)) { /* get hex values */ match = SVG.regex.hex.exec(this._fullHex(color)) /* parse numeric values */ this.r = parseInt(match[1], 16) this.g = parseInt(match[2], 16) this.b = parseInt(match[3], 16) } else if (SVG.regex.isHsb.test(color)) { /* get hsb values */ match = SVG.regex.hsb.exec(color.replace(/\s/g,'')) /* convert hsb to rgb */ color = this._hsbToRgb(match[1], match[2], match[3]) } } else if (typeof color == 'object') { if (SVG.Color.isHsb(color)) color = this._hsbToRgb(color.h, color.s, color.b) this.r = color.r this.g = color.g this.b = color.b } } SVG.extend(SVG.Color, { // Default to hex conversion toString: function() { return this.toHex() } // Build hex value , toHex: function() { return '#' + this._compToHex(this.r) + this._compToHex(this.g) + this._compToHex(this.b) } // Build rgb value , toRgb: function() { return 'rgb(' + [this.r, this.g, this.b].join() + ')' } // Calculate true brightness , brightness: function() { return (this.r / 255 * 0.30) + (this.g / 255 * 0.59) + (this.b / 255 * 0.11) } // Private: convert hsb to rgb , _hsbToRgb: function(h, s, v) { var vs, vsf /* process hue */ h = parseInt(h) % 360 if (h < 0) h += 360 /* process saturation */ s = parseInt(s) s = s > 100 ? 100 : s /* process brightness */ v = parseInt(v) v = (v < 0 ? 0 : v > 100 ? 100 : v) * 255 / 100 /* compile rgb */ vs = v * s / 100 vsf = (vs * ((h * 256 / 60) % 256)) / 256 switch (Math.floor(h / 60)) { case 0: r = v g = v - vs + vsf b = v - vs break case 1: r = v - vsf g = v b = v - vs break case 2: r = v - vs g = v b = v - vs + vsf break case 3: r = v - vs g = v - vsf b = v break case 4: r = v - vs + vsf g = v - vs b = v break case 5: r = v g = v - vs b = v - vsf break } /* parse values */ return { r: Math.floor(r + 0.5) , g: Math.floor(g + 0.5) , b: Math.floor(b + 0.5) } } // Private: ensure to six-based hex , _fullHex: function(hex) { return hex.length == 4 ? [ '#', hex.substring(1, 2), hex.substring(1, 2) , hex.substring(2, 3), hex.substring(2, 3) , hex.substring(3, 4), hex.substring(3, 4) ].join('') : hex } // Private: component to hex value , _compToHex: function(comp) { var hex = comp.toString(16) return hex.length == 1 ? '0' + hex : hex } }) // Test if given value is a color string SVG.Color.test = function(color) { color += '' return SVG.regex.isHex.test(color) || SVG.regex.isRgb.test(color) || SVG.regex.isHsb.test(color) } // Test if given value is a rgb object SVG.Color.isRgb = function(color) { return color && typeof color.r == 'number' } // Test if given value is a hsb object SVG.Color.isHsb = function(color) { return color && typeof color.h == 'number' } SVG.ViewBox = function(element) { var x, y, width, height , box = element.bbox() , view = (element.attr('viewBox') || '').match(/[\d\.]+/g) /* clone attributes */ this.x = box.x this.y = box.y this.width = element.node.offsetWidth || element.attr('width') this.height = element.node.offsetHeight || element.attr('height') if (view) { /* get width and height from viewbox */ x = parseFloat(view[0]) y = parseFloat(view[1]) width = parseFloat(view[2]) - x height = parseFloat(view[3]) - y /* calculate zoom accoring to viewbox */ this.zoom = ((this.width / this.height) > (width / height)) ? this.height / height : this.width / width /* calculate real pixel dimensions on parent SVG.Doc element */ this.x = x this.y = y this.width = width this.height = height } /* ensure a default zoom value */ this.zoom = this.zoom || 1 } SVG.extend(SVG.ViewBox, { // Parse viewbox to string toString: function() { return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height } }) SVG.BBox = function(element) { /* actual, native bounding box */ var box = element.node.getBBox() /* include translations on x an y */ this.x = box.x + element.trans.x this.y = box.y + element.trans.y /* plain width and height */ this.width = box.width * element.trans.scaleX this.height = box.height * element.trans.scaleY /* add the center */ this.cx = this.x + this.width / 2 this.cy = this.y + this.height / 2 } SVG.Element = function(node) { /* make stroke value accessible dynamically */ this._stroke = SVG.default.attrs.stroke /* initialize style store */ this.styles = {} /* initialize transformation store with defaults */ this.trans = SVG.default.trans() /* keep reference to the element node */ if (this.node = node) { this.type = node.nodeName this.node.instance = this } } // SVG.extend(SVG.Element, { // Move over x-axis x: function(x) { if (x) x /= this.trans.scaleX return this.attr('x', x) } // Move over y-axis , y: function(y) { if (y) y /= this.trans.scaleY return this.attr('y', y) } // Move by center over x-axis , cx: function(x) { return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2) } // Move by center over y-axis , cy: function(y) { return y == null ? this.bbox().cy : this.y(y - this.bbox().height / 2) } // Move element to given x and y values , move: function(x, y) { return this.x(x).y(y) } // Move element by its center , center: function(x, y) { return this.cx(x).cy(y) } // Set element size to given width and height , size: function(width, height) { return this.attr({ width: width , height: height }) } // Clone element , clone: function() { var clone , attr , type = this.type /* invoke shape method with shape-specific arguments */ clone = type == 'rect' || type == 'ellipse' ? this.parent[type](0,0) : type == 'line' ? this.parent[type](0,0,0,0) : type == 'image' ? this.parent[type](this.src) : type == 'text' ? this.parent[type](this.content) : type == 'path' ? this.parent[type](this.attr('d')) : type == 'polyline' || type == 'polygon' ? this.parent[type](this.attr('points')) : type == 'g' ? this.parent.group() : this.parent[type]() /* apply attributes attributes */ attr = this.attr() delete attr.id clone.attr(attr) /* copy transformations */ clone.trans = this.trans /* apply attributes and translations */ return clone.transform({}) } // Remove element , remove: function() { if (this.parent) this.parent.removeElement(this) return this } // Get parent document , doc: function(type) { return this._parent(type || SVG.Doc) } // Set svg element attribute , attr: function(a, v, n) { if (a == null) { /* get an object of attributes */ a = {} v = this.node.attributes for (n = v.length - 1; n >= 0; n--) a[v[n].nodeName] = v[n].nodeValue return a } else if (typeof a == 'object') { /* apply every attribute individually if an object is passed */ for (v in a) this.attr(v, a[v]) } else if (v === null) { /* remove value */ this.node.removeAttribute(a) } else if (v == null) { /* act as a getter for style attributes */ if (this._isStyle(a)) { return a == 'text' ? this.content : a == 'leading' ? this.leading() : this.style(a) /* act as a getter if the first and only argument is not an object */ } else { v = this.node.getAttribute(a) return v == null ? SVG.default.attrs[a] : SVG.regex.test(v, 'isNumber') ? parseFloat(v) : v } } else if (a == 'style') { /* redirect to the style method */ return this.style(v) } else { /* treat x differently on text elements */ if (a == 'x' && this instanceof SVG.Text) for (n = this.lines.length - 1; n >= 0; n--) this.lines[n].attr(a, v) /* BUG FIX: some browsers will render a stroke if a color is given even though stroke width is 0 */ if (a == 'stroke-width') this.attr('stroke', parseFloat(v) > 0 ? this._stroke : null) else if (a == 'stroke') this._stroke = v /* ensure hex color */ if (SVG.Color.test(v) || SVG.Color.isRgb(v) || SVG.Color.isHsb(v)) v = new SVG.Color(v).toHex() /* set give attribute on node */ n != null ? this.node.setAttributeNS(n, a, v) : this.node.setAttribute(a, v) /* if the passed argument belongs to the style as well, add it there */ if (this._isStyle(a)) { a == 'text' ? this.text(v) : a == 'leading' ? this.leading(v) : this.style(a, v) /* rebuild if required */ if (this.rebuild) this.rebuild() } } return this } // Manage transformations , transform: function(o, v) { if (typeof o === 'string') { /* act as a getter if only one string argument is given */ if (arguments.length < 2) return this.trans[o] /* apply transformations as object if key value arguments are given*/ var transform = {} transform[o] = v return this.transform(transform) } /* ... otherwise continue as a setter */ var transform = [] /* parse matrix */ o = this._parseMatrix(o) /* merge values */ for (v in o) if (o[v] != null) this.trans[v] = o[v] /* compile matrix */ this.trans.matrix = this.trans.a + ',' + this.trans.b + ',' + this.trans.c + ',' + this.trans.d + ',' + this.trans.e + ',' + this.trans.f /* alias current transformations */ o = this.trans /* add matrix */ if (o.matrix != SVG.default.matrix) transform.push('matrix(' + o.matrix + ')') /* add rotation */ if (o.rotation != 0) { transform.push( 'rotate(' + o.rotation + ',' + (o.cx != null ? o.cx : this.bbox().cx) + ',' + (o.cy != null ? o.cy : this.bbox().cy) + ')' ) } /* add scale */ if (o.scaleX != 1 || o.scaleY != 1) transform.push('scale(' + o.scaleX + ',' + o.scaleY + ')') /* add skew on x axis */ if (o.skewX != 0) transform.push('skewX(' + o.skewX + ')') /* add skew on y axis */ if (o.skewY != 0) transform.push('skewY(' + o.skewY + ')') /* add translation */ if (o.x != 0 || o.y != 0) transform.push('translate(' + o.x / o.scaleX + ',' + o.y / o.scaleY + ')') /* add offset translation */ if (this._offset) transform.push('translate(' + (-this._offset.x) + ',' + (-this._offset.y) + ')') /* add only te required transformations */ if (transform.length > 0) this.node.setAttribute('transform', transform.join(' ')) return this } // Dynamic style generator , style: function(s, v) { if (arguments.length == 0) { /* get full style */ return this.attr('style') || '' } else if (arguments.length < 2) { /* apply every style individually if an object is passed */ if (typeof s == 'object') { for (v in s) this.style(v, s[v]) } else if (SVG.regex.isCss.test(s)) { /* parse css string */ s = s.split(';') /* apply every definition individually */ for (var i = 0; i < s.length; i++) { v = s[i].split(':') if (v.length == 2) this.style(v[0].replace(/\s+/g, ''), v[1].replace(/^\s+/,'').replace(/\s+$/,'')) } } else { /* act as a getter if the first and only argument is not an object */ return this.styles[s] } } else if (v === null || SVG.regex.test(v, 'isBlank')) { /* remove value */ delete this.styles[s] } else { /* store value */ this.styles[s] = v } /* rebuild style string */ s = '' for (v in this.styles) s += v + ':' + this.styles[v] + ';' /* apply style */ this.node.setAttribute('style', s) return this } // Store data values on svg nodes , data: function(a, v, r) { if (arguments.length < 2) { try { return JSON.parse(this.attr('data-' + a)) } catch(e) { return this.attr('data-' + a) } } else { this.attr('data-' + a, v === null ? null : r === true ? v : JSON.stringify(v)) } return this } // Get bounding box , bbox: function() { return new SVG.BBox(this) } // Checks whether the given point inside the bounding box of the element , inside: function(x, y) { var box = this.bbox() return x > box.x && y > box.y && x < box.x + box.width && y < box.y + box.height } // Show element , show: function() { return this.style('display', '') } // Hide element , hide: function() { return this.style('display', 'none') } // Is element visible? , visible: function() { return this.style('display') != 'none' } // Private: find svg parent by instance , _parent: function(parent) { var element = this while (element != null && !(element instanceof parent)) element = element.parent return element } // Private: tester method for style detection , _isStyle: function(a) { return typeof a == 'string' ? SVG.regex.test(a, 'isStyle') : false } // Private: parse a matrix string , _parseMatrix: function(o) { if (o.matrix) { /* split matrix string */ var m = o.matrix.replace(/\s/g, '').split(',') /* pasrse values */ if (m.length == 6) { o.a = parseFloat(m[0]) o.b = parseFloat(m[1]) o.c = parseFloat(m[2]) o.d = parseFloat(m[3]) o.e = parseFloat(m[4]) o.f = parseFloat(m[5]) } } return o } }) SVG.Container = function(element) { this.constructor.call(this, element) } // Inherit from SVG.Element SVG.Container.prototype = new SVG.Element // SVG.extend(SVG.Container, { // Returns all child elements children: function() { return this._children || (this._children = []) } // Add given element at a position , add: function(element, i) { if (!this.has(element)) { /* define insertion index if none given */ i = i == null ? this.children().length : i /* remove references from previous parent */ if (element.parent) { var index = element.parent.children().indexOf(element) element.parent.children().splice(index, 1) } /* add element references */ this.children().splice(i, 0, element) this.node.insertBefore(element.node, this.node.childNodes[i] || null) element.parent = this } return this } // Basically does the same as `add()` but returns the added element instead , put: function(element, i) { this.add(element, i) return element } // Checks if the given element is a child , has: function(element) { return this.children().indexOf(element) >= 0 } // Iterates over all children and invokes a given block , each: function(block) { var index, children = this.children() for (index = 0, length = children.length; index < length; index++) if (children[index] instanceof SVG.Shape) block.apply(children[index], [index, children]) return this } // Remove a child element at a position , removeElement: function(element) { var i = this.children().indexOf(element) this.children().splice(i, 1) this.node.removeChild(element.node) element.parent = null return this } // Returns defs element , defs: function() { return this._defs || (this._defs = this.put(new SVG.Defs, 0)) } // Re-level defs to first positon in element stack , level: function() { return this.removeElement(this.defs()).put(this.defs(), 0) } // Create a group element , group: function() { return this.put(new SVG.G) } // Create a rect element , rect: function(width, height) { return this.put(new SVG.Rect().size(width, height)) } // Create circle element, based on ellipse , circle: function(size) { return this.ellipse(size, size) } // Create an ellipse , ellipse: function(width, height) { return this.put(new SVG.Ellipse().size(width, height).move(0, 0)) } // Create a line element , line: function(x1, y1, x2, y2) { return this.put(new SVG.Line().plot(x1, y1, x2, y2)) } // Create a wrapped polyline element , polyline: function(points, unbiased) { return this.put(new SVG.Polyline(unbiased)).plot(points) } // Create a wrapped polygon element , polygon: function(points, unbiased) { return this.put(new SVG.Polygon(unbiased)).plot(points) } // Create a wrapped path element , path: function(data, unbiased) { return this.put(new SVG.Path(unbiased)).plot(data) } // Create image element, load image and set its size , image: function(source, width, height) { width = width != null ? width : 100 return this.put(new SVG.Image().load(source).size(width, height != null ? height : width)) } // Create text element , text: function(text) { return this.put(new SVG.Text().text(text)) } // Create nested svg document , nested: function() { return this.put(new SVG.Nested) } // Create gradient element in defs , gradient: function(type, block) { return this.defs().gradient(type, block) } // Create pattern element in defs , pattern: function(width, height, block) { return this.defs().pattern(width, height, block) } // Create masking element , mask: function() { return this.defs().put(new SVG.Mask) } // Create clipping element , clip: function() { return this.defs().put(new SVG.Clip) } // Get first child, skipping the defs node , first: function() { return this.children()[0] instanceof SVG.Defs ? this.children()[1] : this.children()[0] } // Get the last child , last: function() { return this.children()[this.children().length - 1] } // Get the viewBox and calculate the zoom value , viewbox: function(v) { if (arguments.length == 0) /* act as a getter if there are no arguments */ return new SVG.ViewBox(this) /* otherwise act as a setter */ v = arguments.length == 1 ? [v.x, v.y, v.width, v.height] : [].slice.call(arguments) return this.attr('viewBox', v.join(' ')) } // Remove all elements in this container , clear: function() { /* remove children */ for (var i = this.children().length - 1; i >= 0; i--) this.removeElement(this.children()[i]) /* create new defs node */ this.defs() return this } }) SVG.FX = function(element) { /* store target element */ this.target = element } // SVG.extend(SVG.FX, { // Add animation parameters and start animation animate: function(d, ease, delay) { var fx = this /* dissect object if one is passed */ if (typeof d == 'object') { delay = d.delay ease = d.ease d = d.duration } /* delay animation */ this.timeout = setTimeout(function() { /* ensure default duration and easing */ d = d == null ? 1000 : d ease = ease || '<>' var akeys, tkeys, skeys , interval = 1000 / 60 , element = fx.target , start = new Date().getTime() , finish = start + d /* start animation */ fx.interval = setInterval(function(){ // This code was borrowed from the emile.js micro framework by Thomas Fuchs, aka MadRobby. var i, key , time = new Date().getTime() , pos = time > finish ? 1 : (time - start) / d /* collect attribute keys */ if (akeys == null) { akeys = [] for (key in fx.attrs) akeys.push(key) } /* collect transformation keys */ if (tkeys == null) { tkeys = [] for (key in fx.trans) tkeys.push(key) } /* collect style keys */ if (skeys == null) { skeys = [] for (key in fx.styles) skeys.push(key) } /* apply easing */ pos = ease == '<>' ? (-Math.cos(pos * Math.PI) / 2) + 0.5 : ease == '>' ? Math.sin(pos * Math.PI / 2) : ease == '<' ? -Math.cos(pos * Math.PI / 2) + 1 : ease == '-' ? pos : typeof ease == 'function' ? ease(pos) : pos /* run all x-position properties */ if (fx._x) element.x(fx._at(fx._x, pos)) else if (fx._cx) element.cx(fx._at(fx._cx, pos)) /* run all y-position properties */ if (fx._y) element.y(fx._at(fx._y, pos)) else if (fx._cy) element.cy(fx._at(fx._cy, pos)) /* run all size properties */ if (fx._size) element.size(fx._at(fx._size.width, pos), fx._at(fx._size.height, pos)) /* run all viewbox properties */ if (fx._viewbox) element.viewbox( fx._at(fx._viewbox.x, pos) , fx._at(fx._viewbox.y, pos) , fx._at(fx._viewbox.width, pos) , fx._at(fx._viewbox.height, pos) ) /* animate attributes */ for (i = akeys.length - 1; i >= 0; i--) element.attr(akeys[i], fx._at(fx.attrs[akeys[i]], pos)) /* animate transformations */ for (i = tkeys.length - 1; i >= 0; i--) element.transform(tkeys[i], fx._at(fx.trans[tkeys[i]], pos)) /* animate styles */ for (i = skeys.length - 1; i >= 0; i--) element.style(skeys[i], fx._at(fx.styles[skeys[i]], pos)) /* callback for each keyframe */ if (fx._during) fx._during.call(element, pos, function(from, to) { return fx._at({ from: from, to: to }, pos) }) /* finish off animation */ if (time > finish) { clearInterval(fx.interval) fx._after ? fx._after.apply(element, [fx]) : fx.stop() } }, d > interval ? interval : d) }, delay || 0) return this } // Get bounding box of target element , bbox: function() { return this.target.bbox() } // Add animatable attributes , attr: function(a, v, n) { if (typeof a == 'object') for (var key in a) this.attr(key, a[key]) else this.attrs[a] = { from: this.target.attr(a), to: v } return this } // Add animatable transformations , transform: function(o, v) { if (arguments.length == 1) { /* parse matrix string */ o = this.target._parseMatrix(o) /* dlete matrixstring from object */ delete o.matrix /* store matrix values */ for (v in o) this.trans[v] = { from: this.target.trans[v], to: o[v] } } else { /* apply transformations as object if key value arguments are given*/ var transform = {} transform[o] = v this.transform(transform) } return this } // Add animatable styles , style: function(s, v) { if (typeof s == 'object') for (var key in s) this.style(key, s[key]) else this.styles[s] = { from: this.target.style(s), to: v } return this } // Animatable x-axis , x: function(x) { this._x = { from: this.target.x(), to: x } return this } // Animatable y-axis , y: function(y) { this._y = { from: this.target.y(), to: y } return this } // Animatable center x-axis , cx: function(x) { this._cx = { from: this.target.cx(), to: x } return this } // Animatable center y-axis , cy: function(y) { this._cy = { from: this.target.cy(), to: y } return this } // Add animatable move , move: function(x, y) { return this.x(x).y(y) } // Add animatable center , center: function(x, y) { return this.cx(x).cy(y) } // Add animatable size , size: function(width, height) { if (this.target instanceof SVG.Text) { /* animate font size for Text elements */ this.attr('font-size', width) } else { /* animate bbox based size for all other elements */ var box = this.target.bbox() this._size = { width: { from: box.width, to: width } , height: { from: box.height, to: height } } } return this } // Add animatable viewbox , viewbox: function(x, y, width, height) { if (this.target instanceof SVG.Container) { var box = this.target.viewbox() this._viewbox = { x: { from: box.x, to: x } , y: { from: box.y, to: y } , width: { from: box.width, to: width } , height: { from: box.height, to: height } } } return this } // Add callback for each keyframe , during: function(during) { this._during = during return this } // Callback after animation , after: function(after) { this._after = after return this } // Stop running animation , stop: function() { /* stop current animation */ clearTimeout(this.timeout) clearInterval(this.interval) /* reset storage for properties that need animation */ this.attrs = {} this.trans = {} this.styles = {} delete this._x delete this._y delete this._cx delete this._cy delete this._size delete this._after delete this._during delete this._viewbox return this } // Private: calculate position according to from and to , _at: function(o, pos) { /* number recalculation */ return typeof o.from == 'number' ? o.from + (o.to - o.from) * pos : /* unit recalculation */ SVG.regex.unit.test(o.to) ? this._unit(o, pos) : /* color recalculation */ o.to && (o.to.r || SVG.Color.test(o.to)) ? this._color(o, pos) : /* for all other values wait until pos has reached 1 to return the final value */ pos < 1 ? o.from : o.to } // Private: tween unit , _unit: function(o, pos) { var match, from /* convert FROM unit */ match = SVG.regex.unit.exec(o.from.toString()) from = parseFloat(match ? match[1] : 0) /* convert TO unit */ match = SVG.regex.unit.exec(o.to) return (from + (parseFloat(match[1]) - from) * pos) + match[2] } // Private: tween color , _color: function(o, pos) { var from, to /* normalise pos */ pos = pos < 0 ? 0 : pos > 1 ? 1 : pos /* convert FROM */ from = new SVG.Color(o.from) /* convert TO hex to rgb */ to = new SVG.Color(o.to) /* tween color and return hex */ return new SVG.Color({ r: ~~(from.r + (to.r - from.r) * pos) , g: ~~(from.g + (to.g - from.g) * pos) , b: ~~(from.b + (to.b - from.b) * pos) }).toHex() } }) // SVG.extend(SVG.Element, { // Get fx module or create a new one, then animate with given duration and ease animate: function(d, ease, delay) { return (this.fx || (this.fx = new SVG.FX(this))).stop().animate(d, ease, delay) }, // Stop current animation; this is an alias to the fx instance stop: function() { if (this.fx) this.fx.stop() return this } }) // Usage: // rect.animate(1500, '>').move(200, 300).after(function() { // this.fill({ color: '#f06' }) // }) ;[ 'click' , 'dblclick' , 'mousedown' , 'mouseup' , 'mouseover' , 'mouseout' , 'mousemove' , 'mouseenter' , 'mouseleave' , 'touchstart' , 'touchend' , 'touchmove' , 'touchcancel' ].forEach(function(event) { /* add event to SVG.Element */ SVG.Element.prototype[event] = function(f) { var self = this /* bind event to element rather than element node */ this.node['on' + event] = typeof f == 'function' ? function() { return f.apply(self, arguments) } : null return this } }) // Add event binder in the SVG namespace SVG.on = function(node, event, listener) { if (node.addEventListener) node.addEventListener(event, listener, false) else node.attachEvent('on' + event, listener) } // Add event unbinder in the SVG namespace SVG.off = function(node, event, listener) { if (node.removeEventListener) node.removeEventListener(event, listener, false) else node.detachEvent('on' + event, listener) } // SVG.extend(SVG.Element, { // Bind given event to listener on: function(event, listener) { SVG.on(this.node, event, listener) return this } // Unbind event from listener , off: function(event, listener) { SVG.off(this.node, event, listener) return this } }) SVG.G = function() { this.constructor.call(this, SVG.create('g')) } // Inherit from SVG.Container SVG.G.prototype = new SVG.Container SVG.extend(SVG.G, { // Move over x-axis x: function(x) { return x == null ? this.trans.x : this.transform('x', x) } // Move over y-axis , y: function(y) { return y == null ? this.trans.y : this.transform('y', y) } // Get defs , defs: function() { return this.doc().defs() } }) SVG.extend(SVG.Element, { // Get all siblings, including myself siblings: function() { return this.parent.children() } // Get the curent position siblings , position: function() { return this.siblings().indexOf(this) } // Get the next element (will return null if there is none) , next: function() { return this.siblings()[this.position() + 1] } // Get the next element (will return null if there is none) , previous: function() { return this.siblings()[this.position() - 1] } // Send given element one step forward , forward: function() { return this.parent.removeElement(this).put(this, this.position() + 1) } // Send given element one step backward , backward: function() { this.parent.level() var i = this.position() if (i > 1) this.parent.removeElement(this).add(this, i - 1) return this } // Send given element all the way to the front , front: function() { return this.parent.removeElement(this).put(this) } // Send given element all the way to the back , back: function() { this.parent.level() if (this.position() > 1) this.parent.removeElement(this).add(this, 0) return this } }) SVG.Defs = function() { this.constructor.call(this, SVG.create('defs')) } // Inherits from SVG.Container SVG.Defs.prototype = new SVG.Container SVG.Mask = function() { this.constructor.call(this, SVG.create('mask')) } // Inherit from SVG.Container SVG.Mask.prototype = new SVG.Container SVG.extend(SVG.Element, { // Distribute mask to svg element maskWith: function(element) { /* use given mask or create a new one */ this.mask = element instanceof SVG.Mask ? element : this.parent.mask().add(element) return this.attr('mask', 'url(#' + this.mask.attr('id') + ')') } }) SVG.Clip = function() { this.constructor.call(this, SVG.create('clipPath')) } // Inherit from SVG.Container SVG.Clip.prototype = new SVG.Container SVG.extend(SVG.Element, { // Distribute clipPath to svg element clipWith: function(element) { /* use given clip or create a new one */ this.clip = element instanceof SVG.Clip ? element : this.parent.clip().add(element) return this.attr('clip-path', 'url(#' + this.clip.attr('id') + ')') } }) SVG.Pattern = function(type) { this.constructor.call(this, SVG.create('pattern')) } // Inherit from SVG.Container SVG.Pattern.prototype = new SVG.Container // SVG.extend(SVG.Pattern, { // Return the fill id fill: function() { return 'url(#' + this.attr('id') + ')' } }) // SVG.extend(SVG.Defs, { /* define gradient */ pattern: function(width, height, block) { var element = this.put(new SVG.Pattern()) /* invoke passed block */ block(element) return element.attr({ x: 0 , y: 0 , width: width , height: height , patternUnits: 'userSpaceOnUse' }) } }); SVG.Gradient = function(type) { this.constructor.call(this, SVG.create(type + 'Gradient')) /* store type */ this.type = type } // Inherit from SVG.Container SVG.Gradient.prototype = new SVG.Container // SVG.extend(SVG.Gradient, { // From position from: function(x, y) { return this.type == 'radial' ? this.attr({ fx: x + '%', fy: y + '%' }) : this.attr({ x1: x + '%', y1: y + '%' }) } // To position , to: function(x, y) { return this.type == 'radial' ? this.attr({ cx: x + '%', cy: y + '%' }) : this.attr({ x2: x + '%', y2: y + '%' }) } // Radius for radial gradient , radius: function(radius) { return this.type == 'radial' ? this.attr({ r: radius + '%' }) : this } // Add a color stop , at: function(stop) { return this.put(new SVG.Stop(stop)) } // Update gradient , update: function(block) { /* remove all stops */ while (this.node.hasChildNodes()) this.node.removeChild(this.node.lastChild) /* invoke passed block */ block(this) return this } // Return the fill id , fill: function() { return 'url(#' + this.attr('id') + ')' } }) // SVG.extend(SVG.Defs, { // define gradient gradient: function(type, block) { var element = this.put(new SVG.Gradient(type)) /* invoke passed block */ block(element) return element } }) SVG.Stop = function(stop) { this.constructor.call(this, SVG.create('stop')) /* immediatelly build stop */ this.update(stop) } // Inherit from SVG.Element SVG.Stop.prototype = new SVG.Element() // SVG.extend(SVG.Stop, { // add color stops update: function(o) { var index , attr = ['opacity', 'color'] /* build style attribute */ for (index = attr.length - 1; index >= 0; index--) if (o[attr[index]] != null) this.style('stop-' + attr[index], o[attr[index]]) /* set attributes */ return this.attr('offset', (o.offset != null ? o.offset : this.attr('offset')) + '%') } }) SVG.Doc = function(element) { this.constructor.call(this, SVG.create('svg')) /* ensure the presence of a html element */ this.parent = typeof element == 'string' ? document.getElementById(element) : element /* set svg element attributes and create the <defs> node */ this .attr({ xmlns: SVG.ns, version: '1.1', width: '100%', height: '100%' }) .attr('xlink', SVG.xlink, SVG.ns) .defs() /* ensure correct rendering for safari */ this.stage() } // Inherits from SVG.Container SVG.Doc.prototype = new SVG.Container // Hack for safari preventing text to be rendered in one line. // Basically it sets the position of the svg node to absolute // when the dom is loaded, and resets it to relative a few milliseconds later. SVG.Doc.prototype.stage = function() { var check , element = this , wrapper = document.createElement('div') /* set temp wrapper to position relative */ wrapper.style.cssText = 'position:relative;height:100%;' /* put element into wrapper */ element.parent.appendChild(wrapper) wrapper.appendChild(element.node) /* check for dom:ready */ check = function() { if (document.readyState === 'complete') { element.style('position:absolute;') setTimeout(function() { /* set position back to relative */ element.style('position:relative;') /* remove temp wrapper */ element.parent.removeChild(element.node.parentNode) element.node.parentNode.removeChild(element.node) element.parent.appendChild(element.node) }, 5) } else { setTimeout(check, 10) } } check() return this } SVG.Shape = function(element) { this.constructor.call(this, element) } // Inherit from SVG.Element SVG.Shape.prototype = new SVG.Element SVG.Rect = function() { this.constructor.call(this, SVG.create('rect')) } // Inherit from SVG.Shape SVG.Rect.prototype = new SVG.Shape SVG.Ellipse = function() { this.constructor.call(this, SVG.create('ellipse')) } // Inherit from SVG.Shape SVG.Ellipse.prototype = new SVG.Shape // SVG.extend(SVG.Ellipse, { // Move over x-axis x: function(x) { return x == null ? this.cx() - this.attr('rx') : this.cx(x + this.attr('rx')) } // Move over y-axis , y: function(y) { return y == null ? this.cy() - this.attr('ry') : this.cy(y + this.attr('ry')) } // Move by center over x-axis , cx: function(x) { return x == null ? this.attr('cx') : this.attr('cx', x / this.trans.scaleX) } // Move by center over y-axis , cy: function(y) { return y == null ? this.attr('cy') : this.attr('cy', y / this.trans.scaleY) } // Custom size function , size: function(width, height) { return this.attr({ rx: width / 2, ry: height / 2 }) } }) // Usage: // draw.ellipse(200, 100) SVG.Line = function() { this.constructor.call(this, SVG.create('line')) } // Inherit from SVG.Shape SVG.Line.prototype = new SVG.Shape // Add required methods SVG.extend(SVG.Line, { // Move over x-axis x: function(x) { var b = this.bbox() return x == null ? b.x : this.attr({ x1: this.attr('x1') - b.x + x , x2: this.attr('x2') - b.x + x }) } // Move over y-axis , y: function(y) { var b = this.bbox() return y == null ? b.y : this.attr({ y1: this.attr('y1') - b.y + y , y2: this.attr('y2') - b.y + y }) } // Move by center over x-axis , cx: function(x) { var half = this.bbox().width / 2 return x == null ? this.x() + half : this.x(x - half) } // Move by center over y-axis , cy: function(y) { var half = this.bbox().height / 2 return y == null ? this.y() + half : this.y(y - half) } // Set line size by width and height , size: function(width, height) { var b = this.bbox() return this .attr(this.attr('x1') < this.attr('x2') ? 'x2' : 'x1', b.x + width) .attr(this.attr('y1') < this.attr('y2') ? 'y2' : 'y1', b.y + height) } // Set path data , plot: function(x1, y1, x2, y2) { return this.attr({ x1: x1 , y1: y1 , x2: x2 , y2: y2 }) } }) SVG.Polyline = function(unbiased) { this.constructor.call(this, SVG.create('polyline')) this.unbiased = unbiased } // Inherit from SVG.Shape SVG.Polyline.prototype = new SVG.Shape SVG.Polygon = function(unbiased) { this.constructor.call(this, SVG.create('polygon')) this.unbiased = unbiased } // Inherit from SVG.Shape SVG.Polygon.prototype = new SVG.Shape // Add polygon-specific functions SVG.extend(SVG.Polyline, SVG.Polygon, { // Private: Native plot _plot: function(p) { if (Array.isArray(p)) { var i, l, points = [] for (i = 0, l = p.length; i < l; i++) points.push(p[i].join(',')) p = points.length == 0 ? points.join(' ') : '0,0' } return this.attr('points', p || '0,0') } }) SVG.Path = function(unbiased) { this.constructor.call(this, SVG.create('path')) this.unbiased = unbiased } // Inherit from SVG.Shape SVG.Path.prototype = new SVG.Shape SVG.extend(SVG.Path, { // Private: Native plot _plot: function(data) { return this.attr('d', data || 'M0,0') } }) SVG.extend(SVG.Polyline, SVG.Polygon, SVG.Path, { // Move over x-axis x: function(x) { return x == null ? this.bbox().x : this.transform('x', x) } // Move over y-axis , y: function(y) { return y == null ? this.bbox().y : this.transform('y', y) } // Set the actual size in pixels , size: function(width, height) { var scale = width / this._offset.width return this.transform({ scaleX: scale , scaleY: height != null ? height / this._offset.height : scale }) } // Set path data , plot: function(data) { var x = this.trans.scaleX , y = this.trans.scaleY /* native plot */ this._plot(data) /* store offset */ this._offset = this.transform({ scaleX: 1, scaleY: 1 }).bbox() /* get and store the actual offset of the element */ if (this.unbiased) { this._offset.x = this._offset.y = 0 } else { this._offset.x -= this.trans.x this._offset.y -= this.trans.y } return this.transform({ scaleX: x, scaleY: y }) } }) SVG.Image = function() { this.constructor.call(this, SVG.create('image')) } // Inherit from SVG.Element SVG.Image.prototype = new SVG.Shape SVG.extend(SVG.Image, { // (re)load image load: function(url) { return (url ? this.attr('xlink:href', (this.src = url), SVG.xlink) : this) } }) var _styleAttr = ('size family weight stretch variant style').split(' ') SVG.Text = function() { this.constructor.call(this, SVG.create('text')) /* define default style */ this.styles = { 'font-size': 16 , 'font-family': 'Helvetica, Arial, sans-serif' , 'text-anchor': 'start' } this._leading = 1.2 } // Inherit from SVG.Element SVG.Text.prototype = new SVG.Shape SVG.extend(SVG.Text, { // Move over x-axis x: function(x, a) { /* act as getter */ if (x == null) return a ? this.attr('x') : this.bbox().x /* set x taking anchor in mind */ if (!a) { a = this.style('text-anchor') x = a == 'start' ? x : a == 'end' ? x + this.bbox().width : x + this.bbox().width / 2 } return this.attr('x', x) } // Move center over x-axis , cx: function(x, a) { return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2) } // Move center over y-axis , cy: function(y, a) { return y == null ? this.bbox().cy : this.y(a ? y : y - this.bbox().height / 2) } // Move element to given x and y values , move: function(x, y, a) { return this.x(x, a).y(y) } // Move element by its center , center: function(x, y, a) { return this.cx(x, a).cy(y, a) } // Set the text content , text: function(text) { /* act as getter */ if (text == null) return this.content /* remove existing lines */ this.clear() /* update the content */ this.content = SVG.regex.isBlank.test(text) ? 'text' : text var i, il , lines = text.split('\n') /* build new lines */ for (i = 0, il = lines.length; i < il; i++) this.tspan(lines[i]) return this.attr('textLength', 1).attr('textLength', null) } // Create a tspan , tspan: function(text) { var tspan = new SVG.TSpan().text(text) /* add new tspan */ this.node.appendChild(tspan.node) this.lines.push(tspan) return tspan.attr('style', this.style()) } // Set font size , size: function(size) { return this.attr('font-size', size) } // Set / get leading , leading: function(value) { /* act as getter */ if (value == null) return this._leading /* act as setter */ this._leading = value return this.rebuild() } // rebuild appearance type , rebuild: function() { var i, il , size = this.styles['font-size'] /* define position of all lines */ for (i = 0, il = this.lines.length; i < il; i++) this.lines[i].attr({ dy: size * this._leading - (i == 0 ? size * 0.276666666 : 0) , x: (this.attr('x') || 0) , style: this.style() }) return this } // Clear all lines , clear: function() { /* remove existing child nodes */ while (this.node.hasChildNodes()) this.node.removeChild(this.node.lastChild) this.lines = [] return this } }) // tspan class SVG.TSpan = function() { this.constructor.call(this, SVG.create('tspan')) } // Inherit from SVG.Shape SVG.TSpan.prototype = new SVG.Shape // Include the container object SVG.extend(SVG.TSpan, { // Set text content text: function(text) { this.node.appendChild(document.createTextNode(text)) return this } }) SVG.Nested = function() { this.constructor.call(this, SVG.create('svg')) this.style('overflow', 'visible') } // Inherit from SVG.Container SVG.Nested.prototype = new SVG.Container SVG._stroke = ['color', 'width', 'opacity', 'linecap', 'linejoin', 'miterlimit', 'dasharray', 'dashoffset'] SVG._fill = ['color', 'opacity', 'rule'] // Prepend correct color prefix var _colorPrefix = function(type, attr) { return attr == 'color' ? type : type + '-' + attr } /* Add sugar for fill and stroke */ ;['fill', 'stroke'].forEach(function(method) { var extension = {} extension[method] = function(o) { var indexOf if (typeof o == 'string' || SVG.Color.isRgb(o) || SVG.Color.isHsb(o)) this.attr(method, o) else /* set all attributes from _fillAttr and _strokeAttr list */ for (index = SVG['_' + method].length - 1; index >= 0; index--) if (o[SVG['_' + method][index]] != null) this.attr(_colorPrefix(method, SVG['_' + method][index]), o[SVG['_' + method][index]]) return this } SVG.extend(SVG.Shape, SVG.FX, extension) }) SVG.extend(SVG.Element, SVG.FX, { // Rotation rotate: function(deg, x, y) { return this.transform({ rotation: deg || 0 , cx: x , cy: y }) } // Skew , skew: function(x, y) { return this.transform({ skewX: x || 0 , skewY: y || 0 }) } // Scale , scale: function(x, y) { return this.transform({ scaleX: x, scaleY: y == null ? x : y }) } // Matrix , matrix: function(m) { return this.transform({ matrix: m }) } // Opacity , opacity: function(value) { return this.attr('opacity', value) } }) if (SVG.Text) { SVG.extend(SVG.Text, SVG.FX, { // Set font font: function(o) { for (var key in o) key == 'anchor' ? this.attr('text-anchor', o[key]) : _styleAttr.indexOf(key) > -1 ? this.attr('font-'+ key, o[key]) : this.attr(key, o[key]) return this } }) } }).call(this);
// oj.VimeoVideo.js ;(function(root, factory){ // Export to Node if (typeof module === 'object' && module.exports) module.exports = factory(root) // Export to RequireJS else if (typeof define === 'function' && define.amd) define(function(){return factory(root)}) // Export to OJ else factory(root, root.oj) }(this, function(root, oj){ // Froogaloop is the offical javascript api to Vimeo // https://github.com/vimeo/player-api/tree/master/javascript var Froogaloop=function(){function e(a){return new e.fn.init(a)}function h(a,c,b){if(!b.contentWindow.postMessage)return!1;var f=b.getAttribute("src").split("?")[0],a=JSON.stringify({method:a,value:c});"//"===f.substr(0,2)&&(f=window.location.protocol+f);b.contentWindow.postMessage(a,f)}function j(a){var c,b;try{c=JSON.parse(a.data),b=c.event||c.method}catch(f){}"ready"==b&&!i&&(i=!0);if(a.origin!=k)return!1;var a=c.value,e=c.data,g=""===g?null:c.player_id;c=g?d[g][b]:d[b];b=[];if(!c)return!1;void 0!== a&&b.push(a);e&&b.push(e);g&&b.push(g);return 0<b.length?c.apply(null,b):c.call()}function l(a,c,b){b?(d[b]||(d[b]={}),d[b][a]=c):d[a]=c}var d={},i=!1,k="";e.fn=e.prototype={element:null,init:function(a){"string"===typeof a&&(a=document.getElementById(a));this.element=a;a=this.element.getAttribute("src");"//"===a.substr(0,2)&&(a=window.location.protocol+a);for(var a=a.split("/"),c="",b=0,f=a.length;b<f;b++){if(3>b)c+=a[b];else break;2>b&&(c+="/")}k=c;return this},api:function(a,c){if(!this.element|| !a)return!1;var b=this.element,f=""!==b.id?b.id:null,d=!c||!c.constructor||!c.call||!c.apply?c:null,e=c&&c.constructor&&c.call&&c.apply?c:null;e&&l(a,e,f);h(a,d,b);return this},addEvent:function(a,c){if(!this.element)return!1;var b=this.element,d=""!==b.id?b.id:null;l(a,c,d);"ready"!=a?h("addEventListener",a,b):"ready"==a&&i&&c.call(null,d);return this},removeEvent:function(a){if(!this.element)return!1;var c=this.element,b;a:{if((b=""!==c.id?c.id:null)&&d[b]){if(!d[b][a]){b=!1;break a}d[b][a]=null}else{if(!d[a]){b= !1;break a}d[a]=null}b=!0}"ready"!=a&&b&&h("removeEventListener",a,c)}};e.fn.init.prototype=e.fn;window.addEventListener?window.addEventListener("message",j,!1):window.attachEvent("onmessage",j);return window.Froogaloop=e}(); // Create url from Vimeo options function vimeoUrl(video, options) { var out = 'http://player.vimeo.com/video/' + video + '?api=1&player_id=' + options.player_id; for(k in options) out += '&' + k + '=' + options[k]; return out; } var plugin = function(oj,settings){ if (typeof settings !== 'object') settings = {} var VimeoVideo = oj.createType('VimeoVideo', { // The model-key bind to the url of the movie base: oj.View, // VimeoVideo(videoID, properties) constructor: function(){ var this_ = this; var union = oj.unionArguments(arguments); var options = union.options; var args = union.args; // First argument is video id if(args.length > 0) this.video = args[0]; // Shift properties var props = [ 'width', 'height', 'video', 'showTitle', 'showByline', 'showPortrait', 'color', 'autoplay', 'loop' ]; for (var i = 0; i < props.length; i++) { var prop = props[i]; if (options[prop] != null) this[prop] = oj.argumentShift(options, prop); } this.el = oj(function(){ oj.iframe({ src: this_.src, width:this_.width, height:this_.height, frameborder:0, webkitAllowFullScreen:1, mozallowfullscreen:1, allowFullScreen:1, }); }); VimeoVideo.base.constructor.apply(this, [options]); // // // Bind events using javascript API // this.player = Froogaloop(this.el); // // // When the player is ready, add listeners for pause, finish, and playProgress // this.player.addEvent('ready', function() {}); // console.log("ready called"); // this_.player.addEvent('pause', function(){this_.onPause.apply(this_,arguments)}); // this_.player.addEvent('finish', function(){this_.onFinish.apply(this_,arguments)}); // this_.player.addEvent('playProgress', function(){this_.onPlayProgress.apply(this_,arguments)}); // }); // if (oj.isClient) { // console.log("starting: ", starting); // player.api('starting'); // } }, properties: { width: { get: function(){ return this._width || 300; }, set: function(v){ this._width = v; if (this.isConstructed) this.$el.attr('width', v); } }, height: { get: function(){ return this._height || 178; }, set: function(v){ this._height = v; if (this.isConstructed) this.$el.attr('height', v); } }, // The video id video: 24715531, // Show title (readwrite) showTitle: false, // Show the users byline on the video (readwrite) showByline: false, // Show the user's portrait on the video (readwrite) showPortrait: false, // Color of controls (readwrite) color: { get: function(){return this._color || '00adef';}, set: function(v){ // Remove prefix of '#' if(v.length > 0 && v[0] == '#') v = v.slice(1); this._color = v; } }, // Play the video automatically on load autoplay: false, // Repeat video when it reaches the end loop: false, src: { get: function(){ return vimeoUrl(this.video, this.videoOptions); } }, // Gather options to set url (readonly) videoOptions: { get: function(){ return { title: (this.showTitle ? 1 : 0), byline: (this.showByline ? 1 : 0), portrait: (this.showPortrait ? 1 : 0), color: this.color, autoplay: (this.autoplay ? 1 : 0), loop: (this.loop ? 1 : 0), player_id: (this.id ? 1 : 0) }; } } }, methods: { play: function(){ }, stop: function(){ }, rewind: function(){ }, onPause: function(id) { console.log('paused', id); }, onFinish: function(id) { console.log('finish', id); }, onPlayProgress: function(data, id) { console.log('playProgress: ', data, id); } } }); return {VimeoVideo:VimeoVideo}; }; // Export to OJ if (typeof oj != 'undefined') oj.use(plugin); return plugin; }));
var tap = require("tap") , minimatch = require("../") tap.test("brace expansion", function (t) { // [ pattern, [expanded] ] ; [ [ "a{b,c{d,e},{f,g}h}x{y,z}" , [ "abxy" , "abxz" , "acdxy" , "acdxz" , "acexy" , "acexz" , "afhxy" , "afhxz" , "aghxy" , "aghxz" ] ] , [ "a{1..5}b" , [ "a1b" , "a2b" , "a3b" , "a4b" , "a5b" ] ] , [ "a{b}c", ["a{b}c"] ] ].forEach(function (tc) { var p = tc[0] , expect = tc[1] t.equivalent(minimatch.braceExpand(p), expect, p) }) console.error("ending") t.end() })
YUI.add('model-list', function(Y) { /** The app framework provides simple MVC-like building blocks (models, model lists, views, and URL-based routing) for writing single-page JavaScript applications. @main app @module app @since 3.4.0 **/ /** Provides an API for managing an ordered list of Model instances. @submodule model-list @since 3.4.0 **/ /** Provides an API for managing an ordered list of Model instances. In addition to providing convenient `add`, `create`, `reset`, and `remove` methods for managing the models in the list, ModelLists are also bubble targets for events on the model instances they contain. This means, for example, that you can add several models to a list, and then subscribe to the `*:change` event on the list to be notified whenever any model in the list changes. ModelLists also maintain sort order efficiently as models are added and removed, based on a custom `comparator` function you may define (if no comparator is defined, models are sorted in insertion order). @class ModelList @extends Base @uses ArrayList @constructor @since 3.4.0 **/ var AttrProto = Y.Attribute.prototype, Lang = Y.Lang, YArray = Y.Array, /** Fired when a model is added to the list. Listen to the `on` phase of this event to be notified before a model is added to the list. Calling `e.preventDefault()` during the `on` phase will prevent the model from being added. Listen to the `after` phase of this event to be notified after a model has been added to the list. @event add @param {Model} model The model being added. @param {Number} index The index at which the model will be added. @preventable _defAddFn **/ EVT_ADD = 'add', /** Fired when an error occurs, such as when an attempt is made to add a duplicate model to the list, or when a sync layer response can't be parsed. @event error @param {Any} error Error message, object, or exception generated by the error. Calling `toString()` on this should result in a meaningful error message. @param {String} src Source of the error. May be one of the following (or any custom error source defined by a ModelList subclass): * `add`: Error while adding a model (probably because it's already in the list and can't be added again). The model in question will be provided as the `model` property on the event facade. * `parse`: An error parsing a JSON response. The response in question will be provided as the `response` property on the event facade. * `remove`: Error while removing a model (probably because it isn't in the list and can't be removed). The model in question will be provided as the `model` property on the event facade. **/ EVT_ERROR = 'error', /** Fired when the list is completely reset via the `reset()` method or sorted via the `sort()` method. Listen to the `on` phase of this event to be notified before the list is reset. Calling `e.preventDefault()` during the `on` phase will prevent the list from being reset. Listen to the `after` phase of this event to be notified after the list has been reset. @event reset @param {Model[]} models Array of the list's new models after the reset. @param {String} src Source of the event. May be either `'reset'` or `'sort'`. @preventable _defResetFn **/ EVT_RESET = 'reset', /** Fired when a model is removed from the list. Listen to the `on` phase of this event to be notified before a model is removed from the list. Calling `e.preventDefault()` during the `on` phase will prevent the model from being removed. Listen to the `after` phase of this event to be notified after a model has been removed from the list. @event remove @param {Model} model The model being removed. @param {int} index The index of the model being removed. @preventable _defRemoveFn **/ EVT_REMOVE = 'remove'; function ModelList() { ModelList.superclass.constructor.apply(this, arguments); } Y.ModelList = Y.extend(ModelList, Y.Base, { // -- Public Properties ---------------------------------------------------- /** The `Model` class or subclass of the models in this list. This property is `null` by default, and is intended to be overridden in a subclass or specified as a config property at instantiation time. It will be used to create model instances automatically based on attribute hashes passed to the `add()`, `create()`, and `reset()` methods. @property model @type Model @default `null` **/ model: null, // -- Lifecycle Methods ---------------------------------------------------- initializer: function (config) { config || (config = {}); var model = this.model = config.model || this.model; this.publish(EVT_ADD, {defaultFn: this._defAddFn}); this.publish(EVT_RESET, {defaultFn: this._defResetFn}); this.publish(EVT_REMOVE, {defaultFn: this._defRemoveFn}); if (model) { this.after('*:idChange', this._afterIdChange); } else { } this._clear(); }, destructor: function () { YArray.each(this._items, this._detachList, this); }, // -- Public Methods ------------------------------------------------------- /** Adds the specified model or array of models to this list. @example // Add a single model instance. list.add(new Model({foo: 'bar'})); // Add a single model, creating a new instance automatically. list.add({foo: 'bar'}); // Add multiple models, creating new instances automatically. list.add([ {foo: 'bar'}, {baz: 'quux'} ]); @method add @param {Model|Model[]|Object|Object[]} models Models to add. May be existing model instances or hashes of model attributes, in which case new model instances will be created from the hashes. @param {Object} [options] Data to be mixed into the event facade of the `add` event(s) for the added models. @param {Boolean} [options.silent=false] If `true`, no `add` event(s) will be fired. @return {Model|Model[]} Added model or array of added models. **/ add: function (models, options) { if (Lang.isArray(models)) { return YArray.map(models, function (model) { return this._add(model, options); }, this); } else { return this._add(models, options); } }, /** Define this method to provide a function that takes a model as a parameter and returns a value by which that model should be sorted relative to other models in this list. By default, no comparator is defined, meaning that models will not be sorted (they'll be stored in the order they're added). @example var list = new Y.ModelList({model: Y.Model}); list.comparator = function (model) { return model.get('id'); // Sort models by id. }; @method comparator @param {Model} model Model being sorted. @return {Number|String} Value by which the model should be sorted relative to other models in this list. **/ // comparator is not defined by default /** Creates or updates the specified model on the server, then adds it to this list if the server indicates success. @method create @param {Model|Object} model Model to create. May be an existing model instance or a hash of model attributes, in which case a new model instance will be created from the hash. @param {Object} [options] Options to be passed to the model's `sync()` and `set()` methods and mixed into the `add` event when the model is added to the list. @param {Boolean} [options.silent=false] If `true`, no `add` event(s) will be fired. @param {Function} [callback] Called when the sync operation finishes. @param {Error} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsy. @param {Any} callback.response The server's response. @return {Model} Created model. **/ create: function (model, options, callback) { var self = this; // Allow callback as second arg. if (typeof options === 'function') { callback = options; options = {}; } if (!(model instanceof Y.Model)) { model = new this.model(model); } return model.save(options, function (err) { if (!err) { self.add(model, options); } callback && callback.apply(null, arguments); }); }, /** Executes the supplied function on each model in this list. Returns an array containing the models for which the supplied function returned a truthy value. @example // Get an array containing only the models whose "enabled" attribute is // truthy. var filtered = list.filter(function (model) { return model.get('enabled'); }); @method filter @param {Function} callback Function to execute on each model. @param {Model} callback.model Model instance. @param {Number} callback.index Index of the current model. @param {ModelList} callback.list The ModelList being filtered. @param {Object} [thisObj] Optional `this` object (defaults to this ModelList instance). @return {Array} Array of models for which the callback function returned a truthy value (empty if it never returned a truthy value). @since 3.5.0 */ filter: function (callback, thisObj) { var filtered = [], items = this._items, i, item, len; thisObj || (thisObj = this); for (i = 0, len = items.length; i < len; ++i) { item = items[i]; if (callback.call(thisObj, item, i, this)) { filtered.push(item); } } return filtered; }, /** If _name_ refers to an attribute on this ModelList instance, returns the value of that attribute. Otherwise, returns an array containing the values of the specified attribute from each model in this list. @method get @param {String} name Attribute name or object property path. @return {Any|Array} Attribute value or array of attribute values. @see Model.get() **/ get: function (name) { if (this.attrAdded(name)) { return AttrProto.get.apply(this, arguments); } return this.invoke('get', name); }, /** If _name_ refers to an attribute on this ModelList instance, returns the HTML-escaped value of that attribute. Otherwise, returns an array containing the HTML-escaped values of the specified attribute from each model in this list. The values are escaped using `Escape.html()`. @method getAsHTML @param {String} name Attribute name or object property path. @return {String|String[]} HTML-escaped value or array of HTML-escaped values. @see Model.getAsHTML() **/ getAsHTML: function (name) { if (this.attrAdded(name)) { return Y.Escape.html(AttrProto.get.apply(this, arguments)); } return this.invoke('getAsHTML', name); }, /** If _name_ refers to an attribute on this ModelList instance, returns the URL-encoded value of that attribute. Otherwise, returns an array containing the URL-encoded values of the specified attribute from each model in this list. The values are encoded using the native `encodeURIComponent()` function. @method getAsURL @param {String} name Attribute name or object property path. @return {String|String[]} URL-encoded value or array of URL-encoded values. @see Model.getAsURL() **/ getAsURL: function (name) { if (this.attrAdded(name)) { return encodeURIComponent(AttrProto.get.apply(this, arguments)); } return this.invoke('getAsURL', name); }, /** Returns the model with the specified _clientId_, or `null` if not found. @method getByClientId @param {String} clientId Client id. @return {Model} Model, or `null` if not found. **/ getByClientId: function (clientId) { return this._clientIdMap[clientId] || null; }, /** Returns the model with the specified _id_, or `null` if not found. Note that models aren't expected to have an id until they're saved, so if you're working with unsaved models, it may be safer to call `getByClientId()`. @method getById @param {String|Number} id Model id. @return {Model} Model, or `null` if not found. **/ getById: function (id) { return this._idMap[id] || null; }, /** Calls the named method on every model in the list. Any arguments provided after _name_ will be passed on to the invoked method. @method invoke @param {String} name Name of the method to call on each model. @param {Any} [args*] Zero or more arguments to pass to the invoked method. @return {Array} Array of return values, indexed according to the index of the model on which the method was called. **/ invoke: function (name /*, args* */) { var args = [this._items, name].concat(YArray(arguments, 1, true)); return YArray.invoke.apply(YArray, args); }, /** Returns the model at the specified _index_. @method item @param {Number} index Index of the model to fetch. @return {Model} The model at the specified index, or `undefined` if there isn't a model there. **/ // item() is inherited from ArrayList. /** Loads this list of models from the server. This method delegates to the `sync()` method to perform the actual load operation, which is an asynchronous action. Specify a _callback_ function to be notified of success or failure. If the load operation succeeds, a `reset` event will be fired. @method load @param {Object} [options] Options to be passed to `sync()` and to `reset()` when adding the loaded models. It's up to the custom sync implementation to determine what options it supports or requires, if any. @param {Function} [callback] Called when the sync operation finishes. @param {Error} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsy. @param {Any} callback.response The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an array of model attribute hashes. @chainable **/ load: function (options, callback) { var self = this; // Allow callback as only arg. if (typeof options === 'function') { callback = options; options = {}; } this.sync('read', options, function (err, response) { if (!err) { self.reset(self.parse(response), options); } callback && callback.apply(null, arguments); }); return this; }, /** Executes the specified function on each model in this list and returns an array of the function's collected return values. @method map @param {Function} fn Function to execute on each model. @param {Model} fn.model Current model being iterated. @param {Number} fn.index Index of the current model in the list. @param {Model[]} fn.models Array of models being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Array} Array of return values from _fn_. **/ map: function (fn, thisObj) { return YArray.map(this._items, fn, thisObj); }, /** Called to parse the _response_ when the list is loaded from the server. This method receives a server _response_ and is expected to return an array of model attribute hashes. The default implementation assumes that _response_ is either an array of attribute hashes or a JSON string that can be parsed into an array of attribute hashes. If _response_ is a JSON string and either `Y.JSON` or the native `JSON` object are available, it will be parsed automatically. If a parse error occurs, an `error` event will be fired and the model will not be updated. You may override this method to implement custom parsing logic if necessary. @method parse @param {Any} response Server response. @return {Object[]} Array of model attribute hashes. **/ parse: function (response) { if (typeof response === 'string') { try { return Y.JSON.parse(response) || []; } catch (ex) { this.fire(EVT_ERROR, { error : ex, response: response, src : 'parse' }); return null; } } return response || []; }, /** Removes the specified model or array of models from this list. @method remove @param {Model|Model[]} models Models to remove. @param {Object} [options] Data to be mixed into the event facade of the `remove` event(s) for the removed models. @param {Boolean} [options.silent=false] If `true`, no `remove` event(s) will be fired. @return {Model|Model[]} Removed model or array of removed models. **/ remove: function (models, options) { if (Lang.isArray(models)) { return YArray.map(models, function (model) { return this._remove(model, options); }, this); } else { return this._remove(models, options); } }, /** Completely replaces all models in the list with those specified, and fires a single `reset` event. Use `reset` when you want to add or remove a large number of items at once without firing `add` or `remove` events for each one. @method reset @param {Model[]|Object[]} [models] Models to add. May be existing model instances or hashes of model attributes, in which case new model instances will be created from the hashes. Calling `reset()` without passing in any models will clear the list. @param {Object} [options] Data to be mixed into the event facade of the `reset` event. @param {Boolean} [options.silent=false] If `true`, no `reset` event will be fired. @chainable **/ reset: function (models, options) { models || (models = []); options || (options = {}); var facade = Y.merge(options, { src : 'reset', models: YArray.map(models, function (model) { return model instanceof Y.Model ? model : new this.model(model); }, this) }); // Sort the models in the facade before firing the reset event. if (this.comparator) { facade.models.sort(Y.bind(this._sort, this)); } options.silent ? this._defResetFn(facade) : this.fire(EVT_RESET, facade); return this; }, /** Forcibly re-sorts the list. Usually it shouldn't be necessary to call this method since the list maintains its sort order when items are added and removed, but if you change the `comparator` function after items are already in the list, you'll need to re-sort. @method sort @param {Object} [options] Data to be mixed into the event facade of the `reset` event. @param {Boolean} [options.silent=false] If `true`, no `reset` event will be fired. @chainable **/ sort: function (options) { var models = this._items.concat(), facade; if (!this.comparator) { return this; } options || (options = {}); models.sort(Y.bind(this._sort, this)); facade = Y.merge(options, { models: models, src : 'sort' }); options.silent ? this._defResetFn(facade) : this.fire(EVT_RESET, facade); return this; }, /** Override this method to provide a custom persistence implementation for this list. The default method just calls the callback without actually doing anything. This method is called internally by `load()`. @method sync @param {String} action Sync action to perform. May be one of the following: * `create`: Store a list of newly-created models for the first time. * `delete`: Delete a list of existing models. * `read` : Load a list of existing models. * `update`: Update a list of existing models. Currently, model lists only make use of the `read` action, but other actions may be used in future versions. @param {Object} [options] Sync options. It's up to the custom sync implementation to determine what options it supports or requires, if any. @param {Function} [callback] Called when the sync operation finishes. @param {Error} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsy. @param {Any} [callback.response] The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an array of model attribute hashes. **/ sync: function (/* action, options, callback */) { var callback = YArray(arguments, 0, true).pop(); if (typeof callback === 'function') { callback(); } }, /** Returns an array containing the models in this list. @method toArray @return {Array} Array containing the models in this list. **/ toArray: function () { return this._items.concat(); }, /** Returns an array containing attribute hashes for each model in this list, suitable for being passed to `Y.JSON.stringify()`. Under the hood, this method calls `toJSON()` on each model in the list and pushes the results into an array. @method toJSON @return {Object[]} Array of model attribute hashes. @see Model.toJSON() **/ toJSON: function () { return this.map(function (model) { return model.toJSON(); }); }, // -- Protected Methods ---------------------------------------------------- /** Adds the specified _model_ if it isn't already in this list. @method _add @param {Model|Object} model Model or object to add. @param {Object} [options] Data to be mixed into the event facade of the `add` event for the added model. @param {Boolean} [options.silent=false] If `true`, no `add` event will be fired. @return {Model} The added model. @protected **/ _add: function (model, options) { var facade; options || (options = {}); if (!(model instanceof Y.Model)) { model = new this.model(model); } if (this._clientIdMap[model.get('clientId')]) { this.fire(EVT_ERROR, { error: 'Model is already in the list.', model: model, src : 'add' }); return; } facade = Y.merge(options, { index: this._findIndex(model), model: model }); options.silent ? this._defAddFn(facade) : this.fire(EVT_ADD, facade); return model; }, /** Adds this list as a bubble target for the specified model's events. @method _attachList @param {Model} model Model to attach to this list. @protected **/ _attachList: function (model) { // Attach this list and make it a bubble target for the model. model.lists.push(this); model.addTarget(this); }, /** Clears all internal state and the internal list of models, returning this list to an empty state. Automatically detaches all models in the list. @method _clear @protected **/ _clear: function () { YArray.each(this._items, this._detachList, this); this._clientIdMap = {}; this._idMap = {}; this._items = []; }, /** Removes this list as a bubble target for the specified model's events. @method _detachList @param {Model} model Model to detach. @protected **/ _detachList: function (model) { var index = YArray.indexOf(model.lists, this); if (index > -1) { model.lists.splice(index, 1); model.removeTarget(this); } }, /** Returns the index at which the given _model_ should be inserted to maintain the sort order of the list. @method _findIndex @param {Model} model The model being inserted. @return {Number} Index at which the model should be inserted. @protected **/ _findIndex: function (model) { var comparator = this.comparator, items = this._items, max = items.length, min = 0, item, middle, needle; if (!comparator || !items.length) { return items.length; } needle = comparator(model); // Perform an iterative binary search to determine the correct position // based on the return value of the `comparator` function. while (min < max) { middle = (min + max) >> 1; // Divide by two and discard remainder. item = items[middle]; if (comparator(item) < needle) { min = middle + 1; } else { max = middle; } } return min; }, /** Removes the specified _model_ if it's in this list. @method _remove @param {Model} model Model to remove. @param {Object} [options] Data to be mixed into the event facade of the `remove` event for the removed model. @param {Boolean} [options.silent=false] If `true`, no `remove` event will be fired. @return {Model} Removed model. @protected **/ _remove: function (model, options) { var index = this.indexOf(model), facade; options || (options = {}); if (index === -1) { this.fire(EVT_ERROR, { error: 'Model is not in the list.', model: model, src : 'remove' }); return; } facade = Y.merge(options, { index: index, model: model }); options.silent ? this._defRemoveFn(facade) : this.fire(EVT_REMOVE, facade); return model; }, /** Array sort function used by `sort()` to re-sort the models in the list. @method _sort @param {Model} a First model to compare. @param {Model} b Second model to compare. @return {Number} `-1` if _a_ is less than _b_, `0` if equal, `1` if greater. @protected **/ _sort: function (a, b) { var aValue = this.comparator(a), bValue = this.comparator(b); return aValue < bValue ? -1 : (aValue > bValue ? 1 : 0); }, // -- Event Handlers ------------------------------------------------------- /** Updates the model maps when a model's `id` attribute changes. @method _afterIdChange @param {EventFacade} e @protected **/ _afterIdChange: function (e) { Lang.isValue(e.prevVal) && delete this._idMap[e.prevVal]; Lang.isValue(e.newVal) && (this._idMap[e.newVal] = e.target); }, // -- Default Event Handlers ----------------------------------------------- /** Default event handler for `add` events. @method _defAddFn @param {EventFacade} e @protected **/ _defAddFn: function (e) { var model = e.model, id = model.get('id'); this._clientIdMap[model.get('clientId')] = model; if (Lang.isValue(id)) { this._idMap[id] = model; } this._attachList(model); this._items.splice(e.index, 0, model); }, /** Default event handler for `remove` events. @method _defRemoveFn @param {EventFacade} e @protected **/ _defRemoveFn: function (e) { var model = e.model, id = model.get('id'); this._detachList(model); delete this._clientIdMap[model.get('clientId')]; if (Lang.isValue(id)) { delete this._idMap[id]; } this._items.splice(e.index, 1); }, /** Default event handler for `reset` events. @method _defResetFn @param {EventFacade} e @protected **/ _defResetFn: function (e) { // When fired from the `sort` method, we don't need to clear the list or // add any models, since the existing models are sorted in place. if (e.src === 'sort') { this._items = e.models.concat(); return; } this._clear(); if (e.models.length) { this.add(e.models, {silent: true}); } } }, { NAME: 'modelList' }); Y.augment(ModelList, Y.ArrayList); }, '@VERSION@' ,{requires:['array-extras', 'array-invoke', 'arraylist', 'base-build', 'escape', 'json-parse', 'model']});
dirty document
(function() { var extend, __slice = [].slice, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; extend = function() { var args, key, object, replacement, result, value, _i, _len, _ref; object = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; result = object || {}; for (_i = 0, _len = args.length; _i < _len; _i++) { replacement = args[_i]; _ref = replacement || {}; for (key in _ref) { value = _ref[key]; if (typeof result[key] === "object") { result[key] = extend(result[key], value); } else { result[key] || (result[key] = value); } } } return result; }; this.WOW = (function() { WOW.prototype.defaults = { boxClass: 'wow', animateClass: 'animated', offset: 0 }; function WOW(options) { if (options == null) { options = {}; } this.scrollCallback = __bind(this.scrollCallback, this); this.scrollHandler = __bind(this.scrollHandler, this); this.start = __bind(this.start, this); this.config = extend(options, this.defaults); this.scrolled = true; } WOW.prototype.init = function() { if (document.readyState === "complete") { return this.start(); } else { return document.addEventListener('DOMContentLoaded', this.start); } }; WOW.prototype.start = function() { var box, _i, _len, _ref; this.element = window.document.documentElement; this.boxes = this.element.getElementsByClassName(this.config.boxClass); if (this.boxes.length) { _ref = this.boxes; for (_i = 0, _len = _ref.length; _i < _len; _i++) { box = _ref[_i]; this.applyStyle(box, true); } window.addEventListener('scroll', this.scrollHandler, false); window.addEventListener('resize', this.scrollHandler, false); return this.interval = setInterval(this.scrollCallback, 50); } }; WOW.prototype.stop = function() { window.removeEventListener('scroll', this.scrollHandler, false); window.removeEventListener('resize', this.scrollHandler, false); if (this.interval != null) { return clearInterval(this.interval); } }; WOW.prototype.show = function(box) { this.applyStyle(box); return box.className = "" + box.className + " " + this.config.animateClass; }; WOW.prototype.applyStyle = function(box, hidden) { var delay, duration, iteration; duration = box.getAttribute('data-wow-duration'); delay = box.getAttribute('data-wow-delay'); iteration = box.getAttribute('data-wow-iteration'); return box.setAttribute('style', this.customStyle(hidden, duration, delay, iteration)); }; WOW.prototype.customStyle = function(hidden, duration, delay, iteration) { var style; style = hidden ? "visibility: hidden; -webkit-animation-name: none; -moz-animation-name: none; animation-name: none;" : "visibility: visible;"; if (duration) { style += "-webkit-animation-duration: " + duration + "; -moz-animation-duration: " + duration + "; animation-duration: " + duration + ";"; } if (delay) { style += "-webkit-animation-delay: " + delay + "; -moz-animation-delay: " + delay + "; animation-delay: " + delay + ";"; } if (iteration) { style += "-webkit-animation-iteration-count: " + iteration + "; -moz-animation-iteration-count: " + iteration + "; animation-iteration-count: " + iteration + ";"; } return style; }; WOW.prototype.scrollHandler = function() { return this.scrolled = true; }; WOW.prototype.scrollCallback = function() { var box; if (this.scrolled) { this.scrolled = false; this.boxes = (function() { var _i, _len, _ref, _results; _ref = this.boxes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { box = _ref[_i]; if (!(box)) { continue; } if (this.isVisible(box)) { this.show(box); continue; } _results.push(box); } return _results; }).call(this); if (!this.boxes.length) { return this.stop(); } } }; WOW.prototype.offsetTop = function(element) { var top; top = element.offsetTop; while (element = element.offsetParent) { top += element.offsetTop; } return top; }; WOW.prototype.isVisible = function(box) { var bottom, offset, top, viewBottom, viewTop; offset = box.getAttribute('data-wow-offset') || this.config.offset; viewTop = window.pageYOffset; viewBottom = viewTop + this.element.clientHeight - offset; top = this.offsetTop(box); bottom = top + box.clientHeight; return top <= viewBottom && bottom >= viewTop; }; return WOW; })(); }).call(this);
/* AngularJS v1.2.0-rc.2 (c) 2010-2012 Google, Inc. http://angularjs.org License: MIT */ (function(m,g,n){'use strict';function h(a){var d={};a=a.split(",");var c;for(c=0;c<a.length;c++)d[a[c]]=!0;return d}function C(a,d){function c(a,b,c,f){b=g.lowercase(b);if(r[b])for(;e.last()&&s[e.last()];)k("",e.last());t[b]&&e.last()==b&&k("",b);(f=u[b]||!!f)||e.push(b);var l={};c.replace(D,function(a,b,d,c,e){l[b]=p(d||c||e||"")});d.start&&d.start(b,l,f)}function k(a,b){var c=0,k;if(b=g.lowercase(b))for(c=e.length-1;0<=c&&e[c]!=b;c--);if(0<=c){for(k=e.length-1;k>=c;k--)d.end&&d.end(e[k]);e.length= c}}var b,f,e=[],l=a;for(e.last=function(){return e[e.length-1]};a;){f=!0;if(e.last()&&v[e.last()])a=a.replace(RegExp("(.*)<\\s*\\/\\s*"+e.last()+"[^>]*>","i"),function(a,b){b=b.replace(E,"$1").replace(F,"$1");d.chars&&d.chars(p(b));return""}),k("",e.last());else{if(0===a.indexOf("\x3c!--"))b=a.indexOf("--\x3e"),0<=b&&(d.comment&&d.comment(a.substring(4,b)),a=a.substring(b+3),f=!1);else if(G.test(a)){if(b=a.match(w))a=a.substring(b[0].length),b[0].replace(w,k),f=!1}else H.test(a)&&(b=a.match(x))&& (a=a.substring(b[0].length),b[0].replace(x,c),f=!1);f&&(b=a.indexOf("<"),f=0>b?a:a.substring(0,b),a=0>b?"":a.substring(b),d.chars&&d.chars(p(f)))}if(a==l)throw I("badparse",a);l=a}k()}function p(a){q.innerHTML=a.replace(/</g,"&lt;");return q.innerText||q.textContent||""}function y(a){return a.replace(/&/g,"&amp;").replace(J,function(a){return"&#"+a.charCodeAt(0)+";"}).replace(/</g,"&lt;").replace(/>/g,"&gt;")}function z(a){var d=!1,c=g.bind(a,a.push);return{start:function(a,b,f){a=g.lowercase(a); !d&&v[a]&&(d=a);d||!0!=A[a]||(c("<"),c(a),g.forEach(b,function(a,b){var d=g.lowercase(b);!0!=K[d]||!0===B[d]&&!a.match(L)||(c(" "),c(b),c('="'),c(y(a)),c('"'))}),c(f?"/>":">"))},end:function(a){a=g.lowercase(a);d||!0!=A[a]||(c("</"),c(a),c(">"));a==d&&(d=!1)},chars:function(a){d||c(y(a))}}}var I=g.$$minErr("$sanitize"),x=/^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,w=/^<\s*\/\s*([\w:-]+)[^>]*>/,D=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, H=/^</,G=/^<\s*\//,E=/\x3c!--(.*?)--\x3e/g,F=/<!\[CDATA\[(.*?)]]\x3e/g,L=/^((ftp|https?):\/\/|mailto:|tel:|#)/i,J=/([^\#-~| |!])/g,u=h("area,br,col,hr,img,wbr");m=h("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr");n=h("rp,rt");var t=g.extend({},n,m),r=g.extend({},m,h("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")),s=g.extend({},n,h("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var")), v=h("script,style"),A=g.extend({},u,r,s,t),B=h("background,cite,href,longdesc,src,usemap"),K=g.extend({},B,h("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,span,start,summary,target,title,type,valign,value,vspace,width")),q=document.createElement("pre");g.module("ngSanitize",[]).value("$sanitize",function(a){var d=[]; C(a,z(d));return d.join("")});g.module("ngSanitize").filter("linky",function(){var a=/((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/,d=/^mailto:/;return function(c,k){if(!c)return c;var b,f=c,e=[],l=z(e),h,m,n={};g.isDefined(k)&&(n.target=k);for(;b=f.match(a);)h=b[0],b[2]==b[3]&&(h="mailto:"+h),m=b.index,l.chars(f.substr(0,m)),n.href=h,l.start("a",n),l.chars(b[0].replace(d,"")),l.end("a"),f=f.substring(m+b[0].length);l.chars(f);return e.join("")}})})(window,window.angular); /* //@ sourceMappingURL=angular-sanitize.min.js.map */
'use strict' const pump = require('pump') const trips = require('vbb-trips') const through = require('through2') const omit = require('lodash.omit') const csv = require('csv-write-stream') const fs = require('fs') const readSchedule = require('./read-schedule') const buildCalendar = (file) => { return new Promise((yay, nay) => { pump( trips.schedules('all'), through.obj(readSchedule), through.obj((sched, _, cb) => { cb(null, omit(sched, ['exceptions'])) }), csv(), fs.createWriteStream(file), (err) => { if (err) nay(err) else yay() } ) }) } module.exports = buildCalendar
"use strict"; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; exports.check = check; exports.ObjectExpression = ObjectExpression; exports.__esModule = true; var memoiseDecorators = _interopRequire(require("../../helpers/memoise-decorators")); var defineMap = _interopRequireWildcard(require("../../helpers/define-map")); var t = _interopRequireWildcard(require("../../../types")); var metadata = { optional: true, stage: 1 }; exports.metadata = metadata; function check(node) { return !!node.decorators; } function ObjectExpression(node, parent, scope, file) { var hasDecorators = false; for (var i = 0; i < node.properties.length; i++) { var prop = node.properties[i]; if (prop.decorators) { hasDecorators = true; break; } } if (!hasDecorators) return; var mutatorMap = {}; for (var i = 0; i < node.properties.length; i++) { var prop = node.properties[i]; if (prop.decorators) memoiseDecorators(prop.decorators, scope); if (prop.kind === "init") { prop.kind = ""; prop.value = t.functionExpression(null, [], t.blockStatement([t.returnStatement(prop.value)])); } defineMap.push(mutatorMap, prop, "initializer", file); } var obj = defineMap.toClassObject(mutatorMap); obj = defineMap.toComputedObjectFromClass(obj); return t.callExpression(file.addHelper("create-decorated-object"), [obj]); }
var namespace = require('./namespace') // set nested object property function set (obj, prop, val) { var parts = (/^(.+)\.(.+)$/).exec(prop) if (parts) namespace(obj, parts[1])[parts[2]] = val else obj[prop] = val } module.exports = set
import React from 'react'; import PropTypes from 'prop-types'; import {NativeModules, requireNativeComponent} from 'react-native'; import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource'; import { toJSONString, cloneReactChildrenWithProps, viewPropTypes, isFunction, } from '../utils'; const MapboxGL = NativeModules.MGLModule; export const NATIVE_MODULE_NAME = 'RCTMGLShapeSource'; /** * ShapeSource is a map content source that supplies vector shapes to be shown on the map. * The shape may be a url or a GeoJSON object */ class ShapeSource extends React.Component { static NATIVE_ASSETS_KEY = 'assets'; static propTypes = { ...viewPropTypes, /** * A string that uniquely identifies the source. */ id: PropTypes.string, /** * An HTTP(S) URL, absolute file URL, or local file URL relative to the current application’s resource bundle. */ url: PropTypes.string, /** * The contents of the source. A shape can represent a GeoJSON geometry, a feature, or a feature colllection. */ shape: PropTypes.object, /** * Enables clustering on the source for point shapes. */ cluster: PropTypes.bool, /** * Specifies the radius of each cluster if clustering is enabled. * A value of 512 produces a radius equal to the width of a tile. * The default value is 50. */ clusterRadius: PropTypes.number, /** * Specifies the maximum zoom level at which to cluster points if clustering is enabled. * Defaults to one zoom level less than the value of maxZoomLevel so that, at the maximum zoom level, * the shapes are not clustered. */ clusterMaxZoomLevel: PropTypes.number, /** * Specifies the maximum zoom level at which to create vector tiles. * A greater value produces greater detail at high zoom levels. * The default value is 18. */ maxZoomLevel: PropTypes.number, /** * Specifies the size of the tile buffer on each side. * A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself. * Larger values produce fewer rendering artifacts near tile edges and slower performance. * The default value is 128. */ buffer: PropTypes.number, /** * Specifies the Douglas-Peucker simplification tolerance. * A greater value produces simpler geometries and improves performance. * The default value is 0.375. */ tolerance: PropTypes.number, /** * Specifies the external images in key-value pairs required for the shape source. * If you have an asset under Image.xcassets on iOS and the drawables directory on android * you can specify an array of string names with assets as the key `{ assets: ['pin'] }`. */ images: PropTypes.object, /** * Source press listener, gets called when a user presses one of the children layers only * if that layer has a higher z-index than another source layers */ onPress: PropTypes.func, /** * Overrides the default touch hitbox(44x44 pixels) for the source layers */ hitbox: PropTypes.shape({ width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, }), }; static defaultProps = { id: MapboxGL.StyleSource.DefaultSourceID, }; _getShape() { if (!this.props.shape) { return; } return toJSONString(this.props.shape); } _getImages() { if (!this.props.images) { return; } const images = {}; let nativeImages = []; const imageNames = Object.keys(this.props.images); for (const imageName of imageNames) { if ( imageName === ShapeSource.NATIVE_ASSETS_KEY && Array.isArray(this.props.images[ShapeSource.NATIVE_ASSETS_KEY]) ) { nativeImages = this.props.images[ShapeSource.NATIVE_ASSETS_KEY]; continue; } const res = resolveAssetSource(this.props.images[imageName]); if (res && res.uri) { images[imageName] = res.uri; } } return { images, nativeImages, }; } render() { const props = { id: this.props.id, url: this.props.url, shape: this._getShape(), hitbox: this.props.hitbox, hasPressListener: isFunction(this.props.onPress), onMapboxShapeSourcePress: this.props.onPress, cluster: this.props.cluster ? 1 : 0, clusterRadius: this.props.clusterRadius, clusterMaxZoomLevel: this.props.clusterMaxZoomLevel, maxZoomLevel: this.props.maxZoomLevel, buffer: this.props.buffer, tolerance: this.props.tolerance, ...this._getImages(), onPress: undefined, }; return ( <RCTMGLShapeSource {...props}> {cloneReactChildrenWithProps(this.props.children, { sourceID: this.props.id, })} </RCTMGLShapeSource> ); } } const RCTMGLShapeSource = requireNativeComponent( NATIVE_MODULE_NAME, ShapeSource, { nativeOnly: { nativeImages: true, hasPressListener: true, onMapboxShapeSourcePress: true, }, }, ); export default ShapeSource;
module.exports = (function(){ "use strict" var util = require('util'); var PreProcessor = require('./preprocessor'); var parser = require('./parser'); var TypeAnalyzer = require('./type-analyzer'); var Generator = require('./generator'); var ParserUtil = require('../src/parser-util'); var O2S = function() {}; var _estimateTabSize = function(source) { var tabSizeCountMap = {}; var estimatedTabSize = 4, maxTabSizeCount = -1; source = source.replace(/\t/g,' '); source.replace(/\n(\s*).*?\{\n(\s*)/g,function(m,p1,p2){ var size = p2.length - p1.length; if(!tabSizeCountMap[size]) tabSizeCountMap[size]=0; var newCount = tabSizeCountMap[size]++; if(maxTabSizeCount < newCount) { maxTabSizeCount = newCount; estimatedTabSize = size; } }); return 2 * Math.ceil(estimatedTabSize/2); }; O2S.prototype.preprocessOnly = function(source) { return new PreProcessor().process(source); }; O2S.prototype.buildErrorMessage = function(e, source, file) { return ParserUtil.buildErrorMessage(e, source, file); }; O2S.prototype.parse = function(source,options) { options = options || {}; var start = Date.now(); var pp = new PreProcessor(options); this.typeAnalyzer = new TypeAnalyzer(options); var p_source = pp.process(source,this.typeAnalyzer); if(!options.quiet) { console.error("Preprocess : " + (Date.now() - start) + "ms"); } start = Date.now(); var ast = parser.parse(p_source,options); if(!options.quiet) { console.error("Parse : " + (Date.now() - start) + "ms"); } start = Date.now(); this.typeAnalyzer.analyze(ast); if(!options.quiet) { console.error("Analyze : " + (Date.now()-start) + "ms"); } if(options.ast) { console.log(JSON.stringify(ast,function(k,v){ if(k=="ast") { return "(...)"; } if(!options.verbose) { if(k=="_typeInfo") { return v?(v.kind+" "+v.name):"(error)"; } if(k=="_declInfo") { return v?(v.kind+" "+v.name):"(error)"; } } return v; },' ')); } if(options.query) { var qs = options.query.split(','); var result = {} for(var i=0;i<qs.length;i++) { var info = this.typeAnalyzer.findDeclInfoByQuery(qs[i]); if(info) { result[qs[i]] = info; } else { result[qs[i]] = null; } } console.log(JSON.stringify(result,function(k,v){if(k=="ast")return"(...)";else return v;},' ')); } return ast; }; O2S.prototype.generate = function(ast, options) { options = options||{}; var start = Date.now(); var generator = new Generator(this.typeAnalyzer,options); var ret = generator.generate(ast); if(!options.quiet) { console.error("Generate : " + (Date.now()-start) + "ms"); } return ret; }; O2S.prototype.convert = function(source, options) { var ast = this.parse(source, options); return this.generate(ast, options); }; O2S.canUseTracer = function() { return parser.DefaultTracer!=null; }; return O2S; })();
import React from 'react'; import {Alert} from 'react-native'; import MapboxGL from '@mapbox/react-native-mapbox-gl'; import sheet from '../styles/sheet'; import BaseExamplePropTypes from './common/BaseExamplePropTypes'; import TabBarPage from './common/TabBarPage'; const layerStyles = MapboxGL.StyleSheet.create({ building: { fillExtrusionOpacity: 1, fillExtrusionHeight: MapboxGL.StyleSheet.identity('height'), fillExtrusionBase: MapboxGL.StyleSheet.identity('min_height'), fillExtrusionColor: MapboxGL.StyleSheet.source( [[0, 'white'], [50, 'blue'], [100, 'red']], 'height', MapboxGL.InterpolationMode.Exponential, ), fillExtrusionColorTransition: {duration: 2000, delay: 0}, }, streets: { lineColor: 'blue', lineWidth: 2, lineOpacity: 0.5, lineJoin: 'round', lineCap: 'round', lineDasharray: [2, 2], }, }); class FlyTo extends React.Component { static SF_OFFICE_LOCATION = [-122.400021, 37.789085]; static DC_OFFICE_LOCATION = [-77.036086, 38.910233]; static propTypes = { ...BaseExamplePropTypes, }; constructor(props) { super(props); this._flyToOptions = [ {label: 'SF', data: FlyTo.SF_OFFICE_LOCATION}, {label: 'DC', data: FlyTo.DC_OFFICE_LOCATION}, ]; this.onFlyToPress = this.onFlyToPress.bind(this); this.onFlyToComplete = this.onFlyToComplete.bind(this); } async onFlyToPress(i, coordinates) { await this.map.flyTo(coordinates, 6000); this.onFlyToComplete(); } onFlyToComplete() { Alert.alert('Fly To Animation Completed', 'We did it!!!'); } render() { return ( <TabBarPage {...this.props} options={this._flyToOptions} onOptionPress={this.onFlyToPress} > <MapboxGL.MapView zoomLevel={16} pitch={45} centerCoordinate={FlyTo.SF_OFFICE_LOCATION} ref={ref => (this.map = ref)} style={sheet.matchParent} > <MapboxGL.VectorSource> <MapboxGL.FillExtrusionLayer id="building3d" sourceLayerID="building" style={layerStyles.building} /> <MapboxGL.LineLayer id="streetLineColor" sourceLayerID="road" minZoomLevel={14} belowLayerID="building3d" style={layerStyles.streets} /> </MapboxGL.VectorSource> </MapboxGL.MapView> </TabBarPage> ); } } export default FlyTo;
import { fromJS } from 'immutable'; import { getEntityModule } from './entity-module'; const ENTITY_URL = 'cashFlows'; const ENTITY_LABEL = 'Cash Flows'; const TYPES = ['客訂金', '客尾數', '廠訂金', '廠尾數']; const INITIAL_STATE = fromJS({ entityConfig: { apiUrl: 'SET_IN_ACL', label: ENTITY_LABEL, url: ENTITY_URL, identity: '_id', fields: [ { label: '_id', name: '_id', type: 'hidden' }, { label: 'purchaseOrderId', name: 'purchaseOrderId', type: 'hidden' }, { label: 'Date', name: 'date', type: 'date' }, { label: 'Sales', name: 'sales', type: 'text', disabled: true }, { label: 'Type', name: 'type', type: 'number', disabled: true, transform: value => TYPES[value] }, { label: 'Title', name: 'title', type: 'text' }, { label: 'Amount', name: 'amount', type: 'number' }, { label: 'Done', name: 'done', type: 'bool' } ], iconClass: 'map' }, listView: { ui: { title: `All ${ENTITY_LABEL}`, loading: false, error: null, order: [[0, 'asc']], page: 0, search: '', filters: [ { name: 'sales' }, { name: 'type' }, { name: 'done', value: 'No' } ], actions: ['export'], listActions: ['edit', 'delete'], displayClosedDone: true, displayContextMenu: false, contextMenuLeft: 0, contextMenuTop: 0 }, data: { entities: [], contextMenuEntity: null } }, newView: { ui: { title: `New ${ENTITY_LABEL}`, loading: false, error: null }, data: { entity: null } }, editView: { ui: { title: `Edit ${ENTITY_LABEL}`, loading: false, error: null }, data: { entity: null } }, acls: { master: [ { keyPath: ['entityConfig', 'apiUrl'], value: `master--${ENTITY_URL}` } ], ones: [ { keyPath: ['entityConfig', 'apiUrl'], value: `ones--${ENTITY_URL}` } ], ppp: [ { keyPath: ['entityConfig', 'apiUrl'], value: `ppp--${ENTITY_URL}` } ], 'purchase@123.com': [ { keyPath: ['listView', 'ui', 'actions'], value: [] }, { keyPath: ['listView', 'ui', 'listActions'], value: [] }, ] } }); export default getEntityModule(ENTITY_URL, INITIAL_STATE);
'use strict' const md5hex = require('md5-hex') const encoder = require('./encoder') const pluginRegistry = require('./pluginRegistry') const argumentsValue = require('./complexValues/arguments') const arrayBufferValue = require('./complexValues/arrayBuffer') const boxedValue = require('./complexValues/boxed') const dataViewValue = require('./complexValues/dataView') const dateValue = require('./complexValues/date') const errorValue = require('./complexValues/error') const functionValue = require('./complexValues/function') const globalValue = require('./complexValues/global') const mapValue = require('./complexValues/map') const objectValue = require('./complexValues/object') const promiseValue = require('./complexValues/promise') const regexpValue = require('./complexValues/regexp') const setValue = require('./complexValues/set') const typedArrayValue = require('./complexValues/typedArray') const itemDescriptor = require('./metaDescriptors/item') const mapEntryDescriptor = require('./metaDescriptors/mapEntry') const pointerDescriptor = require('./metaDescriptors/pointer') const propertyDescriptor = require('./metaDescriptors/property') const statsDescriptors = require('./metaDescriptors/stats') const bigIntValue = require('./primitiveValues/bigInt') const booleanValue = require('./primitiveValues/boolean') const nullValue = require('./primitiveValues/null') const numberValue = require('./primitiveValues/number') const stringValue = require('./primitiveValues/string') const symbolValue = require('./primitiveValues/symbol') const undefinedValue = require('./primitiveValues/undefined') // Increment if encoding layout, descriptor IDs, or value types change. Previous // Concordance versions will not be able to decode buffers generated by a newer // version, so changing this value will require a major version bump of // Concordance itself. The version is encoded as an unsigned 16 bit integer. const VERSION = 3 // Adding or removing mappings or changing an index requires the version in // encoder.js to be bumped, which necessitates a major version bump of // Concordance itself. Indexes are hexadecimal to make reading the binary // output easier. const mappings = [ [0x01, bigIntValue.tag, bigIntValue.deserialize], [0x02, booleanValue.tag, booleanValue.deserialize], [0x03, nullValue.tag, nullValue.deserialize], [0x04, numberValue.tag, numberValue.deserialize], [0x05, stringValue.tag, stringValue.deserialize], [0x06, symbolValue.tag, symbolValue.deserialize], [0x07, undefinedValue.tag, undefinedValue.deserialize], [0x08, objectValue.tag, objectValue.deserialize], [0x09, statsDescriptors.iterableTag, statsDescriptors.deserializeIterableStats], [0x0A, statsDescriptors.listTag, statsDescriptors.deserializeListStats], [0x0B, itemDescriptor.complexTag, itemDescriptor.deserializeComplex], [0x0C, itemDescriptor.primitiveTag, itemDescriptor.deserializePrimitive], [0x0D, statsDescriptors.propertyTag, statsDescriptors.deserializePropertyStats], [0x0E, propertyDescriptor.complexTag, propertyDescriptor.deserializeComplex], [0x0F, propertyDescriptor.primitiveTag, propertyDescriptor.deserializePrimitive], [0x10, pointerDescriptor.tag, pointerDescriptor.deserialize], [0x11, mapValue.tag, mapValue.deserialize], [0x12, mapEntryDescriptor.tag, mapEntryDescriptor.deserialize], [0x13, argumentsValue.tag, argumentsValue.deserialize], [0x14, arrayBufferValue.tag, arrayBufferValue.deserialize], [0x15, boxedValue.tag, boxedValue.deserialize], [0x16, dataViewValue.tag, dataViewValue.deserialize], [0x17, dateValue.tag, dateValue.deserialize], [0x18, errorValue.tag, errorValue.deserialize], [0x19, functionValue.tag, functionValue.deserialize], [0x1A, globalValue.tag, globalValue.deserialize], [0x1B, promiseValue.tag, promiseValue.deserialize], [0x1C, regexpValue.tag, regexpValue.deserialize], [0x1D, setValue.tag, setValue.deserialize], [0x1E, typedArrayValue.tag, typedArrayValue.deserialize], [0x1F, typedArrayValue.bytesTag, typedArrayValue.deserializeBytes] ] const tag2id = new Map(mappings.map(mapping => [mapping[1], mapping[0]])) const id2deserialize = new Map(mappings.map(mapping => [mapping[0], mapping[2]])) class DescriptorSerializationError extends Error { constructor (descriptor) { super('Could not serialize descriptor') this.name = 'DescriptorSerializationError' this.descriptor = descriptor } } class MissingPluginError extends Error { constructor (pluginName) { super(`Could not deserialize buffer: missing plugin ${JSON.stringify(pluginName)}`) this.name = 'MissingPluginError' this.pluginName = pluginName } } class PointerLookupError extends Error { constructor (index) { super(`Could not deserialize buffer: pointer ${index} could not be resolved`) this.name = 'PointerLookupError' this.index = index } } class UnsupportedPluginError extends Error { constructor (pluginName, serializerVersion) { super(`Could not deserialize buffer: plugin ${JSON.stringify(pluginName)} expects a different serialization`) this.name = 'UnsupportedPluginError' this.pluginName = pluginName this.serializerVersion = serializerVersion } } class UnsupportedVersion extends Error { constructor (serializerVersion) { super('Could not deserialize buffer: a different serialization was expected') this.name = 'UnsupportedVersion' this.serializerVersion = serializerVersion } } function shallowSerializeDescriptor (descriptor, resolvePluginRef) { if (!descriptor.serialize) return undefined return serializeState(descriptor.serialize(), resolvePluginRef) } function serializeState (state, resolvePluginRef) { if (Array.isArray(state)) return state.map(serializeState) if (state && state.tag) { let id, pluginIndex if (tag2id.has(state.tag)) { id = tag2id.get(state.tag) pluginIndex = 0 } else { const ref = resolvePluginRef(state.tag) if (ref) { id = ref.id pluginIndex = ref.pluginIndex } } if (id !== undefined) { const serialized = [pluginIndex, id, shallowSerializeDescriptor(state, resolvePluginRef)] serialized[encoder.descriptorSymbol] = true return serialized } } return state } function serialize (descriptor) { const usedPlugins = new Map() const resolvePluginRef = tag => { const ref = pluginRegistry.resolveDescriptorRef(tag) if (!ref) return null if (!usedPlugins.has(ref.name)) { // Start at 1, since 0 is reserved for Concordance's descriptors. const index = usedPlugins.size + 1 usedPlugins.set(ref.name, Object.assign({index}, ref.serialization)) } return { id: ref.id, pluginIndex: usedPlugins.get(ref.name).index } } const seen = new Set() const stack = [] let topIndex = -1 let rootRecord do { if (descriptor.isComplex === true) { if (seen.has(descriptor.pointer)) { descriptor = pointerDescriptor.describe(descriptor.pointer) } else { seen.add(descriptor.pointer) } } let id let pluginIndex = 0 if (tag2id.has(descriptor.tag)) { id = tag2id.get(descriptor.tag) } else { const ref = resolvePluginRef(descriptor.tag) if (!ref) throw new DescriptorSerializationError(descriptor) id = ref.id pluginIndex = ref.pluginIndex } const record = { id, pluginIndex, children: [], state: shallowSerializeDescriptor(descriptor, resolvePluginRef) } if (!rootRecord) { rootRecord = record } else { stack[topIndex].children.push(record) } if (descriptor.createRecursor) { stack.push({ recursor: descriptor.createRecursor(), children: record.children }) topIndex++ } while (topIndex >= 0) { descriptor = stack[topIndex].recursor() if (descriptor === null) { stack.pop() topIndex-- } else { break } } } while (topIndex >= 0) return encoder.encode(VERSION, rootRecord, usedPlugins) } exports.serialize = serialize function deserializeState (state, getDescriptorDeserializer) { if (state && state[encoder.descriptorSymbol] === true) { return shallowDeserializeDescriptor(state, getDescriptorDeserializer) } return Array.isArray(state) ? state.map(item => deserializeState(item, getDescriptorDeserializer)) : state } function shallowDeserializeDescriptor (entry, getDescriptorDeserializer) { const deserializeDescriptor = getDescriptorDeserializer(entry[0], entry[1]) return deserializeDescriptor(entry[2]) } function deserializeRecord (record, getDescriptorDeserializer, buffer) { const deserializeDescriptor = getDescriptorDeserializer(record.pluginIndex, record.id) const state = deserializeState(record.state, getDescriptorDeserializer) if (record.pointerAddresses.length === 0) { return deserializeDescriptor(state) } const endIndex = record.pointerAddresses.length let index = 0 const recursor = () => { if (index === endIndex) return null const recursorRecord = encoder.decodeRecord(buffer, record.pointerAddresses[index++]) return deserializeRecord(recursorRecord, getDescriptorDeserializer, buffer) } return deserializeDescriptor(state, recursor) } function buildPluginMap (buffer, options) { const cache = options && options.deserializedPluginsCache const cacheKey = md5hex(buffer) if (cache && cache.has(cacheKey)) return cache.get(cacheKey) const decodedPlugins = encoder.decodePlugins(buffer) if (decodedPlugins.size === 0) { const pluginMap = new Map() if (cache) cache.set(cacheKey, pluginMap) return pluginMap } const deserializerLookup = new Map() if (Array.isArray(options && options.plugins)) { for (const deserializer of pluginRegistry.getDeserializers(options.plugins)) { deserializerLookup.set(deserializer.name, deserializer) } } const pluginMap = new Map() for (const index of decodedPlugins.keys()) { const used = decodedPlugins.get(index) const pluginName = used.name const serializerVersion = used.serializerVersion // TODO: Allow plugin author to encode a helpful message in its serialization if (!deserializerLookup.has(pluginName)) { throw new MissingPluginError(pluginName) } if (serializerVersion !== deserializerLookup.get(pluginName).serializerVersion) { throw new UnsupportedPluginError(pluginName, serializerVersion) } pluginMap.set(index, deserializerLookup.get(pluginName).id2deserialize) } if (cache) cache.set(cacheKey, pluginMap) return pluginMap } function deserialize (buffer, options) { const version = encoder.extractVersion(buffer) if (version !== VERSION) throw new UnsupportedVersion(version) const decoded = encoder.decode(buffer) const pluginMap = buildPluginMap(decoded.pluginBuffer, options) const descriptorsByPointerIndex = new Map() const mapPointerDescriptor = descriptor => { if (descriptor.isPointer === true) { if (!descriptorsByPointerIndex.has(descriptor.index)) throw new PointerLookupError(descriptor.index) return descriptorsByPointerIndex.get(descriptor.index) } else if (descriptor.isComplex === true) { descriptorsByPointerIndex.set(descriptor.pointer, descriptor) } return descriptor } const getDescriptorDeserializer = (pluginIndex, id) => { return (state, recursor) => { const deserializeDescriptor = pluginIndex === 0 ? id2deserialize.get(id) : pluginMap.get(pluginIndex).get(id) return mapPointerDescriptor(deserializeDescriptor(state, recursor)) } } return deserializeRecord(decoded.rootRecord, getDescriptorDeserializer, buffer) } exports.deserialize = deserialize
'use strict' const EventStorePromise = require('../esp') const async = require('asyncawait/async') const await = require('asyncawait/await') const _ = require('highland') // A convenient wrapper to await the result of a highland stream. Always gives an array though. const await_ = stream => await(new Promise((res, rej) => stream.errors(rej).toArray(res))) // A stub applyEvent that justs take the event object and boils down the latest value of each key. const applyEvent = (state, event) => { console.log('Received and applying event:', event) return Object.assign({}, state, event) } // Stream to boil down. const streamId = 'testStream' async(() => { // Connect to EventStore. const esp = await(EventStorePromise({ mysql: { user: 'esp', password: 'esp', database: 'esp', }, amqp: { url: 'amqp://localhost', exchange: 'events', } }, {timeout: 10000})) // Try adding some events asynchronously. setInterval(async(() => { const event = {foo: 'bar', mydate: Date()} console.log('Adding event in stream', streamId) await(esp.writeEvents(streamId, esp.ExpectedVersion.Any, false, [{eventId: esp.createGuid(), eventType: 'test', data: event}])) console.log('Event is now added asynchronously and awaited.') }), 1000) try { //const stream = esp.readStreamEventsUntil(streamId, 0, 10) //stream.on('data', event => { // console.log('Got data on non highland stream') //}) // Read all events up until event 10. This will wait for events to come in. const result = await_(_(esp.readStreamEventsUntil(streamId, 0, 10)).reduce(0, applyEvent)) console.log('Got result', result) } catch (err) { // Catching errors, probably timeout for too few events. console.log('Caught error', err) } console.log('\nAll done.') process.exit() })().done()
function Router (routes) { this.routes = routes window.addEventListener('popstate', function (event) { this.route() }.bind(this)) document.addEventListener('click', function (event) { if (event.target.tagName === 'A') { if (event.target.href.startsWith(window.location.origin)) { event.preventDefault() history.pushState(null, '', event.target.attributes.href.value) this.route() } } }.bind(this)) this.route() } Router.prototype.route = function () { Array.from(document.querySelectorAll('section')) .forEach(function (section) { section.style.display = 'none' }) var route = this.routes.find(function (route) { const pattern = route.route return pattern.test(window.location.pathname) }) if (route) { document.title = route.title document.querySelector(route.element).style.display = 'block' } } module.exports = Router
'use strict'; var forEach = require('es5-ext/object/for-each') , isObject = require('es5-ext/object/is-object') , encode = require('querystring/encode') , id = require('./id') , stringify = JSON.stringify; module.exports = function (deck/*, options*/) { var options = Object(arguments[1]) , path = (options.xhrPath || '/slide/') + '?id=' + id; deck.on('activate', function (e) { var result = {}, xhr; if (e.server) return; forEach(e, function (value, key) { if (isObject(value)) return; result[key] = value; }); xhr = new XMLHttpRequest(); xhr.open('POST', path, true); xhr.send(encode({ data: stringify(result) })); if (options.log) console.log("Client[" + id + "] -> Server", result); }); };
const express = require('express'); const router = express.Router(); /* GET home page. */ router.get('/', (req, res) => { if (req.user) { res.render('index', { title: 'Welcome', user: req.user }); } else { res.cookie('hosted_on', `https://${req.header('Host')}`) .render('index'); } }); module.exports = router;
/** * * Initilize TinyMCE editor with all required options */ // Invisible space constants const ZERO_SPACE = '&#8203;' const RAJE_SELECTOR = 'body#tinymce' // Selector constants (to move inside a new const file) const HEADER_SELECTOR = 'header.page-header.container.cgen' const FIRST_HEADING = `${RAJE_SELECTOR}>section:first>h1:first` const TINYMCE_TOOLBAR_HEIGTH = 76 let ipcRenderer, webFrame if (hasBackend) { ipcRenderer = require('electron').ipcRenderer webFrame = require('electron').webFrame /** * Initilise TinyMCE */ $(document).ready(function () { // Override the margin botton given by RASH for the footer $('body').css({ 'margin-bottom': 0 }) //hide footer $('footer.footer').hide() //attach whole body inside a placeholder div $('body').html(`<div id="raje_root">${$('body').html()}</div>`) // setNonEditableHeader() tinymce.init({ // Select the element to wrap selector: '#raje_root', // Set window size height: window.innerHeight - TINYMCE_TOOLBAR_HEIGTH, // Set the styles of the content wrapped inside the element content_css: ['css/bootstrap.min.css', 'css/rash.css', 'css/rajemce.css'], // Set plugins plugins: "raje_inlineFigure fullscreen link codesample raje_inlineCode raje_inlineQuote raje_section table image noneditable raje_image raje_codeblock raje_table raje_listing raje_inline_formula raje_formula raje_crossref raje_footnotes raje_metadata paste raje_lists raje_save", // Remove menubar menubar: false, // Custom toolbar toolbar: 'undo redo bold italic link superscript subscript raje_inlineCode raje_inlineQuote raje_inline_formula raje_crossref raje_footnotes | raje_ol raje_ul raje_codeblock blockquote raje_table raje_image raje_listing raje_formula | raje_section raje_metadata raje_save', // Setup full screen on init setup: function (editor) { // Set fullscreen editor.on('init', function (e) { editor.execCommand('mceFullScreen') // Move caret at the first h1 element of main section // Or right after heading tinymce.activeEditor.selection.setCursorLocation(tinymce.activeEditor.dom.select(FIRST_HEADING)[0], 0) }) editor.on('keyDown', function (e) { // Prevent shift+enter if (e.keyCode == 13 && e.shiftKey) { e.preventDefault() } }) // Prevent span editor.on('nodeChange', function (e) { let selectedElement = $(tinymce.activeEditor.selection.getNode()) // Move caret to first heading if is after or before not editable header if (selectedElement.is('p') && (selectedElement.next().is(HEADER_SELECTOR) || (selectedElement.prev().is(HEADER_SELECTOR) && tinymce.activeEditor.dom.select(FIRST_HEADING).length))) tinymce.activeEditor.selection.setCursorLocation(tinymce.activeEditor.dom.select(FIRST_HEADING)[0], 0) // If the current element isn't inside header, only in section this is permitted if (selectedElement.parents('section').length) { if (selectedElement.is('span#_mce_caret[data-mce-bogus]') || selectedElement.parent().is('span#_mce_caret[data-mce-bogus]')) { // Remove span normally created with bold if (selectedElement.parent().is('span#_mce_caret[data-mce-bogus]')) selectedElement = selectedElement.parent() let bm = tinymce.activeEditor.selection.getBookmark() selectedElement.replaceWith(selectedElement.html()) tinymce.activeEditor.selection.moveToBookmark(bm) } } // Check if a change in the structure is made // Then notify the backend if (tinymce.activeEditor.undoManager.hasUndo()) updateDocumentState(true) }) // Update saved content on undo and redo events editor.on('Undo', function (e) { tinymce.triggerSave() }) editor.on('Redo', function (e) { tinymce.triggerSave() }) }, // Set default target default_link_target: "_blank", // Prepend protocol if the link starts with www link_assume_external_targets: true, // Hide target list target_list: false, // Hide title link_title: false, // Set formats formats: { inline_quote: { inline: 'q' } }, // Remove "powered by tinymce" branding: false, // Prevent auto br on element insert apply_source_formatting: false, // Prevent non editable object resize object_resizing: false, // Update the table popover layout table_toolbar: "tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol", image_advtab: true, paste_block_drop: true, extended_valid_elements: "svg[*],defs[*],pattern[*],desc[*],metadata[*],g[*],mask[*],path[*],line[*],marker[*],rect[*],circle[*],ellipse[*],polygon[*],polyline[*],linearGradient[*],radialGradient[*],stop[*],image[*],view[*],text[*],textPath[*],title[*],tspan[*],glyph[*],symbol[*],switch[*],use[*]", formula: { path: 'node_modules/tinymce-formula/' }, cleanup_on_startup: false, trim_span_elements: false, verify_html: false, cleanup: false, convert_urls: false }) }) /** * Open and close the headings dropdown */ $(window).load(function () { // Open and close menu headings Näive way $(`div[aria-label='heading']`).find('button').trigger('click') $(`div[aria-label='heading']`).find('button').trigger('click') }) /** * Update content in the iframe, with the one stored by tinymce * And save/restore the selection */ function updateIframeFromSavedContent() { // Save the bookmark let bookmark = tinymce.activeEditor.selection.getBookmark(2, true) // Update iframe content tinymce.activeEditor.setContent($('#raje_root').html()) // Restore the bookmark tinymce.activeEditor.selection.moveToBookmark(bookmark) } /** * Accept a js object that exists in frame * @param {*} element */ function moveCaret(element, toStart) { tinymce.activeEditor.selection.select(element, true) tinymce.activeEditor.selection.collapse(toStart) tinymce.activeEditor.focus() } /** * * @param {*} element */ function moveCursorToEnd(element) { let heading = element let offset = 0 if (heading.contents().length) { heading = heading.contents().last() // If the last node is a strong,em,q etc. we have to take its text if (heading[0].nodeType != 3) heading = heading.contents().last() offset = heading[0].wholeText.length } tinymce.activeEditor.focus() tinymce.activeEditor.selection.setCursorLocation(heading[0], offset) } /** * * @param {*} element */ function moveCursorToStart(element) { let heading = element let offset = 0 tinymce.activeEditor.focus() tinymce.activeEditor.selection.setCursorLocation(heading[0], offset) } /** * Create custom into notification * @param {*} text * @param {*} timeout */ function notify(text, type, timeout) { // Display only one notification, blocking all others if (tinymce.activeEditor.notificationManager.getNotifications().length == 0) { let notify = { text: text, type: type ? type : 'info', timeout: timeout ? timeout : 1000 } tinymce.activeEditor.notificationManager.open(notify) } } /** * * @param {*} elementSelector */ function scrollTo(elementSelector) { $(tinymce.activeEditor.getBody()).find(elementSelector).get(0).scrollIntoView(); } /** * */ function getSuccessiveElementId(elementSelector, SUFFIX) { let lastId = 0 $(elementSelector).each(function () { let currentId = parseInt($(this).attr('id').replace(SUFFIX, '')) lastId = currentId > lastId ? currentId : lastId }) return `${SUFFIX}${lastId+1}` } /** * */ function headingDimension() { $('h1,h2,h3,h4,h5,h6').each(function () { if (!$(this).parents(HEADER_SELECTOR).length) { var counter = 0; $(this).parents("section").each(function () { if ($(this).children("h1,h2,h3,h4,h5,h6").length > 0) { counter++; } }); $(this).replaceWith("<h" + counter + ">" + $(this).html() + "</h" + counter + ">") } }); } /** * */ function markTinyMCE() { $('div[id^=mceu_]').attr('data-rash-original-content', '') } /** * */ function setNonEditableHeader() { $(HEADER_SELECTOR).addClass('mceNonEditable') } /** * */ function checkIfApp() { return ipcRenderer.sendSync('isAppSync') } /** * */ function selectImage() { return ipcRenderer.sendSync('selectImageSync') } /** * Send a message to the backend, notify the structural change * * If the document is draft state = true * If the document is saved state = false */ function updateDocumentState(state) { return ipcRenderer.send('updateDocumentState', state) } /** * */ function saveAsArticle(options) { return ipcRenderer.send('saveAsArticle', options) } /** * */ function saveArticle(options) { return ipcRenderer.send('saveArticle', options) } /** * Start the save as process getting the data and sending it * to the main process */ ipcRenderer.on('executeSaveAs', (event, data) => { saveManager.saveAs() }) /** * Start the save process getting the data and sending it * to the main process */ ipcRenderer.on('executeSave', (event, data) => { saveManager.save() }) /** * */ ipcRenderer.on('notify', (event, data) => { notify(data.text, data.type, data.timeout) }) }
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.controllers' is found in controllers.js angular.module('skjutsgruppen', [ 'ionic', 'ngCordova', 'skjutsgruppen.controllers', 'skjutsgruppen.factories', 'skjutsgruppen.JSONReader', 'ionic-timepicker', 'ionic-datepicker']) .run(function ($ionicPlatform) { $ionicPlatform.ready(function () { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); }) .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) { $ionicConfigProvider.backButton.text('Bakåt'); $stateProvider .state('app', { url: '/app', abstract: true, templateUrl: 'templates/menu.html', controller: 'AppCtrl' }) .state('app.search', { url: '/search', views: { 'menuContent': { templateUrl: 'templates/search.html' } } }) .state('app.startpage', { url: '/startpage', views: { 'menuContent': { templateUrl: 'templates/startpage.html', controller: 'StartpageCtrl' } } }) .state('app.registerTripDriver', { url: '/registerTripDriver', views: { 'menuContent': { templateUrl: 'templates/registerTripDriver.html', controller: 'registerTripDriverCtrl' } } }) .state('app.result', { url: '/result', views: { 'menuContent': { templateUrl: 'templates/result.html', controller: 'ResultCtrl' } } }) .state('app.summary', { url: '/summary', views: { 'menuContent': { templateUrl: 'templates/summary.html', controller: 'SummaryCtrl' } } }) .state('app.push', { url: '/push', views: { 'menuContent': { templateUrl: 'templates/push.html', controller: 'PushCtrl' } } }) .state('app.achievements', { url: '/achievements', views: { 'menuContent': { templateUrl: 'templates/achievements.html', controller: 'AchievementsCtrl' } } }) .state('app.statistics', { url: '/statistics', views: { 'menuContent': { templateUrl: 'templates/statistics.html', controller: 'StatisticsCtrl' } } }) .state('app.settings', { url: '/settings', views: { 'menuContent': { templateUrl: 'templates/settings.html', controller: 'SettingsCtrl' } } }) .state('app.map', { url: '/map', views: { 'menuContent': { templateUrl: 'templates/map.html', controller: 'MapCtrl' } } }) .state('app.registerTripPassenger', { url: '/registerTripPassenger', views: { 'menuContent': { templateUrl: 'templates/registerTripPassenger.html', controller: 'registerTripPassengerCtrl' } } }) .state('app.profile', { url: '/profile', views: { 'menuContent': { templateUrl: 'templates/profile.html', controller: 'ProfileCtrl' } } }) .state('app.popupTemplate', { url: '/popupTemplate', views: { 'menuContent': { templateUrl: 'templates/popupTemplate.html', controller: 'popupTemplateCtrl' } } }); // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/app/startpage'); });
import {expect} from 'chai'; import {List, Map} from 'immutable'; import {setEntries, next, vote} from '../src/core'; describe('immutability', () => { describe('a number', () => { function increment(currentState) { return currentState + 1; } it('is immutable', () => { let state = 42; let nextState = increment(state); expect(nextState).to.equal(43); expect(state).to.equal(42); }); }); describe('A List', () => { function addMovie(currentState, movie) { return currentState.push(movie); } it('is immutable', () => { let state = List.of('Trainspotting', '28 Days Later'); let nextState = addMovie(state, 'Sunshine'); expect(nextState).to.equal(List.of( 'Trainspotting', '28 Days Later', 'Sunshine' )); expect(state).to.equal(List.of( 'Trainspotting', '28 Days Later' )); }); }); describe('a tree', () => { function addMovie(currentState, movie) { return currentState.update('movies', movies => movies.push(movie)); } it('is immutable', () => { let state = Map({ movies: List.of('Trainspotting', '28 Days Later') }); let nextState = addMovie(state, 'Sunshine'); expect(nextState).to.equal(Map({ movies: List.of( 'Trainspotting', '28 Days Later', 'Sunshine' ) })); expect(state).to.equal(Map({ movies: List.of( 'Trainspotting', '28 Days Later' ) })); }); }); });
var fiveZeroOneIFFE = (function(numberOfPlayers) { var startPoints = 501, numberOfRounds = 25, playerPoints = [], playerNames = [], currentPlayerTurn = 0, currentRound = 1; function displayConfigurationScreen() { var $configurationScreen = $('#configurationScreen'), templateData = {players: []}; for(var i = 1; i <= numberOfPlayers; i += 1) { templateData.players.push(i); } var source = $("#501-configuration-screen").html(); var template = Handlebars.compile(source); $configurationScreen.append (template(templateData)); $configurationScreen.show(); } // Change points handler var $body = $('body'); $body.on('change', '#startPoints', function() { var $this = $(this), value = $this.val(); $('#configurationTitle').text(value + ' Configuration'); startPoints = value; }); displayConfigurationScreen(); // Game start button $body.on('click', '#startGameButton', function() { var $configurationScreen = $('#configurationScreen'), $gameScreen = $('#gameScreen'), templateData = {players: []}; startPoints = $('#startPoints').val() | 0; numberOfRounds = $('#numberOfRounds').val() | 0; var i = 0; for(i = 0; i < numberOfPlayers; i += 1) { playerPoints.push(startPoints); var currentPlayerName = $('#playerName-' + i).val(); playerNames.push(currentPlayerName); templateData.players.push({ name: playerNames[i], points: playerPoints[i] }); } templateData.currentPlayerTurnName = playerNames[0]; templateData.numberOfRounds = numberOfRounds; templateData.currentRound = currentRound; var source = $("#501-game-screen").html(); var template = Handlebars.compile(source); $gameScreen.append (template(templateData)); $configurationScreen.hide(); $gameScreen.show(); $('ul#fiveZeroOneScoreUl li#playerLi-' + currentPlayerTurn).addClass('active'); }); $body.on('click', '#nextTurnBtn', function() { var hitPoints, newPoints; hitPoints = $('#hitPoints').val() | 0; newPoints = playerPoints[currentPlayerTurn] - hitPoints; if (newPoints < 0) { nextTurn(); } else { playerPoints[currentPlayerTurn] = newPoints; $('#playerPoints-' + currentPlayerTurn).text(playerPoints[currentPlayerTurn]); if (checkIfPlayerWins()) { } else { nextTurn(); } } }); $body.on('click', '#resetTurnBtn', function() { $('#hitPoints').val(0); }); $body.on('click', '#newGameBtn', function() { location.reload(); }); function checkIfPlayerWins() { if (playerPoints[currentPlayerTurn] == 0) { finishGame(playerNames[currentPlayerTurn], playerPoints[currentPlayerTurn]); return true; } return false; } function nextTurn() { var previousPlayerTurn = currentPlayerTurn; if (currentPlayerTurn + 1 >= numberOfPlayers) { currentPlayerTurn = 0; checkIfFinalRound(); } else { currentPlayerTurn += 1; } $('#hitPoints').val(''); $('#currentPlayerTurnName').text(playerNames[currentPlayerTurn]); $('ul#fiveZeroOneScoreUl li#playerLi-' + previousPlayerTurn).removeClass('active'); $('ul#fiveZeroOneScoreUl li#playerLi-' + currentPlayerTurn).addClass('active'); } function checkIfFinalRound() { if (currentRound == numberOfRounds) { var winnerPlayerName, winnerPlayerPoints, previousPlayerPoints = playerPoints[0], winnerPlayerIndex = 0, currentPlayerPoints; for(var i = 1; i < numberOfPlayers; i += 1) { currentPlayerPoints = playerPoints[i]; if (currentPlayerPoints < previousPlayerPoints) { winnerPlayerIndex = i; } previousPlayerPoints = playerPoints[i]; } winnerPlayerName = playerNames[winnerPlayerIndex]; winnerPlayerPoints= playerPoints[winnerPlayerIndex]; finishGame(winnerPlayerName, winnerPlayerPoints); } else { currentRound += 1; $('#currentRound').text(currentRound); } } function finishGame(winnerName, winnerPoints) { $('#gameOver').show(); $('#actionButtons').hide(); $('#winnerPlayerName').text(winnerName); $('#winnerPlayerPoints').text(winnerPoints); $('#winnerRound').text(currentRound); $body.animate({scrollTop: 0}, 350); } });
OpenLayers.Control.SelectFeature=OpenLayers.Class(OpenLayers.Control,{multipleKey:null,toggleKey:null,multiple:!1,clickout:!0,toggle:!1,hover:!1,highlightOnly:!1,box:!1,onBeforeSelect:function(){},onSelect:function(){},onUnselect:function(){},scope:null,geometryTypes:null,layer:null,layers:null,callbacks:null,selectStyle:null,renderIntent:"select",handlers:null,initialize:function(a,b){OpenLayers.Control.prototype.initialize.apply(this,[b]);null===this.scope&&(this.scope=this);this.initLayer(a);var c= {click:this.clickFeature,clickout:this.clickoutFeature};this.hover&&(c.over=this.overFeature,c.out=this.outFeature);this.callbacks=OpenLayers.Util.extend(c,this.callbacks);this.handlers={feature:new OpenLayers.Handler.Feature(this,this.layer,this.callbacks,{geometryTypes:this.geometryTypes})};this.box&&(this.handlers.box=new OpenLayers.Handler.Box(this,{done:this.selectBox},{boxDivClassName:"olHandlerBoxSelectFeature"}))},initLayer:function(a){OpenLayers.Util.isArray(a)?(this.layers=a,this.layer= new OpenLayers.Layer.Vector.RootContainer(this.id+"_container",{layers:a})):this.layer=a},destroy:function(){this.active&&this.layers&&this.map.removeLayer(this.layer);OpenLayers.Control.prototype.destroy.apply(this,arguments);this.layers&&this.layer.destroy()},activate:function(){this.active||(this.layers&&this.map.addLayer(this.layer),this.handlers.feature.activate(),this.box&&this.handlers.box&&this.handlers.box.activate());return OpenLayers.Control.prototype.activate.apply(this,arguments)},deactivate:function(){this.active&& (this.handlers.feature.deactivate(),this.handlers.box&&this.handlers.box.deactivate(),this.layers&&this.map.removeLayer(this.layer));return OpenLayers.Control.prototype.deactivate.apply(this,arguments)},unselectAll:function(a){var b=this.layers||[this.layer],c,e,d,f;for(d=0;d<b.length;++d)if(c=b[d],f=0,null!=c.selectedFeatures)for(;c.selectedFeatures.length>f;)e=c.selectedFeatures[f],a&&a.except==e?++f:this.unselect(e)},clickFeature:function(a){this.hover||(-1<OpenLayers.Util.indexOf(a.layer.selectedFeatures, a)?this.toggleSelect()?this.unselect(a):this.multipleSelect()||this.unselectAll({except:a}):(this.multipleSelect()||this.unselectAll({except:a}),this.select(a)))},multipleSelect:function(){return this.multiple||this.handlers.feature.evt&&this.handlers.feature.evt[this.multipleKey]},toggleSelect:function(){return this.toggle||this.handlers.feature.evt&&this.handlers.feature.evt[this.toggleKey]},clickoutFeature:function(a){!this.hover&&this.clickout&&this.unselectAll()},overFeature:function(a){var b= a.layer;this.hover&&(this.highlightOnly?this.highlight(a):-1==OpenLayers.Util.indexOf(b.selectedFeatures,a)&&this.select(a))},outFeature:function(a){if(this.hover)if(this.highlightOnly){if(a._lastHighlighter==this.id)if(a._prevHighlighter&&a._prevHighlighter!=this.id){delete a._lastHighlighter;var b=this.map.getControl(a._prevHighlighter);b&&b.highlight(a)}else this.unhighlight(a)}else this.unselect(a)},highlight:function(a){var b=a.layer;!1!==this.events.triggerEvent("beforefeaturehighlighted",{feature:a})&& (a._prevHighlighter=a._lastHighlighter,a._lastHighlighter=this.id,b.drawFeature(a,this.selectStyle||this.renderIntent),this.events.triggerEvent("featurehighlighted",{feature:a}))},unhighlight:function(a){var b=a.layer;void 0==a._prevHighlighter?delete a._lastHighlighter:(a._prevHighlighter!=this.id&&(a._lastHighlighter=a._prevHighlighter),delete a._prevHighlighter);b.drawFeature(a,a.style||a.layer.style||"default");this.events.triggerEvent("featureunhighlighted",{feature:a})},select:function(a){var b= this.onBeforeSelect.call(this.scope,a),c=a.layer;!1!==b&&(b=c.events.triggerEvent("beforefeatureselected",{feature:a}),!1!==b&&(c.selectedFeatures.push(a),this.highlight(a),this.handlers.feature.lastFeature||(this.handlers.feature.lastFeature=c.selectedFeatures[0]),c.events.triggerEvent("featureselected",{feature:a}),this.onSelect.call(this.scope,a)))},unselect:function(a){var b=a.layer;this.unhighlight(a);OpenLayers.Util.removeItem(b.selectedFeatures,a);b.events.triggerEvent("featureunselected", {feature:a});this.onUnselect.call(this.scope,a)},selectBox:function(a){if(a instanceof OpenLayers.Bounds){var b=this.map.getLonLatFromPixel({x:a.left,y:a.bottom});a=this.map.getLonLatFromPixel({x:a.right,y:a.top});b=new OpenLayers.Bounds(b.lon,b.lat,a.lon,a.lat);this.multipleSelect()||this.unselectAll();a=this.multiple;this.multiple=!0;var c=this.layers||[this.layer];this.events.triggerEvent("boxselectionstart",{layers:c});for(var e,d=0;d<c.length;++d){e=c[d];for(var f=0,h=e.features.length;f<h;++f){var g= e.features[f];g.getVisibility()&&(null==this.geometryTypes||-1<OpenLayers.Util.indexOf(this.geometryTypes,g.geometry.CLASS_NAME))&&b.toGeometry().intersects(g.geometry)&&-1==OpenLayers.Util.indexOf(e.selectedFeatures,g)&&this.select(g)}}this.multiple=a;this.events.triggerEvent("boxselectionend",{layers:c})}},setMap:function(a){this.handlers.feature.setMap(a);this.box&&this.handlers.box.setMap(a);OpenLayers.Control.prototype.setMap.apply(this,arguments)},setLayer:function(a){var b=this.active;this.unselectAll(); this.deactivate();this.layers&&(this.layer.destroy(),this.layers=null);this.initLayer(a);this.handlers.feature.layer=this.layer;b&&this.activate()},CLASS_NAME:"OpenLayers.Control.SelectFeature"}); OpenLayers.Control.PanZoomBar=OpenLayers.Class(OpenLayers.Control.PanZoom,{zoomStopWidth:4,zoomStopHeight:9,slider:null,sliderEvents:null,zoombarDiv:null,zoomWorldIcon:!1,panIcons:!1,forceFixedZoomLevel:!1,mouseDragStart:null,deltaY:null,zoomStart:null,destroy:function(){this._removeZoomBar();this.map.events.un({changebaselayer:this.redraw,updatesize:this.redraw,scope:this});OpenLayers.Control.PanZoom.prototype.destroy.apply(this,arguments);delete this.mouseDragStart;delete this.zoomStart},setMap:function(a){OpenLayers.Control.PanZoom.prototype.setMap.apply(this, arguments);this.map.events.on({changebaselayer:this.redraw,updatesize:this.redraw,scope:this})},redraw:function(){null!=this.div&&(this.removeButtons(),this._removeZoomBar());this.draw()},draw:function(a){OpenLayers.Control.prototype.draw.apply(this,arguments);a=this.position.clone();this.buttons=[];this._addButton("zoomin","zoomin.png",a,{w:18,h:17});centered=this._addZoomBar(a.add(0,17));this._addButton("zoomout","zoomout.png",centered,{w:18,h:18});return this.div},_addButton:function(a,b,c,e){b= S3.Ap.concat("/static/themes/Vulnerability/img/gis/"+b);c=OpenLayers.Util.createAlphaImageDiv(this.id+"_"+a,c,e,b,"absolute");c.style.cursor="pointer";this.div.appendChild(c);c.action=a;c.className="olButton";this.buttons.push(c);return c},_addZoomBar:function(a){var b=S3.Ap.concat("/static/themes/Vulnerability/img/gis/slider.png"),c=this.id+"_"+this.map.id,e=this.map.getMinZoom(),d=this.map.getNumZoomLevels()-1-this.map.getZoom(),d=OpenLayers.Util.createAlphaImageDiv(c,a.add(-1,d*this.zoomStopHeight), {w:18,h:10},b,"absolute");d.style.cursor="move";this.slider=d;this.sliderEvents=new OpenLayers.Events(this,d,null,!0,{includeXY:!0});this.sliderEvents.on({touchstart:this.zoomBarDown,touchmove:this.zoomBarDrag,touchend:this.zoomBarUp,mousedown:this.zoomBarDown,mousemove:this.zoomBarDrag,mouseup:this.zoomBarUp});var f={w:this.zoomStopWidth,h:this.zoomStopHeight*(this.map.getNumZoomLevels()-e)},b=S3.Ap.concat("/static/themes/Vulnerability/img/gis/bar.png"),c=null;OpenLayers.Util.alphaHack()?(c=this.id+ "_"+this.map.id,c=OpenLayers.Util.createAlphaImageDiv(c,a.add(6,0),{w:f.w,h:this.zoomStopHeight},b,"absolute",null,"crop"),c.style.height=f.h+"px"):c=OpenLayers.Util.createDiv("OpenLayers_Control_PanZoomBar_Zoombar"+this.map.id,a.add(6,0),f,b);c.style.cursor="pointer";c.className="olButton";this.zoombarDiv=c;this.div.appendChild(c);this.startTop=parseInt(c.style.top);this.div.appendChild(d);this.map.events.register("zoomend",this,this.moveZoomBar);return a=a.add(0,this.zoomStopHeight*(this.map.getNumZoomLevels()- e))},_removeZoomBar:function(){this.sliderEvents.un({touchstart:this.zoomBarDown,touchmove:this.zoomBarDrag,touchend:this.zoomBarUp,mousedown:this.zoomBarDown,mousemove:this.zoomBarDrag,mouseup:this.zoomBarUp});this.sliderEvents.destroy();this.div.removeChild(this.zoombarDiv);this.zoombarDiv=null;this.div.removeChild(this.slider);this.slider=null;this.map.events.unregister("zoomend",this,this.moveZoomBar)},onButtonClick:function(a){switch(a.buttonElement.action){case "zoomin":this.map.zoomIn();break; case "zoomout":this.map.zoomOut();break;case "zoombarDiv":a=a.buttonXY.y/this.zoomStopHeight;if(this.forceFixedZoomLevel||!this.map.fractionalZoom)a=Math.floor(a);a=this.map.getNumZoomLevels()-1-a;a=Math.min(Math.max(a,0),this.map.getNumZoomLevels()-1);this.map.zoomTo(a)}},passEventToSlider:function(a){this.sliderEvents.handleBrowserEvent(a)},zoomBarDown:function(a){if(OpenLayers.Event.isLeftClick(a)||OpenLayers.Event.isSingleTouch(a))this.map.events.on({touchmove:this.passEventToSlider,mousemove:this.passEventToSlider, mouseup:this.passEventToSlider,scope:this}),this.mouseDragStart=a.xy.clone(),this.zoomStart=a.xy.clone(),this.div.style.cursor="move",this.zoombarDiv.offsets=null,OpenLayers.Event.stop(a)},zoomBarDrag:function(a){if(null!=this.mouseDragStart){var b=this.mouseDragStart.y-a.xy.y,c=OpenLayers.Util.pagePosition(this.zoombarDiv);0<a.clientY-c[1]&&a.clientY-c[1]<parseInt(this.zoombarDiv.style.height)-2&&(b=parseInt(this.slider.style.top)-b,this.slider.style.top=b+"px",this.mouseDragStart=a.xy.clone()); this.deltaY=this.zoomStart.y-a.xy.y;OpenLayers.Event.stop(a)}},zoomBarUp:function(a){if((OpenLayers.Event.isLeftClick(a)||"touchend"===a.type)&&this.mouseDragStart){this.div.style.cursor="";this.map.events.un({touchmove:this.passEventToSlider,mouseup:this.passEventToSlider,mousemove:this.passEventToSlider,scope:this});var b=this.map.zoom;!this.forceFixedZoomLevel&&this.map.fractionalZoom?(b+=this.deltaY/this.zoomStopHeight,b=Math.min(Math.max(b,0),this.map.getNumZoomLevels()-1)):(b+=this.deltaY/this.zoomStopHeight, b=Math.max(Math.round(b),0));this.map.zoomTo(b);this.zoomStart=this.mouseDragStart=null;this.deltaY=0;OpenLayers.Event.stop(a)}},moveZoomBar:function(){var a=(this.map.getNumZoomLevels()-1-this.map.getZoom())*this.zoomStopHeight+this.startTop+1;this.slider.style.top=a+"px"},CLASS_NAME:"OpenLayers.Control.PanZoomBar"}); OpenLayers.Popup.FramedCloudLocation=OpenLayers.Class(OpenLayers.Popup.FramedCloud,{imageSize:new OpenLayers.Size(12,24),maxSize:new OpenLayers.Size(300,300),fixedRelativePosition:!0,relativePosition:"tl",positionBlocks:{tl:{offset:new OpenLayers.Pixel(0,0),padding:new OpenLayers.Bounds(5,0,0,145),blocks:[{size:new OpenLayers.Size(12,24),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(0,0)}]}},initialize:function(a,b,c,e,d,f,h){this.imageSrc=S3.Ap.concat("/static/themes/Vulnerability/img/mapWindowCornerPng8.png"); OpenLayers.Popup.Framed.prototype.initialize.apply(this,arguments);this.contentDiv.className=this.contentDisplayClass},CLASS_NAME:"OpenLayers.Popup.FramedCloudLocation"}); OpenLayers.Handler.FeatureDoubleClick=OpenLayers.Class(OpenLayers.Handler.Feature,{delay:300,single:!0,"double":!0,pixelTolerance:0,dblclickTolerance:13,stopSingle:!1,stopDouble:!1,timerId:null,touchstart:function(a){this.touch||(this.unregisterMouseListeners(),this.touch=!0);this.down=this.getEventInfo(a);this.last=this.getEventInfo(a);return!0},touchmove:function(a){this.last=this.getEventInfo(a);return!0},touchend:function(a){this.down&&(a.xy=this.last.xy,a.lastTouches=this.last.touches,this.handleSingle(a), this.down=null);return!0},unregisterMouseListeners:function(){this.map.events.un({mousedown:this.mousedown,mouseup:this.mouseup,click:this.click,dblclick:this.dblclick,scope:this})},mousedown:function(a){this.down=this.getEventInfo(a);this.last=this.getEventInfo(a);return!0},mouseup:function(a){var b=!0;this.checkModifiers(a)&&this.control.handleRightClicks&&OpenLayers.Event.isRightClick(a)&&(b=this.rightclick(a));return b},click:function(a){this.last||(this.last=this.getEventInfo(a));this.handleSingle(a); return!this.stopSingle},dblclick:function(a){this.handleDouble(a);return!this.stopDouble},handleDouble:function(a){this.passesDblclickTolerance(a)&&(this["double"]&&this.handle(a),this.clearTimer())},handleSingle:function(a){this.passesTolerance(a)&&(null!=this.timerId?(this.last.touches&&1===this.last.touches.length&&(this["double"]&&OpenLayers.Event.stop(a),this.handleDouble(a)),this.last.touches&&2===this.last.touches.length||this.clearTimer()):(this.first=this.getEventInfo(a),a=this.single?OpenLayers.Util.extend({}, a):null,this.queuePotentialClick(a)))},queuePotentialClick:function(a){this.timerId=window.setTimeout(OpenLayers.Function.bind(this.delayedCall,this,a),this.delay)},passesTolerance:function(a){var b=!0;if(null!=this.pixelTolerance&&this.down&&this.down.xy&&(b=this.pixelTolerance>=this.down.xy.distanceTo(a.xy))&&this.touch&&this.down.touches.length===this.last.touches.length){a=0;for(var c=this.down.touches.length;a<c;++a)if(this.getTouchDistance(this.down.touches[a],this.last.touches[a])>this.pixelTolerance){b= !1;break}}return b},getTouchDistance:function(a,b){return Math.sqrt(Math.pow(a.clientX-b.clientX,2)+Math.pow(a.clientY-b.clientY,2))},passesDblclickTolerance:function(a){a=!0;this.down&&this.first&&(a=this.down.xy.distanceTo(this.first.xy)<=this.dblclickTolerance);return a},clearTimer:function(){null!=this.timerId&&(window.clearTimeout(this.timerId),this.timerId=null);null!=this.rightclickTimerId&&(window.clearTimeout(this.rightclickTimerId),this.rightclickTimerId=null)},delayedCall:function(a){this.timerId= null;a&&this.handle(a)},getEventInfo:function(a){var b;if(a.touches){var c=a.touches.length;b=Array(c);for(var e,d=0;d<c;d++)e=a.touches[d],b[d]={clientX:e.clientX,clientY:e.clientY}}return{xy:a.xy,touches:b}},CLASS_NAME:"OpenLayers.Handler.FeatureDoubleClick"}); OpenLayers.Control.SelectFeatureDouble=OpenLayers.Class(OpenLayers.Control.SelectFeature,{initialize:function(a,b){OpenLayers.Control.SelectFeature.prototype.initialize.apply(this,[a,b]);this.handlers={feature:new OpenLayers.Handler.FeatureDoubleClick(this,this.layer,this.callbacks,{geometryTypes:this.geometryTypes,stopDouble:!0})}},CLASS_NAME:"OpenLayers.Control.SelectFeatureDouble"}); OpenLayers.Popup.FramedCloudVolunteer=OpenLayers.Class(OpenLayers.Popup.FramedCloud,{imageSize:new OpenLayers.Size(12,12),maxSize:new OpenLayers.Size(200,200),fixedRelativePosition:!0,relativePosition:"tr",positionBlocks:{tr:{offset:new OpenLayers.Pixel(-80,0),padding:new OpenLayers.Bounds(0,25,0,0),blocks:[{size:new OpenLayers.Size(12,12),anchor:new OpenLayers.Bounds(80,30,null,null),position:new OpenLayers.Pixel(0,0)}]}},initialize:function(a,b,c,e,d,f,h){this.imageSrc=S3.Ap.concat("/static/themes/Vulnerability/img/mapPopupStemVolunteer.png"); OpenLayers.Popup.Framed.prototype.initialize.apply(this,arguments);this.contentDiv.className=this.contentDisplayClass},addCloseBox:function(a){OpenLayers.Popup.Framed.prototype.addCloseBox.apply(this,arguments);this.closeDiv.className="olVolPopupCloseBox"},CLASS_NAME:"OpenLayers.Popup.FramedCloudVolunteer"});
define(['PhysicsComponent'], function (PhysicsComponent) { 'use strict'; function CirclePhysicsComponent(gameObject, center, radius, startingAngle, endingAngle, counterClockwise) { PhysicsComponent.call(this, gameObject); this.center = center; this.radius = radius; if (startingAngle !== null || startingAngle !== undefined) { this.startingAngle = startingAngle; } else { this.startingAngle = 0; } if (endingAngle !== null || endingAngle !== undefined) { this.endingAngle = endingAngle; } else { this.endingAngle = Math.PI * 2; } if (counterClockwise !== null || counterClockwise !== undefined) { this.counterClockwise = counterClockwise; } else { this.counterClockwise = false; } } CirclePhysicsComponent.prototype = Object.create(PhysicsComponent.prototype); CirclePhysicsComponent.prototype.constructor = CirclePhysicsComponent; CirclePhysicsComponent.prototype.update = function () { }; CirclePhysicsComponent.prototype.move = function (speed) { this.center.x += speed.x; this.center.y += speed.y; }; return CirclePhysicsComponent; });
export const SET_ACTIVE_GROUP = 'SET_ACTIVE_GROUP' export function setActiveGroup(groupId) { return { type: SET_ACTIVE_GROUP, groupId } }
define(["lib/text", "lib/pegjs"], function (text, PEG) { var buildMap = {}; var buildTemplateSource = "define('{pluginName}!{moduleName}', [], function () { return {content} });\n"; return { version: '0.1.0', load: function(moduleName, parentRequire, onLoad, config) { var ext = (config.reqpeg && config.reqpeg.extension) || '.pegjs'; var path = (config.reqpeg && config.reqpeg.path) || ''; text.load(path + moduleName + ext, parentRequire, function (source) { if (config.isBuild) { buildMap[moduleName] = PEG.buildParser(source).toSource(); onLoad(); } else { var parser = PEG.buildParser(source); onLoad(parser); } }, config); }, write: function (pluginName, moduleName, write, config) { var content = buildMap[moduleName]; if (content) { write.asModule(pluginName + '!' + moduleName, buildTemplateSource .replace('{pluginName}', pluginName) .replace('{moduleName}', moduleName) .replace('{content}', content)); } } } });