/*!
* jQuery Browser Plugin 0.0.8
* https://github.com/gabceb/jquery-browser-plugin
*
* Original jquery-browser code Copyright 2005, 2015 jQuery Foundation, Inc. and other contributors
* http://jquery.org/license
*
* Modifications Copyright 2015 Gabriel Cebrian
* https://github.com/gabceb
*
* Released under the MIT license
*
* Date: 05-07-2015
*/
/*global window: false */
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], function ($) {
return factory($);
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
// Node-like environment
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function(jQuery) {
"use strict";
function uaMatch( ua ) {
// If an UA is not provided, default to the current browser UA.
if ( ua === undefined ) {
ua = window.navigator.userAgent;
}
ua = ua.toLowerCase();
var match = /(edge)\/([\w.]+)/.exec( ua ) ||
/(opr)[\/]([\w.]+)/.exec( ua ) ||
/(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
var platform_match = /(ipad)/.exec( ua ) ||
/(ipod)/.exec( ua ) ||
/(iphone)/.exec( ua ) ||
/(kindle)/.exec( ua ) ||
/(silk)/.exec( ua ) ||
/(android)/.exec( ua ) ||
/(windows phone)/.exec( ua ) ||
/(win)/.exec( ua ) ||
/(mac)/.exec( ua ) ||
/(linux)/.exec( ua ) ||
/(cros)/.exec( ua ) ||
/(playbook)/.exec( ua ) ||
/(bb)/.exec( ua ) ||
/(blackberry)/.exec( ua ) ||
[];
var browser = {},
matched = {
browser: match[ 5 ] || match[ 3 ] || match[ 1 ] || "",
version: match[ 2 ] || match[ 4 ] || "0",
versionNumber: match[ 4 ] || match[ 2 ] || "0",
platform: platform_match[ 0 ] || ""
};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
browser.versionNumber = parseInt(matched.versionNumber, 10);
}
if ( matched.platform ) {
browser[ matched.platform ] = true;
}
// These are all considered mobile platforms, meaning they run a mobile browser
if ( browser.android || browser.bb || browser.blackberry || browser.ipad || browser.iphone ||
browser.ipod || browser.kindle || browser.playbook || browser.silk || browser[ "windows phone" ]) {
browser.mobile = true;
}
// These are all considered desktop platforms, meaning they run a desktop browser
if ( browser.cros || browser.mac || browser.linux || browser.win ) {
browser.desktop = true;
}
// Chrome, Opera 15+ and Safari are webkit based browsers
if ( browser.chrome || browser.opr || browser.safari ) {
browser.webkit = true;
}
// IE11 has a new token so we will assign it msie to avoid breaking changes
// IE12 disguises itself as Chrome, but adds a new Edge token.
if ( browser.rv || browser.edge ) {
var ie = "msie";
matched.browser = ie;
browser[ie] = true;
}
// Blackberry browsers are marked as Safari on BlackBerry
if ( browser.safari && browser.blackberry ) {
var blackberry = "blackberry";
matched.browser = blackberry;
browser[blackberry] = true;
}
// Playbook browsers are marked as Safari on Playbook
if ( browser.safari && browser.playbook ) {
var playbook = "playbook";
matched.browser = playbook;
browser[playbook] = true;
}
// BB10 is a newer OS version of BlackBerry
if ( browser.bb ) {
var bb = "blackberry";
matched.browser = bb;
browser[bb] = true;
}
// Opera 15+ are identified as opr
if ( browser.opr ) {
var opera = "opera";
matched.browser = opera;
browser[opera] = true;
}
// Stock Android browsers are marked as Safari on Android.
if ( browser.safari && browser.android ) {
var android = "android";
matched.browser = android;
browser[android] = true;
}
// Kindle browsers are marked as Safari on Kindle
if ( browser.safari && browser.kindle ) {
var kindle = "kindle";
matched.browser = kindle;
browser[kindle] = true;
}
// Kindle Silk browsers are marked as Safari on Kindle
if ( browser.safari && browser.silk ) {
var silk = "silk";
matched.browser = silk;
browser[silk] = true;
}
// Assign the name and platform variable
browser.name = matched.browser;
browser.platform = matched.platform;
return browser;
}
// Run the matching process, also assign the function to the returned object
// for manual, jQuery-free use if desired
window.jQBrowser = uaMatch( window.navigator.userAgent );
window.jQBrowser.uaMatch = uaMatch;
// Only assign to jQuery.browser if jQuery is loaded
if ( jQuery ) {
jQuery.browser = window.jQBrowser;
}
return window.jQBrowser;
}));
/* jshint strict: false, maxlen: 90, evil: true */
/* global -$, WYMeditor: true, console */
/*@version 1.1.1 */
/**
WYMeditor
=========
version 1.1.1
WYMeditor : what you see is What You Mean web-based editor
Main JS file with core classes and functions.
Copyright
---------
Copyright (c) 2005 - 2010 Jean-Francois Hovinne, http://www.wymeditor.org/
Dual licensed under the MIT (MIT-license.txt)
and GPL (GPL-license.txt) licenses.
Website
-------
For further information visit:
http://www.wymeditor.org/
Authors
-------
See AUTHORS file
*/
// Global WYMeditor namespace.
if (typeof (WYMeditor) === 'undefined') {
/* jshint -W079 */
var WYMeditor = {};
/* jshint +W079 */
}
// Wrap the Firebug console in WYMeditor.console
(function () {
if (typeof window.console === 'undefined' &&
typeof console === 'undefined') {
// No in-browser console logging available
var names = [
"log", "debug", "info", "warn", "error", "assert", "dir",
"dirxml", "group", "groupEnd", "time", "timeEnd", "count",
"trace", "profile", "profileEnd"
],
noOp = function () {},
i;
WYMeditor.console = {};
for (i = 0; i < names.length; i += 1) {
WYMeditor.console[names[i]] = noOp;
}
} else if (typeof console !== 'undefined') {
// ie8+
WYMeditor.console = console;
} else if (window.console.firebug) {
// FF with firebug
WYMeditor.console = window.console;
} else if (window.console) {
// Chrome
WYMeditor.console = window.console;
}
}());
jQuery.extend(WYMeditor, {
/**
Constants
=========
Global WYMeditor constants.
VERSION - Defines WYMeditor version.
INSTANCES - An array of loaded WYMeditor.editor instances.
STRINGS - An array of loaded WYMeditor language pairs/values.
SKINS - An array of loaded WYMeditor skins.
NAME - The "name" attribute.
WYM_INDEX - A string used to get/set the instance index.
WYM_PATH - A string replaced by WYMeditor's main JS file path.
IFRAME_BASE_PATH - String replaced by the designmode iframe's base path.
IFRAME_DEFAULT - The iframe's default base path.
JQUERY_PATH - A string replaced by the computed jQuery path.
DIRECTION - A string replaced by the text direction (rtl or ltr).
LOGO - A string replaced by WYMeditor logo.
TOOLS - A string replaced by the toolbar's HTML.
TOOLS_ITEMS - A string replaced by the toolbar items.
TOOL_NAME - A string replaced by a toolbar item's name.
TOOL_TITLE - A string replaced by a toolbar item's title.
TOOL_CLASS - A string replaced by a toolbar item's class.
CLASSES - A string replaced by the classes panel's HTML.
CLASSES_ITEMS - A string replaced by the classes items.
CLASS_NAME - A string replaced by a class item's name.
CLASS_TITLE - A string replaced by a class item's title.
CONTAINERS - A string replaced by the containers panel's HTML.
CONTAINERS_ITEMS - A string replaced by the containers items.
CONTAINER_NAME - A string replaced by a container item's name.
CONTAINER_TITLE - A string replaced by a container item's title.
CONTAINER_CLASS - A string replaced by a container item's class.
HTML - A string replaced by the HTML view panel's HTML.
IFRAME - A string replaced by the designmode iframe.
STATUS - A string replaced by the status panel's HTML.
BODY - The BODY element.
STRING - The "string" type.
BODY,DIV,P,
H1,H2,H3,H4,H5,H6,
PRE,BLOCKQUOTE,
A,BR,IMG,
TABLE,TD,TH,
UL,OL,LI - HTML elements string representation.
CLASS,HREF,SRC,
TITLE,REL,ALT - HTML attributes string representation.
KEY - Standard key codes.
NODE - Node types.
*/
A : "a",
ALT : "alt",
BLOCKQUOTE : "blockquote",
BODY : "body",
CLASS : "class",
CLASSES : "{Wym_Classes}",
CLASSES_ITEMS : "{Wym_Classes_Items}",
CLASS_NAME : "{Wym_Class_Name}",
CLASS_TITLE : "{Wym_Class_Title}",
CONTAINERS : "{Wym_Containers}",
CONTAINERS_ITEMS : "{Wym_Containers_Items}",
CONTAINER_CLASS : "{Wym_Container_Class}",
CONTAINER_NAME : "{Wym_Container_Name}",
CONTAINER_TITLE : "{Wym_Containers_Title}",
DIRECTION : "{Wym_Direction}",
DIV : "div",
H1 : "h1",
H2 : "h2",
H3 : "h3",
H4 : "h4",
H5 : "h5",
H6 : "h6",
HREF : "href",
HTML : "{Wym_Html}",
IFRAME : "{Wym_Iframe}",
IFRAME_BASE_PATH : "{Wym_Iframe_Base_Path}",
IFRAME_DEFAULT : "iframe/default/",
IMG : "img",
INSERT_HTML : "InsertHTML",
INSTANCES : [],
JQUERY_PATH : "{Wym_Jquery_Path}",
LI : "li",
LOGO : "{Wym_Logo}",
NAME : "name",
NBSP : '\xA0',
NEWLINE : "\n",
OL : "ol",
P : "p",
PRE : "pre",
REL : "rel",
SKINS : [],
SRC : "src",
STATUS : "{Wym_Status}",
STRING : "string",
STRINGS : [],
TABLE : "table",
TD : "td",
TH : "th",
TITLE : "title",
TOOLS : "{Wym_Tools}",
TOOLS_ITEMS : "{Wym_Tools_Items}",
TOOL_CLASS : "{Wym_Tool_Class}",
TOOL_NAME : "{Wym_Tool_Name}",
TOOL_TITLE : "{Wym_Tool_Title}",
TR : "tr",
UL : "ul",
VERSION : "1.1.1",
WYM_INDEX : "wym_index",
WYM_PATH : "{Wym_Wym_Path}",
// Commands for the `editor.exec` method
EXEC_COMMANDS: {
// Inline wrapping element toggles
BOLD : "Bold",
ITALIC : "Italic",
SUPERSCRIPT : "Superscript",
SUBSCRIPT : "Subscript",
// Other manipulations
CREATE_LINK : "CreateLink",
UNLINK : "Unlink",
FORMAT_BLOCK : "FormatBlock",
INSERT_IMAGE : "InsertImage",
UNDO : "Undo",
REDO : "Redo",
INSERT_LINEBREAK : "InsertLineBreak",
// Lists
INSERT_ORDEREDLIST : "InsertOrderedList",
INSERT_UNORDEREDLIST: "InsertUnorderedList",
INDENT : "Indent",
OUTDENT : "Outdent",
// UI
TOGGLE_HTML : "ToggleHtml"
},
// Containers that we allow at the root of the document (as a direct child
// of the body tag)
ROOT_CONTAINERS : [
"macro",
"blockquote",
"div",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"p",
"pre"
],
// Containers that we explicitly do not allow at the root of the document.
// These containers must be wrapped in a valid root container.
FORBIDDEN_ROOT_CONTAINERS : [
"a",
"b",
"em",
"i",
"span",
"strong",
"sub",
"sup"
],
// All block (as opposed to inline) tags
BLOCKS : [
"macro",
"address",
"blockquote",
"dd",
"div",
"dl",
"dt",
"fieldset",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"li",
"noscript",
"ol",
"p",
"pre",
"table",
"tbody",
"td",
"tfoot",
"th",
"thead",
"tr",
"ul"
],
// The subset of the `ROOT_CONTAINERS` that prevent the user from using
// up/down/enter/backspace from moving above or below them. They
// effectively block the creation of new blocks.
BLOCKING_ELEMENTS : [
"blockquote",
"pre",
"table"
],
// Elements that are not containers. They don't generally have any child
// nodes.
NON_CONTAINING_ELEMENTS : [
"macro",
"br",
"col",
"hr",
"img"
],
// Elements that should not contain collapsed selection directly.
NO_CARET_ELEMENTS: [
"blockquote",
"br",
"col",
"colgroup",
"dl",
"hr",
"img",
"ol",
"table",
"tbody",
"tfoot",
"thead",
"tr",
"ul"
],
// Inline elements.
INLINE_ELEMENTS : [
"a",
"abbr",
"acronym",
"b",
"bdo",
"big",
"br",
"button",
"cite",
"code",
"dfn",
"em",
"i",
"img",
"input",
"kbd",
"label",
"map",
"object",
"q",
"samp",
"script",
"select",
"small",
"span",
"strong",
"sub",
"sup",
"textarea",
"tt",
"var"
],
// The remaining `ROOT_CONTAINERS` that are not considered
// `BLOCKING_ELEMENTS`
NON_BLOCKING_ELEMENTS : [
"div",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"p"
],
// The elements that define a type of list.
LIST_TYPE_ELEMENTS : [
"ol",
"ul"
],
// The elements that define a heading
HEADING_ELEMENTS : [
"h1",
"h2",
"h3",
"h4",
"h5",
"h6"
],
// The elements that are allowed to be turned in to lists. If an item in
// this array isn't in the ROOT_CONTAINERS array, then its contents will be
// turned in to a list instead.
POTENTIAL_LIST_ELEMENTS : [
"blockquote",
"div",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"p",
"pre",
"td"
],
// The elements that are allowed to have a table inserted after them or
// within them.
POTENTIAL_TABLE_INSERT_ELEMENTS : [
"blockquote",
"div",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"li",
"p",
"pre"
],
// The elements that are allowed to have a table inserted inline within
// them.
INLINE_TABLE_INSERTION_ELEMENTS : [
"li"
],
// The elements used in tables that can be selected by the user by clicking
// in them.
SELECTABLE_TABLE_ELEMENTS: [
"caption",
"td",
"th"
],
// Class for marking br elements used to space apart blocking elements in
// the editor.
BLOCKING_ELEMENT_SPACER_CLASS: "wym-blocking-element-spacer",
// Class used to flag an element for removal by the xhtml parser so that
// the element is removed from the output and only shows up internally
// within the editor.
EDITOR_ONLY_CLASS: "wym-editor-only",
// Class for resize handles
RESIZE_HANDLE_CLASS: "wym-resize-handle",
// Classes that will be removed from all tags' class attribute by the
// parser.
CLASSES_REMOVED_BY_PARSER: [
"apple-style-span"
],
// Keyboard mappings so that we don't have to remember that 38 means up
// when reading keyboard handlers
KEY_CODE : {
B: 66,
BACKSPACE: 8,
COMMAND: 224,
CTRL: 17,
CURSOR: [37, 38, 39, 40],
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
HOME: 36,
I: 73,
LEFT: 37,
R: 82,
RIGHT: 39,
TAB: 9,
UP: 38
},
// Key codes for the keys that can potentially create a block element when
// inputted
POTENTIAL_BLOCK_ELEMENT_CREATION_KEYS : [
8, // BACKSPACE
13, // ENTER
37, // LEFT
38, // UP
39, // RIGHT
40, // DOWN
46 // DELETE
],
EVENTS : {
'postBlockMaybeCreated': 'wym-postBlockMaybeCreated',
'postIframeInitialization': 'wym-postIframeInitialization',
'postModification': 'wym-postModification',
'postUndo': 'wym-postUndo',
'postRedo': 'wym-postRedo'
},
// domNode.nodeType constants
NODE_TYPE : {
ELEMENT: 1,
ATTRIBUTE: 2,
TEXT: 3
},
/**
WYMeditor.editor
================
WYMeditor editor main class, instantiated for each editor occurrence.
See also: WYMeditor.editor.init
Use
---
Initializes main values (index, elements, paths, ...)
and calls WYMeditor.editor.init which initializes the editor.
### Parameters
elem - The HTML element to be replaced by the editor.
options - The hash of options.
### Returns
Nothing.
*/
editor : function (elem, options) {
if (jQuery.getWymeditorByTextarea(elem[0])) {
throw "It seems that this textarea already belongs to a " +
"WYMeditor instance.";
}
var wym = this;
// Store the instance in the INSTANCES array and store the index
wym._index = WYMeditor.INSTANCES.push(wym) - 1;
// The element replaced by the editor
wym.element = elem;
wym._options = options;
// Path to the WYMeditor core
wym._options.wymPath = wym._options.wymPath ||
WYMeditor._computeWymPath();
// Path to the main JS files
wym._options.basePath = wym._options.basePath ||
WYMeditor._computeBasePath(wym._options.wymPath);
// The designmode iframe's base path
wym._options.iframeBasePath = wym._options.iframeBasePath ||
wym._options.basePath + WYMeditor.IFRAME_DEFAULT;
// Initialize the editor instance
wym._init();
},
EXTERNAL_MODULES : {}
});
/********** jQuery Plugin Definition **********/
/**
wymeditor
=========
jQuery plugin function for replacing an HTML element with a WYMeditor
instance.
Example
-------
`jQuery(".wymeditor").wymeditor({});`
*/
jQuery.fn.wymeditor = function (options) {
var $textareas = this;
options = jQuery.extend({
html: "",
basePath: false,
wymPath: false,
iframeBasePath: false,
jQueryPath: false,
skin: "default",
lang: "en",
direction: "ltr",
customCommands: [],
// These values will override the default for their respective
// `DocumentStructureManager.structureRules`
structureRules: {
defaultRootContainer: 'p'
},
boxHtml: String() +
"
" +
"
" +
WYMeditor.TOOLS +
"
" +
"
" +
"
" +
WYMeditor.CONTAINERS +
WYMeditor.CLASSES +
"
" +
"
" +
WYMeditor.HTML +
WYMeditor.IFRAME +
WYMeditor.STATUS +
"
" +
"
" +
WYMeditor.LOGO +
"
" +
"
",
logoHtml: String() +
'WYMeditor',
iframeHtml: String() +
'' +
'' +
"
",
toolsHtml: String() +
'',
toolsItemHtml: String() +
'' +
'' +
WYMeditor.TOOL_TITLE +
'' +
'',
toolsItems: [
{
'name': 'Bold',
'title': 'Strong',
'css': 'wym_tools_strong'
},
{
'name': 'Italic',
'title': 'Emphasis',
'css': 'wym_tools_emphasis'
},
{
'name': 'Superscript',
'title': 'Superscript',
'css': 'wym_tools_superscript'
},
{
'name': 'Subscript',
'title': 'Subscript',
'css': 'wym_tools_subscript'
},
{
'name': 'InsertOrderedList',
'title': 'Ordered_List',
'css': 'wym_tools_ordered_list'
},
{
'name': 'InsertUnorderedList',
'title': 'Unordered_List',
'css': 'wym_tools_unordered_list'
},
{
'name': 'Indent',
'title': 'Indent',
'css': 'wym_tools_indent'
},
{
'name': 'Outdent',
'title': 'Outdent',
'css': 'wym_tools_outdent'
},
{
'name': 'Undo',
'title': 'Undo',
'css': 'wym_tools_undo'
},
{
'name': 'Redo',
'title': 'Redo',
'css': 'wym_tools_redo'
},
{
'name': 'CreateLink',
'title': 'Link',
'css': 'wym_tools_link wym_opens_dialog'
},
{
'name': 'Unlink',
'title': 'Unlink',
'css': 'wym_tools_unlink'
},
{
'name': 'InsertImage',
'title': 'Image',
'css': 'wym_tools_image wym_opens_dialog'
},
{
'name': 'InsertTable',
'title': 'Table',
'css': 'wym_tools_table wym_opens_dialog'
},
{
'name': 'Paste',
'title': 'Paste_From_Word',
'css': 'wym_tools_paste wym_opens_dialog'
},
{
'name': 'ToggleHtml',
'title': 'HTML',
'css': 'wym_tools_html'
},
{
'name': 'Preview',
'title': 'Preview',
'css': 'wym_tools_preview wym_opens_dialog'
}
],
containersHtml: String() +
'' +
'
{Containers}
' +
'
' +
WYMeditor.CONTAINERS_ITEMS +
'
' +
'
',
containersItemHtml: String() +
'' +
'' +
WYMeditor.CONTAINER_TITLE +
'' +
'',
containersItems: [
{'name': 'P', 'title': 'Paragraph', 'css': 'wym_containers_p'},
{'name': 'H1', 'title': 'Heading_1', 'css': 'wym_containers_h1'},
{'name': 'H2', 'title': 'Heading_2', 'css': 'wym_containers_h2'},
{'name': 'H3', 'title': 'Heading_3', 'css': 'wym_containers_h3'},
{'name': 'H4', 'title': 'Heading_4', 'css': 'wym_containers_h4'},
{'name': 'H5', 'title': 'Heading_5', 'css': 'wym_containers_h5'},
{'name': 'H6', 'title': 'Heading_6', 'css': 'wym_containers_h6'},
{'name': 'PRE', 'title': 'Preformatted', 'css': 'wym_containers_pre'},
{'name': 'BLOCKQUOTE', 'title': 'Blockquote',
'css': 'wym_containers_blockquote'},
{'name': 'TH', 'title': 'Table_Header', 'css': 'wym_containers_th'}
],
classesHtml: String() +
'' +
'
{Classes}
' +
'
' +
WYMeditor.CLASSES_ITEMS +
'
' +
'
',
classesItemHtml: String() +
'' +
'' +
WYMeditor.CLASS_TITLE +
'' +
'',
classesItems: [],
statusHtml: String() +
'' +
'
{Status}
' +
'',
htmlHtml: String() +
'' +
'
{Source_Code}
' +
'' +
'',
boxSelector: ".wym_box",
toolsSelector: ".wym_tools",
toolsListSelector: " ul",
containersSelector: ".wym_containers",
classesSelector: ".wym_classes",
htmlSelector: ".wym_html",
iframeSelector: ".wym_iframe iframe",
iframeBodySelector: ".wym_iframe",
statusSelector: ".wym_status",
toolSelector: ".wym_tools a",
containerSelector: ".wym_containers a",
classSelector: ".wym_classes a",
htmlValSelector: ".wym_html_val",
updateSelector: ".wymupdate",
updateEvent: "click",
stringDelimiterLeft: "{",
stringDelimiterRight: "}",
preInit: null,
preBind: null,
postInit: null
}, options);
options = jQuery.extend(WYMeditor.DEFAULT_DIALOG_OPTIONS, options);
return $textareas.each(function () {
var textarea = this;
// Assigning to _wym because the return value from new isn't
// actually used, but we need to use new to properly change the
// prototype
textarea._wym = new WYMeditor.editor(jQuery(textarea), options);
});
};
// Enable accessing of wymeditor instances via jQuery.wymeditors
jQuery.extend({
wymeditors: function (i) {
return WYMeditor.INSTANCES[i];
}
});
jQuery.extend({
getWymeditorByTextarea: function (textarea) {
var i;
if (
!(
textarea &&
textarea.tagName &&
textarea.tagName.toLowerCase() === 'textarea'
)
) {
throw "jQuery.getWymeditorByTextarea requires a textarea element.";
}
for (i = 0; i < WYMeditor.INSTANCES.length; i++) {
if (textarea === WYMeditor.INSTANCES[i].element[0]) {
return WYMeditor.INSTANCES[i];
}
}
return false;
}
});
/**
jQuery.copyPropsFromObjectToObject
=====================================
General helper function that copies specified list of properties from a
specified origin object to a specified target object.
@param origin The origin object.
@param target The target object.
@param propNames An array of strings, representing the properties to copy.
*/
jQuery.extend({
copyPropsFromObjectToObject: function (origin, target, propNames) {
var i,
propName,
prop,
props = {};
for (i = 0; i < propNames.length; i++) {
propName = propNames[i];
prop = origin[propName];
props[propName] = prop;
}
jQuery.extend(target, props);
}
});
/**
WYMeditor.isInternetExplorerPre11
=================================
Returns true if the current browser is an Internet Explorer version
previous to 11. Otherwise, returns false.
*/
WYMeditor.isInternetExplorerPre11 = function () {
if (
jQuery.browser.msie &&
jQuery.browser.versionNumber < 11
) {
return true;
}
return false;
};
/**
WYMeditor.isInternetExplorer11OrNewer
=====================================
Returns true if the current browser is an Internet Explorer version 11 or
newer. Otherwise, returns false.
*/
WYMeditor.isInternetExplorer11OrNewer = function () {
if (
jQuery.browser.msie &&
jQuery.browser.versionNumber >= 11
) {
return true;
}
return false;
};
/**
WYMeditor._computeWymPath
=========================
Get the relative path to the WYMeditor core js file for usage as
a src attribute for script inclusion.
Looks for script tags on the current page and finds the first matching
src attribute matching any of these values:
* jquery.wymeditor.pack.js
* jquery.wymeditor.min.js
* jquery.wymeditor.packed.js
* jquery.wymeditor.js
* /core.js
*/
WYMeditor._computeWymPath = function () {
var script = jQuery(
jQuery.grep(
jQuery('script'),
function (s) {
if (!s.src) {
return null;
}
return (
s.src.match(
/jquery\.wymeditor(\.pack|\.min|\.packed)?\.js(\?.*)?$/
) ||
s.src.match(
/\/core\.js(\?.*)?$/
)
);
}
)
);
if (script.length > 0) {
return script.attr('src');
}
// We couldn't locate the base path. This will break language loading
// and other features.
WYMeditor.console.warn(
"Error determining wymPath. No base WYMeditor file located."
);
WYMeditor.console.warn("Assuming wymPath to be the current URL");
WYMeditor.console.warn("Please pass a correct wymPath option");
// Guess that the wymPath is the current directory
return '';
};
/**
WYMeditor._computeBasePath
==========================
Get the relative path to the WYMeditor directory root based on the path to
the wymeditor base file. This path is used as the basis for loading:
* Language files
* Skins
* The popup document https://github.com/wymeditor/wymeditor/issues/731
*/
WYMeditor._computeBasePath = function (wymPath) {
// Strip everything after the last slash to get the base path
var lastSlashIndex = wymPath.lastIndexOf('/');
return wymPath.substr(0, lastSlashIndex + 1);
};
/********** HELPERS **********/
// Returns true if it is a text node with whitespaces only
jQuery.fn.isPhantomNode = function () {
var $nodes = this;
if ($nodes[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
return !(/[^\t\n\r ]/.test($nodes[0].data));
}
return false;
};
/**
jQuery.fn.nextContentsUntil
===========================
Acts like jQuery.nextUntil() but includes text nodes and comments and only
works on the first element in the given jQuery collection..
*/
jQuery.fn.nextContentsUntil = function (selector, filter) {
var $nodes = this,
matched = [],
$matched,
cur = $nodes.get(0);
selector = selector ? selector : '';
filter = filter ? filter : '';
if (!cur) {
// Called on an empty selector. The sibling of nothing is nothing
return jQuery();
}
// We don't want to include this element, only its siblings
cur = cur.nextSibling;
while (cur) {
if (!jQuery(cur).is(selector)) {
matched.push(cur);
cur = cur.nextSibling;
} else {
break;
}
}
$matched = jQuery(matched);
if (filter) {
return $matched.filter(filter);
}
return $matched;
};
/**
jQuery.fn.nextAllContents
=========================
Acts like jQuery.nextAll() but includes text nodes and comments and only
works on the first element in the given jQuery collection..
Mostly cribbed from the jQuery source.
*/
jQuery.fn.nextAllContents = function () {
var $nodes = this;
return jQuery($nodes).nextContentsUntil('', '');
};
/**
jQuery.fn.prevContentsUntil
===========================
Acts like jQuery.prevUntil() but includes text nodes and comments and only
works on the first element in the given jQuery collection..
*/
jQuery.fn.prevContentsUntil = function (selector, filter) {
var $nodes = this,
matched = [],
$matched,
cur = $nodes.get(0);
selector = selector ? selector : '';
filter = filter ? filter : '';
if (!cur) {
// Called on an empty selector. The sibling of nothing is nothing
return jQuery();
}
// We don't want to include this element, only its siblings
cur = cur.previousSibling;
while (cur) {
if (!jQuery(cur).is(selector)) {
matched.push(cur);
cur = cur.previousSibling;
} else {
break;
}
}
$matched = jQuery(matched);
if (filter) {
return $matched.filter(filter);
}
return $matched;
};
/**
jQuery.fn.prevAllContents
=========================
Acts like jQuery.prevAll() but includes text nodes and comments and only
works on the first element in the given jQuery collection..
Mostly cribbed from the jQuery source.
*/
jQuery.fn.prevAllContents = function () {
var $nodes = this;
return jQuery($nodes).prevContentsUntil('', '');
};
WYMeditor.isPhantomNode = function (n) {
if (n.nodeType === WYMeditor.NODE_TYPE.TEXT) {
return !(/[^\t\n\r ]/.test(n.data));
}
return false;
};
WYMeditor.isPhantomString = function (str) {
return !(/[^\t\n\r ]/.test(str));
};
jQuery.fn.addBack = jQuery.fn.addBack ? jQuery.fn.addBack : jQuery.fn.andSelf;
// Returns the Parents or the node itself
// `selector` = a jQuery selector
jQuery.fn.parentsOrSelf = function (selector) {
var $n = this;
if (selector) {
return $n.parents().addBack().filter(selector);
} else {
return $n.parents().addBack();
}
};
// Various helpers
WYMeditor.Helper = {
//replace all instances of 'old' by 'rep' in 'str' string
replaceAllInStr: function (str, old, rep) {
var rExp = new RegExp(old, "g");
return str.replace(rExp, rep);
},
//insert 'inserted' at position 'pos' in 'str' string
insertAt: function (str, inserted, pos) {
return str.substr(0, pos) + inserted + str.substring(pos);
},
//trim 'str' string
trim: function (str) {
return str.replace(/^(\s*)|(\s*)$/gm, '');
},
//Returns true if `array`` contains `thing`. Uses `===` for comparison of
//provided `thing` with contents of provided `array`.
arrayContains: function (arr, elem) {
var i;
for (i = 0; i < arr.length; i += 1) {
if (arr[i] === elem) {
return true;
}
}
return false;
},
//return 'item' position in 'arr' array, or -1
indexOf: function (arr, item) {
var ret = -1, i;
for (i = 0; i < arr.length; i += 1) {
if (arr[i] === item) {
ret = i;
break;
}
}
return ret;
},
//return 'item' object in 'arr' array, checking its 'name' property, or null
_getFromArrayByName: function (arr, name) {
var i, item;
for (i = 0; i < arr.length; i += 1) {
item = arr[i];
if (item.name === name) {
return item;
}
}
return null;
},
// naively returns all event types
// of the provided an element
// according the its property keys that
// begin with 'on'
getAllEventTypes: function (elem) {
var result = [];
for (var key in elem) {
if (key.indexOf('on') === 0 && key !== 'onmousemove') {
result.push(key.slice(2));
}
}
return result.join(' ');
}
};
/**
WYMeditor._getWymClassForBrowser
================================
Returns the constructor for the browser-specific wymeditor instance.
If does not detect a supported browser, returns false;
*/
WYMeditor._getWymClassForBrowser = function () {
// Using https://github.com/gabceb/jquery-browser-plugin
switch (jQuery.browser.name) {
case "msie":
if (WYMeditor.isInternetExplorerPre11()) {
return WYMeditor.WymClassTridentPre7;
} else if (WYMeditor.isInternetExplorer11OrNewer()) {
return WYMeditor.WymClassTrident7;
} else {
return false;
}
break;
case "mozilla":
return WYMeditor.WymClassGecko;
case "chrome":
return WYMeditor.WymClassBlink;
case "safari":
return WYMeditor.WymClassSafari;
}
if (jQuery.browser.webkit) {
return WYMeditor.WymClassWebKit;
}
WYMeditor.console.warn("WYMeditor could not instantiate: this browser " +
"is not supported");
return false;
};
"use strict";
/**
editor._openPopupWindow
=======================
Opens a popup window, provided the `windowFeatures`.
*/
WYMeditor.editor.prototype._openPopupWindow = function (windowFeatures) {
var wym = this,
popup,
basePath = wym._options.basePath;
popup = window.open(
// https://github.com/wymeditor/wymeditor/issues/731
jQuery.browser.msie ? basePath + 'popup.html' : '',
"wymPopupWindow",
windowFeatures
);
return popup;
};
/**
editor.dialog
=============
Open a dialog box
*/
WYMeditor.editor.prototype.dialog = function (
dialog,
pDialogWindowFeatures,
pBodyHtml
) {
var wym = this,
i,
DIALOGS = WYMeditor.DIALOGS,
dialogObject,
dialogWindowFeatures,
wDialog,
htmlStrReplacements,
dialogHtml,
doc,
selectedContainer,
options = wym._options;
if (jQuery.isPlainObject(dialog)) {
// Dialog object provided. This is the documented public API way.
dialogObject = dialog;
} else if (
// Dialog name string provided. This is undocumented.
typeof dialog === "string" &&
DIALOGS.hasOwnProperty(dialog)
) {
WYMeditor.console.warn("DEPRECATION WARNING: `dialog` method " +
"received a string dialog name. Please provide a dialog object " +
"instead.");
dialogObject = DIALOGS[dialog];
}
if (
jQuery.isPlainObject(dialogObject) !== true &&
typeof pBodyHtml !== "string"
) {
throw "`dialog` method: No dialog provided";
}
if (dialogObject) {
if (
dialogObject.hasOwnProperty("title") !== true ||
dialogObject.hasOwnProperty("shouldOpen") !== true ||
dialogObject.hasOwnProperty("getBodyHtml") !== true
) {
throw "Expected the dialog object to contain at least `title`, " +
"`shouldOpen` and `getbodyHtml`";
}
}
// Return `false` early if this dialog should not open. Use the dialog's
// own function to check this.
if (
dialogObject &&
dialogObject.shouldOpen.call(wym) !== true
) {
return false;
}
// Close any existing dialog, just in case
if (wym.opened_dialog)
wym.opened_dialog.close();
dialogHtml = pBodyHtml || dialogObject.getBodyHtml.call(wym);
dialogHtml = wym.replaceStrings(dialogHtml);
dialogHtml = '' + dialogHtml + '
';
dialog = jQuery(dialogHtml).insertAfter(wym.element);
if (dialogObject && dialogObject.getBodyClass) {
jQuery(dialog).addClass(dialogObject.getBodyClass.call(wym));
}
// Fake a popup window object
wDialog = wym.opened_dialog = {
close: function() {
dialog.remove();
wym.opened_dialog = undefined;
}
};
// Pre-init function
if (jQuery.isFunction(options.preInitDialog)) {
options.preInitDialog(wym, wDialog);
}
// Dialog-specific initialization
if (dialogObject && dialogObject.initialize) {
dialogObject.initialize.call(wym, wDialog);
}
if (dialogObject && dialogObject.submitHandler) {
// TODO: One alternative could be to remove this code and let
// dialogObject.initialize() register its own handler (and use
// it's own class or id for the form).
jQuery("form.wym_dialog_submit", dialog).submit(function () {
dialogObject.submitHandler.call(wym, wDialog);
});
}
// Cancel button
jQuery(options.cancelSelector, dialog).click(function () {
wDialog.close();
wym.focusOnDocument();
});
// Post-init function
if (jQuery.isFunction(options.postInitDialog)) {
options.postInitDialog(wym, wDialog);
}
return wDialog;
};
/*
* An object of default dialogs.
*
* See API documentation for the `dialog` method.
*/
WYMeditor.DIALOGS = {
CreateLink: {
title: "Link",
shouldOpen: function () {
var wym = this,
selectedContainer;
if (wym.hasSelection() !== true) {
return false;
}
selectedContainer = wym.selectedContainer();
if (selectedContainer === false) {
return false;
}
if (
wym.selection().isCollapsed &&
selectedContainer.tagName.toLowerCase() !== "a"
) {
return false;
}
return true;
},
getBodyHtml: function () {
var wym = this;
return wym._options.dialogLinkHtml || String() +
'';
},
getBodyClass: function () {
var wym = this;
return wym._options.dialogSelectorLink || "wym_dialog_link";
},
initialize: function (wDialog) {
var wym = this,
doc = wDialog.document,
options = wym._options,
selectedContainer = wym.selectedContainer(),
$hrefInput,
$titleInput,
$relInput,
currentHref,
currentTitle,
currentRel;
if (!selectedContainer) {
return;
}
$hrefInput = jQuery(options.hrefSelector, doc);
$titleInput = jQuery(options.titleSelector, doc);
$relInput = jQuery(options.relSelector, doc);
currentHref = jQuery(selectedContainer).attr(WYMeditor.HREF);
currentTitle = jQuery(selectedContainer).attr(WYMeditor.TITLE);
currentRel = jQuery(selectedContainer).attr(WYMeditor.REL);
$hrefInput.val(currentHref);
$titleInput.val(currentTitle);
$relInput.val(currentRel);
},
submitHandler: function (wDialog) {
var wym = this,
options = wym._options,
href = jQuery(options.hrefSelector, wDialog.document).val(),
title = jQuery(options.titleSelector, wDialog.document).val(),
rel = jQuery(options.relSelector, wDialog.document).val();
wym.link({
href: href,
title: title,
rel: rel
});
wDialog.close();
}
},
InsertImage: {
title: "Image",
shouldOpen: function () {
var wym = this,
selectedImage = wym.getSelectedImage();
if (
selectedImage &&
selectedImage.tagName &&
selectedImage.tagName.toLowerCase() === "img"
) {
return true;
}
return wym.hasSelection();
},
getBodyHtml: function () {
var wym = this;
return wym._options.dialogImageHtml || String() +
'';
},
getBodyClass: function () {
var wym = this;
return wym._options.dialogImageSelector || "wym_dialog_image";
},
initialize: function (wDialog) {
var wym = this,
doc = wDialog.document,
options = wym._options,
selectedImage = wym.getSelectedImage(),
$srcInput,
$titleInput,
$altInput,
currentSrc,
currentTitle,
currentAlt;
if (!selectedImage) {
return;
}
$srcInput = jQuery(options.srcSelector, doc);
$titleInput = jQuery(options.titleSelector, doc);
$altInput = jQuery(options.altSelector, doc);
currentSrc = jQuery(selectedImage).attr(WYMeditor.SRC);
currentTitle = jQuery(selectedImage).attr(WYMeditor.TITLE);
currentAlt = jQuery(selectedImage).attr(WYMeditor.ALT);
$srcInput.val(currentSrc);
$titleInput.val(currentTitle);
$altInput.val(currentAlt);
},
submitHandler: function (wDialog) {
var wym = this,
options = wym._options,
imgAttrs,
selectedImage = wym.getSelectedImage();
imgAttrs = {
src: jQuery(options.srcSelector, wDialog.document).val(),
title: jQuery(options.titleSelector, wDialog.document).val(),
alt: jQuery(options.altSelector, wDialog.document).val()
};
wym.focusOnDocument();
if (selectedImage) {
wym._updateImageAttrs(selectedImage, imgAttrs);
wym.registerModification();
} else {
wym.insertImage(imgAttrs);
}
wDialog.close();
}
},
InsertTable: {
title: "Table",
shouldOpen: function () {
var wym = this;
if (
wym.hasSelection() !== true ||
wym.selection().isCollapsed !== true
) {
return false;
}
return true;
},
getBodyHtml: function () {
var wym = this;
return wym._options.dialogTableHtml || String() +
'';
},
getBodyClass: function () {
var wym = this;
return wym._options.dialogTableSelector || "wym_dialog_table";
},
submitHandler: function (wDialog) {
var wym = this,
options = wym._options,
doc = wDialog.document,
numRows = jQuery(options.rowsSelector, doc).val(),
numColumns = jQuery(options.colsSelector, doc).val(),
caption = jQuery(options.captionSelector, doc).val(),
summary = jQuery(options.summarySelector, doc).val();
wym.insertTable(numRows, numColumns, caption, summary);
wDialog.close();
}
},
Paste: {
title: "Paste_From_Word",
shouldOpen: function () {
var wym = this;
return wym.hasSelection();
},
getBodyHtml: function () {
var wym = this;
return wym._options.dialogPasteHtml || String() +
'';
},
getBodyClass: function () {
var wym = this;
return wym._options.dialogPasteSelector || "wym_dialog_paste";
},
submitHandler: function (wDialog) {
var wym = this,
sText;
sText = jQuery(wym._options.textSelector, wDialog.document).val();
wym.paste(sText);
wDialog.close();
}
},
Preview: {
title: "Preview",
shouldOpen: function () {
return true;
},
getBodyHtml: function () {
var wym = this;
return wym._options.dialogPreviewHtml || wym.html();
},
getWindowFeatures: function () {
return [
"menubar=no",
"titlebar=no",
"toolbar=no",
"resizable=no",
"width=560",
"height=300",
"top=0",
"left=0",
"scrollbars=yes"
].join(",");
},
getBodyClass: function () {
var wym = this;
return wym._options.dialogPreviewSelector || "wym_dialog_preview";
}
}
};
WYMeditor.DIALOG_TITLE = "{Wym_Dialog_Title}";
WYMeditor.DIALOG_BODY = "{Wym_Dialog_Body}";
WYMeditor.DIALOG_BUTTON_SELECTOR = ".wym_opens_dialog a";
WYMeditor.DEFAULT_DIALOG_OPTIONS = {
hrefSelector: ".wym_href",
srcSelector: ".wym_src",
titleSelector: ".wym_title",
relSelector: ".wym_rel",
altSelector: ".wym_alt",
textSelector: ".wym_text",
rowsSelector: ".wym_rows",
colsSelector: ".wym_cols",
captionSelector: ".wym_caption",
summarySelector: ".wym_summary",
submitSelector: "form",
cancelSelector: ".wym_cancel",
previewSelector: "",
dialogLinkSelector: ".wym_dialog_link",
dialogImageSelector: ".wym_dialog_image",
dialogTableSelector: ".wym_dialog_table",
dialogPasteSelector: ".wym_dialog_paste",
dialogPreviewSelector: ".wym_dialog_preview"
};
/* jshint evil: true, camelcase: false, maxlen: 100 */
/* global -$, rangy */
"use strict";
/**
WYMeditor.editor._init
======================
Initialize a wymeditor instance, including detecting the
current browser and enabling the browser-specific subclass.
*/
WYMeditor.editor.prototype._init = function () {
// Load the browser-specific subclass
// If this browser isn't supported, do nothing
var wym = this,
WymClass,
browserInstance,
SaxListener,
prop,
h,
iframeHtml,
boxHtml,
aTools,
sTools,
oTool,
sTool,
i,
aClasses,
sClasses,
oClass,
sClass,
aContainers,
sContainers,
sContainer,
oContainer;
// Get the constructor for the browser-specific instance
WymClass = WYMeditor._getWymClassForBrowser();
if (!WymClass) {
// We don't support this browser. Don't initialize.
return;
}
// Initialize the browser-specific instance
browserInstance = new WymClass(wym);
if (jQuery.isFunction(wym._options.preInit)) {
wym._options.preInit(wym);
}
wym.parser = null;
wym.helper = null;
SaxListener = new WYMeditor.XhtmlSaxListener();
wym.parser = new WYMeditor.XhtmlParser(SaxListener);
wym.helper = new WYMeditor.XmlHelper();
// Extend the editor object with the browser-specific version.
// We're not using jQuery.extend because we *want* to copy properties via
// the prototype chain
for (prop in browserInstance) {
/*jshint forin: false*/
// Explicitly not using hasOwnProperty for the inheritance here
// because we want to go up the prototype chain to get all of the
// browser-specific editor methods. This is kind of a code smell,
// but works just fine.
wym[prop] = browserInstance[prop];
}
// Load wymbox
wym._box = jQuery(wym.element).hide().after(
wym._options.boxHtml
).next().addClass(
'wym_box_' + wym._index
);
// Store the instance index and replaced element in wymbox
// but keep it compatible with jQuery < 1.2.3, see #122
if (jQuery.isFunction(jQuery.fn.data)) {
jQuery.data(wym._box.get(0), WYMeditor.WYM_INDEX, wym._index);
jQuery.data(wym.element.get(0), WYMeditor.WYM_INDEX, wym._index);
}
h = WYMeditor.Helper;
// Construct the iframe
iframeHtml = wym._options.iframeHtml;
iframeHtml = h.replaceAllInStr(
iframeHtml,
WYMeditor.IFRAME_BASE_PATH,
wym._options.iframeBasePath
);
// Construct wymbox
boxHtml = jQuery(wym._box).html();
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.LOGO, wym._options.logoHtml);
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.TOOLS, wym._options.toolsHtml);
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.CONTAINERS, wym._options.containersHtml);
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.CLASSES, wym._options.classesHtml);
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.HTML, wym._options.htmlHtml);
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.IFRAME, iframeHtml);
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.STATUS, wym._options.statusHtml);
// Construct the tools list
aTools = eval(wym._options.toolsItems);
sTools = "";
for (i = 0; i < aTools.length; i += 1) {
oTool = aTools[i];
sTool = '';
if (oTool.name && oTool.title) {
sTool = wym._options.toolsItemHtml;
}
sTool = h.replaceAllInStr(sTool, WYMeditor.TOOL_NAME, oTool.name);
sTool = h.replaceAllInStr(
sTool,
WYMeditor.TOOL_TITLE,
wym._options.stringDelimiterLeft + oTool.title + wym._options.stringDelimiterRight
);
sTool = h.replaceAllInStr(sTool, WYMeditor.TOOL_CLASS, oTool.css);
sTools += sTool;
}
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.TOOLS_ITEMS, sTools);
// Construct the classes list
aClasses = eval(wym._options.classesItems);
sClasses = "";
for (i = 0; i < aClasses.length; i += 1) {
oClass = aClasses[i];
sClass = '';
if (oClass.name && oClass.title) {
sClass = wym._options.classesItemHtml;
}
sClass = h.replaceAllInStr(sClass, WYMeditor.CLASS_NAME, oClass.name);
sClass = h.replaceAllInStr(sClass, WYMeditor.CLASS_TITLE, oClass.title);
sClasses += sClass;
}
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.CLASSES_ITEMS, sClasses);
// Construct the containers list
aContainers = eval(wym._options.containersItems);
sContainers = "";
for (i = 0; i < aContainers.length; i += 1) {
oContainer = aContainers[i];
sContainer = '';
if (oContainer.name && oContainer.title) {
sContainer = wym._options.containersItemHtml;
}
sContainer = h.replaceAllInStr(
sContainer,
WYMeditor.CONTAINER_NAME,
oContainer.name
);
sContainer = h.replaceAllInStr(sContainer, WYMeditor.CONTAINER_TITLE,
wym._options.stringDelimiterLeft +
oContainer.title +
wym._options.stringDelimiterRight);
sContainer = h.replaceAllInStr(
sContainer,
WYMeditor.CONTAINER_CLASS,
oContainer.css
);
sContainers += sContainer;
}
boxHtml = h.replaceAllInStr(boxHtml, WYMeditor.CONTAINERS_ITEMS, sContainers);
// I10n
boxHtml = wym.replaceStrings(boxHtml);
// Load the html in wymbox
jQuery(wym._box).html(boxHtml);
// Hide the html value
jQuery(wym._box).find(wym._options.htmlSelector).hide();
wym.documentStructureManager = new WYMeditor.DocumentStructureManager(
wym,
wym._options.structureRules.defaultRootContainer
);
// Some browsers like to trigger an iframe's load event multiple times
// depending on all sorts of small, annoying details. Instead of attempting
// to work-around old ones and predict new ones, let's just ensure the
// initialization only happens once. All methods of detecting load are
// unreliable.
wym.iframeInitialized = false;
wym._iframe = jQuery(wym._box).find('iframe')[0];
jQuery(wym._iframe).on('load', function () {
wym._onEditorIframeLoad(wym);
});
wym.element.attr('data-wym-initialized', 'yes');
wym._initSkin();
};
/**
WYMeditor.editor._assignWymDoc
==============================
Assigns an editor's document to the `_doc` property.
*/
WYMeditor.editor.prototype._assignWymDoc = function () {
var wym = this;
wym._doc = wym._iframe.contentDocument;
};
/**
WYMeditor.editor._isDesignModeOn
================================
Returns true if the designMode property of the editor's document is "On".
Returns false, otherwise.
*/
WYMeditor.editor.prototype._isDesignModeOn = function () {
var wym = this;
if (
typeof wym._doc.designMode === "string" &&
wym._doc.designMode.toLowerCase() === "on"
) {
return true;
}
return false;
};
/**
WYMeditor.editor._onEditorIframeLoad
====================================
This is a part of the initialization of an editor.
The initialization procedure of an editor turns asynchronous because part of
it must occur after the loading of the editor's Iframe.
This function is supposed to be the event handler of the loading of the
editor's Iframe. Therefore, it is the first step since the initialization
procedure gets asynchronous.
@param wym The editor instance that's being initialized.
*/
WYMeditor.editor.prototype._onEditorIframeLoad = function (wym) {
wym._setBaseUrl();
wym._assignWymDoc();
wym._enableDesignModeOnDocument();
wym._afterDesignModeOn();
};
/**
WYMeditor.editor.get$Buttons
============================
Returns a jQuery object, containing all the UI buttons.
*/
WYMeditor.editor.prototype.get$Buttons = function () {
var wym = this,
buttonsSelector,
$buttons;
buttonsSelector = [
wym._options.toolSelector,
wym._options.containerSelector,
wym._options.classSelector
].join(', ');
$buttons = jQuery(wym._box).find(buttonsSelector);
return $buttons;
};
/**
WYMeditor.editor.focusOnDocument
================================
Sets focus on the document.
*/
WYMeditor.editor.prototype.focusOnDocument = function () {
var wym = this,
doc = wym._iframe.contentWindow;
doc.focus();
};
/**
WYMeditor.editor.registerModification
=====================================
Registers a change in the document. This should be called after changes
are made in the document.
Triggers the `postModification` event afterwards.
*/
WYMeditor.editor.prototype.registerModification = function (isNativeEdit) {
var wym = this;
wym.undoRedo._add();
if (!isNativeEdit) {
// A non-native-edit modification is registered. Reset Edited.
wym.nativeEditRegistration.edited.reset();
}
jQuery(wym.element).trigger(WYMeditor.EVENTS.postModification);
};
/**
WYMeditor.editor._bindFocusOnDocumentToButtons
==============================================
Binds a handler to clicks on the UI buttons, that sets focus back to the
document.
Doesn't bind to dialog-opening buttons, because that would cause them to
fall behind the opening window, in some browsers.
*/
WYMeditor.editor.prototype._bindFocusOnDocumentToButtons = function () {
var wym = this,
$buttons = wym.get$Buttons();
$buttons = $buttons.parent().not('.wym_opens_dialog').children('a');
$buttons.click(function () {
wym.focusOnDocument();
});
};
/**
WYMeditor.editor._uiQuirks
==========================
A hook for browser quirks that work on the UI.
To be run after plugins had a chance to modify the UI.
*/
WYMeditor.editor.prototype._uiQuirks = function () {
return;
};
/**
WYMeditor.editor._setBaseUrl
===================================
This is part of the initialization of an editor, designed to be called
soon after the editor iframe is created. It adds a base tag to the
iframe based on the parent document's base url, so any relative
links inside the iframe will be resolved in the same way as outside
of it.
*/
WYMeditor.editor.prototype._setBaseUrl = function () {
var wym = this;
// This creates an images with an empty src url and lets the browser
// resolve it to figure out the base url used by the parent
// document. See https://stackoverflow.com/a/49299675/740048
var base_url = $('
')[0].src;
// Insert a base tag into the iframe
var base = wym._iframe.contentDocument.createElement("base");
base.setAttribute('href', base_url);
wym._iframe.contentDocument.getElementsByTagName("head")[0].appendChild(base);
}
/**
WYMeditor.editor._afterDesignModeOn
===================================
This is part of the initialization of an editor, designed to be called
after the editor's document is in designMode.
*/
WYMeditor.editor.prototype._afterDesignModeOn = function () {
var wym = this;
if (wym.iframeInitialized === true) {
return;
}
wym._assignWymDoc();
wym.$body().addClass("wym_iframe combokeys");
wym._doc.title = wym._index;
// Set the text direction.
jQuery('html', wym._doc).attr('dir', wym._options.direction);
wym.keyboard = new WYMeditor.Keyboard(wym);
wym.keyboard._attachDefaultKeyboardShortcuts();
wym._docEventQuirks();
wym._initializeDocumentContent();
if (jQuery.isFunction(wym._options.preBind)) {
wym._options.preBind(wym);
}
wym._bindUIEvents();
wym.iframeInitialized = true;
if (jQuery.isFunction(wym._options.postInit)) {
wym._options.postInit(wym);
}
// Importantly, these two are after `postInit`, where plugins had a chance
// to modify the UI (add buttons, etc.).
wym._bindFocusOnDocumentToButtons();
wym._uiQuirks();
// Add event listeners to doc elements, e.g. images
wym._listen();
wym.undoRedo = new WYMeditor.UndoRedo(wym);
wym.nativeEditRegistration = new WYMeditor.NativeEditRegistration(wym);
wym.ih = new WYMeditor.ImageHandler(wym);
jQuery(wym.element).trigger(
WYMeditor.EVENTS.postIframeInitialization,
wym
);
};
/**
WYMeditor.editor._initializeDocumentContent
===========================================
Populates the editor's document with the initial content, according to the
configuration and/or the textarea element's value.
*/
WYMeditor.editor.prototype._initializeDocumentContent = function () {
var wym = this;
if (wym._options.html) {
// Populate from the configuration option
wym.html(wym._options.html);
} else {
// Populate from the textarea element
wym.html(wym.element[0].value);
}
};
/**
WYMeditor.editor._docEventQuirks
================================
Misc. event bindings on the editor's document, that may be required.
*/
WYMeditor.editor.prototype._docEventQuirks = function () {
return;
};
/**
WYMeditor.editor._bindUIEvents
==============================
Binds event handlers for the UI elements.
*/
WYMeditor.editor.prototype._bindUIEvents = function () {
var wym = this,
$toolbarButtons = jQuery(wym._box).find(wym._options.toolSelector),
dialogButtonSelector = WYMeditor.DIALOG_BUTTON_SELECTOR,
$html_val;
// Action buttons
$toolbarButtons.not(dialogButtonSelector).click(function () {
var button = this;
wym.exec(jQuery(button).attr(WYMeditor.NAME));
return false;
});
// Dialog buttons
$toolbarButtons.filter(dialogButtonSelector).click(function () {
var button = this,
dialogName = jQuery(button).attr(WYMeditor.NAME),
dialog = WYMeditor.DIALOGS[dialogName];
// The following would also work, but is deprecated:
// wym.dialog(dialogName);
wym.dialog(dialog);
return false;
});
// Containers buttons
jQuery(wym._box).find(wym._options.containerSelector).click(function () {
var containerButton = this;
wym.setRootContainer(jQuery(containerButton).attr(WYMeditor.NAME));
return false;
});
// Handle keyup event on the HTML value textarea: set the editor value
// Handle focus/blur events to check if the element has focus, see #147
$html_val = jQuery(wym._box).find(wym._options.htmlValSelector);
$html_val.keyup(function () {
var valTextarea = this;
wym.$body().html(jQuery(valTextarea).val());
});
$html_val.focus(function () {
var valTextarea = this;
jQuery(valTextarea).toggleClass('hasfocus');
});
$html_val.blur(function () {
var valTextarea = this;
jQuery(valTextarea).toggleClass('hasfocus');
});
// Handle click events on classes buttons
jQuery(wym._box).find(wym._options.classSelector).click(function () {
var classButton = this,
aClasses = eval(wym._options.classesItems),
sName = jQuery(classButton).attr(WYMeditor.NAME),
oClass = WYMeditor.Helper._getFromArrayByName(aClasses, sName),
jqexpr;
if (oClass) {
jqexpr = oClass.expr;
wym.toggleClass(sName, jqexpr);
}
return false;
});
// Handle update event on update element
jQuery(wym._options.updateSelector).bind(
wym._options.updateEvent,
function () {
wym.update();
}
);
// This may recover an unexpected shut down of `designMode`.
wym.$body().bind("focus", function () {
if (wym._isDesignModeOn() !== true) {
wym._enableDesignModeOnDocument();
}
});
};
/**
WYMeditor.editor._enableDesignModeOnDocument
============================================
Enables `designMode` on the document, if it is not already enabled.
*/
WYMeditor.editor.prototype._enableDesignModeOnDocument = function () {
var wym = this;
if (wym._isDesignModeOn()) {
throw "Expected `designMode` to be off.";
}
try {
wym._doc.designMode = "On";
} catch (e) {
// Bail out gracefully if this went wrong.
}
if (typeof wym._designModeQuirks === "function") {
wym._designModeQuirks();
}
};
/**
WYMeditor.editor.get$WymBox
===========================
Get a jQuery containing the WYMeditor box.
*/
WYMeditor.editor.prototype.get$WymBox = function () {
var wym = this;
return wym._box;
};
/**
WYMeditor.editor.vanish
=========================
Removes the WYMeditor instance from existence and replaces the
'data-wym-initialized' attirbute of its textarea with 'data-wym-vanished'.
*/
WYMeditor.editor.prototype.vanish = function () {
var wym = this,
instances = WYMeditor.INSTANCES,
i;
wym._box.remove();
wym.element
.removeAttr('data-wym-initialized')
.attr('data-wym-vanished', '')
.show();
instances.splice(wym._index, 1);
// Refresh each editor's _index value
for (i = 0; i < instances.length; i++) {
instances[i]._index = i;
}
};
WYMeditor.editor.prototype._exec = function (cmd, param) {
var wym = this,
$span;
if (typeof cmd !== "string") {
throw "`_exec` expected a String `cmd`";
}
if (param && typeof param !== "string") {
throw "`_exec` expected a String `param`";
}
if (
wym.selectedContainer() === wym.body() &&
// These are the two commands that are allowed directly in the body.
cmd !== WYMeditor.EXEC_COMMANDS.INSERT_IMAGE &&
cmd !== WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK
) {
return false;
}
wym._doc.execCommand(cmd, false, param);
$span = jQuery(wym.selectedContainer()).filter("span").not("[id]");
if ($span.length === 0) {
return true;
}
if (
$span.attr("class") === "" &&
$span.attr("style") === "font-weight: normal;" ||
$span.attr("class").toLowerCase() === "apple-style-span"
) {
// An undesireable `span` was created. WebKit & Blink do this.
$span.contents().unwrap();
}
return true;
};
/**
WYMeditor.editor.rawHtml
=====================
Get or set the wymbox html value. HTML is NOT parsed when either set/get.
Use html() if you are unsure what this function does.
*/
WYMeditor.editor.prototype.rawHtml = function (html) {
var wym = this;
if (typeof html === 'string') {
wym.$body().html(html);
wym.update();
} else {
return wym.$body().html();
}
};
/**
WYMeditor.editor.html
=====================
Get or set the wymbox html value. HTML is parsed before it is inserted and
parsed before it is return. Use rawHtml() if parsing is not wanted/needed.
*/
WYMeditor.editor.prototype.html = function (html) {
var wym = this;
if (typeof html === 'string') {
wym.rawHtml(wym.parser.parse(html));
wym.prepareDocForEditing();
} else {
return wym.parser.parse(wym.rawHtml());
}
};
/**
WYMeditor.editor.exec
=====================
Execute a button command on the currently-selected container. The command
can be anything from "indent this element" to "open a dialog to create a
table."
`cmd` is a string corresponding to the command that should be run, roughly
matching the designMode execCommand strategy (and falling through to
execCommand in some cases).
*/
WYMeditor.editor.prototype.exec = function (cmd) {
var wym = this,
custom_run;
switch (cmd) {
case WYMeditor.EXEC_COMMANDS.TOGGLE_HTML:
wym.update();
wym.toggleHtml();
break;
case WYMeditor.EXEC_COMMANDS.INSERT_ORDEREDLIST:
wym._insertOrderedList();
break;
case WYMeditor.EXEC_COMMANDS.INSERT_UNORDEREDLIST:
wym._insertUnorderedList();
break;
case WYMeditor.EXEC_COMMANDS.INDENT:
wym.indent();
break;
case WYMeditor.EXEC_COMMANDS.OUTDENT:
wym.outdent();
break;
case WYMeditor.EXEC_COMMANDS.UNDO:
wym.undoRedo.undo();
break;
case WYMeditor.EXEC_COMMANDS.REDO:
wym.undoRedo.redo();
break;
default:
custom_run = false;
jQuery.each(wym._options.customCommands, function () {
var customCommand = this;
if (cmd === customCommand.name) {
custom_run = true;
customCommand.run.apply(wym);
return false;
}
});
if (!custom_run) {
if (
// Deligate all other commands to `_exec`
wym._exec(cmd) === true
) {
wym.registerModification();
}
}
break;
}
};
/**
WYMeditor.editor.selection
==========================
Override the default selection function to use rangy.
*/
WYMeditor.editor.prototype.selection = function () {
var wym = this,
iframe = wym._iframe,
sel;
if (window.rangy && !rangy.initialized) {
rangy.init();
}
sel = rangy.getIframeSelection(iframe);
return sel;
};
/**
WYMeditor.editor.nodeAfterSel
=============================
Returns the node that is immediately after the selection.
*/
WYMeditor.editor.prototype.nodeAfterSel = function () {
var wym = this,
sel = wym.selection();
// Different browsers describe selection differently. Here be dragons.
if (
sel.anchorNode.tagName &&
jQuery.inArray(
sel.anchorNode.tagName.toLowerCase(),
WYMeditor.NON_CONTAINING_ELEMENTS
) === -1
) {
if (sel.anchorNode.childNodes.length === 0) {
return;
}
return sel.anchorNode.childNodes[sel.anchorOffset];
}
if (
sel.focusNode.nodeType === WYMeditor.NODE_TYPE.TEXT &&
sel.focusNode.data.length === sel.focusOffset
) {
if (!sel.focusNode.nextSibling) {
return;
}
return sel.focusNode.nextSibling;
}
return sel.focusNode;
};
/**
WYMeditor.editor.get$CommonParent
=================================
Returns a jQuery of the common parent of two nodes.
*/
WYMeditor.editor.prototype.get$CommonParent = function (one, two) {
if (
typeof one !== 'object' ||
typeof one.nodeType !== 'number' ||
typeof two !== 'object' ||
typeof two.nodeType !== 'number'
) {
throw "`one` and `two` must be DOM nodes.";
}
if (one.nodeType === WYMeditor.NODE_TYPE.TEXT) {
// These checks seem to be required for our tests to pass in PhantomJS.
one = one.parentNode;
}
if (two.nodeType === WYMeditor.NODE_TYPE.TEXT) {
// These checks seem to be required for our tests to pass in PhantomJS.
two = two.parentNode;
}
if (one === two) {
// This is just an optimisation.
return jQuery(one);
}
var $one = jQuery(one),
$two = jQuery(two),
$commonParent;
$commonParent = $one.parents().addBack().has($two).last();
if ($commonParent.length === 0) {
throw "Couldn't find common parent. This shouldn't happen.";
}
return $commonParent;
};
/**
WYMeditor.editor.selectedContainer
==================================
Get the selected container.
* If no selection, returns `false`.
* If selection starts and ends in the same element, returns that element.
* If an element that contains one end of the selection is ancestor to the
element that contains the other end, return that ancestor element.
* Otherwise, returns `false`.
For example (``|`` marks selection ends):
|Foo bar|
The ``p`` is returned.
Foo |bar|
The ``i`` is returned.
*/
WYMeditor.editor.prototype.selectedContainer = function () {
var wym = this,
selection,
$anchor,
$focus,
$selectedContainer;
if (wym.hasSelection() !== true) {
return false;
}
selection = wym.selection();
$anchor = jQuery(selection.anchorNode);
$focus = jQuery(selection.focusNode);
if ($anchor[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
$anchor = $anchor.parent();
}
if ($focus[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
$focus = $focus.parent();
}
if ($anchor[0] === $focus[0]) {
return $anchor[0];
}
$selectedContainer = $anchor.has($focus);
if ($selectedContainer.length === 0) {
$selectedContainer = $focus.has($anchor);
}
if ($selectedContainer.length === 0) {
return false;
}
return $selectedContainer[0];
};
// Deprecated in favor of `WYMeditor.editor.selectedContainer`.
WYMeditor.editor.prototype.selected = function () {
var wym = this;
WYMeditor.console.warn(
"The function WYMeditor.editor.selected() is " +
"deprecated. Use WYMeditor.editor.selectedContainer"
);
return wym.selectedContainer();
};
/**
WYMeditor.editor.isBlockNode
=============================
Returns true if the provided node is a block type node. Otherwise
returns false.
@param node The node to check.
*/
WYMeditor.editor.prototype.isBlockNode = function (node) {
if (
node.tagName &&
jQuery.inArray(
node.tagName.toLowerCase(),
WYMeditor.BLOCKS
) > -1
) {
return true;
}
return false;
};
/**
WYMeditor.editor.isInlineNode
=============================
Returns true if the provided node is an inline type node. Otherwise
returns false.
@param node The node to check.
*/
WYMeditor.editor.prototype.isInlineNode = function (node) {
if (
node.nodeType === WYMeditor.NODE_TYPE.TEXT ||
jQuery.inArray(
node.tagName.toLowerCase(),
WYMeditor.INLINE_ELEMENTS
) > -1
) {
return true;
}
return false;
};
/**
WYMeditor.editor.isListNode
===========================
Returns true if the provided node is a list element. Otherwise
returns false.
@param node The node to check.
*/
WYMeditor.editor.prototype.isListNode = function (node) {
if (
node.tagName &&
jQuery.inArray(
node.tagName.toLowerCase(),
WYMeditor.LIST_TYPE_ELEMENTS
) > -1
) {
return true;
}
return false;
};
/**
WYMeditor.editor.unwrapIfMeaninglessSpan
If the given node is a span with no useful attributes, unwrap it.
For certain editing actions (mostly list indent/outdent), it's necessary to
wrap content in a span element to retain grouping because it's not obvious that
the content will stay together without grouping. This method detects that
specific situation and then unwraps the content if the span is in fact not
necessary.
@param element The element.
*/
WYMeditor.editor.prototype.unwrapIfMeaninglessSpan = function (element) {
var $element = jQuery(element),
i = 0,
attrName,
meaninglessAttrNames = [
'_wym_visited',
'length',
'ie8_length'
];
if (!element || typeof (element.tagName) === 'undefined' ||
element.tagName.toLowerCase() !== 'span') {
return false;
}
while (i < element.attributes.length) {
attrName = element.attributes[i].nodeName;
if (jQuery.inArray(attrName, meaninglessAttrNames) === -1) {
return false;
}
i++;
}
$element.before($element.contents());
$element.remove();
return true;
};
/**
WYMeditor.editor.getRootContainer
=================================
Get the selected root container.
*/
WYMeditor.editor.prototype.getRootContainer = function () {
var wym = this;
return jQuery(wym.selectedContainer())
.parentsOrSelf()
.not('html, body, blockquote')
.last()[0];
};
/**
WYMeditor.editor.setRootContainer
=================================
Set the selected root container.
*/
WYMeditor.editor.prototype.setRootContainer = function (sType) {
var wym = this,
container = null,
aTypes,
newNode,
blockquote,
nodes,
lgt,
firstNode,
x;
if (sType.toLowerCase() === WYMeditor.TH) {
container = wym.selectedContainer();
// Find the TD or TH container
switch (container.tagName.toLowerCase()) {
case WYMeditor.TD:
case WYMeditor.TH:
break;
default:
aTypes = [WYMeditor.TD, WYMeditor.TH];
container = wym.findUp(wym.selectedContainer(), aTypes);
break;
}
// If it exists, switch
if (container !== null) {
sType = WYMeditor.TD;
if (container.tagName.toLowerCase() === WYMeditor.TD) {
sType = WYMeditor.TH;
}
wym.restoreSelectionAfterManipulation(function () {
wym.switchTo(container, sType, false);
return true;
});
wym.update();
wym.registerModification();
}
} else {
// Set the container type
aTypes = [
WYMeditor.P,
WYMeditor.DIV,
WYMeditor.H1,
WYMeditor.H2,
WYMeditor.H3,
WYMeditor.H4,
WYMeditor.H5,
WYMeditor.H6,
WYMeditor.PRE,
WYMeditor.BLOCKQUOTE
];
container = wym.findUp(wym.selectedContainer(), aTypes);
if (container) {
if (sType.toLowerCase() === WYMeditor.BLOCKQUOTE) {
// Blockquotes must contain a block level element
blockquote = wym.findUp(
wym.selectedContainer(),
WYMeditor.BLOCKQUOTE
);
if (blockquote === null) {
newNode = wym._doc.createElement(sType);
container.parentNode.insertBefore(newNode, container);
newNode.appendChild(container);
wym.setCaretIn(newNode.firstChild);
} else {
nodes = blockquote.childNodes;
lgt = nodes.length;
if (lgt > 0) {
firstNode = nodes.item(0);
}
for (x = 0; x < lgt; x += 1) {
blockquote.parentNode.insertBefore(
nodes.item(0),
blockquote
);
}
blockquote.parentNode.removeChild(blockquote);
if (firstNode) {
wym.setCaretIn(firstNode);
}
}
} else {
// Not a blockquote
wym.restoreSelectionAfterManipulation(function () {
wym.switchTo(container, sType, false);
return true;
});
}
wym.update();
wym.registerModification();
}
}
return false;
};
/**
WYMeditor.editor.isForbiddenRootContainer
=========================================
Returns true if provided `tagName` is disallowed as a root container.
Returns false if it is allowed.
@param tagName A string of the tag name.
*/
WYMeditor.editor.prototype.isForbiddenRootContainer = function (tagName) {
return jQuery.inArray(tagName.toLowerCase(),
WYMeditor.FORBIDDEN_ROOT_CONTAINERS) > -1;
};
/**
WYMeditor.editor.keyCanCreateBlockElement
=========================================
Determines whether the key represented by the passed keyCode can create a
block element within the editor when pressed. Returns true if the key can
create a block element when pressed, and returns false if otherwise.
@param keyCode A numberic key code representing a key
*/
WYMeditor.editor.prototype.keyCanCreateBlockElement = function (keyCode) {
return jQuery.inArray(keyCode,
WYMeditor.POTENTIAL_BLOCK_ELEMENT_CREATION_KEYS) > -1;
};
/**
WYMeditor.editor.toggleClass
============================
Toggle a class on the selected element or one of its parents
*/
WYMeditor.editor.prototype.toggleClass = function (sClass, jqexpr) {
var wym = this,
$element;
$element = jQuery(wym.getSelectedImage());
if ($element.length !== 1) {
$element = jQuery(wym.selectedContainer())
// `.last()` is used here because the `.addBack()` from
// `.parentsOrSelf` reverses the array.
.parentsOrSelf(jqexpr).last();
}
$element.toggleClass(sClass);
if (!$element.attr(WYMeditor.CLASS)) {
$element.removeAttr(wym._class);
}
wym.registerModification();
};
/**
WYMeditor.editor.getSelectedImage
=================================
If selection encompasses exactly a single image, returns that image.
Otherwise returns `false`.
*/
WYMeditor.editor.prototype.getSelectedImage = function () {
var wym = this,
selectedNodes,
selectedNode;
if (wym.hasSelection() !== true) {
return false;
}
if (wym.selection().isCollapsed !== false) {
return false;
}
selectedNodes = wym._getSelectedNodes();
if (selectedNodes.length !== 1) {
return false;
}
selectedNode = selectedNodes[0];
if (
!selectedNode.tagName ||
selectedNode.tagName.toLowerCase() !== "img"
) {
return false;
}
return selectedNode;
};
/**
WYMeditor.editor.findUp
=======================
Return the first parent or self container, based on its type
`filter` is a string or an array of strings on which to filter the container
*/
WYMeditor.editor.prototype.findUp = function (node, filter) {
if (typeof (node) === 'undefined' || node === null) {
return null;
}
if (node.nodeName === "#text") {
// For text nodes, we need to look from the nodes container object
node = node.parentNode;
}
var tagname = node.tagName.toLowerCase(),
bFound,
i;
if (typeof (filter) === WYMeditor.STRING) {
while (tagname !== filter && tagname !== WYMeditor.BODY) {
node = node.parentNode;
tagname = node.tagName.toLowerCase();
}
} else {
bFound = false;
while (!bFound && tagname !== WYMeditor.BODY) {
for (i = 0; i < filter.length; i += 1) {
if (tagname === filter[i]) {
bFound = true;
break;
}
}
if (!bFound) {
node = node.parentNode;
if (node === null) {
// No parentNode, so we're not going to find anything
// up the ancestry chain that matches
return null;
}
tagname = node.tagName.toLowerCase();
}
}
}
if (tagname === WYMeditor.BODY) {
return null;
}
return node;
};
/**
WYMeditor.editor.switchTo
=========================
Switch the type of an element.
@param element The element.
@param sType A string of the desired type. For example, 'p'.
@param stripAttrs a boolean that determines whether the attributes of
the element will be stripped or preserved.
*/
WYMeditor.editor.prototype.switchTo = function (
element,
sType,
stripAttrs
) {
var wym = this,
$element = jQuery(element),
newElement,
i,
attrs = element.attributes;
if (!element.tagName) {
throw "This must be an element.";
}
if (element.tagName.toLowerCase() === 'img') {
throw "Will not change the type of an 'img' element.";
}
newElement = wym._doc.createElement(sType);
jQuery(newElement).append(element.childNodes);
$element.replaceWith(newElement);
if (!stripAttrs) {
for (i = 0; i < attrs.length; ++i) {
newElement.setAttribute(
attrs.item(i).nodeName,
attrs.item(i).value
);
}
}
return newElement;
};
WYMeditor.editor.prototype.replaceStrings = function (sVal) {
var wym = this,
key;
// Check if the language file has already been loaded
// if not, get it via a synchronous ajax call
if (!WYMeditor.STRINGS[wym._options.lang]) {
WYMeditor.console.error(
"WYMeditor: language '" + wym._options.lang + "' not found."
);
WYMeditor.console.error(
"Unable to perform i10n."
);
return sVal;
}
// Replace all the strings in sVal and return it
for (key in WYMeditor.STRINGS[wym._options.lang]) {
if (WYMeditor.STRINGS[wym._options.lang].hasOwnProperty(key)) {
sVal = WYMeditor.Helper.replaceAllInStr(
sVal,
wym._options.stringDelimiterLeft + key + wym._options.stringDelimiterRight,
WYMeditor.STRINGS[wym._options.lang][key]
);
}
}
return sVal;
};
WYMeditor.editor.prototype._encloseString = function (sVal) {
var wym = this;
return wym._options.stringDelimiterLeft +
sVal +
wym._options.stringDelimiterRight;
};
/**
editor.getCurrentState
======================
Returns an object with the current state of the editor.
The state includes:
``html``
The return value of ``editor.rawHtml()``.
``savedSelection``
A Rangy saved selection, if anything is selected.
The ``win`` and the ``doc`` properties are deleted,
instead of referencing the window object and the document object,
respectively.
In order to provide this as an argument to Rangy's ``restoreSelection``,
these must be reassigned.
It may include more things in the future.
*/
WYMeditor.editor.prototype.getCurrentState = function () {
var wym = this,
state = {},
selection,
wymIframeWindow = wym._iframe.contentWindow;
if (wym.hasSelection()) {
selection = wym.selection();
}
if (
selection &&
selection.anchorNode === wym.body() &&
selection.anchorOffset === 0 &&
selection.isCollapsed
) {
// meaningless selection
selection = false;
}
if (selection) {
state.savedSelection = rangy.saveSelection(wymIframeWindow);
}
state.html = wym.rawHtml();
if (state.savedSelection) {
// Selection was saved. This means that in the document, DOM elements,
// which are markers for the selection, were placed, and that references
// to these markers were saved in `state.savedselection`. The markers
// were saved in `state.html`, along with the whole document, as HTML.
// Restoring the selection removes the markers and restores the
// selection to almost exactly as it was before it was saved.
rangy.restoreSelection(state.savedSelection);
// This is for time-travel, so selection is considered not to be
// restored. The markers may be created again from the saved HTML. In
// that case, leaving this value at `true` would mean that
// `rangy.restoreSelection` will refuse to restore this selection.
state.savedSelection.restored = false;
// These refer to the window and the document and can't be processed by
// the `object-history` module that is used by the `UndoRedo` module.
delete state.savedSelection.win;
delete state.savedSelection.doc;
}
return state;
};
/**
editor.hasSelection
===================
Returns true if there is a selection. Returns false otherwise.
*/
WYMeditor.editor.prototype.hasSelection = function () {
var wym = this;
if (
// `isSelectionValid` is undocumented in current Rangy (`1.2.2`).
// It seems to be required because the `rangeCount` in `IE <= 8` seems
// to be misleading.
rangy.isSelectionValid(wym._iframe.contentWindow) !== true
) {
return false;
}
if (wym.selection().rangeCount === 0) {
return false;
}
return true;
};
/**
editor._setSingleSelectionRange
===============================
Sets the selection to the single provided Rangy range.
@param range A Rangy range.
*/
WYMeditor.editor.prototype._setSingleSelectionRange = function (range) {
var wym = this,
selection;
selection = wym.selection();
selection.setSingleRange(range);
};
/**
editor.status
=============
Print the given string as a status message.
*/
WYMeditor.editor.prototype.status = function (sMessage) {
var wym = this;
// Print status message
jQuery(wym._box).find(wym._options.statusSelector).html(sMessage);
};
/**
editor.update
=============
Update the element and textarea values.
*/
WYMeditor.editor.prototype.update = function () {
var wym = this,
html;
html = wym.html();
jQuery(wym.element).val(html);
jQuery(wym._box).find(wym._options.htmlValSelector).not('.hasfocus').val(html); //#147
};
/**
editor.prepareDocForEditing
===========================
Makes some editor-only modifications to the body of the document, which are necessary
for the user interface. For example, inserts `br` elements in certain places.
These modifications will not show up in the HTML output.
*/
WYMeditor.editor.prototype.prepareDocForEditing = function () {
var wym = this,
$body;
wym._spaceBlockingElements();
wym._fixDoubleBr();
$body = wym.$body();
if ($body.children().length === 0) {
wym.$body().append('
');
}
jQuery(wym.element).trigger(WYMeditor.EVENTS.postBlockMaybeCreated, wym);
};
/**
editor._spaceBlockingElements
=============================
Insert
elements between adjacent blocking elements and
p elements, between block elements or blocking elements and the
start/end of the document.
*/
WYMeditor.editor.prototype._spaceBlockingElements = function () {
var wym = this,
blockingSelector =
WYMeditor.DocumentStructureManager.CONTAINERS_BLOCKING_NAVIGATION.join(', '),
$body = wym.$body(),
children = $body.children(),
placeholderNode,
$firstChild,
$lastChild,
blockSepSelector,
blockInListSepSelector,
$blockInList;
if (jQuery.browser.mozilla) {
placeholderNode = '
';
} else {
placeholderNode = '
';
}
// Make sure that we still have a placeholder node at both the begining and
// end
if (children.length > 0) {
$firstChild = jQuery(children[0]);
$lastChild = jQuery(children[children.length - 1]);
if ($firstChild.is(blockingSelector)) {
$firstChild.before(placeholderNode);
}
if ($lastChild.is(blockingSelector)) {
$lastChild.after(placeholderNode);
}
}
blockSepSelector = wym._getBlockSepSelector();
// Put placeholder nodes between consecutive blocking elements and between
// blocking elements and normal block-level elements
$body.find(blockSepSelector).before(placeholderNode);
blockInListSepSelector = wym._getBlockInListSepSelector();
$blockInList = $body.find(blockInListSepSelector);
// The $blockInList selection must be iterated over to only add placeholder
// nodes after blocking elements at the end of a list item rather than all
// blocking elements in a list. No jQuery selection that is supported on
// all browsers can do this check, so that is why it must be done by using
// `each` to iterate over the selection. Note that the handling of the
// spacing of other blocking elements in a list besides after the last
// blocking element in a list item is already handled by the
// blockSepSelector used before this.
$blockInList.each(function () {
var block = this,
$block = jQuery(block);
if (!$block.next(blockingSelector).length &&
!$block.next('br').length) {
$block.after(placeholderNode);
}
});
};
/**
editor._getBlockSepSelector
===========================
Build a string representing a jquery selector that will find all
elements which need a spacer
before them. This includes all consecutive
blocking elements and between blocking elements and normal non-blocking
elements.
*/
WYMeditor.editor.prototype._getBlockSepSelector = function () {
var wym = this,
blockCombo = [],
containersBlockingNav =
WYMeditor.DocumentStructureManager.CONTAINERS_BLOCKING_NAVIGATION,
containersNotBlockingNav;
if (typeof (wym._blockSpacersSel) !== 'undefined') {
return wym._blockSpacersSel;
}
// Generate the list of non-blocking elements by removing the blocking
// elements from the list of validRootContainers
containersNotBlockingNav = jQuery.grep(
wym.documentStructureManager.structureRules.validRootContainers,
function (item) {
return jQuery.inArray(item, containersBlockingNav) === -1;
}
);
// Consecutive blocking elements need separators
jQuery.each(
containersBlockingNav,
function (indexO, elementO) {
jQuery.each(
containersBlockingNav,
function (indexI, elementI) {
blockCombo.push(elementO + ' + ' + elementI);
}
);
}
);
// A blocking element either followed by or preceeded by a not blocking
// element needs separators
jQuery.each(
containersBlockingNav,
function (indexO, elementO) {
jQuery.each(
containersNotBlockingNav,
function (indexI, elementI) {
blockCombo.push(elementO + ' + ' + elementI);
blockCombo.push(elementI + ' + ' + elementO);
}
);
}
);
wym._blockSpacersSel = blockCombo.join(', ');
return wym._blockSpacersSel;
};
/*
editor._getBlockInListSepSelector
=================================
Returns a selector for getting all of the block elements in lists
or sublists. The block elements at the end of lists or sublists should have
a spacer line break after them in the editor at all times.
*/
WYMeditor.editor.prototype._getBlockInListSepSelector = function () {
var wym = this,
blockCombo = [];
if (typeof (wym._blockInListSpacersSel) !== 'undefined') {
return wym._blockInListSpacersSel;
}
jQuery.each(WYMeditor.LIST_TYPE_ELEMENTS, function (indexO, elementO) {
jQuery.each(WYMeditor.BLOCKING_ELEMENTS, function (indexI, elementI) {
blockCombo.push(elementO + ' ' + elementI);
});
});
wym._blockInListSpacersSel = blockCombo.join(', ');
return wym._blockInListSpacersSel;
};
/**
editor._fixDoubleBr
===================
Remove the
elements that are inserted between
paragraphs, usually after hitting enter from an existing paragraph.
*/
WYMeditor.editor.prototype._fixDoubleBr = function () {
var wym = this,
$body = wym.$body(),
$last_br;
// Strip consecutive brs unless they're in a pre tag
$body.children('br + br').filter(':not(pre br)').remove();
// Also remove any brs between two p's
$body.find('p + br').next('p').prev('br').remove();
// Remove brs floating at the end after a p
$last_br = $body.find('p + br').slice(-1);
if ($last_br.length > 0) {
if ($last_br.next().length === 0) {
$last_br.remove();
}
}
};
/**
WYMeditor.editor.link
======================
Creates a link, or changes attributes of an `a`, at selection.
@param attrs Object with key-value pairs of attributes for the `a`.
*/
WYMeditor.editor.prototype.link = function (attrs) {
var wym = this,
$selected,
uniqueStamp,
$a;
if (jQuery.isPlainObject(attrs) !== true) {
throw "Expected a plain object.";
}
if (
attrs.hasOwnProperty('href') !== true ||
typeof attrs.href !== 'string' ||
attrs.href.length === 0
) {
// Would probably be best to throw here, but...
// This is used by a dialog that doesn't check input.
// The dialog is created by `WYMeditor.INIT_DIALOG`.
return;
}
$selected = jQuery(wym.selectedContainer());
if ($selected.is('a')) {
$a = $selected;
} else {
uniqueStamp = wym.uniqueStamp();
wym._exec(WYMeditor.EXEC_COMMANDS.CREATE_LINK, uniqueStamp);
$a = jQuery("a[href=" + uniqueStamp + "]", wym.body());
}
if ($a.length === 0) {
// This occurs when a link wasn't created, because, for example
// the selection didn't allow it.
return;
}
$a.attr(attrs);
wym.registerModification();
};
/**
WYMeditor.editor.insertImage
============================
Inserts an image at selection.
@param attrs Object with key-value pairs of attributes for the `img`.
*/
WYMeditor.editor.prototype.insertImage = function (attrs) {
var wym = this,
uniqueStamp,
$img;
if (jQuery.isPlainObject(attrs) !== true) {
throw "Expected a plain object.";
}
if (
attrs.hasOwnProperty('src') !== true ||
typeof attrs.src !== 'string' ||
attrs.src.length === 0
) {
// Would probably be best to throw here, but...
// This is used by a dialog that doesn't check input.
// The dialog is created by `WYMeditor.INIT_DIALOG`.
return;
}
uniqueStamp = wym.uniqueStamp();
wym._exec(WYMeditor.EXEC_COMMANDS.INSERT_IMAGE, uniqueStamp);
$img = jQuery("img[src=" + uniqueStamp + "]", wym.body());
if ($img.length === 0) {
// This occurs when a link wasn't created, because, for example
// the selection didn't allow it.
return;
}
$img.attr(attrs);
// PhantomJS seems to add strange spans around images.
wym.$body().find('.Apple-style-span').children().unwrap();
wym.registerModification();
};
/**
editor._updateImageAttrs
========================
Updates provided `img`'s attributes with provided `attrs`.
*/
WYMeditor.editor.prototype._updateImageAttrs = function (img, attrs) {
var $img = jQuery(img);
if (attrs.src !== $img.attr('src')) {
// this data is used in the ImageHandler.
// height/width ratio is now most likely invalid
$img.data('DimensionsRatio', null);
// since the height/width ration is most likely different
// these proportions are most likely wrong.
// easiest solution is to remove them
// and let the user deal with
// the real size of the source image
// and he'll be able to resize it
$img.removeAttr('height').removeAttr('width');
}
$img.attr(attrs);
};
/**
editor.toggleHtml
=================
Show/Hide the HTML textarea.
*/
WYMeditor.editor.prototype.toggleHtml = function () {
var wym = this;
jQuery(wym._box).find(wym._options.htmlSelector).toggle();
};
WYMeditor.editor.prototype.uniqueStamp = function () {
var now = new Date();
return "wym" + now.getTime();
};
/**
Paste the given array of paragraph-items at the given range inside the given $container.
It has already been determined that the paragraph has multiple lines and
that the container we're pasting to is a block container capable of accepting
further nested blocks.
*/
WYMeditor.editor.prototype._handleMultilineBlockContainerPaste = function (
wym, $container, range, paragraphStrings
) {
var i,
$insertAfter,
html,
blockSplitter,
leftSide,
rightSide,
rangeNodeComparison,
$splitRightParagraph,
firstParagraphString,
firstParagraphHtml,
blockParent,
blockParentType;
// Now append all subsequent paragraphs
$insertAfter = jQuery(blockParent);
// Just need to split the current container and put new block elements
// in between
blockSplitter = 'p';
if ($container.is('li')) {
// Instead of creating paragraphs on line breaks, we'll need to create li's
blockSplitter = 'li';
}
// Split the selected element then build and insert the appropriate html
// This accounts for cases where the start selection is at the
// start of a node or in the middle of a text node by splitting the
// text nodes using rangy's splitBoundaries()
range.splitBoundaries(); // Split any partially-select text nodes
blockParent = wym.findUp(
range.startContainer,
['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li']
);
blockParentType = blockParent.tagName;
leftSide = [];
rightSide = [];
jQuery(blockParent).contents().each(function (index, element) {
// Capture all of the dom nodes to the left and right of our
// range. We can't remove them in the same step because that
// loses the selection in webkit
rangeNodeComparison = range.compareNode(element);
if (rangeNodeComparison === range.NODE_BEFORE ||
(rangeNodeComparison === range.NODE_BEFORE_AND_AFTER &&
range.startOffset === range.startContainer.length)) {
// Because of the way splitBoundaries() works, the
// collapsed selection might appear in the right-most index
// of the border node, which means it will show up as
//
// eg. | is the selection and <> are text node boundaries
//
//
// We detect that case by counting any
// NODE_BEFORE_AND_AFTER result where the offset is at the
// very end of the node as a member of the left side
leftSide.push(element);
} else {
rightSide.push(element);
}
});
// Now remove all of the left and right nodes
for (i = 0; i < leftSide.length; i++) {
jQuery(leftSide[i]).remove();
}
for (i = 0; i < rightSide.length; i++) {
jQuery(rightSide[i]).remove();
}
// Rebuild our split nodes and add the inserted content
if (leftSide.length > 0) {
// We have left-of-selection content
// Put the content back inside our blockParent
jQuery(blockParent).prepend(leftSide);
}
if (rightSide.length > 0) {
// We have right-of-selection content.
// Split it off in to a node of the same type after our
// blockParent
$splitRightParagraph = jQuery('<' + blockParentType + '>' +
'' + blockParentType + '>', wym._doc);
$splitRightParagraph.insertAfter(jQuery(blockParent));
$splitRightParagraph.append(rightSide);
}
// Insert the first paragraph in to the current node, and then
// start appending subsequent paragraphs
firstParagraphString = paragraphStrings.splice(
0,
1
)[0];
firstParagraphHtml = firstParagraphString.split(WYMeditor.NEWLINE).join('
');
jQuery(blockParent).html(jQuery(blockParent).html() + firstParagraphHtml);
// Now append all subsequent paragraphs
$insertAfter = jQuery(blockParent);
for (i = 0; i < paragraphStrings.length; i++) {
html = '<' + blockSplitter + '>' +
(paragraphStrings[i].split(WYMeditor.NEWLINE).join('
')) +
'' + blockSplitter + '>';
$insertAfter = jQuery(html, wym._doc).insertAfter($insertAfter);
}
};
/**
editor.paste
============
Paste text into the editor below the carret, used for "Paste from Word".
Takes the string to insert as an argument. Two or more newlines separates
paragraphs. May contain inline HTML.
*/
WYMeditor.editor.prototype.paste = function (str) {
var wym = this,
container = wym.selectedContainer(),
paragraphStrings,
j,
textNodesToInsert,
blockSplitter,
$container = jQuery(container),
html = '',
paragraphs,
i,
isSingleLine = false,
sel = wym.selection(),
textNode,
range = sel.getRangeAt(0),
insertionNodes;
// Start by collapsing the range to the start of the selection. We're
// punting on implementing a paste that also replaces existing content for
// now,
range.collapse(true); // Collapse to the the begining of the selection
// Split string into paragraphs by two or more newlines
paragraphStrings = str.split(new RegExp(WYMeditor.NEWLINE + '{2,}', 'g'));
if (paragraphStrings.length === 1) {
// This is a one-line paste, which is an easy case.
// We try not to wrap these in paragraphs
isSingleLine = true;
}
if (typeof container === 'undefined' ||
(container && container.tagName.toLowerCase() === WYMeditor.BODY)) {
// No selection, or body selection. Paste at the end of the document
if (isSingleLine) {
// Easy case. Wrap the string in p tags
paragraphs = jQuery(
'' + paragraphStrings[0] + '
',
wym._doc
).appendTo(wym._doc.body);
} else {
// Need to build paragraphs and insert them at the end
blockSplitter = 'p';
for (i = paragraphStrings.length - 1; i >= 0; i -= 1) {
// Going backwards because rangy.insertNode leaves the
// selection in front of the inserted node
html = '<' + blockSplitter + '>' +
(paragraphStrings[i].split(WYMeditor.NEWLINE).join('
')) +
'' + blockSplitter + '>';
// Build multiple nodes from the HTML because ie6 chokes
// creating multiple nodes implicitly via jquery
insertionNodes = jQuery(html, wym._doc);
for (j = insertionNodes.length - 1; j >= 0; j--) {
// Loop backwards through all of the nodes because
// insertNode moves that direction
range.insertNode(insertionNodes[j]);
}
}
}
} else {
// Pasting inside an existing element
if (isSingleLine || $container.is('pre')) {
// Easy case. Insert a text node at the current selection
textNode = wym._doc.createTextNode(str);
range.insertNode(textNode);
} else if ($container.is('p,h1,h2,h3,h4,h5,h6,li')) {
wym._handleMultilineBlockContainerPaste(wym, $container, range, paragraphStrings);
} else {
// We're in a container that doesn't accept nested paragraphs (eg. td). Use
//
separators everywhere instead
textNodesToInsert = str.split(WYMeditor.NEWLINE);
for (i = textNodesToInsert.length - 1; i >= 0; i -= 1) {
// Going backwards because rangy.insertNode leaves the
// selection in front of the inserted node
textNode = wym._doc.createTextNode(textNodesToInsert[i]);
range.insertNode(textNode);
if (i > 0) {
// Don't insert an opening br
range.insertNode(jQuery('
', wym._doc).get(0));
}
}
}
}
wym.registerModification();
};
WYMeditor.editor.prototype.insert = function (html) {
// Do we have a selection?
var wym = this,
selection = wym.hasSelection() ? wym.selection() : false,
range,
node;
if (selection) {
// Overwrite selection with provided html
range = selection.getRangeAt(0);
node = range.createContextualFragment(html);
range.deleteContents();
range.insertNode(node);
}
};
/**
editor.canSetCaretBefore
========================
Returns true if it is OK to set a collapsed selection immediately before
a node. Otherwise returns false.
@param node A node to check about.
*/
WYMeditor.editor.prototype.canSetCaretBefore = function (node) {
var wym = this;
if (node.nodeType === WYMeditor.NODE_TYPE.TEXT) {
return true;
}
if (
node.tagName &&
node.tagName.toLowerCase() === 'br'
) {
if (
!node.previousSibling
) {
return true;
} else if (
node.previousSibling.tagName &&
node.previousSibling.tagName.toLowerCase() === 'br'
) {
return true;
} else if (wym.isBlockNode(node.previousSibling)) {
return true;
} else if (node.previousSibling.nodeType === WYMeditor.NODE_TYPE.TEXT) {
return true;
}
}
return false;
};
/**
editor.setCaretBefore
=====================
Sets a collapsed selection to immediately before a provided node.
Not to be confused with `editor.setCaretIn`, which sets a collapsed
selection inside a container node, at the start.
@param node A node to set the selection to immediately before of.
*/
WYMeditor.editor.prototype.setCaretBefore = function (node) {
var wym = this,
range = rangy.createRange(wym._doc),
selection = wym.selection();
if (!wym.canSetCaretBefore(node)) {
throw "Can't set caret before this node.";
}
range.selectNode(node);
range.collapse(true);
selection.setSingleRange(range);
};
/**
editor.canSetCaretIn
====================
Returns true if it is OK to set a collapsed selection inside a node.
Otherwise returns false.
@param node A node to check about.
*/
WYMeditor.editor.prototype.canSetCaretIn = function (node) {
var wym = this;
if (
node.nodeType === WYMeditor.NODE_TYPE.TEXT ||
(
node.tagName &&
jQuery.inArray(
node.tagName.toLowerCase(),
WYMeditor.NO_CARET_ELEMENTS
) > -1
)
) {
return false;
}
// Rangy issue #209.
if (wym.isInlineNode(node)) {
if (node.childNodes.length === 0) {
// Not possible to work-around this issue.
return false;
}
// It is possible to work-around this issue by setting a non-collapsed
// selection. Warn about this.
WYMeditor.console.warn("Can set a non-collapsed selection. Rangy issue #209.");
}
return true;
};
/**
editor.setCaretIn
=================
Sets a collapsed selection to inside provided container element, at the start.
Not to be confused with `editor.setCaretBefore`, which sets a collapsed
selection immediately before a node.
@param element An element to set the selection inside of, at the start.
*/
WYMeditor.editor.prototype.setCaretIn = function (element) {
var wym = this,
range = rangy.createRange(wym._doc),
selection = wym.selection();
if (
!wym.canSetCaretIn(element)
) {
throw "The element must be able to contain other elements. Perhaps " +
" you would like to use `setCaretBefore`, instead.";
}
range.selectNodeContents(element);
// Rangy issue #209.
if (wym.isInlineNode(element)) {
// Don't collapse the range. As long as
// this occurs only in tests it is probably OK. Warn.
WYMeditor.console.warn("Can't set a collapsed selection. Setting " +
"a non-collapsed selection, instead. Rangy issue #209.");
} else {
range.collapse(true);
}
selection.setSingleRange(range);
};
/**
editor._splitListItemContents
=============================
Utility
Splits a list item into the content that should stay with the li as it is
indented/outdent and the things that should stay at their current indent level.
`itemContents` are what a user would consider that list's contents
`sublistContents` are the sub-items that are nested inside the li
(basically everything after the first ol/ul inclusive).
The returned object has `itemContents` and `sublistContents` properties.
*/
WYMeditor.editor.prototype._splitListItemContents = function ($listItem) {
var $allContents,
i,
elmnt,
hitSublist = false,
splitObject = {itemContents: [], sublistContents: []};
$allContents = $listItem.contents();
for (i = 0; i < $allContents.length; i++) {
elmnt = $allContents.get(i);
if (hitSublist || jQuery(elmnt).is('ol,ul')) {
// We've hit the first sublist. Everything from this point on is
// considered `sublistContents`
hitSublist = true;
splitObject.sublistContents.push(elmnt);
} else {
splitObject.itemContents.push(elmnt);
}
}
return splitObject;
};
/**
editor._joinAdjacentLists
=========================
Utility
Joins two lists if they are adjacent and are of the same type.
The end result will be `listTwo`s contents being appended to `listOne`
*/
WYMeditor.editor.prototype._joinAdjacentLists = function (listOne, listTwo) {
var $listTwoContents;
if (typeof listOne === 'undefined' ||
typeof listTwo === 'undefined') {
// Invalid arguments
return;
}
if (listOne.nextSibling !== listTwo ||
listOne.tagName.toLowerCase() !== listTwo.tagName.toLowerCase()) {
return;
}
$listTwoContents = jQuery(listTwo).contents();
$listTwoContents.unwrap(); // Kill listTwo
$listTwoContents.detach();
jQuery(listOne).append($listTwoContents);
};
/**
editor._indentSingleItem
========================
Indent a single list item via the dom, ensuring that the selected node moves in
exactly one level and all other nodes stay at the same level.
*/
WYMeditor.editor.prototype._indentSingleItem = function (listItem) {
var wym = this,
$liToIndent,
listType,
spacerHtml,
containerHtml,
splitContent,
$itemContents,
$sublistContents,
$prevLi,
$prevSublist,
$firstSublist,
$spacer,
$spacerContents;
// The algorithm used here is generally:
// 1. Ensure there's a previous li to put the `liToIndent`.
// 2. Move the `liToIndent` into a sublist in the previous li.
// 3. If we added a spacer_li after `liToIndent` remove it and move its
// contents inside `liToIndent`.
// For step 2, the sublist to use can either be:
// 1. An existing sublist of the correct type at the end of the previous li.
// 2. An existing sublist inside `liToIndent`.
// 3. A new sublist that we create.
$liToIndent = jQuery(listItem);
listType = $liToIndent.parent()[0].tagName.toLowerCase();
// Separate out the contents into things that should stay with the li as it
// moves and things that should stay at their current level
splitContent = wym._splitListItemContents($liToIndent);
$sublistContents = jQuery(splitContent.sublistContents);
$itemContents = jQuery(splitContent.itemContents);
$prevLi = $liToIndent.prev().filter('li');
// Ensure we actually have a previous li in which to put the `liToIndent`
if ($prevLi.length === 0) {
spacerHtml = '';
$liToIndent.before(spacerHtml);
$prevLi = $liToIndent.prev();
}
// Move `liToIndent` to a sublist inside its previous sibling li
$prevSublist = $prevLi.contents().last().filter('ol,ul');
if ($prevSublist.length > 0) {
// Case 1: We have a sublist at the appropriate level as a previous
// sibling. Leave the sublist contents where they are and join the
// previous sublist
// Join our node at the end of the target sublist
$prevSublist.append($liToIndent);
// Stick all of the sublist contents at the end of the previous li
$sublistContents.detach();
$prevLi.append($sublistContents);
// If we just moved two lists of the same type next to eachother, join
// them
$firstSublist = $sublistContents.first();
wym._joinAdjacentLists($prevSublist.get(0), $firstSublist.get(0));
} else {
if ($sublistContents.length > 0) {
// Case 2: We need to move our existing sublist to the previous li
$sublistContents.detach();
$prevLi.append($sublistContents);
$prevSublist = $sublistContents.first();
} else {
// Case 3: Create a spacer sublist in the previous li in which to
// place `liToIndent`
containerHtml = '<' + listType + '>' + listType + '>';
$prevLi.append(containerHtml);
$prevSublist = $prevLi.contents().last();
}
// Move our li to the start of the sublist
$prevSublist.prepend($liToIndent);
}
// If we eliminated the need for a spacer_li, remove it
if ($liToIndent.next().is('.spacer_li')) {
$spacer = $liToIndent.next('.spacer_li');
$spacerContents = $spacer.contents();
$spacerContents.detach();
$liToIndent.append($spacerContents);
$spacer.remove();
}
};
/**
editor._outdentSingleItem
=========================
Outdent a single list item via the dom, ensuring that the selected node moves in
exactly one level and all other nodes stay at the same level.
*/
WYMeditor.editor.prototype._outdentSingleItem = function (listItem) {
var wym = this,
$liToOutdent,
listType,
spacerListHtml,
splitContent,
$itemContents,
$sublistContents,
$parentLi,
$parentList,
$subsequentSiblingContent,
$subsequentParentListSiblingContent,
$sublist;
// The algorithm used here is generally:
// 1. Gather all subsequent sibling content in `liToIndent`s list along
// with all subsequent sibling content in `liToIndent`s parent list.
// 2. Move `liToIndent` after the li whose sublist it's in.
// 3. Create a sublist of the same type of `liToIndent`s parent list inside
// `liToIndent`.
// 4. If `liToIndent` has a sublist, use a spacer_li and list to hold its
// position inside the new sublist.
// 5. Append all original subsequent siblings inside the created sublist.
// 6. Append all of `liToIndent`s original parent list subsequent sibling
// content after the created sublist.
// 7. Remove `liToOutdent`'s original parent list and parent li if either
// are now empty
$liToOutdent = jQuery(listItem);
listType = $liToOutdent.parent()[0].tagName.toLowerCase();
// If this list item isn't already indented at least one level, don't allow
// outdenting
if (!$liToOutdent.parent().parent().is('ol,ul,li')) {
return;
}
if (!$liToOutdent.parent().parent().is('li')) {
// We have invalid list nesting and we need to fix that
WYMeditor.console.log(
'Attempting to fix invalid list nesting before outdenting.'
);
wym._fixInvalidListNesting(listItem);
}
// Separate out the contents into things that should stay with the li as it
// moves and things that should stay at their current level
splitContent = wym._splitListItemContents($liToOutdent);
$sublistContents = jQuery(splitContent.sublistContents);
$itemContents = jQuery(splitContent.itemContents);
// Gather subsequent sibling and parent sibling content
$parentLi = $liToOutdent.parent().parent('li');
// Invalid HTML could cause this selector to fail, which breaks our logic.
// Bail out rather than possibly losing content
if ($parentLi.length === 0) {
WYMeditor.console.error('Invalid list. No parentLi found, so aborting outdent');
return;
}
$parentList = $liToOutdent.parent();
$subsequentSiblingContent = $liToOutdent.nextAllContents();
$subsequentParentListSiblingContent = $parentList.nextAllContents();
// Move the li to after the parent li
$liToOutdent.detach();
$parentLi.after($liToOutdent);
// If this node has one or more sublists, they will need to be indented
// by one with a fake parent to hold their previous position
if ($sublistContents.length > 0) {
spacerListHtml = '<' + listType + '>' +
'' +
'' + listType + '>';
$liToOutdent.append(spacerListHtml);
$sublist = $liToOutdent.children().last();
// Add all of the sublistContents inside our new spacer li
$sublistContents.detach();
$sublist.children('li').append($sublistContents);
}
if ($subsequentSiblingContent.length > 0) {
// Nest the previously-subsequent items inside the list to
// retain order and their indent level
if (typeof $sublist === 'undefined') {
// Insert a sublist if we don't already have one
spacerListHtml = '<' + listType + '>' + listType + '>';
$liToOutdent.append(spacerListHtml);
$sublist = $liToOutdent.children().last();
}
$subsequentSiblingContent.detach();
$sublist.append($subsequentSiblingContent);
}
// If we have a parentItem with content after our parent list
// eg.
// - one
//
//
// we'll need to split that parentItem to retain proper content ordering
if ($subsequentParentListSiblingContent.length > 0) {
// Move the subsequent content in to a new list item after our parent li
$subsequentParentListSiblingContent.detach();
// If our last content and the first content in the subsequent content
// are both text nodes, insert a
spacer to avoid crunching the
// text together visually. This maintains the same "visual" structure.
if ($liToOutdent.contents().length > 0 &&
$liToOutdent.contents().last()[0].nodeType === WYMeditor.NODE_TYPE.TEXT &&
$subsequentParentListSiblingContent[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
$liToOutdent.append('
');
}
$liToOutdent.append($subsequentParentListSiblingContent);
}
// Remove our parentList if it's empty and if we just removed that, the
// parentLi is likely to be empty also
if ($parentList.contents().length === 0) {
$parentList.remove();
}
if ($parentLi.contents().length === 0) {
$parentLi.remove();
}
};
/**
editor._fixInvalidListNesting
=============================
Take an li/ol/ul and correct any list nesting issues in the entire list
tree.
Corrected lists have the following properties:
1. ol and ul nodes *only* allow li children.
2. All li nodes have either an ol or ul parent.
The `alreadyCorrected` argument is used to indicate if a correction has
already been made, which means we need to return true even if no further
corrections are made.
Returns true if any nodes were corrected.
*/
WYMeditor.editor.prototype._fixInvalidListNesting = function (listItem, alreadyCorrected) {
// Travel up the dom until we're at the root ol/ul/li
var wym = this,
currentNode = listItem,
parentNode,
tagName;
if (typeof alreadyCorrected === 'undefined') {
alreadyCorrected = false;
}
if (!currentNode) {
return alreadyCorrected;
}
while (currentNode.parentNode) {
parentNode = currentNode.parentNode;
if (parentNode.nodeType !== WYMeditor.NODE_TYPE.ELEMENT) {
// Our parent is outside a valid list structure. Stop at this node.
break;
}
tagName = parentNode.tagName.toLowerCase();
if (tagName !== 'ol' && tagName !== 'ul' && tagName !== 'li') {
// Our parent is outside a valid list structure. Stop at this node.
break;
}
// We're still traversing up a list structure. Keep going
currentNode = parentNode;
}
// We have the root node. Make sure it's legit
if (jQuery(currentNode).is('li')) {
// We have an li as the "root" because its missing a parent list.
// Correct this problem and then try again to correct the nesting.
WYMeditor.console.log(
"Correcting orphaned root li before correcting invalid list nesting."
);
wym._correctOrphanedListItem(currentNode);
return wym._fixInvalidListNesting(currentNode, true);
}
if (!jQuery(currentNode).is('ol,ul')) {
WYMeditor.console.error("Can't correct invalid list nesting. No root list found");
return alreadyCorrected;
}
return wym._fixInvalidlyNestedList(currentNode, alreadyCorrected);
};
/**
editor._isPOrDivAfterEnterInEmptyNestedLi(container)
====================================================
Detects one of the types of resulting DOM in issue #430.
The case is when a 'p' or a 'div' are introduced into the parent 'li'.
Since we don't allow a 'p' or a 'div' directly within 'li's it is replaced
with a 'br'.
Returns true if detected positively and false otherwise.
@param container An element to check this about.
*/
WYMeditor.editor.prototype._isPOrDivAfterEnterInEmptyNestedLi = function
(container) {
if (
jQuery.inArray(
container.tagName.toLowerCase(),
WYMeditor.DocumentStructureManager.VALID_DEFAULT_ROOT_CONTAINERS
) > -1 &&
container.parentNode.tagName.toLowerCase() === 'li'
) {
switch (container.childNodes.length) {
case 0:
return true;
case 1:
if (
container.childNodes[0].tagName &&
container.childNodes[0].tagName.toLowerCase() === 'br'
) {
return true;
} else if (
container.childNodes[0].nodeType === WYMeditor.NODE_TYPE.TEXT &&
container.childNodes[0].data === WYMeditor.NBSP
) {
return true;
}
}
}
return false;
};
/**
editor._isSpilledListAfterEnterInEmptyLi
========================================
Detects one of the types of resulting DOM in issue #430.
In this type of resulting DOM, the contents of a `li` have been
"spilled" after that `li`.
Returns true if detected positively and false otherwise.
@param container An element to check this about.
*/
WYMeditor.editor.prototype._isSpilledListAfterEnterInEmptyLi = function
(container) {
var wym = this;
if (
container.tagName.toLowerCase() === 'li' &&
container.previousSibling &&
wym.isListNode(container.previousSibling) &&
container.previousSibling.previousSibling &&
container.previousSibling.previousSibling.tagName
.toLowerCase() === 'li' &&
wym.isListNode(container.parentNode)
) {
return true;
}
return false;
};
/**
editor._handlePotentialEnterInEmptyNestedLi
===========================================
Issue #430. When the caret is in an empty nested `li` and the enter key is
pressed, browsers perform DOM manipulations that are different than what
we desire.
This detects two out of three types of the DOM manipulations and calls for
their correction.
The third type of DOM manipulation is harder to detect, but, luckily, it
is tolerable, so it goes undetected. This results in a difference in UX
across browsers.
For detailed information on this please see the issue #430's description.
@param keyPressed The code of the key that was pressed, to check whether
it is an enter.
@param container The currently selected container.
*/
WYMeditor.editor.prototype._handlePotentialEnterInEmptyNestedLi = function (
keyPressed, container) {
if (keyPressed !== WYMeditor.KEY_CODE.ENTER) {
// Only an enter key press can result a p/div in an empty nested list.
return null;
}
var wym = this;
if (wym._isPOrDivAfterEnterInEmptyNestedLi(container)) {
wym._replaceNodeWithBrAndSetCaret(container);
} else if (wym._isSpilledListAfterEnterInEmptyLi(container)) {
wym._appendSiblingsUntilNextLiToPreviousLi(container);
wym._replaceNodeWithBrAndSetCaret(container);
}
};
/**
editor._replaceNodeWithBrAndSetCaret
====================================
Replaces a node with a `br` element and sets caret before it.
If the previousSibling is inline (except for a `br`) then another `br`
is added before.
@param node This is the node to be replaced.
*/
WYMeditor.editor.prototype._replaceNodeWithBrAndSetCaret = function (node) {
var wym = this,
$node = jQuery(node);
if (
node.previousSibling &&
!node.previousSibling.tagName ||
node.previousSibling.tagName.toLowerCase() !== 'br' &&
wym.isInlineNode(node.previousSibling)
) {
$node.before('
');
}
$node.before('
');
wym.setCaretBefore(node.previousSibling);
$node.remove();
};
/**
editor._appendSiblingsUntilNextLiToPreviousLi
=============================================
This corrects the type of resulting DOM from issue #430 where the
contents of a `li` have been spilled to after that `li`.
It only corrects the spillage itself and doesn't modify the new `li`.
@param newLi This is the new 'li' that was created. It is supposed to
contain the caret.
*/
WYMeditor.editor.prototype._appendSiblingsUntilNextLiToPreviousLi =
function (newLi) {
var $newLi = jQuery(newLi),
// The spilled nodes are a subset of these.
$parentContents = $newLi.parent().contents(),
// This is the `li` that spilled its contents.
$sadLi = $newLi.prevAll('li').first(),
// This is the next `li` after the newLi. If it exists, it marks the
// end of the spill.
$nextLi = $newLi.nextAll('li').first(),
// The spill start index is after the source `li`.
spillStart = $sadLi.index() + 1,
$spilled;
if ($nextLi.length === 1) {
$spilled = $parentContents.slice(spillStart, $nextLi.index());
} else {
// There are no `li` elements after our newLi. The spill ends at the
// end of its parent.
$spilled = $parentContents.slice(spillStart);
}
$sadLi.append($spilled);
};
/**
editor._correctOrphanedListItem
===============================
Ensure that the given ophaned list item has a proper list parent.
Uses the sibling nodes to determine what kind of list should be used. Also
wraps sibling adjacent orphaned li nodes in the same list.
*/
WYMeditor.editor.prototype._correctOrphanedListItem = function (listNode) {
var prevAdjacentLis,
nextAdjacentLis,
$adjacentLis = jQuery(),
prevList,
prevNode;
prevAdjacentLis = jQuery(listNode).prevContentsUntil(':not(li)');
nextAdjacentLis = jQuery(listNode).nextContentsUntil(':not(li)');
// Merge the collections together
$adjacentLis = $adjacentLis.add(prevAdjacentLis);
$adjacentLis = $adjacentLis.add(listNode);
$adjacentLis = $adjacentLis.add(nextAdjacentLis);
// Determine if we have a list node in which to insert all of our orphaned
// li's
prevNode = $adjacentLis[0].previousSibling;
if (prevNode && jQuery(prevNode).is('ol,ul')) {
prevList = prevNode;
} else {
// No previous existing list to use. Need to create one
$adjacentLis.before('
');
prevList = $adjacentLis.prev()[0];
}
// Insert all of the adjacent orphaned lists inside the new parent
jQuery(prevList).append($adjacentLis);
};
/**
editor._fixInvalidlyNestedList
==============================
This is the function that actually does the list correction.
_fixInvalidListNesting is just a helper function that first finds the root
of the list.
Returns true if any correction was made.
We use a reverse preorder traversal to navigate the DOM because we might be:
* Making nodes children of their previous sibling (in the ...
case)
* Adding nodes at the current level (wrapping any non-li node inside a ul/ol in a new li node)
Adapted from code at: Tavs Dokkedahl from
http://www.jslab.dk/articles/non.recursive.preorder.traversal.part3
*/
WYMeditor.editor.prototype._fixInvalidlyNestedList = function (listNode, alreadyCorrected) {
var rootNode = listNode,
currentNode = listNode,
wasCorrected = false,
previousSibling,
tagName,
ancestorNode,
nodesToMove,
targetLi,
lastContentNode,
spacerHtml = '';
if (typeof alreadyCorrected !== 'undefined') {
wasCorrected = alreadyCorrected;
}
while (currentNode) {
if (currentNode._wym_visited) {
// This node has already been visited.
// Remove mark for visited nodes
currentNode._wym_visited = false;
// Once we reach the root element again traversal
// is done and we can break
if (currentNode === rootNode) {
break;
}
if (currentNode.previousSibling) {
currentNode = currentNode.previousSibling;
} else {
currentNode = currentNode.parentNode;
}
} else {
// This is the first visit for this node
// All non-li nodes must have an
// ancestor li node that's closer than any ol/ul ancestor node.
// Basically, everything needs to be inside an li node.
if (currentNode !== rootNode && !jQuery(currentNode).is('li')) {
// We have a non-li node.
// Ensure that we have an li ancestor before we have any ol/ul
// ancestors
ancestorNode = currentNode;
while (ancestorNode.parentNode) {
ancestorNode = ancestorNode.parentNode;
if (jQuery(ancestorNode).is('li')) {
// Everything is ok. Hit an li before a ol/ul
break;
}
if (ancestorNode.nodeType !== WYMeditor.NODE_TYPE.ELEMENT) {
// Our parent is outside a valid list structure. Stop at this node.
break;
}
tagName = ancestorNode.tagName.toLowerCase();
if (tagName === 'ol' || tagName === 'ul') {
// We've hit a list container before any list item.
// This isn't valid html and causes editing problems.
//
// Convert the list to a valid structure that closely
// mimics the layout and behavior of invalidly nested
// content inside a list. The browser treats the
// content similar to how it would treat that same
// content separated by a
within its previous
// sibling list item, so recreate that structure.
//
// The algorithm for performing this is basically:
// 1. Gather this and any previous siblings up until the
// previous li (if one exists) as content to move.
// 2. If we don't have any previous or subsequent li
// sibling, create a spacer li in which to insert all
// the gathered content.
// 3. Move all of the content to the previous li or the
// subsequent li (in that priority).
WYMeditor.console.log("Fixing orphaned list content");
wasCorrected = true;
// Gather this and previous sibling until the previous li
nodesToMove = [currentNode];
previousSibling = currentNode;
targetLi = null;
while (previousSibling.previousSibling) {
previousSibling = previousSibling.previousSibling;
if (jQuery(previousSibling).is('li')) {
targetLi = previousSibling;
// We hit an li. Store it as the target in
// which to move the nodes
break;
}
nodesToMove.push(previousSibling);
}
// We have our nodes ordered right to left and we need
// them left to right
nodesToMove.reverse();
// If there are no previous siblings, we can join the next li instead
if (!targetLi && nodesToMove.length === 1) {
if (jQuery(currentNode.nextSibling).is('li')) {
targetLi = currentNode.nextSibling;
}
}
// If we still don't have an li in which to move, we
// need to create a spacer li
if (!targetLi) {
jQuery(nodesToMove[0]).before(spacerHtml);
targetLi = jQuery(nodesToMove[0]).prev()[0];
}
// Move all of our content inside the li we've chosen
// If the last content node inside the target li is
// text and so is the first content node to move, separate them
// with a
to preserve the visual layout of them
// being on separate lines
lastContentNode = jQuery(targetLi).contents().last();
if (lastContentNode.length === 1 &&
lastContentNode[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
if (nodesToMove[0].nodeType === WYMeditor.NODE_TYPE.TEXT) {
jQuery(targetLi).append('
');
}
}
jQuery(targetLi).append(jQuery(nodesToMove));
break;
}
// We're still traversing up a list structure. Keep going
}
}
if (currentNode.lastChild) {
// Since we have childnodes, mark this as visited because
// we'll return later
currentNode._wym_visited = true;
currentNode = currentNode.lastChild;
} else if (currentNode.previousSibling) {
currentNode = currentNode.previousSibling;
} else {
currentNode = currentNode.parentNode;
}
}
}
return wasCorrected;
};
/**
editor._getCommonParentList
===========================
Get the common parent ol/ul for the given li nodes. If the parent ol/ul for
each cell isn't the same, returns null.
@param listItems An array of list item nodes to check for a common parent
@param getClosest If true, checks if the closest list parent to each list
node is the same. If false, checks if the furthest list
parent to each list node is the same.
*/
WYMeditor.editor.prototype._getCommonParentList = function (listItems, getClosest) {
var firstLi,
parentList,
rootList,
haveCommonParent = true;
listItems = jQuery(listItems).filter('li');
if (listItems.length === 0) {
return null;
}
firstLi = listItems[0];
parentList = jQuery(firstLi).parents('ol,ul');
parentList = (getClosest ? parentList.first() : parentList.last());
if (parentList.length === 0) {
return null;
}
rootList = parentList[0];
// Ensure that all of the li's have the same parent list
jQuery(listItems).each(function (index, elmnt) {
parentList = jQuery(elmnt).parents('ol,ul');
parentList = (getClosest ? parentList.first() : parentList.last());
if (parentList.length === 0 || parentList[0] !== rootList) {
haveCommonParent = false;
}
});
if (!haveCommonParent) {
return null;
}
return rootList;
};
/**
editor.deselect
===============
Removes seletion.
*/
WYMeditor.editor.prototype.deselect = function () {
var wym = this;
wym.selection().removeAllRanges();
// Blur seems to be required for IE8.
wym.body().blur();
};
/**
editor._getSelectedNodes
========================
Returns an array of the selected and partially selected nodes.
Returns false if there is not selection.
Returns false if there is no selection.
*/
WYMeditor.editor.prototype._getSelectedNodes = function () {
var wym = this,
selection = wym.selection(),
selectedNodes;
if (wym.hasSelection() !== true) {
return false;
}
selectedNodes = selection.getAllRanges()
.reduce(function (nodes, range) {
return nodes.concat(range.getNodes());
}, []);
return selectedNodes;
};
/**
editor._getSelectedListItems
============================
Determine which `li` nodes are "selected" from the user's standpoint.
These are the `li` nodes that they would expect to be affected by an action
with the given selection.
For a better understanding, comments are provided inside.
@param selection A Rangy Selection object.
*/
WYMeditor.editor.prototype._getSelectedListItems = function (selection) {
var wym = this,
$selectedContainer,
$selectedNodes,
$selectedLis;
if (selection.isCollapsed) {
$selectedContainer = jQuery(wym.selectedContainer());
if ($selectedContainer.closest('li, table').is('table')) {
// Inside a table and not inside a list inside it. This prevents
// the inclusion of the list item that might be an ancestor of the
// table.
return [];
}
return $selectedContainer.closest('li');
}
// All the selected nodes in the selection's first range.
$selectedNodes = jQuery(wym._getSelectedNodes());
if ($selectedNodes.closest('li, table').filter('li').length === 0) {
// Selection is in a table before it is in a list. This prevents
// inclusion of the list item that the table may be contained
// in.
return [];
}
// The technique is to get selected contents of the list items and then
// get their closest parent list items. So we don't want the list elements.
// Some list items may be empty and we do want those so we'll add them back
// later.
$selectedLis = $selectedNodes.not('li, ol, ul')
// IE doesn't include the Rangy selection boundary `span` in the above
// `.getNodes`. This effects an edge case, where a `li` contains only
// that `span`.
.add($selectedNodes.find('.rangySelectionBoundary'))
// Add back the text nodes because jQuery.not always excludes them.
.add(
$selectedNodes.filter(
function () {
return wym.nodeType === WYMeditor.NODE_TYPE.TEXT;
}
)
)
.closest('li')
// Add `li`s that are selected and are empty. Because they didn't
// get found by `.closest`. We can safely add them because they don't
// contain other list items so surely if they are in the selection it is
// because the user wants to manipulate them.
.add($selectedNodes.filter('li:empty'))
// Exclude list items that are children of table elements that are in the
// selection.
.not($selectedNodes.filter('table').find('li'));
return jQuery.unique($selectedLis.get());
};
/**
editor._selectionOnlyInList
===========================
Tests if all of the nodes within the passed selection are contained in one
list. Returns true if all of the nodes are within one list, and returns
false if otherwise.
@param sel A selection to test for being entirely contained within one
list.
*/
WYMeditor.editor.prototype._selectionOnlyInList = function (sel) {
var wym = this,
selStartNode,
selEndNode,
i;
for (i = 0; i < sel.rangeCount; ++i) {
selStartNode = wym.findUp(sel.getRangeAt(i).startContainer, ['li']);
selEndNode = wym.findUp(sel.getRangeAt(i).endContainer, ['li']);
// If the start or end node is not contained within a list item, return
// false.
if (!selStartNode || !selEndNode) {
return false;
}
// If the two list items do not have a common parent list, return
// false.
if (!wym._getCommonParentList([selStartNode, selEndNode], false)) {
return false;
}
}
return true;
};
/**
editor.indent
=============
Indent the selected list items via the dom.
Only list items that have a common list will be indented.
*/
WYMeditor.editor.prototype.indent = function () {
var wym = this,
sel = wym.selection(),
listItems,
manipulationFunc,
i;
// First, make sure this list is properly structured
manipulationFunc = function () {
var selection = wym.selection(),
selectedBlock = wym.get$CommonParent(
selection.anchorNode,
selection.focusNode
)[0],
potentialListBlock = wym.findUp(
selectedBlock,
['ol', 'ul', 'li']
);
return wym._fixInvalidListNesting(potentialListBlock);
};
if (wym.restoreSelectionAfterManipulation(manipulationFunc)) {
// We actually made some list correction
// Don't actually perform the action if we've potentially just changed
// the list, and maybe the list appearance as a result.
wym.registerModification();
return true;
}
// We just changed and restored the selection when possibly correcting the
// lists
sel = wym.selection();
// If all of the selected nodes are not contained within one list, don't
// perform the action.
if (!wym._selectionOnlyInList(sel)) {
return false;
}
// Gather the li nodes the user means to affect based on their current
// selection
listItems = wym._getSelectedListItems(sel);
if (listItems.length === 0) {
return false;
}
manipulationFunc = function () {
var domChanged = false;
for (i = 0; i < listItems.length; i++) {
wym._indentSingleItem(listItems[i]);
domChanged = true;
}
return domChanged;
};
return wym.restoreSelectionAfterManipulation(manipulationFunc) &&
wym.registerModification();
};
/**
editor.outdent
==============
Outdent a list item, accounting for firefox bugs to ensure consistent
behavior and valid HTML.
*/
WYMeditor.editor.prototype.outdent = function () {
var wym = this,
sel = wym.selection(),
listItems,
manipulationFunc,
i;
// First, make sure this list is properly structured
manipulationFunc = function () {
var selection = wym.selection(),
selectedBlock = wym.get$CommonParent(
selection.anchorNode,
selection.focusNode
)[0],
potentialListBlock = wym.findUp(
selectedBlock,
['ol', 'ul', 'li']
);
return wym._fixInvalidListNesting(potentialListBlock);
};
if (wym.restoreSelectionAfterManipulation(manipulationFunc)) {
// We actually made some list correction
// Don't actually perform the action if we've potentially just changed
// the list, and maybe the list appearance as a result.
wym.registerModification();
return true;
}
// We just changed and restored the selection when possibly correcting the
// lists
sel = wym.selection();
// If all of the selected nodes are not contained within one list, don't
// perform the action.
if (!wym._selectionOnlyInList(sel)) {
return false;
}
// Gather the li nodes the user means to affect based on their current
// selection
listItems = wym._getSelectedListItems(sel);
if (listItems.length === 0) {
return false;
}
manipulationFunc = function () {
var domChanged = false;
for (i = 0; i < listItems.length; i++) {
wym._outdentSingleItem(listItems[i]);
domChanged = true;
}
return domChanged;
};
return wym.restoreSelectionAfterManipulation(manipulationFunc) &&
wym.registerModification();
};
/**
editor.restoreSelectionAfterManipulation
========================================
A helper function to ensure that the selection is restored to the same
location after a potentially complicated DOM manipulation is performed. This
also handles the case where the DOM manipulation throws an error by cleaning
up any selection markers that were added to the DOM.
`manipulationFunc` is a function that takes no arguments and performs the
manipulation. It should return `true` if changes were made that could have
potentially destroyed the selection.
*/
WYMeditor.editor.prototype.restoreSelectionAfterManipulation = function (manipulationFunc) {
var wym = this,
savedSelection = rangy.saveSelection(
rangy.dom.getIframeWindow(wym._iframe)
),
changesMade = true;
// If something goes wrong, we don't want to leave selection markers
// floating around
try {
changesMade = manipulationFunc();
if (changesMade) {
rangy.restoreSelection(savedSelection);
} else {
rangy.removeMarkers(savedSelection);
}
} catch (e) {
WYMeditor.console.error("Error during manipulation");
WYMeditor.console.error(e);
rangy.removeMarkers(savedSelection);
}
return changesMade;
};
/**
editor._insertOrderedList
=========================
Convert the selected block in to an ordered list.
If the selection is already inside a list, switch the type of the nearest
parent list to an ``. If the selection is in a block element that can be a
valid list, place that block element's contents inside an ordered list.
Pure dom implementation consistently cross-browser implementation of
`execCommand(InsertOrderedList)`.
*/
WYMeditor.editor.prototype._insertOrderedList = function () {
var wym = this,
manipulationFunc;
// First, make sure this list is properly structured
manipulationFunc = function () {
// There is a design flaw here. Especially in the case where we may
// have multiple root-level lists or even `li` items (which shouldn't
// happen) selected. This code seems to make our tests pass but this
// should be considered broken.
var potentialListBlock = jQuery(wym._getSelectedNodes())
.parents().addBack().filter('ol, ul, li').last()[0];
potentialListBlock = potentialListBlock || wym.selectedContainer();
return wym._fixInvalidListNesting(potentialListBlock);
};
if (wym.restoreSelectionAfterManipulation(manipulationFunc)) {
// We actually made some list correction
// Don't actually perform the action if we've potentially just changed
// the list, and maybe the list appearance as a result.
wym.registerModification();
return true;
}
// Actually perform the list insertion
manipulationFunc = function () {
return wym.insertList('ol');
};
return wym.restoreSelectionAfterManipulation(manipulationFunc) &&
wym.registerModification();
};
/**
editor._insertUnorderedList
===========================
Convert the selected block in to an unordered list.
Exactly the same as `editor.insert_orderedlist` except with `` instead.
Pure dom implementation consistently cross-browser implementation of
`execCommand(InsertUnorderedList)`.
*/
WYMeditor.editor.prototype._insertUnorderedList = function () {
var wym = this,
manipulationFunc;
// First, make sure this list is properly structured
manipulationFunc = function () {
// There is a design flaw here. Especially in the case where we may
// have multiple root-level lists or even `li` items (which shouldn't
// happen) selected. This code seems to make our tests pass but this
// should be considered broken.
var potentialListBlock = jQuery(wym._getSelectedNodes())
.parents().addBack().filter('ol, ul, li').last()[0];
potentialListBlock = potentialListBlock || wym.selectedContainer();
return wym._fixInvalidListNesting(potentialListBlock);
};
if (wym.restoreSelectionAfterManipulation(manipulationFunc)) {
// We actually made some list correction
// Don't actually perform the action if we've potentially just changed
// the list, and maybe the list appearance as a result.
wym.registerModification();
return true;
}
// Actually perform the list insertion
manipulationFunc = function () {
return wym.insertList('ul');
};
return wym.restoreSelectionAfterManipulation(manipulationFunc) &&
wym.registerModification();
};
/**
editor.insertList
=================
This either manipulates existing lists or creates a new one.
The action that will be performed depends on the contents of the
selection and their context.
This can result in one of:
1. Changing the type of lists.
2. Removing items from list.
3. Creating a list.
4. Nothing.
If existing list items are selected this means either changing list type
or de-listing. Changing list type occurs when selected list items all share
a list of a different type than the requested. Removing items from lists
occurs when selected list items are all of the same type as the requested.
If no list items are selected, then, if possible, a list will be created.
If not possible, no change is made.
Returns `true` if a change was made, `false` otherwise.
@param listType A string, representing the user's action, either 'ul'
or 'ol'.
*/
WYMeditor.editor.prototype.insertList = function (listType) {
var wym = this,
sel = wym.selection(),
listItems,
$listItems,
$parentListsOfDifferentType,
commonParentList,
potentialListBlock;
listItems = wym._getSelectedListItems(sel);
if (listItems.length > 0) {
// We have existing list items selected. This means either changing
// their parent lists' types or de-listing.
$listItems = jQuery(listItems);
$parentListsOfDifferentType = $listItems
.parent(':not(' + listType + ')');
if ($parentListsOfDifferentType.length > 0) {
// Some of the lists are of a different type than that which was
// requested.
// Change list type only if selected list items share a common parent
// list. TODO: Change types over several lists:
// https://github.com/wymeditor/wymeditor/issues/541
commonParentList = wym._getCommonParentList(listItems, true);
if (commonParentList) {
wym.changeListType(commonParentList, listType);
return true;
}
} else {
// List types are the same as requested. De-list.
wym._removeItemsFromList($listItems);
return true;
}
}
// Get a potential block element from selection that could be converted
// into a list:
// TODO: Use `_containerRules['root']` minus the ol/ul and
// `_containerRules['contentsCanConvertToList']
potentialListBlock = wym.findUp(
wym.selectedContainer(),
WYMeditor.POTENTIAL_LIST_ELEMENTS
);
if (potentialListBlock) {
wym.convertToList(potentialListBlock, listType);
return true;
}
// The user has something selected that wouldn't be a valid list
return false;
};
WYMeditor.editor.prototype.changeListType = function (list, listType) {
var wym = this;
// Wrap the contents in a new list of `listType` and remove the old list
// container.
return wym.switchTo(list, listType);
};
WYMeditor.editor.prototype.convertToList = function (blockElement, listType) {
var wym = this,
$blockElement = jQuery(blockElement),
newListHtml,
$newList;
// ie6 doesn't support calling wrapInner with a dom node. Build html
newListHtml = '<' + listType + '>' + listType + '>';
if (wym.findUp(blockElement, WYMeditor.ROOT_CONTAINERS) === blockElement) {
// TODO: Handle ol/ul elements, since these are now in the `root`
// containers list
// This is a root container block, so we can just replace it with the
// list structure
$blockElement.wrapInner(newListHtml);
$newList = $blockElement.children();
$newList.unwrap();
return $newList.get(0);
}
// We're converting a block that's not a root container, so we need to nest
// this list around its contents and NOT remove the container (eg. a td
// node).
$blockElement.wrapInner(newListHtml);
$newList = $blockElement.children();
return $newList.get(0);
};
/**
editor._removeItemsFromList
===========================
De-list the provided list items.
@param listItems A jQuery object of list items.
*/
WYMeditor.editor.prototype._removeItemsFromList = function ($listItems) {
var wym = this,
$listItem,
i,
j,
listItemChild,
$childNodesToTransfer,
k,
$childNodeToTransfer,
rootContainer = wym.documentStructureManager.structureRules
.defaultRootContainer,
attributes;
// This is left here for future reference because it may or may not be a
// better behavior:
// It is reasonable to de-list only a subset of the provided list items.
// The subset are the list items which are not ancestors of any other list
// items.
//$listItems = $listItems.not($listItems.find('li'));
for (i = 0; i < $listItems.length; i++) {
$listItem = $listItems.eq(i);
// Determine the type of element this list item will be transformed
// into and call for this transformation.
if ($listItem.parent().parent('li, th, td').length === 1) {
// The list item will end up inside another list item or inside a
// table cell. Turn it into a `span`.
$listItem = jQuery(
wym.switchTo(
$listItem[0],
'span',
false
)
);
} else {
// The list item will end up in the root of the document. Turn it
// into a default root container.
$listItem = jQuery(
wym.switchTo(
$listItem[0],
rootContainer,
false
)
);
}
// The transformation should be complete and the element is no longer
// a list item, hence we call it 'the de-listed element'.
// Move the de-listed element according to its relation to its
// sibling nodes.
if ($listItem.parent().children().length === 1) {
// It is the only child in the list.
$listItem.parent().before($listItem);
// Remove the list because it is empty.
$listItem.next().remove();
} else if ($listItem[0] === $listItem.parent().children().first()[0]) {
// It is not the only child. It is the first child.
$listItem.parent().before($listItem);
} else if (
$listItem[0] !== $listItem.parent().children().first()[0] &&
$listItem[0] !== $listItem.parent().children().last()[0]
) {
// It is not the first and not the last child.
$listItem.parent().before(
'<' + $listItem.parent()[0].tagName + '/>'
);
jQuery($listItem.prevAll().toArray().reverse())
.appendTo($listItem.parent().prev());
$listItem.parent().before($listItem);
} else if ($listItem[0] === $listItem.parent().children().last()[0]) {
// It is not the only child. It is the last child.
$listItem.parent().after($listItem);
}
// The de-listed element should now be at it's final destination.
// Now, deal with its contents.
for (j = 0; j < $listItem.contents().length; j++) {
listItemChild = $listItem.contents()[j];
if (
wym.isBlockNode(listItemChild) &&
// Prevents a rangy selection boundary element from interfering.
listItemChild.className !== 'rangySelectionBoundary' &&
listItemChild.tagName.toLowerCase() !== 'br'
) {
// We have hit the first block child. From this child onward,
// the contents will be moved to after the de-listed element.
$childNodesToTransfer = $listItem.contents().slice(j);
if (
$listItem[0].tagName.toLowerCase() ===
rootContainer
) {
// The destination of these nodes is the root element.
// Prepare them as such.
for (k = 0; k < $childNodesToTransfer.length; k++) {
$childNodeToTransfer = $childNodesToTransfer.eq(k);
if (
$childNodeToTransfer[0]
.nodeType === WYMeditor.NODE_TYPE.TEXT
) {
$childNodeToTransfer.wrap(
'<' + rootContainer + ' />'
);
} else if (
$childNodeToTransfer[0].tagName &&
!(wym.isBlockNode($childNodeToTransfer[0])) &&
$childNodeToTransfer[0].tagName
.toLowerCase() !== 'br'
) {
wym.switchTo(
$childNodesToTransfer[k],
rootContainer,
false
);
}
}
}
// The contents should be ready now.
$listItem.after($listItem.contents().slice(j));
// The loop was for finding the first block element.
break;
}
}
// `br`s may have been transferred to the root container. They don't
// belong there.
wym.$body().children('br').remove();
if ($listItem[0].tagName.toLowerCase() === 'span') {
// Get rid of empty `span`s and ones that contain only `br`s.
if (
$listItem.contents(':not(.rangySelectionBoundary)')
.length === 0 ||
$listItem.contents(':not(.rangySelectionBoundary)').length ===
$listItem.contents('br').length
) {
// The Rangy selection boundary `span` may be inside.
$listItem.before($listItem.contents('.rangySelectionBoundary'));
$listItem.remove();
} else {
// The `span` wasn't removed.
// Add `br` elements that may be necessary because by turning
// a `li` element into a `span` element we turn a block
// type element into an inline type element.
if (
$listItem[0].previousSibling &&
$listItem[0].previousSibling.nodeType === WYMeditor
.NODE_TYPE.TEXT ||
$listItem.prevAll(':not(.rangySelectionBoundary)')
.length > 0 &&
wym.isBlockNode(
$listItem.prevAll(':not(.rangySelectionBoundary)')[0]
) === false
) {
$listItem.before('
');
}
if (
$listItem[0].nextSibling &&
$listItem[0].nextSibling.nodeType === WYMeditor
.NODE_TYPE.TEXT ||
$listItem.nextAll(':not(.rangySelectionBoundary)')
.length > 0 &&
wym.isBlockNode(
$listItem.nextAll(':not(.rangySelectionBoundary)')[0]
) === false
) {
$listItem.after('
');
}
// If the de-listed element has no meaningful attributes, there is
// no use for it being a span.
attributes = $listItem[0].attributes;
wym.unwrapIfMeaninglessSpan($listItem[0]);
}
}
}
// Reintroduce any necessary DOM-level corrections for editing purposes
wym.prepareDocForEditing();
};
/**
editor.insertTable
==================
Insert a table at the current selection with the given number of rows
and columns and with the given caption and summary text.
*/
WYMeditor.editor.prototype.insertTable = function (rows, columns, caption, summary) {
if ((rows <= 0) || (columns <= 0)) {
// We need rows and columns to make a table
// TODO: It seems to me we should warn the user when zero columns and/or
// rows were entered.
return;
}
var wym = this,
table = wym._doc.createElement(WYMeditor.TABLE),
newRow = null,
newCaption,
x,
y,
container,
selectedNode;
// Create the table caption
newCaption = table.createCaption();
newCaption.innerHTML = caption;
// Create the rows and cells
for (x = 0; x < rows; x += 1) {
newRow = table.insertRow(x);
for (y = 0; y < columns; y += 1) {
newRow.insertCell(y);
}
}
if (summary !== "") {
// Only need to set the summary if we actually have a summary
jQuery(table).attr('summary', summary);
}
// Find the currently-selected container
container = jQuery(
wym.findUp(wym.selectedContainer(), WYMeditor.POTENTIAL_TABLE_INSERT_ELEMENTS)
).get(0);
if (!container || !container.parentNode) {
// No valid selected container. Put the table at the end.
wym.$body().append(table);
} else if (jQuery.inArray(container.nodeName.toLowerCase(),
WYMeditor.INLINE_TABLE_INSERTION_ELEMENTS) > -1) {
// Insert table after selection if container is allowed to have tables
// inserted inline.
selectedNode = wym.selection().focusNode;
// If the selection is within a table, move the selection to the parent
// table to avoid nesting the tables.
if (jQuery.inArray(selectedNode.nodeName.toLowerCase(),
WYMeditor.SELECTABLE_TABLE_ELEMENTS) > -1 ||
jQuery.inArray(selectedNode.parentNode.nodeName.toLowerCase(),
WYMeditor.SELECTABLE_TABLE_ELEMENTS) > -1) {
while (selectedNode.nodeName.toLowerCase() !== WYMeditor.TABLE) {
selectedNode = selectedNode.parentNode;
}
}
// If the list item itself is selected, append the table to it. If the
// selection is within the list item, put the table after it. Either
// way, this ensures the table will always be inserted within the list
// item.
if (selectedNode.nodeName.toLowerCase() === WYMeditor.LI) {
jQuery(selectedNode).append(table);
} else {
jQuery(selectedNode).after(table);
}
} else {
// If the table is not allowed to be inserted inline with the
// container, insert it after the container.
jQuery(container).after(table);
}
// Handle any browser-specific cleanup
wym._afterInsertTable(table);
wym.prepareDocForEditing();
wym.registerModification();
return table;
};
/**
editor._afterInsertTable
========================
Handle cleanup/normalization after inserting a table. Different browsers
need slightly different tweaks.
*/
WYMeditor.editor.prototype._afterInsertTable = function () {
};
WYMeditor.editor.prototype._listen = function () {
var wym = this;
jQuery(wym._doc).bind('paste', function () {
wym._handlePasteEvent();
});
};
WYMeditor.editor.prototype._handlePasteEvent = function () {
var wym = this;
// The paste event happens *before* the paste actually occurs.
// Use a timer to delay execution until after whatever is being pasted has
// actually been added.
window.setTimeout(
function () {
jQuery(wym.element).trigger(
WYMeditor.EVENTS.postBlockMaybeCreated,
wym
);
},
20
);
};
/**
WYMeditor.editor._selectSingleNode
==================================
Sets selection to a single node, exclusively.
Not public API because not tested enough.
For example, what happens when selecting containing element, this way?
*/
WYMeditor.editor.prototype._selectSingleNode = function (node) {
var wym = this,
selection,
nodeRange;
if (!node) {
throw "Expected a node";
}
selection = wym.selection();
nodeRange = rangy.createRangyRange();
nodeRange.selectNode(node);
selection.setSingleRange(nodeRange);
};
/**
WYMeditor.editor._initSkin
==========================
Apply the appropriate CSS class to "activate" that skin's CSS and call the
skin's javascript `init` method.
*/
WYMeditor.editor.prototype._initSkin = function () {
var wym = this;
// Put the classname (ex. wym_skin_default) on wym_box
jQuery(wym._box).addClass("wym_skin_" + wym._options.skin);
// Init the skin, if needed
if (typeof WYMeditor.SKINS[wym._options.skin] !== "undefined") {
if (typeof WYMeditor.SKINS[wym._options.skin].init === "function") {
WYMeditor.SKINS[wym._options.skin].init(wym);
}
} else {
WYMeditor.console.warn(
"Chosen skin _" + wym.options.skin + "_ not found."
);
}
};
/**
WYMeditor.editor.body
=====================
Returns the document's body element.
*/
WYMeditor.editor.prototype.body = function () {
var wym = this,
body;
if (!wym._doc.body) {
throw "The document seems to have no body element.";
}
body = wym._doc.body;
if (
!body.tagName ||
body.tagName.toLowerCase() !== 'body'
) {
throw "The document's body doesn't seem to be a `body` element.";
}
return body;
};
/**
WYMEditor.editor.$body
======================
Returns a jQuery object of the document's body element.
*/
WYMeditor.editor.prototype.$body = function () {
var wym = this,
body;
body = wym.body();
return jQuery(body);
};
/**
WYMeditor.editor.doesElementContainSelection
============================================
Returns ``true`` if the supplied element contains at least part of the
selection.
Otherwise returns ``false``.
*/
WYMeditor.editor.prototype.doesElementContainSelection = function (element) {
var wym = this,
$element,
selectedContainer,
$selectedNodes,
i,
$selectedNodeAncestors,
j;
if (wym.hasSelection() !== true) {
return false;
}
$element = jQuery(element);
if (wym.selection().isCollapsed === true) {
selectedContainer = wym.selectedContainer();
if (element === selectedContainer) {
return true;
}
if ($element.has(selectedContainer).length > 0) {
return true;
}
return false;
}
// For non-collapsed selections.
// We could have used the following, but it
// doesn't work in IE8.
// if ($element.has(wym._getSelectedNodes()).length > 0) {
// return true;
// }
$selectedNodes = jQuery(wym._getSelectedNodes());
for (i = 0; i < $selectedNodes.length; i++) {
$selectedNodeAncestors = $selectedNodes.eq(i).parents();
for (j = 0; j < $selectedNodeAncestors.length; j++) {
if ($selectedNodeAncestors[j] === element) {
return true;
}
}
}
return false;
};
/*jslint maxlen: 90 */
/* global -$ */
"use strict";
/**
* WYMeditor.DocumentStructureManager
* ==================================
*
* This manager controls the rules for the subset of HTML that WYMeditor will
* allow the user to create. For technical users, there are justifiable reasons
* to use any in-spec HTML, but for users of WYMeditor (not implementors), the
* goal is make it intuitive for them to create the structured markup that will
* fit their needs.
*
* For example, while it's valid HTML to have a mix
* of DIV and P tags at the top level of a document, in practice, this is
* confusing for non-technical users. The DocumentStructureManager allows the
* WYMeditor implementor to standardize on P tags in the root of the document,
* which will automatically convert DIV tags in the root to P tags.
*
*/
WYMeditor.DocumentStructureManager = function (wym, defaultRootContainer) {
var dsm = this;
dsm._wym = wym;
dsm.structureRules = WYMeditor.DocumentStructureManager.DEFAULTS;
dsm.setDefaultRootContainer(defaultRootContainer);
};
jQuery.extend(WYMeditor.DocumentStructureManager, {
// Only these containers are allowed as valid `defaultRootContainer`
// options.
VALID_DEFAULT_ROOT_CONTAINERS : [
"p",
"div"
],
// Cooresponding titles for use in the containers panel for the valid
// default root containers
DEFAULT_ROOT_CONTAINER_TITLES : {
p: "Paragraph",
div: "Division"
},
// These containers prevent the user from using up/down/enter/backspace
// to move above or below them, thus effectively blocking the creation
// of new blocks. We must use temporary spacer elements to correct this
// while the document is being edited.
CONTAINERS_BLOCKING_NAVIGATION : ["table", "blockquote", "pre"],
DEFAULTS : {
// By default, this container will be used for all root contents. This
// defines the container used when "enter" is pressed from the root and
// also which container wraps or replaces containers found at the root
// that aren't allowed. Only
// `DocumentStructureManager.VALID_DEFAULT_ROOT_CONTAINERS` are allowed
// here. Whichever you choose, the VALID_DEFAULT_ROOT_CONTAINERS will
// be automatically converted when found at the top level of your
// document.
defaultRootContainer: 'p',
// These containers cannot be used as root containers. This includes
// any default root containers that are not the chosen default root
// container. By default, this is set to the list of valid root
// containers that are not the defaultRootContainer.
notValidRootContainers: ['div'],
// Only these containers are allowed as a direct child of the body tag.
// All other containers located there will be wrapped in the
// `defaultRootContainer`, unless they're one of the tags in
// `convertIfRoot`.
validRootContainers: [
'p',
'div',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'pre',
'blockquote',
'table',
'ol',
'ul'
],
// If these tags are found in the root, they'll be converted to the
// `defaultRootContainer` container instead of the default of being
// wrapped.
convertIfRootContainers: [
'div'
],
// The elements that are allowed to be turned in to lists.
validListConversionTargetContainers: [
"p",
"div",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"pre",
"blockquote",
"td",
"th"
],
// For most block elements, the default behavior when a user attempts
// to convert it to a list is to convert that block to a ol/ul and wrap
// the contents in an li. For containers in `wrapContentsInList`,
// instead of converting the container, we should just wrap the
// contents of the container in a ul/ol + li.
wrapContentsInList: [
'td',
'th'
]
}
});
/**
* Set the default container created/used in the root.
*
* @param defaultRootContainer String A string representation of the tag to
* use.
*/
WYMeditor.DocumentStructureManager.prototype.setDefaultRootContainer = function
(
defaultRootContainer
) {
var dsm = this,
validContainers,
index,
DSManager;
if (dsm.structureRules.defaultRootContainer === defaultRootContainer) {
// This is already our current configuration. No need to do the
// work again.
return;
}
// Make sure the new container is one of the valid options
DSManager = WYMeditor.DocumentStructureManager;
validContainers = DSManager.VALID_DEFAULT_ROOT_CONTAINERS;
index = jQuery.inArray(defaultRootContainer, validContainers);
if (index === -1) {
throw new Error(
"a defaultRootContainer of '" +
defaultRootContainer +
"' is not supported"
);
}
dsm.structureRules.defaultRootContainer = defaultRootContainer;
// No other possible option for default root containers is valid expect for
// the one choosen default root container
dsm.structureRules.notValidRootContainers =
WYMeditor.DocumentStructureManager.VALID_DEFAULT_ROOT_CONTAINERS;
dsm.structureRules.notValidRootContainers.splice(index, 1);
dsm._adjustDefaultRootContainerUI();
// TODO: Actually do all of the switching required to move from p to div or
// from div to p for the topLevelContainer
};
/**
_adjustDefaultRootContainerUI
=============================
Adds a new link for the default root container to the containers panel in
the editor if needed, and removes any other links for valid default root
containers form the containers panel besides the link for the chosen
default root container.
*/
WYMeditor.DocumentStructureManager.prototype._adjustDefaultRootContainerUI = function () {
var dsm = this,
wym = dsm._wym,
defaultRootContainer = dsm.structureRules.defaultRootContainer,
$containerItems,
$containerLink,
$newContainerItem,
containerName,
newContainerLinkNeeded,
newContainerLinkHtml,
i,
DSManager;
$containerItems = jQuery(wym._box).find(wym._options.containersSelector)
.find('li');
newContainerLinkNeeded = true;
// Remove container links for any other valid default root container from
// the containers panel besides the link for the chosen default root
// container
for (i = 0; i < $containerItems.length; ++i) {
$containerLink = $containerItems.eq(i).find('a');
containerName = $containerLink.attr('name').toLowerCase();
if (jQuery.inArray(containerName,
dsm.structureRules.notValidRootContainers) > -1) {
$containerItems.eq(i).remove();
}
if (containerName === defaultRootContainer) {
newContainerLinkNeeded = false;
}
}
// Add new link for the default root container to the containers panel if
// needed
if (newContainerLinkNeeded) {
newContainerLinkHtml = wym._options.containersItemHtml;
newContainerLinkHtml = WYMeditor.Helper.replaceAllInStr(
newContainerLinkHtml,
WYMeditor.CONTAINER_NAME,
defaultRootContainer.toUpperCase()
);
DSManager = WYMeditor.DocumentStructureManager;
newContainerLinkHtml = WYMeditor.Helper.replaceAllInStr(
newContainerLinkHtml,
WYMeditor.CONTAINER_TITLE,
DSManager.DEFAULT_ROOT_CONTAINER_TITLES[defaultRootContainer]
);
newContainerLinkHtml = WYMeditor.Helper.replaceAllInStr(
newContainerLinkHtml,
WYMeditor.CONTAINER_CLASS,
"wym_containers_" + defaultRootContainer
);
$newContainerItem = jQuery(newContainerLinkHtml);
$containerItems = jQuery(wym._box).find(wym._options.containersSelector)
.find('li');
$containerItems.eq(0).before($newContainerItem);
// Bind click event for the new link
$newContainerItem.find('a').click(function () {
var button = this;
wym.setRootContainer(jQuery(button).attr(WYMeditor.NAME));
return false;
});
}
};
/* jshint maxlen:100 */
"use strict";
/*
* # The Image Handler
*
* Give it an editor instance and it will make
* most of your image resizing dreams come true.
*
* ## IE8 Shenanigans
*
* When IE8 is not longer supported,
* `rem` could be used for more accurate UI element dimensions
*
* Dragging and dropping of images is not suggested in the UI.
* See the `_isImgDragDropAllowed` function
* and the `_onImgMousedown` function.
*
* ## IE9 Shenanigans
*
* Dragging and dropping of images is disabled.
* See the `_isImgDragDropAllowed` function.
*
* ## IE8-11 Shenanigans
*
* SVG images are not scaled.
* They are cropped. That's right.
* And applying style to them does not help,
* as well. Ideas are welcome.
*
* ## General Shenanigans (http://i.imgur.com/wbQ6U5C.jpg)
*
* This module is covered by only a few basic tests
* so any change must be meticulously manually tested
* in all the supported browsers
* by psychologically stable individuals.
*
* Dragging and dropping of images
* might produce undesired results on drop.
* Uncharted territory.
*
* In event handlers of events that
* are not expected to perform useful default actions
* `return false` is used to prevent any bad feelings
* towards unexpected browser behavior.
*/
// the image handler class.
WYMeditor.ImageHandler = function (wym) {
var ih = this;
ih._wym = wym;
ih._$resizeHandle = ih._createResizeHandle();
ih._$currentImageMarker = null;
// references the image that
// has the resize handle placed on it
ih._$currentImg = null;
// flags whether a resize operation is
// occurring at this moment
ih._resizingNow = false;
ih._imgDragDropAllowed = WYMeditor.ImageHandler._isImgDragDropAllowed();
ih._addEventListeners();
return ih;
};
WYMeditor.ImageHandler._isImgDragDropAllowed = function () {
var browser = jQuery.browser;
if (browser.msie) {
if (browser.versionNumber <= 9) {
// dragging and dropping seems to not consistently work.
// the image would only some times get picked up by the mouse drag attempt.
// to prevent confusion
return false;
}
}
return true;
};
WYMeditor.ImageHandler._RESIZE_HANDLE_HR_HTML = jQuery('
')
.addClass(WYMeditor.EDITOR_ONLY_CLASS)
.css({margin: 0, padding: 0})
.attr('outerHTML');
WYMeditor.ImageHandler._RESIZE_HANDLE_INNER_HTML = [
'drag this to resize',
'click on image to select'
].join(WYMeditor.ImageHandler._RESIZE_HANDLE_HR_HTML);
WYMeditor.ImageHandler._IMAGE_HIGHLIGHT_COLOR = 'yellow';
// creates and returns
// a yet detached UI resize handle element
// in a jQuery object
WYMeditor.ImageHandler.prototype._createResizeHandle = function () {
var $handle = jQuery('');
// In IE11 it was very easy to
// accidentally enter into editing mode
// in the resize handle.
// This seamlessly prevents it.
$handle.attr('contentEditable', 'false');
$handle.html(WYMeditor.ImageHandler._RESIZE_HANDLE_INNER_HTML);
$handle
.addClass(WYMeditor.RESIZE_HANDLE_CLASS)
.addClass(WYMeditor.EDITOR_ONLY_CLASS);
$handle.css({
margin: '0',
padding: '0',
// when IE9 is no longer supported
// this could be `ns-resize`
cursor: 'row-resize',
'text-align': 'center',
// this means that
// elements after the resize handle
// will not be pushed down because of its presence.
// we later use the `left` and `top` properties
// to keep the resize handle exactly
// below its current image
position: 'absolute',
'background-color': WYMeditor.ImageHandler._IMAGE_HIGHLIGHT_COLOR,
// override default iframe stylesheet
// so that a 'div' does not appear
'background-image': 'none',
// so that the text inside the resize handle
// fits in one line.
// in the theoretical future
// the more appropriate value would be
// `min-content`
'min-width': '13em',
width: '100%'
});
return $handle;
};
WYMeditor.ImageHandler.prototype._getCurrentImageMarker = function () {
var ih = this;
if (
// a marker was not yet created
!ih._$currentImageMarker ||
// a marker was destroyed via native edit
!ih._$currentImageMarker.length
) {
ih._$currentImageMarker = ih._createCurrentImageMarker();
}
return ih._$currentImageMarker;
};
WYMeditor.ImageHandler._IMAGE_MARKER_CLASS = 'wym-image-marker';
WYMeditor.ImageHandler.prototype._createCurrentImageMarker = function () {
return jQuery('')
.addClass(WYMeditor.EDITOR_ONLY_CLASS)
.addClass(WYMeditor.ImageHandler._IMAGE_MARKER_CLASS)
.hide();
};
WYMeditor.ImageHandler.prototype._addEventListeners = function () {
var ih = this;
var $doc = jQuery(ih._wym._doc);
$doc.delegate(
'img', 'mouseover',
ih._onImgMouseover.bind(ih)
);
$doc.delegate(
'img', 'click',
ih._onImgClick.bind(ih)
);
$doc.delegate(
'.' + WYMeditor.RESIZE_HANDLE_CLASS, 'mousedown',
ih._onResizeHandleMousedown.bind(ih)
);
$doc.delegate(
'img',
'mousedown',
ih._onImgMousedown.bind(ih)
);
$doc.delegate(
'img',
'dragstart',
ih._onImgDragstart.bind(ih)
);
$doc.bind(
'mousemove',
ih._onMousemove.bind(ih)
);
$doc.bind(
'mouseup',
ih._onMouseup.bind(ih)
);
ih._edited = new WYMeditor.EXTERNAL_MODULES.Edited(
$doc[0],
function () {}, // do not do anything with strictly sensible edits
ih._onAnyNativeEdit.bind(ih) // handle all edits
);
$doc.delegate(
'.' + WYMeditor.RESIZE_HANDLE_CLASS,
'click dblclick',
ih._onResizeHandleClickDblclick.bind(ih)
);
// useful for debugging
if (false) {
ih._wym.$body().delegate(
'*',
WYMeditor.Helper.getAllEventTypes(ih._wym.$body()[0]),
ih._onAllEvents.bind(ih)
);
}
};
WYMeditor.ImageHandler.prototype._onImgMouseover = function (evt) {
var ih = this;
var $img = jQuery(evt.target);
if (
!$img.data('cE disabled') &&
jQuery.browser.msie
) {
// in IE8-11 it seems that the default cursor for images
// (in `designMode`) is 'move' (4 directions arrow)
// and simply setting a different cursor
// does not change that default.
// this works around the issue.
// the result is still not just any cursor we'd like,
// but only the 'default' cursor,
// which is better than the default 'move' cursor.
// this workaround does not seem to have obvious side effects
$img.attr('contentEditable', 'false');
$img.data('cE disabled', true);
}
ih._setImgCursor($img);
};
WYMeditor.ImageHandler.prototype._setImgCursor = function ($img) {
var ih = this;
if (ih._wym.getSelectedImage() !== $img[0]) {
// hint that image is selectable by click
$img.css('cursor', 'pointer');
return;
}
// image is selected
if (ih._imgDragDropAllowed) {
// in IE8-11 this does not work
// and the cursor remains 'default'.
// see the `_onImgMouseover` handler
$img.css('cursor', 'move');
} else {
$img.css('cursor', 'default');
}
};
WYMeditor.ImageHandler.prototype._onImgClick = function (evt) {
var ih = this;
// firefox seems to natively select the image on mousedown
// this means that by the time this handler executes,
// the image is already selected.
//
// in IE8, by this point
// the image is always deselected,
// even if it was selected just before the click,
// because the mouse event itself
// causes the deselection of the image
// (see the `_selectImage` method).
//
// because of the above browser limitations,
// it is more simple to always select the image here,
// regardless of whether it is selected already or not
ih._selectImage(evt.target);
ih._indicateOnResizeHandleThatImageIsSelected();
return false;
};
WYMeditor.ImageHandler.prototype._selectImage = function (img) {
var ih = this;
var $img = jQuery(img);
if (jQuery.browser.msie && jQuery.browser.versionNumber === 8) {
// in IE8 when the right side of an img is clicked
// (you can't make this up),
// any selection that was set on click is discarded.
// scheduling the image selection
// for after synchronous execution
// works around the issue
setTimeout(function () {
//ih._isAnImgSelected('IE8 ASYNC `_selectImage` (before select)'); // for debugging
ih._wym._selectSingleNode(img);
//ih._isAnImgSelected('IE8 ASYNC `_selectImage` (after select)'); // for debugging
}, 0);
} else {
//ih._isAnImgSelected('`_selectImage` (before select)'); // for debugging
ih._wym._selectSingleNode(img);
//ih._isAnImgSelected('`_selectImage` (after select)'); // for debugging
}
ih._setImgCursor($img);
};
WYMeditor.ImageHandler.prototype._indicateOnResizeHandleThatImageIsSelected = function () {
var ih = this;
var indication = 'image is selected';
if (ih._imgDragDropAllowed) {
indication = [
indication,
'drag image to move it'
].join(WYMeditor.ImageHandler._RESIZE_HANDLE_HR_HTML);
}
ih._$resizeHandle
.css('font-weight', 'bold')
.html(indication);
// ideally, the above indication text would remain
// until the image is no longer selected.
// since it is not easy to detect when that happens,
// the indication text is replaced with the initial text
// after a short moment.
setTimeout(function () {
ih._$resizeHandle
.css('font-weight', 'normal')
.html(WYMeditor.ImageHandler._RESIZE_HANDLE_INNER_HTML);
}, 1000);
};
WYMeditor.ImageHandler.prototype._placeResizeHandleOnImg = function (img) {
var ih = this;
var IMAGE_PADDING = '0.8em';
var $img = jQuery(img);
ih._$currentImg = $img;
ih._getCurrentImageMarker().insertAfter($img);
// colored padding around the image and the handle
// visually marks the image
// that currently has the resize handle placed on it.
// it also makes it possible to resize very small images
// (see the `_detachResizeHandle` method)
$img.css({
'background-color': WYMeditor.ImageHandler._IMAGE_HIGHLIGHT_COLOR,
'padding-top': IMAGE_PADDING,
'padding-right': IMAGE_PADDING,
'padding-bottom': '0',
'padding-left': IMAGE_PADDING,
'margin-top': '-' + IMAGE_PADDING,
'margin-right': '-' + IMAGE_PADDING,
'margin-bottom': '0',
'margin-left': '-' + IMAGE_PADDING
});
// the resize handle, prepended to the body in this way,
// can be removed from the body using DOM manipulation
// such as setting the content with the `html` method.
// so we place it there in case that occurred.
// this could be done conditionally
// but there is practically no performance hit so keeping it simple
ih._$resizeHandle.prependTo(ih._wym.$body());
// it is important that the resize handle's offset
// is updated after the above style modification
// adds top padding to the image
// because that alters the image's outside height
ih._correctResizeHandleOffsetAndWidth();
ih._$resizeHandle.show();
};
WYMeditor.ImageHandler.prototype._correctResizeHandleOffsetAndWidth = function () {
var ih = this;
ih._$resizeHandle.css('max-width', ih._$currentImg.outerWidth());
var offset = ih._$currentImg.offset();
ih._$resizeHandle.css('left', offset.left);
// the Y position of the first pixel after the image's outer Y dimension.
// in other words, just below the image's margin (if it had a margin)
var yAfterImg = offset.top + ih._$currentImg.outerHeight();
if (jQuery.browser.msie) {
// in IE8-11 there might be a visible 1 pixes gap
// between the image and the resize handle
// possibly this issue:
// https://github.com/jquery/jquery/issues/1724
yAfterImg--;
}
ih._$resizeHandle.css('top', yAfterImg);
};
WYMeditor.ImageHandler.prototype._onResizeHandleMousedown = function (evt) {
var ih = this;
if (!ih._resizingNow) {
ih._startResize(evt.clientY);
}
return false;
};
WYMeditor.ImageHandler.prototype._startResize = function (startMouseY) {
var ih = this;
ih._startMouseY = startMouseY;
ih._$currentImg.data('StartHeight', ih._$currentImg.height());
ih._resizingNow = true;
};
WYMeditor.ImageHandler.prototype._onMousemove = function (evt) {
var ih = this;
// default action for this event may be a `mousedown` and `mousemove`
// with the intention to select text
// or to drag (for later dropping of) content
// so be careful about preventing default
if (!evt.target.tagName) {
// IE8 may fire such an event.
// what element was it fired on?
return;
}
if (ih._resizingNow) {
// this is up high in this method for performance
ih._resizeImage(evt.clientY);
return false;
}
if (
evt.target.tagName.toLowerCase() === 'img' &&
!ih._isResizeHandleAttached()
) {
ih._placeResizeHandleOnImg(evt.target);
return false;
}
if (!ih._isResizeHandleAttached()) {
return;
}
// from this point on, this event handler is all about
// checking whether the resize handle should be detached
if (
!jQuery(evt.target).hasClass(WYMeditor.EDITOR_ONLY_CLASS) &&
!ih._isCurrentImg(evt.target)
) {
// this must be after the above check for whether resizing now
// because, while the resize operation does begin
// with the mouse pointing on the resize handle,
// the mouse might leave the resize handle during the resize operation.
// in that case, we would like the operation to continue
ih._detachResizeHandle();
return;
}
if (!ih._isCurrentImgAtMarker()) {
ih._detachResizeHandle();
return;
}
};
WYMeditor.ImageHandler.prototype._isCurrentImgAtMarker = function () {
var ih = this;
var $marker = ih._$currentImageMarker;
if (!$marker.length) {
// the marker was removed by some DOM manipulation
return false;
}
var $img = ih._$currentImg;
var $imgPrevToMarker = $marker.prev('img');
if (
$img.length &&
$imgPrevToMarker.length &&
$imgPrevToMarker[0] === $img[0]
) {
return true;
}
// this happens when:
//
// * the image was selected and
// * replaced by pasted content
// * replaced by character insertion from key press
// * removed with backspace/delete
// * caret was before/after image and delete/backspace pressed
// * the image was dragged and dropped somewhere
return false;
};
WYMeditor.ImageHandler.prototype._isResizeHandle = function (elem) {
return jQuery(elem).hasClass(WYMeditor.RESIZE_HANDLE_CLASS);
};
WYMeditor.ImageHandler.prototype._isCurrentImg = function (img) {
var ih = this;
return img === ih._$currentImg[0];
};
WYMeditor.ImageHandler.prototype._resizeImage = function (currentMouseY) {
var ih = this;
var $img = ih._$currentImg;
var dimensionsRatio = $img.data('DimensionsRatio');
if (!dimensionsRatio) {
// in order to prevent dimensions ratio corruption
var originalHeight = $img.height();
var originalWidth = $img.width();
dimensionsRatio = originalWidth / originalHeight;
$img.data('DimensionsRatio', dimensionsRatio);
}
// calculate the new dimensions
var startHeight = $img.data('StartHeight');
var newHeight = startHeight - ih._startMouseY + currentMouseY;
newHeight = newHeight > 0 ? newHeight : 0;
var newWidth = newHeight * dimensionsRatio;
// update the dimensions
$img.attr('height', newHeight);
$img.attr('width', newWidth);
ih._correctResizeHandleOffsetAndWidth();
};
WYMeditor.ImageHandler.prototype._onMouseup = function () {
// this could be a case where
// there was a `mousedown` on a selection
// and then a `mouseup` without having moved the mouse.
// the default action would be
// to collapse the selection to a caret where the pointer is.
// we'd not like to prevent that
var ih = this;
if (ih._resizingNow) {
ih._stopResize();
}
};
WYMeditor.ImageHandler.prototype._stopResize = function () {
var ih = this;
ih._resizingNow = false;
ih._startMouseY = null;
ih._wym.registerModification();
};
WYMeditor.ImageHandler.prototype._onImgMousedown = function (evt) {
var ih = this;
if (jQuery.browser.msie && jQuery.browser.versionNumber === 11) {
// IE11 on image mousedown places native resize handles around the image.
// selecting the image both here and on `click` refrains from those handles
// completely and seemingly without side effects.
ih._selectImage(evt.target);
// another way to refrain from the handles is preventing default.
// but that would have an undesired side effect
// of not allowing dragging and dropping of images.
}
// returning false here prevents drag of image
// except for in IE8
return ih._imgDragDropAllowed;
};
WYMeditor.ImageHandler.prototype._onAnyNativeEdit = function () {
var ih = this;
// modifications possibly not have occurred yet.
// schedule immediate async in order to execute
// after the possible modifications may have occurred
setTimeout(ih._handlePossibleModification.bind(ih), 0);
};
WYMeditor.ImageHandler.prototype._handlePossibleModification = function () {
var ih = this;
if (!ih._isResizeHandleAttached()) {
return;
}
if (!ih._isCurrentImgAtMarker()) {
ih._detachResizeHandle();
return;
}
// any edit to the document might result
// in the image ending up in a different position than before.
// for example, inserting a character before the image
// pushes it to the right.
ih._correctResizeHandleOffsetAndWidth();
};
WYMeditor.ImageHandler.prototype._isResizeHandleAttached = function () {
var ih = this;
var $handle = ih._getResizeHandle();
return $handle && $handle.css('display') !== 'none';
};
WYMeditor.ImageHandler.prototype._getResizeHandle = function () {
var ih = this;
var $handle = ih._wym.$body().find('.' + WYMeditor.RESIZE_HANDLE_CLASS);
return $handle.length ? $handle : false;
};
WYMeditor.ImageHandler.prototype._detachResizeHandle = function () {
var ih = this;
ih._$currentImageMarker.detach();
if (
// the size of the image might be so small,
// that it would be hard to mouse over it
// in order to make the resize handle appear.
// in that case (an arbitrary number of pixels)
// leave the padding on, as it will allow
// easy mouse over the image,
// even when the image is 0 in size
ih._$currentImg.height() >= 16 &&
ih._$currentImg.width() >= 16
) {
ih._$currentImg.css({padding: 0, margin: 0});
}
ih._$currentImg = null;
ih._$resizeHandle.hide();
};
WYMeditor.ImageHandler.prototype._onImgDragstart = function () {
var ih = this;
ih._detachResizeHandle();
};
WYMeditor.ImageHandler.prototype._onResizeHandleClickDblclick = function () {
var ih = this;
if (jQuery.browser.msie && jQuery.browser.versionNumber === 11) {
// in IE11 some mouse events on the resize handle
// result in native resize handles on it (eight small squares around it).
// trying to resize the resize handle using these native handles
// fails quite gracefully, as they seem to have no effect at all.
// it fails most likely due to prevented native actions
// in one of our event handlers.
// however, deselecting here completely prevents these handles
ih._wym.deselect();
}
// prevents entering edit mode in the handle
return false;
};
// useful for debugging
WYMeditor.ImageHandler.prototype._isAnImgSelected = function (message) {
var ih = this;
message = message.toUpperCase();
function check(prefix) {
var result = ih._wym.getSelectedImage() ? '***YES***' : '';
prefix = prefix ? prefix + ' ' : '';
WYMeditor.console.log(prefix + message + ' ' + result);
}
check('sync');
setTimeout(function () {
check('async');
}, 0);
};
// for debugging
WYMeditor.ImageHandler._onAllEvents = function (evt) {
var ih = this;
ih._isAnImgSelected([
evt.type,
evt.target.tagName,
jQuery(evt.target).attr('className')
].join(' '));
};
/*jslint evil: true */
/* global -$ */
"use strict";
WYMeditor.WymClassGecko = function (wym) {
var wymClassGecko = this;
wymClassGecko._wym = wym;
wymClassGecko._class = "class";
};
// Placeholder cell to allow content in TD cells for FF 3.5+
WYMeditor.WymClassGecko.CELL_PLACEHOLDER = '
';
// Firefox 3.5 and 3.6 require the CELL_PLACEHOLDER and 4.0 doesn't
WYMeditor.WymClassGecko.NEEDS_CELL_FIX = parseInt(
jQuery.browser.version, 10) === 1 &&
jQuery.browser.version >= '1.9.1' &&
jQuery.browser.version < '2.0';
WYMeditor.WymClassGecko.prototype._docEventQuirks = function () {
var wym = this;
var $doc = jQuery(wym._doc);
$doc.keyup(wym._keyup.bind(wym));
$doc.focus(function () {
// not providing _onBodyFocus here because it doesn't exist yet
wym.undoRedo._onBodyFocus();
});
$doc.click(wym._click.bind(wym));
};
// Keyup handler, mainly used for cleanups
WYMeditor.WymClassGecko.prototype._keyup = function (evt) {
var wym = this,
container,
defaultRootContainer,
notValidRootContainers,
name,
parentName;
notValidRootContainers =
wym.documentStructureManager.structureRules.notValidRootContainers;
defaultRootContainer =
wym.documentStructureManager.structureRules.defaultRootContainer;
container = null;
// If the inputted key cannont create a block element and is not a command,
// check to make sure the selection is properly wrapped in a container
if (!wym.keyCanCreateBlockElement(evt.which) &&
evt.which !== WYMeditor.KEY_CODE.CTRL &&
evt.which !== WYMeditor.KEY_CODE.COMMAND &&
!evt.metaKey &&
!evt.ctrlKey) {
container = wym.selectedContainer();
name = container.tagName.toLowerCase();
if (container.parentNode) {
parentName = container.parentNode.tagName.toLowerCase();
}
// Fix forbidden root containers
if (wym.isForbiddenRootContainer(name)) {
name = parentName;
}
// Replace text nodes with default root tags and make sure the
// container is valid if it is a root container
if (name === WYMeditor.BODY ||
(jQuery.inArray(name, notValidRootContainers) > -1 &&
parentName === WYMeditor.BODY)) {
wym._exec(
WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK,
defaultRootContainer
);
wym.prepareDocForEditing();
}
}
// If we potentially created a new block level element or moved to a new
// one, then we should ensure the container is valid and the formatting is
// proper.
if (wym.keyCanCreateBlockElement(evt.which)) {
// If the selected container is a root container, make sure it is not a
// different possible default root container than the chosen one.
container = wym.selectedContainer();
name = container.tagName.toLowerCase();
if (container.parentNode) {
parentName = container.parentNode.tagName.toLowerCase();
}
if (jQuery.inArray(name, notValidRootContainers) > -1 &&
parentName === WYMeditor.BODY) {
wym._exec(
WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK,
defaultRootContainer
);
}
// Call for the check for--and possible correction of--issue #430.
wym._handlePotentialEnterInEmptyNestedLi(evt.which, container);
// Fix formatting if necessary
wym.prepareDocForEditing();
}
};
WYMeditor.WymClassGecko.prototype._click = function () {
var wym = this,
container = wym.selectedContainer(),
sel;
if (WYMeditor.WymClassGecko.NEEDS_CELL_FIX === true) {
if (container && container.tagName.toLowerCase() === WYMeditor.TR) {
// Starting with FF 3.6, inserted tables need some content in their
// cells before they're editable
jQuery(WYMeditor.TD, wym._doc.body).append(
WYMeditor.WymClassGecko.CELL_PLACEHOLDER);
// The user is still going to need to move out of and then back in
// to this cell if the table was inserted via an inner_html call
// (like via the manual HTML editor).
// TODO: Use rangy or some other selection library to consistently
// put the users selection out of and then back in this cell
// so that it appears to be instantly editable
// Once accomplished, can remove the _afterInsertTable handling
}
}
if (container && container.tagName.toLowerCase() === WYMeditor.BODY) {
// A click in the body means there is no content at all, so we
// should automatically create a starter paragraph
sel = wym.selection();
if (sel.isCollapsed === true) {
// If the selection isn't collapsed, we might have a selection that
// drags over the body, but we shouldn't turn everything in to a
// paragraph tag. Otherwise, double-clicking in the space to the
// right of an h2 tag would turn it in to a paragraph
wym._exec(WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK, WYMeditor.P);
}
}
};
WYMeditor.WymClassGecko.prototype._designModeQuirks = function () {
var wym = this;
// Handle any errors that might occur.
try {
wym._doc.execCommand("styleWithCSS", '', false);
wym._doc.execCommand("enableObjectResizing", false, false);
wym._doc.execCommand("enableInlineTableEditing", false, false);
} catch (e) {}
};
/*
* Fix new cell contents and ability to insert content at the front and end of
* the contents.
*/
WYMeditor.WymClassGecko.prototype._afterInsertTable = function (table) {
if (WYMeditor.WymClassGecko.NEEDS_CELL_FIX === true) {
// In certain FF versions, inserted tables need some content in their
// cells before they're editable, otherwise the user has to move focus
// in and then out of a cell first, even with our _click() hack
jQuery(table).find('td').each(function (index, element) {
jQuery(element).append(WYMeditor.WymClassGecko.CELL_PLACEHOLDER);
});
}
};
/*jslint evil: true */
/* global -$ */
"use strict";
WYMeditor.WymClassWebKit = function (wym) {
var wymClassWebKit = this;
wymClassWebKit._wym = wym;
wymClassWebKit._class = "class";
};
WYMeditor.WymClassWebKit.prototype._docEventQuirks = function () {
var wym = this;
jQuery(wym._doc).bind("keyup", function (evt) {
wym._keyup(evt);
});
wym.keyboard.combokeys.bind(
"shift+enter",
// WebKit's shift+enter seems to create a new paragraph so we fix it
function () {
wym._exec(WYMeditor.EXEC_COMMANDS.INSERT_LINEBREAK);
return false;
}
);
wym.$body().bind("focus", function () {
wym.undoRedo._onBodyFocus();
});
};
// A `div` can be created by breaking out of a list in some cases. Issue #549.
WYMeditor.WymClassWebKit.prototype._inListBreakoutDiv = function (evtWhich) {
var wym = this,
$rootContainer = jQuery(wym.getRootContainer());
if (
evtWhich === WYMeditor.KEY_CODE.ENTER &&
$rootContainer.is('div') &&
wym.documentStructureManager.defaultRootContainer !== 'div' &&
$rootContainer.prev('ol, ul').length === 1
) {
return true;
}
return false;
};
// Checks whether this is issue #542.
WYMeditor.WymClassWebKit.prototype._isLiInLiAfterEnter = function (evtWhich) {
var wym = this,
nodeAfterSel = wym.nodeAfterSel(),
parentNode,
previousSibling,
previousSiblingChild,
previousPreviousSibling;
if (evtWhich !== WYMeditor.KEY_CODE.ENTER) {
return false;
}
if (!nodeAfterSel) {
return false;
}
parentNode = nodeAfterSel.parentNode;
if (!parentNode) {
return false;
}
if (typeof parentNode.tagName !== 'string') {
return false;
}
if (parentNode.tagName.toLowerCase() !== 'li') {
return false;
}
previousSibling = nodeAfterSel.previousSibling;
if (!previousSibling) {
return false;
}
if (typeof previousSibling.tagName !== 'string') {
return false;
}
if (previousSibling.tagName.toLowerCase() !== 'li') {
return false;
}
if (previousSibling.childNodes.length !== 1) {
return false;
}
previousSiblingChild = previousSibling.childNodes[0];
if (!previousSiblingChild) {
return false;
}
if (typeof previousSiblingChild.tagName !== 'string') {
return false;
}
if (previousSiblingChild.tagName.toLowerCase() !== 'br') {
return false;
}
previousPreviousSibling = previousSibling.previousSibling;
if (!previousPreviousSibling) {
return false;
}
if (typeof previousPreviousSibling.tagName !== 'string') {
return false;
}
if (
jQuery.inArray(
previousPreviousSibling.tagName.toLowerCase(),
['ol', 'ul']
) === -1
) {
return false;
}
return true;
};
// Fixes issue #542.
WYMeditor.WymClassWebKit.prototype
._fixLiInLiAfterEnter = function () {
var wym = this,
nodeAfterSel = wym.nodeAfterSel(),
$errorLi = jQuery(nodeAfterSel.previousSibling),
$parentLi = $errorLi.parent('li'),
errorLiIndex = $parentLi.contents().index($errorLi),
$contentsAfterErrorLi = $parentLi.contents().slice(errorLiIndex + 1);
$errorLi.remove();
$parentLi.after('
');
$parentLi.next().append($contentsAfterErrorLi);
wym.setCaretBefore($parentLi.next('li').children().first('br')[0]);
};
// Keyup handler, mainly used for cleanups
WYMeditor.WymClassWebKit.prototype._keyup = function (evt) {
var wym = this,
container,
defaultRootContainer,
notValidRootContainers,
name,
parentName,
rootContainer;
notValidRootContainers =
wym.documentStructureManager.structureRules.notValidRootContainers;
defaultRootContainer =
wym.documentStructureManager.structureRules.defaultRootContainer;
// Fix to allow shift + return to insert a line break in older safari
if (jQuery.browser.version < 534.1) {
// Not needed in AT MAX chrome 6.0. Probably safe earlier
if (evt.which === WYMeditor.KEY_CODE.ENTER && evt.shiftKey) {
wym._exec('InsertLineBreak');
}
}
// If the inputted key cannont create a block element and is not a command,
// check to make sure the selection is properly wrapped in a container
if (!wym.keyCanCreateBlockElement(evt.which) &&
evt.which !== WYMeditor.KEY_CODE.CTRL &&
evt.which !== WYMeditor.KEY_CODE.COMMAND &&
!evt.metaKey &&
!evt.ctrlKey) {
container = wym.selectedContainer();
name = container.tagName.toLowerCase();
if (container.parentNode) {
parentName = container.parentNode.tagName.toLowerCase();
}
// Fix forbidden root containers
if (wym.isForbiddenRootContainer(name)) {
name = parentName;
}
// Replace text nodes with default root tags and make sure the
// container is valid if it is a root container
if (name === WYMeditor.BODY ||
(jQuery.inArray(name, notValidRootContainers) > -1 &&
parentName === WYMeditor.BODY)) {
wym._exec(
WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK,
defaultRootContainer
);
wym.prepareDocForEditing();
}
}
// If we potentially created a new block level element or moved to a new
// one, then we should ensure the container is valid and the formatting is
// proper.
if (wym.keyCanCreateBlockElement(evt.which)) {
// If the selected container is a root container, make sure it is not a
// different possible default root container than the chosen one.
container = wym.selectedContainer();
name = container.tagName.toLowerCase();
if (container.parentNode) {
parentName = container.parentNode.tagName.toLowerCase();
}
if (jQuery.inArray(name, notValidRootContainers) > -1 &&
parentName === WYMeditor.BODY) {
wym._exec(
WYMeditor.EXEC_COMMANDS.FORMAT_BLOCK,
defaultRootContainer
);
container = wym.selectedContainer();
}
// Issue #542
if (wym._isLiInLiAfterEnter(evt.which, container)) {
wym._fixLiInLiAfterEnter();
// Container may have changed.
container = wym.selectedContainer();
return;
}
// Call for the check for--and possible correction of--issue #430.
wym._handlePotentialEnterInEmptyNestedLi(evt.which, container);
// Issue #549.
if (wym._inListBreakoutDiv(evt.which)) {
rootContainer = wym.switchTo(
wym.getRootContainer(),
defaultRootContainer
);
wym.setCaretIn(rootContainer);
}
// Fix formatting if necessary
wym.prepareDocForEditing();
}
};
/* jshint evil: true */
"use strict";
WYMeditor.WymClassBlink = function (wym) {
var wymClassBlink = this;
wymClassBlink._wym = wym;
};
jQuery.extend(
WYMeditor.WymClassBlink.prototype,
WYMeditor.WymClassWebKit.prototype
);
/* jshint evil: true */
"use strict";
WYMeditor.WymClassSafari = function (wym) {
var wymClassSafari = this;
wymClassSafari._wym = wym;
};
jQuery.extend(
WYMeditor.WymClassSafari.prototype,
WYMeditor.WymClassWebKit.prototype
);
/*jslint evil: true */
/* global rangy, -$ */
"use strict";
WYMeditor.WymClassTridentPre7 = function (wym) {
var wymClassTridentPre7 = this;
wymClassTridentPre7._wym = wym;
wymClassTridentPre7._class = "className";
};
WYMeditor.WymClassTridentPre7.prototype._onEditorIframeLoad = function (wym) {
wym._assignWymDoc();
if (wym._isDesignModeOn() === false) {
wym._doc.designMode = "On";
} else {
// Pre-7 Trident Internet Explorer versions reload the Iframe when its
// designMode property is set to "on". So this will run on the second
// time this handler is called.
wym._afterDesignModeOn();
}
};
WYMeditor.WymClassTridentPre7.prototype._assignWymDoc = function () {
var wym = this;
wym._doc = wym._iframe.contentWindow.document;
};
WYMeditor.WymClassTridentPre7.prototype._docEventQuirks = function () {
var wym = this;
wym._doc.onbeforedeactivate = function () {
wym._saveCaret();
};
jQuery(wym._doc).bind('keyup', function (evt) {
wym._keyup(evt);
});
wym._doc.onkeyup = function () {
wym._saveCaret();
};
wym._doc.onclick = function () {
wym._saveCaret();
};
wym.$body().bind("focus", function () {
wym.undoRedo._onBodyFocus();
});
wym._doc.body.onbeforepaste = function () {
wym._iframe.contentWindow.event.returnValue = false;
};
wym._doc.body.onpaste = function () {
wym._iframe.contentWindow.event.returnValue = false;
wym.paste(window.clipboardData.getData("Text"));
};
// https://github.com/wymeditor/wymeditor/pull/641
wym.$body().bind("dragend", function (evt) {
if (evt.target.tagName.toLowerCase() === WYMeditor.IMG) {
wym.deselect();
}
});
wym._doc.oncontrolselect = function () {
// this prevents resize handles on various element
// such as images, at least in IE8
return false;
};
};
WYMeditor.WymClassTridentPre7.prototype._setButtonsUnselectable = function () {
// Mark UI buttons as unselectable (#203)
// Issue explained here:
// http://stackoverflow.com/questions/1470932
var wym = this,
$buttons = wym.get$Buttons();
$buttons.attr('unselectable', 'on');
};
WYMeditor.WymClassTridentPre7.prototype._uiQuirks = function () {
var wym = this;
if (jQuery.browser.versionNumber === 8) {
wym._setButtonsUnselectable();
}
};
WYMeditor.WymClassTridentPre7.prototype._saveCaret = function () {
var wym = this,
nativeSelection = wym._doc.selection;
if (nativeSelection.type === "None") {
return;
}
wym._doc.caretPos = nativeSelection.createRange();
};
/**
_wrapWithContainer
==================
Wraps the passed node in a container of the passed type. Also, restores the
selection to being after the node within its new container.
@param node A DOM node to be wrapped in a container
@param containerType A string of an HTML tag that specifies the container
type to use for wrapping the node.
*/
WYMeditor.WymClassTridentPre7.prototype._wrapWithContainer = function (
node, containerType
) {
var wym = this,
$wrappedNode,
selection,
range;
$wrappedNode = jQuery(node).wrap('<' + containerType + ' />');
selection = wym.selection();
range = rangy.createRange(wym._doc);
range.selectNodeContents($wrappedNode[0]);
range.collapse();
selection.setSingleRange(range);
};
WYMeditor.WymClassTridentPre7.prototype._keyup = function (evt) {
var wym = this,
container,
defaultRootContainer,
notValidRootContainers,
name,
parentName,
forbiddenMainContainer = false,
selectedNode;
notValidRootContainers =
wym.documentStructureManager.structureRules.notValidRootContainers;
defaultRootContainer =
wym.documentStructureManager.structureRules.defaultRootContainer;
// If the pressed key can't create a block element and is not a command,
// check to make sure the selection is properly wrapped in a container
if (!wym.keyCanCreateBlockElement(evt.which) &&
evt.which !== WYMeditor.KEY_CODE.CTRL &&
evt.which !== WYMeditor.KEY_CODE.COMMAND &&
!evt.metaKey &&
!evt.ctrlKey) {
container = wym.selectedContainer();
selectedNode = wym.selection().focusNode;
if (container !== null) {
name = container.tagName.toLowerCase();
}
if (container.parentNode) {
parentName = container.parentNode.tagName.toLowerCase();
}
// Fix forbidden root containers
if (wym.isForbiddenRootContainer(name)) {
name = parentName;
forbiddenMainContainer = true;
}
// Wrap text nodes and forbidden root containers with default root node
// tags
if (name === WYMeditor.BODY && selectedNode.nodeName === "#text") {
// If we're in a forbidden root container, switch the selected node
// to its parent node so that we wrap the forbidden root container
// itself and not its inner text content
if (forbiddenMainContainer) {
selectedNode = selectedNode.parentNode;
}
wym._wrapWithContainer(selectedNode, defaultRootContainer);
wym.prepareDocForEditing();
}
if (jQuery.inArray(name, notValidRootContainers) > -1 &&
parentName === WYMeditor.BODY) {
wym.switchTo(container, defaultRootContainer);
wym.prepareDocForEditing();
}
}
// If we potentially created a new block level element or moved to a new
// one, then we should ensure the container is valid and the formatting is
// proper.
if (wym.keyCanCreateBlockElement(evt.which)) {
// If the selected container is a root container, make sure it is not a
// different possible default root container than the chosen one.
container = wym.selectedContainer();
name = container.tagName.toLowerCase();
if (container.parentNode) {
parentName = container.parentNode.tagName.toLowerCase();
}
if (jQuery.inArray(name, notValidRootContainers) > -1 &&
parentName === WYMeditor.BODY) {
wym.switchTo(container, defaultRootContainer);
}
// Call for the check for--and possible correction of--issue #430.
wym._handlePotentialEnterInEmptyNestedLi(evt.which, container);
// IE8 bug https://github.com/wymeditor/wymeditor/issues/446
if (
evt.which === WYMeditor.KEY_CODE.BACKSPACE &&
jQuery.browser.versionNumber === 8 &&
container.parentNode && (
parentName === 'ul' ||
parentName === 'ol'
)
) {
wym._fixInvalidListNesting(container);
}
// Fix formatting if necessary
wym.prepareDocForEditing();
}
};
/* jshint evil: true */
/* global -$ */
"use strict";
/* This file is the custom code for Trident 7 and newer. At the time of writing
* this, it is only IE11.
*/
WYMeditor.WymClassTrident7 = function (wym) {
var wymClassTrident7 = this;
wymClassTrident7._wym = wym;
wymClassTrident7._class = "class";
};
jQuery.extend(
WYMeditor.WymClassTrident7.prototype,
WYMeditor.WymClassGecko.prototype
);
jQuery.copyPropsFromObjectToObject(
WYMeditor.WymClassTridentPre7.prototype,
WYMeditor.WymClassTrident7.prototype,
[
'_exec',
'_keyup',
'_wrapWithContainer'
]
);
// Some tests fail in what seems to be an edge case of selection corruption.
// This method makes those tests pass.
// It seems to be an issue with Rangy and IE11.
WYMeditor.WymClassTrident7.prototype.rawHtml = function (html) {
var wym = this;
if (typeof html === "string") {
wym._doc.designMode = "off";
wym.$body().html(html);
if (wym._isDesignModeOn() !== true) {
wym._enableDesignModeOnDocument();
}
} else {
return wym.$body().html();
}
return false;
};
WYMeditor.WymClassTrident7.prototype._docEventQuirks = function () {
var wym = this;
jQuery(wym._doc).bind("keyup", function (evt) {
wym._keyup(evt);
});
// https://github.com/wymeditor/wymeditor/pull/641
wym.$body().bind("dragend", function (evt) {
if (evt.target.tagName.toLowerCase() === WYMeditor.IMG) {
wym.deselect();
}
});
wym.$body().bind("focus", function () {
wym.undoRedo._onBodyFocus();
});
};
(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.foo = 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 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
return _.filter(obj, function(value, index, list) {
return !iterator.call(context, value, index, list);
}, context);
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs, first) {
if (_.isEmpty(attrs)) return first ? null : [];
return _[first ? 'find' : 'filter'](obj, function(value) {
for (var key in attrs) {
if (attrs[key] !== value[key]) return false;
}
return true;
});
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.where(obj, attrs, true);
};
// Return the maximum element or (element-based computation).
// Can't optimize arrays of integers longer than 65,535 elements.
// See: https://bugs.webkit.org/show_bug.cgi?id=80797
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity, value: -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity, value: Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, value, context) {
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
index : index,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index < right.index ? -1 : 1;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(obj, value, context, behavior) {
var result = {};
var iterator = lookupIterator(value || _.identity);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, value, context) {
return group(obj, value, context, function(result, key, value) {
(_.has(result, key) ? result[key] : (result[key] = [])).push(value);
});
};
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = function(obj, value, context) {
return group(obj, value, context, function(result, key) {
if (!_.has(result, key)) result[key] = 0;
result[key]++;
});
};
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator, context) {
iterator = iterator == null ? _.identity : lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
each(input, function(value) {
if (_.isArray(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator, context) {
if (_.isFunction(isSorted)) {
context = iterator;
iterator = isSorted;
isSorted = false;
}
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(concat.apply(ArrayProto, arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(args, "" + i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, l = list.length; i < l; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
var args = slice.call(arguments, 2);
return function() {
return func.apply(context, args.concat(slice.call(arguments)));
};
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context.
_.partial = function(func) {
var args = slice.call(arguments, 1);
return function() {
return func.apply(this, args.concat(slice.call(arguments)));
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length === 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, result;
var previous = 0;
var later = function() {
previous = new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var values = [];
for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var pairs = [];
for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
_.isFunction(bCtor) && (bCtor instanceof bCtor))) {
return false;
}
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Optimize `isFunction` if appropriate.
if (typeof (/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function(n, iterator, context) {
var accum = Array(n);
for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// List of HTML entities for escaping.
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
}
};
entityMap.unescape = _.invert(entityMap.escape);
// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
// If the value of the named property is a function then invoke it;
// otherwise, return it.
_.result = function(object, property) {
if (object == null) return null;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
// Start chaining a wrapped Underscore object.
chain: function() {
this._chain = true;
return this;
},
// Extracts the result from a wrapped and chained object.
value: function() {
return this._wrapped;
}
});
}).call(this);
},{}],14:[function(require,module,exports){
(function (global){
/**
* @license
* Lo-Dash 2.4.2 (Custom Build)
* Build: `lodash modern -o ./dist/lodash.js`
* Copyright 2012-2013 The Dojo Foundation
* Based on Underscore.js 1.5.2
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license
*/
;(function() {
/** Used as a safe reference for `undefined` in pre ES5 environments */
var undefined;
/** Used to pool arrays and objects used internally */
var arrayPool = [],
objectPool = [];
/** Used to generate unique IDs */
var idCounter = 0;
/** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
var keyPrefix = +new Date + '';
/** Used as the size when optimizations are enabled for large arrays */
var largeArraySize = 75;
/** Used as the max size of the `arrayPool` and `objectPool` */
var maxPoolSize = 40;
/** Used to detect and test whitespace */
var whitespace = (
// whitespace
' \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 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 ES6 template delimiters
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match regexp flags from their coerced string values */
var reFlags = /\w*$/;
/** Used to detected named functions */
var reFuncName = /^\s*function[ \n\r\t]+\w/;
/** Used to match "interpolate" template delimiters */
var reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match leading whitespace and zeros to be removed */
var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');
/** Used to ensure capturing order of template delimiters */
var reNoMatch = /($^)/;
/** Used to detect functions containing a `this` reference */
var reThis = /\bthis\b/;
/** Used to match unescaped characters in compiled string literals */
var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
/** Used to assign default `context` object properties */
var contextProps = [
'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object',
'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
'parseInt', 'setTimeout'
];
/** Used to make template sourceURLs easier to identify */
var templateCounter = 0;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
/** Used to identify object classifications that `_.clone` supports */
var cloneableClasses = {};
cloneableClasses[funcClass] = false;
cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
cloneableClasses[boolClass] = cloneableClasses[dateClass] =
cloneableClasses[numberClass] = cloneableClasses[objectClass] =
cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
/** Used as an internal `_.debounce` options object */
var debounceOptions = {
'leading': false,
'maxWait': 0,
'trailing': false
};
/** Used as the property descriptor for `__bindData__` */
var descriptor = {
'configurable': false,
'enumerable': false,
'value': null,
'writable': false
};
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** Used to escape characters for inclusion in compiled string literals */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Used as a reference to the global object */
var root = (objectTypes[typeof window] && window) || this;
/** 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 the popular CommonJS extension `module.exports` */
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
var freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `_.indexOf` without support for binary searches
* or `fromIndex` constraints.
*
* @private
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value or `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
var index = (fromIndex || 0) - 1,
length = array ? array.length : 0;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* An implementation of `_.contains` for cache objects that mimics the return
* signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
*
* @private
* @param {Object} cache The cache object to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns `0` if `value` is found, else `-1`.
*/
function cacheIndexOf(cache, value) {
var type = typeof value;
cache = cache.cache;
if (type == 'boolean' || value == null) {
return cache[value] ? 0 : -1;
}
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : keyPrefix + value;
cache = (cache = cache[type]) && cache[key];
return type == 'object'
? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
: (cache ? 0 : -1);
}
/**
* Adds a given value to the corresponding cache object.
*
* @private
* @param {*} value The value to add to the cache.
*/
function cachePush(value) {
var cache = this.cache,
type = typeof value;
if (type == 'boolean' || value == null) {
cache[value] = true;
} else {
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : keyPrefix + value,
typeCache = cache[type] || (cache[type] = {});
if (type == 'object') {
(typeCache[key] || (typeCache[key] = [])).push(value);
} else {
typeCache[key] = true;
}
}
}
/**
* Used by `_.max` and `_.min` as the default callback when a given
* collection is a string value.
*
* @private
* @param {string} value The character to inspect.
* @returns {number} Returns the code unit of given character.
*/
function charAtCallback(value) {
return value.charCodeAt(0);
}
/**
* Used by `sortBy` to compare transformed `collection` elements, stable sorting
* them in ascending order.
*
* @private
* @param {Object} a The object to compare to `b`.
* @param {Object} b The object to compare to `a`.
* @returns {number} Returns the sort order indicator of `1` or `-1`.
*/
function compareAscending(a, b) {
var ac = a.criteria,
bc = b.criteria,
index = -1,
length = ac.length;
while (++index < length) {
var value = ac[index],
other = bc[index];
if (value !== other) {
if (value > other || typeof value == 'undefined') {
return 1;
}
if (value < other || typeof other == 'undefined') {
return -1;
}
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to return the same value for
// `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247
//
// This also ensures a stable sort in V8 and other engines.
// See http://code.google.com/p/v8/issues/detail?id=90
return a.index - b.index;
}
/**
* Creates a cache object to optimize linear searches of large arrays.
*
* @private
* @param {Array} [array=[]] The array to search.
* @returns {null|Object} Returns the cache object or `null` if caching should not be used.
*/
function createCache(array) {
var index = -1,
length = array.length,
first = array[0],
mid = array[(length / 2) | 0],
last = array[length - 1];
if (first && typeof first == 'object' &&
mid && typeof mid == 'object' && last && typeof last == 'object') {
return false;
}
var cache = getObject();
cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return result;
}
/**
* Used by `template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {string} match The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(match) {
return '\\' + stringEscapes[match];
}
/**
* Gets an array from the array pool or creates a new one if the pool is empty.
*
* @private
* @returns {Array} The array from the pool.
*/
function getArray() {
return arrayPool.pop() || [];
}
/**
* Gets an object from the object pool or creates a new one if the pool is empty.
*
* @private
* @returns {Object} The object from the pool.
*/
function getObject() {
return objectPool.pop() || {
'array': null,
'cache': null,
'criteria': null,
'false': false,
'index': 0,
'null': false,
'number': null,
'object': null,
'push': null,
'string': null,
'true': false,
'undefined': false,
'value': null
};
}
/**
* Releases the given array back to the array pool.
*
* @private
* @param {Array} [array] The array to release.
*/
function releaseArray(array) {
array.length = 0;
if (arrayPool.length < maxPoolSize) {
arrayPool.push(array);
}
}
/**
* Releases the given object back to the object pool.
*
* @private
* @param {Object} [object] The object to release.
*/
function releaseObject(object) {
var cache = object.cache;
if (cache) {
releaseObject(cache);
}
object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
if (objectPool.length < maxPoolSize) {
objectPool.push(object);
}
}
/**
* Slices the `collection` from the `start` index up to, but not including,
* the `end` index.
*
* Note: This function is used instead of `Array#slice` to support node lists
* in IE < 9 and to ensure dense arrays are returned.
*
* @private
* @param {Array|Object|string} collection The collection to slice.
* @param {number} start The start index.
* @param {number} end The end index.
* @returns {Array} Returns the new array.
*/
function slice(array, start, end) {
start || (start = 0);
if (typeof end == 'undefined') {
end = array ? array.length : 0;
}
var index = -1,
length = end - start || 0,
result = Array(length < 0 ? 0 : length);
while (++index < length) {
result[index] = array[start + index];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Create a new `lodash` function using the given context object.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} [context=root] The context object.
* @returns {Function} Returns the `lodash` function.
*/
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 http://es5.github.io/#x11.1.5.
context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
/** Native constructor references */
var Array = context.Array,
Boolean = context.Boolean,
Date = context.Date,
Function = context.Function,
Math = context.Math,
Number = context.Number,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/**
* Used for `Array` method references.
*
* Normally `Array.prototype` would suffice, however, using an array literal
* avoids issues in Narwhal.
*/
var arrayRef = [];
/** Used for native method references */
var objectProto = Object.prototype;
/** Used to restore the original `_` reference in `noConflict` */
var oldDash = context._;
/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;
/** Used to detect if a method is native */
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
/** Native method shortcuts */
var ceil = Math.ceil,
clearTimeout = context.clearTimeout,
floor = Math.floor,
fnToString = Function.prototype.toString,
getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
hasOwnProperty = objectProto.hasOwnProperty,
push = arrayRef.push,
setTimeout = context.setTimeout,
splice = arrayRef.splice,
unshift = arrayRef.unshift;
/** Used to set meta data on functions */
var defineProperty = (function() {
// IE 8 only accepts DOM elements
try {
var o = {},
func = isNative(func = Object.defineProperty) && func,
result = func(o, o, o) && func;
} catch(e) { }
return result;
}());
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
nativeIsFinite = context.isFinite,
nativeIsNaN = context.isNaN,
nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
nativeMax = Math.max,
nativeMin = Math.min,
nativeParseInt = context.parseInt,
nativeRandom = Math.random;
/** Used to lookup a built-in constructor by [[Class]] */
var ctorByClass = {};
ctorByClass[arrayClass] = Array;
ctorByClass[boolClass] = Boolean;
ctorByClass[dateClass] = Date;
ctorByClass[funcClass] = Function;
ctorByClass[objectClass] = Object;
ctorByClass[numberClass] = Number;
ctorByClass[regexpClass] = RegExp;
ctorByClass[stringClass] = String;
/*--------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps the given value to enable intuitive
* method chaining.
*
* In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
* and `unshift`
*
* Chaining is supported in custom builds as long as the `value` method is
* implicitly or explicitly included in the build.
*
* The chainable wrapper functions are:
* `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
* `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`,
* `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`,
* `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
* `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
* `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
* `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`,
* `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
* `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`,
* `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`,
* and `zip`
*
* The non-chainable wrapper functions are:
* `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
* `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
* `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
* `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
* `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
* `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
* `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
* `template`, `unescape`, `uniqueId`, and `value`
*
* The wrapper functions `first` and `last` return wrapped values when `n` is
* provided, otherwise they return unwrapped values.
*
* Explicit chaining can be enabled by using the `_.chain` method.
*
* @name _
* @constructor
* @category Chaining
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns a `lodash` instance.
* @example
*
* var wrapped = _([1, 2, 3]);
*
* // returns an unwrapped value
* wrapped.reduce(function(sum, num) {
* return sum + num;
* });
* // => 6
*
* // returns a wrapped value
* var squares = wrapped.map(function(num) {
* return num * num;
* });
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
// don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
? value
: new lodashWrapper(value);
}
/**
* A fast path for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap in a `lodash` instance.
* @param {boolean} chainAll A flag to enable chaining for all methods
* @returns {Object} Returns a `lodash` instance.
*/
function lodashWrapper(value, chainAll) {
this.__chain__ = !!chainAll;
this.__wrapped__ = value;
}
// ensure `new lodashWrapper` is an instance of `lodash`
lodashWrapper.prototype = lodash.prototype;
/**
* An object used to flag environments features.
*
* @static
* @memberOf _
* @type Object
*/
var support = lodash.support = {};
/**
* Detect if functions can be decompiled by `Function#toString`
* (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
*
* @memberOf _.support
* @type boolean
*/
support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);
/**
* Detect if `Function#name` is supported (all but IE).
*
* @memberOf _.support
* @type boolean
*/
support.funcNames = typeof Function.name == 'string';
/**
* By default, the template delimiters used by Lo-Dash are similar to 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': /<%-([\s\S]+?)%>/g,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': /<%([\s\S]+?)%>/g,
/**
* 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
}
};
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `_.bind` that creates the bound function and
* sets its meta data.
*
* @private
* @param {Array} bindData The bind data array.
* @returns {Function} Returns the new bound function.
*/
function baseBind(bindData) {
var func = bindData[0],
partialArgs = bindData[2],
thisArg = bindData[4];
function bound() {
// `Function#bind` spec
// http://es5.github.io/#x15.3.4.5
if (partialArgs) {
// avoid `arguments` object deoptimizations by using `slice` instead
// of `Array.prototype.slice.call` and not assigning `arguments` to a
// variable as a ternary expression
var args = slice(partialArgs);
push.apply(args, arguments);
}
// mimic the constructor's `return` behavior
// http://es5.github.io/#x13.2.2
if (this instanceof bound) {
// ensure `new bound` is an instance of `func`
var thisBinding = baseCreate(func.prototype),
result = func.apply(thisBinding, args || arguments);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisArg, args || arguments);
}
setBindData(bound, bindData);
return bound;
}
/**
* The base implementation of `_.clone` without argument juggling or support
* for `thisArg` binding.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep=false] Specify a deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates clones with source counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, isDeep, callback, stackA, stackB) {
if (callback) {
var result = callback(value);
if (typeof result != 'undefined') {
return result;
}
}
// inspect [[Class]]
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className]) {
return value;
}
var ctor = ctorByClass[className];
switch (className) {
case boolClass:
case dateClass:
return new ctor(+value);
case numberClass:
case stringClass:
return new ctor(value);
case regexpClass:
result = ctor(value.source, reFlags.exec(value));
result.lastIndex = value.lastIndex;
return result;
}
} else {
return value;
}
var isArr = isArray(value);
if (isDeep) {
// check for circular references and return corresponding clone
var initedStack = !stackA;
stackA || (stackA = getArray());
stackB || (stackB = getArray());
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
result = isArr ? ctor(value.length) : {};
}
else {
result = isArr ? slice(value) : assign({}, value);
}
// add array properties assigned by `RegExp#exec`
if (isArr) {
if (hasOwnProperty.call(value, 'index')) {
result.index = value.index;
}
if (hasOwnProperty.call(value, 'input')) {
result.input = value.input;
}
}
// exit for shallow clone
if (!isDeep) {
return result;
}
// 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 ? forEach : forOwn)(value, function(objValue, key) {
result[key] = baseClone(objValue, isDeep, callback, stackA, stackB);
});
if (initedStack) {
releaseArray(stackA);
releaseArray(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.
*/
function baseCreate(prototype, properties) {
return isObject(prototype) ? nativeCreate(prototype) : {};
}
// fallback for browsers without `Object.create`
if (!nativeCreate) {
baseCreate = (function() {
function Object() {}
return function(prototype) {
if (isObject(prototype)) {
Object.prototype = prototype;
var result = new Object;
Object.prototype = null;
}
return result || context.Object();
};
}());
}
/**
* The base implementation of `_.createCallback` without support for creating
* "_.pluck" or "_.where" style callbacks.
*
* @private
* @param {*} [func=identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of the created callback.
* @param {number} [argCount] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
*/
function baseCreateCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
// exit early for no `thisArg` or already bound by `Function#bind`
if (typeof thisArg == 'undefined' || !('prototype' in func)) {
return func;
}
var bindData = func.__bindData__;
if (typeof bindData == 'undefined') {
if (support.funcNames) {
bindData = !func.name;
}
bindData = bindData || !support.funcDecomp;
if (!bindData) {
var source = fnToString.call(func);
if (!support.funcNames) {
bindData = !reFuncName.test(source);
}
if (!bindData) {
// checks if `func` references the `this` keyword and stores the result
bindData = reThis.test(source);
setBindData(func, bindData);
}
}
}
// exit early if there are no `this` references or `func` is bound
if (bindData === false || (bindData !== true && bindData[1] & 1)) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 2: return function(a, b) {
return func.call(thisArg, a, b);
};
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);
};
}
return bind(func, thisArg);
}
/**
* The base implementation of `createWrapper` that creates the wrapper and
* sets its meta data.
*
* @private
* @param {Array} bindData The bind data array.
* @returns {Function} Returns the new function.
*/
function baseCreateWrapper(bindData) {
var func = bindData[0],
bitmask = bindData[1],
partialArgs = bindData[2],
partialRightArgs = bindData[3],
thisArg = bindData[4],
arity = bindData[5];
var isBind = bitmask & 1,
isBindKey = bitmask & 2,
isCurry = bitmask & 4,
isCurryBound = bitmask & 8,
key = func;
function bound() {
var thisBinding = isBind ? thisArg : this;
if (partialArgs) {
var args = slice(partialArgs);
push.apply(args, arguments);
}
if (partialRightArgs || isCurry) {
args || (args = slice(arguments));
if (partialRightArgs) {
push.apply(args, partialRightArgs);
}
if (isCurry && args.length < arity) {
bitmask |= 16 & ~32;
return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
}
}
args || (args = arguments);
if (isBindKey) {
func = thisBinding[key];
}
if (this instanceof bound) {
thisBinding = baseCreate(func.prototype);
var result = func.apply(thisBinding, args);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisBinding, args);
}
setBindData(bound, bindData);
return bound;
}
/**
* The base implementation of `_.difference` that accepts a single array
* of values to exclude.
*
* @private
* @param {Array} array The array to process.
* @param {Array} [values] The array of values to exclude.
* @returns {Array} Returns a new array of filtered values.
*/
function baseDifference(array, values) {
var index = -1,
indexOf = getIndexOf(),
length = array ? array.length : 0,
isLarge = length >= largeArraySize && indexOf === baseIndexOf,
result = [];
if (isLarge) {
var cache = createCache(values);
if (cache) {
indexOf = cacheIndexOf;
values = cache;
} else {
isLarge = false;
}
}
while (++index < length) {
var value = array[index];
if (indexOf(values, value) < 0) {
result.push(value);
}
}
if (isLarge) {
releaseObject(values);
}
return result;
}
/**
* The base implementation of `_.flatten` without support for callback
* shorthands or `thisArg` binding.
*
* @private
* @param {Array} array The array to flatten.
* @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
* @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects.
* @param {number} [fromIndex=0] The index to start from.
* @returns {Array} Returns a new flattened array.
*/
function baseFlatten(array, isShallow, isStrict, fromIndex) {
var index = (fromIndex || 0) - 1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value && typeof value == 'object' && typeof value.length == 'number'
&& (isArray(value) || isArguments(value))) {
// recursively flatten arrays (susceptible to call stack limits)
if (!isShallow) {
value = baseFlatten(value, isShallow, isStrict);
}
var valIndex = -1,
valLength = value.length,
resIndex = result.length;
result.length += valLength;
while (++valIndex < valLength) {
result[resIndex++] = value[valIndex];
}
} else if (!isStrict) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.isEqual`, without support for `thisArg` binding,
* that allows partial "_.where" style comparisons.
*
* @private
* @param {*} a The value to compare.
* @param {*} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `a` objects.
* @param {Array} [stackB=[]] Tracks traversed `b` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
// used to indicate that when comparing objects, `a` has at least the properties of `b`
if (callback) {
var result = callback(a, b);
if (typeof result != 'undefined') {
return !!result;
}
}
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined` avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// 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 +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// unwrap any `lodash` wrapped values
var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
bWrapped = hasOwnProperty.call(b, '__wrapped__');
if (aWrapped || bWrapped) {
return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
}
// exit for functions and DOM nodes
if (className != objectClass) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = a.constructor,
ctorB = b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = getArray());
stackB || (stackB = getArray());
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result || isWhere) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (isWhere) {
while (index--) {
if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
break;
}
}
} else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
forIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
}
});
if (result && !isWhere) {
// ensure both objects have the same number of properties
forIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
if (initedStack) {
releaseArray(stackA);
releaseArray(stackB);
}
return result;
}
/**
* The base implementation of `_.merge` without argument juggling or support
* for `thisArg` binding.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [callback] The function to customize merging properties.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
*/
function baseMerge(object, source, callback, stackA, stackB) {
(isArray(source) ? forEach : forOwn)(source, function(source, key) {
var found,
isArr,
result = source,
value = object[key];
if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
// avoid merging previously merged cyclic sources
var stackLength = stackA.length;
while (stackLength--) {
if ((found = stackA[stackLength] == source)) {
value = stackB[stackLength];
break;
}
}
if (!found) {
var isShallow;
if (callback) {
result = callback(value, source);
if ((isShallow = typeof result != 'undefined')) {
value = result;
}
}
if (!isShallow) {
value = isArr
? (isArray(value) ? value : [])
: (isPlainObject(value) ? value : {});
}
// add `source` and associated `value` to the stack of traversed objects
stackA.push(source);
stackB.push(value);
// recursively merge objects and arrays (susceptible to call stack limits)
if (!isShallow) {
baseMerge(value, source, callback, stackA, stackB);
}
}
}
else {
if (callback) {
result = callback(value, source);
if (typeof result == 'undefined') {
result = source;
}
}
if (typeof result != 'undefined') {
value = result;
}
}
object[key] = value;
});
}
/**
* The base implementation of `_.random` without argument juggling or support
* for returning floating-point numbers.
*
* @private
* @param {number} min The minimum possible value.
* @param {number} max The maximum possible value.
* @returns {number} Returns a random number.
*/
function baseRandom(min, max) {
return min + floor(nativeRandom() * (max - min + 1));
}
/**
* The base implementation of `_.uniq` without support for callback shorthands
* or `thisArg` binding.
*
* @private
* @param {Array} array The array to process.
* @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
* @param {Function} [callback] The function called per iteration.
* @returns {Array} Returns a duplicate-value-free array.
*/
function baseUniq(array, isSorted, callback) {
var index = -1,
indexOf = getIndexOf(),
length = array ? array.length : 0,
result = [];
var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf,
seen = (callback || isLarge) ? getArray() : result;
if (isLarge) {
var cache = createCache(seen);
indexOf = cacheIndexOf;
seen = cache;
}
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isSorted
? !index || seen[seen.length - 1] !== computed
: indexOf(seen, computed) < 0
) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
if (isLarge) {
releaseArray(seen.array);
releaseObject(seen);
} else if (callback) {
releaseArray(seen);
}
return result;
}
/**
* Creates a function that aggregates a collection, creating an object composed
* of keys generated from the results of running each element of the collection
* through a callback. The given `setter` function sets the keys and values
* of the composed object.
*
* @private
* @param {Function} setter The setter function.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter) {
return function(collection, callback, thisArg) {
var result = {};
callback = lodash.createCallback(callback, thisArg, 3);
var index = -1,
length = collection ? collection.length : 0;
if (typeof length == 'number') {
while (++index < length) {
var value = collection[index];
setter(result, value, callback(value, index, collection), collection);
}
} else {
forOwn(collection, function(value, key, collection) {
setter(result, value, callback(value, key, collection), collection);
});
}
return result;
};
}
/**
* Creates a function that, when called, either curries or invokes `func`
* with an 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 method flags to compose.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry`
* 8 - `_.curry` (bound)
* 16 - `_.partial`
* 32 - `_.partialRight`
* @param {Array} [partialArgs] An array of arguments to prepend to those
* provided to the new function.
* @param {Array} [partialRightArgs] An array of arguments to append to those
* provided to the new function.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new function.
*/
function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
var isBind = bitmask & 1,
isBindKey = bitmask & 2,
isCurry = bitmask & 4,
isCurryBound = bitmask & 8,
isPartial = bitmask & 16,
isPartialRight = bitmask & 32;
if (!isBindKey && !isFunction(func)) {
throw new TypeError;
}
if (isPartial && !partialArgs.length) {
bitmask &= ~16;
isPartial = partialArgs = false;
}
if (isPartialRight && !partialRightArgs.length) {
bitmask &= ~32;
isPartialRight = partialRightArgs = false;
}
var bindData = func && func.__bindData__;
if (bindData && bindData !== true) {
// clone `bindData`
bindData = slice(bindData);
if (bindData[2]) {
bindData[2] = slice(bindData[2]);
}
if (bindData[3]) {
bindData[3] = slice(bindData[3]);
}
// set `thisBinding` is not previously bound
if (isBind && !(bindData[1] & 1)) {
bindData[4] = thisArg;
}
// set if previously bound but not currently (subsequent curried functions)
if (!isBind && bindData[1] & 1) {
bitmask |= 8;
}
// set curried arity if not yet set
if (isCurry && !(bindData[1] & 4)) {
bindData[5] = arity;
}
// append partial left arguments
if (isPartial) {
push.apply(bindData[2] || (bindData[2] = []), partialArgs);
}
// append partial right arguments
if (isPartialRight) {
unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
}
// merge flags
bindData[1] |= bitmask;
return createWrapper.apply(null, bindData);
}
// fast path for `_.bind`
var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
}
/**
* Used by `escape` to convert characters to HTML entities.
*
* @private
* @param {string} match The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeHtmlChar(match) {
return htmlEscapes[match];
}
/**
* Gets the appropriate "indexOf" function. If the `_.indexOf` method is
* customized, this method returns the custom method, otherwise it returns
* the `baseIndexOf` function.
*
* @private
* @returns {Function} Returns the "indexOf" function.
*/
function getIndexOf() {
var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
return result;
}
/**
* Checks if `value` is a native function.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
*/
function isNative(value) {
return typeof value == 'function' && reNative.test(value);
}
/**
* Sets `this` binding data on a given function.
*
* @private
* @param {Function} func The function to set data on.
* @param {Array} value The data array to set.
*/
var setBindData = !defineProperty ? noop : function(func, value) {
descriptor.value = value;
defineProperty(func, '__bindData__', descriptor);
descriptor.value = null;
};
/**
* A fallback implementation of `isPlainObject` which checks if a given value
* is an object created by the `Object` constructor, assuming objects created
* by the `Object` constructor have no inherited enumerable properties and that
* there are no `Object.prototype` extensions.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
*/
function shimIsPlainObject(value) {
var ctor,
result;
// avoid non Object objects, `arguments` objects, and DOM elements
if (!(value && toString.call(value) == objectClass) ||
(ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) {
return 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.
forIn(value, function(value, key) {
result = key;
});
return typeof result == 'undefined' || hasOwnProperty.call(value, result);
}
/**
* Used by `unescape` to convert HTML entities to characters.
*
* @private
* @param {string} match The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
function unescapeHtmlChar(match) {
return htmlUnescapes[match];
}
/*--------------------------------------------------------------------------*/
/**
* Checks if `value` is an `arguments` object.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })(1, 2, 3);
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == argsClass || false;
}
/**
* Checks if `value` is an array.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an array, else `false`.
* @example
*
* (function() { return _.isArray(arguments); })();
* // => false
*
* _.isArray([1, 2, 3]);
* // => true
*/
var isArray = nativeIsArray || function(value) {
return value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == arrayClass || false;
};
/**
* A fallback implementation of `Object.keys` which produces an array of the
* given object's own enumerable property names.
*
* @private
* @type Function
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names.
*/
var shimKeys = function(object) {
var index, iterable = object, result = [];
if (!iterable) return result;
if (!(objectTypes[typeof object])) return result;
for (index in iterable) {
if (hasOwnProperty.call(iterable, index)) {
result.push(index);
}
}
return result
};
/**
* Creates an array composed of the own enumerable property names of an object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names.
* @example
*
* _.keys({ 'one': 1, 'two': 2, 'three': 3 });
* // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
*/
var keys = !nativeKeys ? shimKeys : function(object) {
if (!isObject(object)) {
return [];
}
return nativeKeys(object);
};
/**
* Used to convert characters to HTML entities:
*
* Though the `>` character is escaped for symmetry, characters like `>` and `/`
* don't require escaping in HTML and have no special meaning unless they're part
* of a tag or an unquoted attribute value.
* http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
*/
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to convert HTML entities to characters */
var htmlUnescapes = invert(htmlEscapes);
/** Used to match HTML entities and HTML characters */
var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'),
reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');
/*--------------------------------------------------------------------------*/
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources will overwrite property assignments of previous
* sources. If a callback is provided it will be executed to produce the
* assigned values. The callback is bound to `thisArg` and invoked with two
* arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @type Function
* @alias extend
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param {Function} [callback] The function to customize assigning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* _.assign({ 'name': 'fred' }, { 'employer': 'slate' });
* // => { 'name': 'fred', 'employer': 'slate' }
*
* var defaults = _.partialRight(_.assign, function(a, b) {
* return typeof a == 'undefined' ? b : a;
* });
*
* var object = { 'name': 'barney' };
* defaults(object, { 'name': 'fred', 'employer': 'slate' });
* // => { 'name': 'barney', 'employer': 'slate' }
*/
var assign = function(object, source, guard) {
var index, iterable = object, result = iterable;
if (!iterable) return result;
var args = arguments,
argsIndex = 0,
argsLength = typeof guard == 'number' ? 2 : args.length;
if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {
var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);
} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {
callback = args[--argsLength];
}
while (++argsIndex < argsLength) {
iterable = args[argsIndex];
if (iterable && objectTypes[typeof iterable]) {
var ownIndex = -1,
ownProps = objectTypes[typeof iterable] && keys(iterable),
length = ownProps ? ownProps.length : 0;
while (++ownIndex < length) {
index = ownProps[ownIndex];
result[index] = callback ? callback(result[index], iterable[index]) : iterable[index];
}
}
}
return result
};
/**
* Creates a clone of `value`. If `isDeep` is `true` nested objects will also
* be cloned, otherwise they will be assigned by reference. If a callback
* is provided it will be executed to produce the cloned values. If the
* callback returns `undefined` cloning will be handled by the method instead.
* The callback is bound to `thisArg` and invoked with one argument; (value).
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to clone.
* @param {boolean} [isDeep=false] Specify a deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the cloned value.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* var shallow = _.clone(characters);
* shallow[0] === characters[0];
* // => true
*
* var deep = _.clone(characters, true);
* deep[0] === characters[0];
* // => false
*
* _.mixin({
* 'clone': _.partialRight(_.clone, function(value) {
* return _.isElement(value) ? value.cloneNode(false) : undefined;
* })
* });
*
* var clone = _.clone(document.body);
* clone.childNodes.length;
* // => 0
*/
function clone(value, isDeep, callback, thisArg) {
// allows working with "Collections" methods without using their `index`
// and `collection` arguments for `isDeep` and `callback`
if (typeof isDeep != 'boolean' && isDeep != null) {
thisArg = callback;
callback = isDeep;
isDeep = false;
}
return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
}
/**
* Creates a deep clone of `value`. If a callback is provided it will be
* executed to produce the cloned values. If the callback returns `undefined`
* cloning will be handled by the method instead. The callback is bound to
* `thisArg` and invoked with one argument; (value).
*
* Note: This method is loosely based on the structured clone algorithm. Functions
* and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
* objects created by constructors other than `Object` are cloned to plain `Object` objects.
* See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the deep cloned value.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* var deep = _.cloneDeep(characters);
* deep[0] === characters[0];
* // => false
*
* var view = {
* 'label': 'docs',
* 'node': element
* };
*
* var clone = _.cloneDeep(view, function(value) {
* return _.isElement(value) ? value.cloneNode(true) : undefined;
* });
*
* clone.node == view.node;
* // => false
*/
function cloneDeep(value, callback, thisArg) {
return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
}
/**
* 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 Objects
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @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) {
var result = baseCreate(prototype);
return properties ? assign(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 defaults of the same property will be ignored.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param- {Object} [guard] Allows working with `_.reduce` without using its
* `key` and `object` arguments as sources.
* @returns {Object} Returns the destination object.
* @example
*
* var object = { 'name': 'barney' };
* _.defaults(object, { 'name': 'fred', 'employer': 'slate' });
* // => { 'name': 'barney', 'employer': 'slate' }
*/
var defaults = function(object, source, guard) {
var index, iterable = object, result = iterable;
if (!iterable) return result;
var args = arguments,
argsIndex = 0,
argsLength = typeof guard == 'number' ? 2 : args.length;
while (++argsIndex < argsLength) {
iterable = args[argsIndex];
if (iterable && objectTypes[typeof iterable]) {
var ownIndex = -1,
ownProps = objectTypes[typeof iterable] && keys(iterable),
length = ownProps ? ownProps.length : 0;
while (++ownIndex < length) {
index = ownProps[ownIndex];
if (typeof result[index] == 'undefined') result[index] = iterable[index];
}
}
}
return result
};
/**
* This method is like `_.findIndex` except that it returns the key of the
* first element that passes the callback check, instead of the element itself.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to search.
* @param {Function|Object|string} [callback=identity] The function called per
* iteration. If a property name or object is provided it will be used to
* create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {string|undefined} Returns the key of the found element, else `undefined`.
* @example
*
* var characters = {
* 'barney': { 'age': 36, 'blocked': false },
* 'fred': { 'age': 40, 'blocked': true },
* 'pebbles': { 'age': 1, 'blocked': false }
* };
*
* _.findKey(characters, function(chr) {
* return chr.age < 40;
* });
* // => 'barney' (property order is not guaranteed across environments)
*
* // using "_.where" callback shorthand
* _.findKey(characters, { 'age': 1 });
* // => 'pebbles'
*
* // using "_.pluck" callback shorthand
* _.findKey(characters, 'blocked');
* // => 'fred'
*/
function findKey(object, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forOwn(object, function(value, key, object) {
if (callback(value, key, object)) {
result = key;
return false;
}
});
return result;
}
/**
* 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 `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to search.
* @param {Function|Object|string} [callback=identity] The function called per
* iteration. If a property name or object is provided it will be used to
* create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {string|undefined} Returns the key of the found element, else `undefined`.
* @example
*
* var characters = {
* 'barney': { 'age': 36, 'blocked': true },
* 'fred': { 'age': 40, 'blocked': false },
* 'pebbles': { 'age': 1, 'blocked': true }
* };
*
* _.findLastKey(characters, function(chr) {
* return chr.age < 40;
* });
* // => returns `pebbles`, assuming `_.findKey` returns `barney`
*
* // using "_.where" callback shorthand
* _.findLastKey(characters, { 'age': 40 });
* // => 'fred'
*
* // using "_.pluck" callback shorthand
* _.findLastKey(characters, 'blocked');
* // => 'pebbles'
*/
function findLastKey(object, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forOwnRight(object, function(value, key, object) {
if (callback(value, key, object)) {
result = key;
return false;
}
});
return result;
}
/**
* Iterates over own and inherited enumerable properties of an object,
* executing the callback for each property. The callback is bound to `thisArg`
* and invoked with three arguments; (value, key, object). Callbacks may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* Shape.prototype.move = function(x, y) {
* this.x += x;
* this.y += y;
* };
*
* _.forIn(new Shape, function(value, key) {
* console.log(key);
* });
* // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
*/
var forIn = function(collection, callback, thisArg) {
var index, iterable = collection, result = iterable;
if (!iterable) return result;
if (!objectTypes[typeof iterable]) return result;
callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
for (index in iterable) {
if (callback(iterable[index], index, collection) === false) return result;
}
return result
};
/**
* This method is like `_.forIn` except that it iterates over elements
* of a `collection` in the opposite order.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* Shape.prototype.move = function(x, y) {
* this.x += x;
* this.y += y;
* };
*
* _.forInRight(new Shape, function(value, key) {
* console.log(key);
* });
* // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
*/
function forInRight(object, callback, thisArg) {
var pairs = [];
forIn(object, function(value, key) {
pairs.push(key, value);
});
var length = pairs.length;
callback = baseCreateCallback(callback, thisArg, 3);
while (length--) {
if (callback(pairs[length--], pairs[length], object) === false) {
break;
}
}
return object;
}
/**
* Iterates over own enumerable properties of an object, executing the callback
* for each property. The callback is bound to `thisArg` and invoked with three
* arguments; (value, key, object). Callbacks may exit iteration early by
* explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* console.log(key);
* });
* // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
*/
var forOwn = function(collection, callback, thisArg) {
var index, iterable = collection, result = iterable;
if (!iterable) return result;
if (!objectTypes[typeof iterable]) return result;
callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
var ownIndex = -1,
ownProps = objectTypes[typeof iterable] && keys(iterable),
length = ownProps ? ownProps.length : 0;
while (++ownIndex < length) {
index = ownProps[ownIndex];
if (callback(iterable[index], index, collection) === false) return result;
}
return result
};
/**
* This method is like `_.forOwn` except that it iterates over elements
* of a `collection` in the opposite order.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* console.log(key);
* });
* // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
*/
function forOwnRight(object, callback, thisArg) {
var props = keys(object),
length = props.length;
callback = baseCreateCallback(callback, thisArg, 3);
while (length--) {
var key = props[length];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
/**
* Creates a sorted array of property names of all enumerable properties,
* own and inherited, of `object` that have function values.
*
* @static
* @memberOf _
* @alias methods
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names that have function values.
* @example
*
* _.functions(_);
* // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
*/
function functions(object) {
var result = [];
forIn(object, function(value, key) {
if (isFunction(value)) {
result.push(key);
}
});
return result.sort();
}
/**
* Checks if the specified property name exists as a direct property of `object`,
* instead of an inherited property.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @param {string} key The name of the property to check.
* @returns {boolean} Returns `true` if key is a direct property, else `false`.
* @example
*
* _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
* // => true
*/
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
/**
* Creates an object composed of the inverted keys and values of the given object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to invert.
* @returns {Object} Returns the created inverted object.
* @example
*
* _.invert({ 'first': 'fred', 'second': 'barney' });
* // => { 'fred': 'first', 'barney': 'second' }
*/
function invert(object) {
var index = -1,
props = keys(object),
length = props.length,
result = {};
while (++index < length) {
var key = props[index];
result[object[key]] = key;
}
return result;
}
/**
* Checks if `value` is a boolean value.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
* @example
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
value && typeof value == 'object' && toString.call(value) == boolClass || false;
}
/**
* Checks if `value` is a date.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a date, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*/
function isDate(value) {
return value && typeof value == 'object' && toString.call(value) == dateClass || false;
}
/**
* Checks if `value` is a DOM element.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*/
function isElement(value) {
return value && value.nodeType === 1 || false;
}
/**
* Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
* length of `0` and objects with no own enumerable properties are considered
* "empty".
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
function isEmpty(value) {
var result = true;
if (!value) {
return result;
}
var className = toString.call(value),
length = value.length;
if ((className == arrayClass || className == stringClass || className == argsClass ) ||
(className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
return !length;
}
forOwn(value, function() {
return (result = false);
});
return result;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent to each other. If a callback is provided it will be executed
* to compare values. If the callback returns `undefined` comparisons will
* be handled by the method instead. The callback is bound to `thisArg` and
* invoked with two arguments; (a, b).
*
* @static
* @memberOf _
* @category Objects
* @param {*} a The value to compare.
* @param {*} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'name': 'fred' };
* var copy = { 'name': 'fred' };
*
* object == copy;
* // => false
*
* _.isEqual(object, copy);
* // => true
*
* var words = ['hello', 'goodbye'];
* var otherWords = ['hi', 'goodbye'];
*
* _.isEqual(words, otherWords, function(a, b) {
* var reGreet = /^(?:hello|hi)$/i,
* aGreet = _.isString(a) && reGreet.test(a),
* bGreet = _.isString(b) && reGreet.test(b);
*
* return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
* });
* // => true
*/
function isEqual(a, b, callback, thisArg) {
return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
}
/**
* Checks if `value` is, or can be coerced to, a finite number.
*
* Note: This is not the same as native `isFinite` which will return true for
* booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is finite, else `false`.
* @example
*
* _.isFinite(-101);
* // => true
*
* _.isFinite('10');
* // => true
*
* _.isFinite(true);
* // => false
*
* _.isFinite('');
* // => false
*
* _.isFinite(Infinity);
* // => false
*/
function isFinite(value) {
return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
}
/**
* Checks if `value` is a function.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*/
function isFunction(value) {
return typeof value == 'function';
}
/**
* Checks if `value` is the language type of Object.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// http://code.google.com/p/v8/issues/detail?id=2291
return !!(value && objectTypes[typeof value]);
}
/**
* Checks if `value` is `NaN`.
*
* Note: This is not the same as native `isNaN` which will return `true` for
* `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// `NaN` as a primitive is the only value that is not equal to itself
// (perform the [[Class]] check first to avoid errors with some host objects in IE)
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(undefined);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is a number.
*
* Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a number, else `false`.
* @example
*
* _.isNumber(8.4 * 5);
* // => true
*/
function isNumber(value) {
return typeof value == 'number' ||
value && typeof value == 'object' && toString.call(value) == numberClass || false;
}
/**
* Checks if `value` is an object created by the `Object` constructor.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* _.isPlainObject(new Shape);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*/
var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
if (!(value && toString.call(value) == objectClass)) {
return false;
}
var valueOf = value.valueOf,
objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
return objProto
? (value == objProto || getPrototypeOf(value) == objProto)
: shimIsPlainObject(value);
};
/**
* Checks if `value` is a regular expression.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
* @example
*
* _.isRegExp(/fred/);
* // => true
*/
function isRegExp(value) {
return value && typeof value == 'object' && toString.call(value) == regexpClass || false;
}
/**
* Checks if `value` is a string.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a string, else `false`.
* @example
*
* _.isString('fred');
* // => true
*/
function isString(value) {
return typeof value == 'string' ||
value && typeof value == 'object' && toString.call(value) == stringClass || false;
}
/**
* Checks if `value` is `undefined`.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
/**
* Creates an object with the same keys as `object` and values generated by
* running each own enumerable property of `object` through the callback.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new object with values of the results of each `callback` execution.
* @example
*
* _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
* // => { 'a': 3, 'b': 6, 'c': 9 }
*
* var characters = {
* 'fred': { 'name': 'fred', 'age': 40 },
* 'pebbles': { 'name': 'pebbles', 'age': 1 }
* };
*
* // using "_.pluck" callback shorthand
* _.mapValues(characters, 'age');
* // => { 'fred': 40, 'pebbles': 1 }
*/
function mapValues(object, callback, thisArg) {
var result = {};
callback = lodash.createCallback(callback, thisArg, 3);
forOwn(object, function(value, key, object) {
result[key] = callback(value, key, object);
});
return result;
}
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* will overwrite property assignments of previous sources. If a callback is
* provided it will be executed to produce the merged values of the destination
* and source properties. If the callback returns `undefined` merging will
* be handled by the method instead. The callback is bound to `thisArg` and
* invoked with two arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param {Function} [callback] The function to customize merging properties.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* var names = {
* 'characters': [
* { 'name': 'barney' },
* { 'name': 'fred' }
* ]
* };
*
* var ages = {
* 'characters': [
* { 'age': 36 },
* { 'age': 40 }
* ]
* };
*
* _.merge(names, ages);
* // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
*
* var food = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var otherFood = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(food, otherFood, function(a, b) {
* return _.isArray(a) ? a.concat(b) : undefined;
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
*/
function merge(object) {
var args = arguments,
length = 2;
if (!isObject(object)) {
return object;
}
// allows working with `_.reduce` and `_.reduceRight` without using
// their `index` and `collection` arguments
if (typeof args[2] != 'number') {
length = args.length;
}
if (length > 3 && typeof args[length - 2] == 'function') {
var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
} else if (length > 2 && typeof args[length - 1] == 'function') {
callback = args[--length];
}
var sources = slice(arguments, 1, length),
index = -1,
stackA = getArray(),
stackB = getArray();
while (++index < length) {
baseMerge(object, sources[index], callback, stackA, stackB);
}
releaseArray(stackA);
releaseArray(stackB);
return object;
}
/**
* Creates a shallow clone of `object` excluding the specified properties.
* Property names may be specified as individual arguments or as arrays of
* property names. If a callback is provided it will be executed for each
* property of `object` omitting the properties the callback returns truey
* for. The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The source object.
* @param {Function|...string|string[]} [callback] The properties to omit or the
* function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns an object without the omitted properties.
* @example
*
* _.omit({ 'name': 'fred', 'age': 40 }, 'age');
* // => { 'name': 'fred' }
*
* _.omit({ 'name': 'fred', 'age': 40 }, function(value) {
* return typeof value == 'number';
* });
* // => { 'name': 'fred' }
*/
function omit(object, callback, thisArg) {
var result = {};
if (typeof callback != 'function') {
var props = [];
forIn(object, function(value, key) {
props.push(key);
});
props = baseDifference(props, baseFlatten(arguments, true, false, 1));
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
result[key] = object[key];
}
} else {
callback = lodash.createCallback(callback, thisArg, 3);
forIn(object, function(value, key, object) {
if (!callback(value, key, object)) {
result[key] = value;
}
});
}
return result;
}
/**
* Creates a two dimensional array of an object's key-value pairs,
* i.e. `[[key1, value1], [key2, value2]]`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns new array of key-value pairs.
* @example
*
* _.pairs({ 'barney': 36, 'fred': 40 });
* // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
*/
function pairs(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 a shallow clone of `object` composed of the specified properties.
* Property names may be specified as individual arguments or as arrays of
* property names. If a callback is provided it will be executed for each
* property of `object` picking the properties the callback returns truey
* for. The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The source object.
* @param {Function|...string|string[]} [callback] The function called per
* iteration or property names to pick, specified as individual property
* names or arrays of property names.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns an object composed of the picked properties.
* @example
*
* _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');
* // => { 'name': 'fred' }
*
* _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) {
* return key.charAt(0) != '_';
* });
* // => { 'name': 'fred' }
*/
function pick(object, callback, thisArg) {
var result = {};
if (typeof callback != 'function') {
var index = -1,
props = baseFlatten(arguments, true, false, 1),
length = isObject(object) ? props.length : 0;
while (++index < length) {
var key = props[index];
if (key in object) {
result[key] = object[key];
}
}
} else {
callback = lodash.createCallback(callback, thisArg, 3);
forIn(object, function(value, key, object) {
if (callback(value, key, object)) {
result[key] = value;
}
});
}
return result;
}
/**
* 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 a callback, with each callback execution
* potentially mutating the `accumulator` object. The callback is bound to
* `thisArg` and invoked with four arguments; (accumulator, value, key, object).
* Callbacks may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
* num *= num;
* if (num % 2) {
* return result.push(num) < 3;
* }
* });
* // => [1, 9, 25]
*
* var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
* result[key] = num * 3;
* });
* // => { 'a': 3, 'b': 6, 'c': 9 }
*/
function transform(object, callback, accumulator, thisArg) {
var isArr = isArray(object);
if (accumulator == null) {
if (isArr) {
accumulator = [];
} else {
var ctor = object && object.constructor,
proto = ctor && ctor.prototype;
accumulator = baseCreate(proto);
}
}
if (callback) {
callback = lodash.createCallback(callback, thisArg, 4);
(isArr ? forEach : forOwn)(object, function(value, index, object) {
return callback(accumulator, value, index, object);
});
}
return accumulator;
}
/**
* Creates an array composed of the own enumerable property values of `object`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property values.
* @example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3] (property order is not guaranteed across environments)
*/
function values(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates an array of elements from the specified indexes, or keys, of the
* `collection`. Indexes may be specified as individual arguments or as arrays
* of indexes.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
* to retrieve, specified as individual indexes or arrays of indexes.
* @returns {Array} Returns a new array of elements corresponding to the
* provided indexes.
* @example
*
* _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
* // => ['a', 'c', 'e']
*
* _.at(['fred', 'barney', 'pebbles'], 0, 2);
* // => ['fred', 'pebbles']
*/
function at(collection) {
var args = arguments,
index = -1,
props = baseFlatten(args, true, false, 1),
length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
result = Array(length);
while(++index < length) {
result[index] = collection[props[index]];
}
return result;
}
/**
* Checks if a given value is present in a collection using strict equality
* for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
* offset from the end of the collection.
*
* @static
* @memberOf _
* @alias include
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {*} target The value to check for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {boolean} Returns `true` if the `target` element is found, else `false`.
* @example
*
* _.contains([1, 2, 3], 1);
* // => true
*
* _.contains([1, 2, 3], 1, 2);
* // => false
*
* _.contains({ 'name': 'fred', 'age': 40 }, 'fred');
* // => true
*
* _.contains('pebbles', 'eb');
* // => true
*/
function contains(collection, target, fromIndex) {
var index = -1,
indexOf = getIndexOf(),
length = collection ? collection.length : 0,
result = false;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
if (isArray(collection)) {
result = indexOf(collection, target, fromIndex) > -1;
} else if (typeof length == 'number') {
result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
} else {
forOwn(collection, function(value) {
if (++index >= fromIndex) {
return !(result = value === target);
}
});
}
return result;
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through the callback. The corresponding value
* of each key is the number of times the key was returned by the callback.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
(hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
});
/**
* Checks if the given callback returns truey value for **all** elements of
* a collection. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias all
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if all elements passed the callback check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes']);
* // => false
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // using "_.pluck" callback shorthand
* _.every(characters, 'age');
* // => true
*
* // using "_.where" callback shorthand
* _.every(characters, { 'age': 36 });
* // => false
*/
function every(collection, callback, thisArg) {
var result = true;
callback = lodash.createCallback(callback, thisArg, 3);
var index = -1,
length = collection ? collection.length : 0;
if (typeof length == 'number') {
while (++index < length) {
if (!(result = !!callback(collection[index], index, collection))) {
break;
}
}
} else {
forOwn(collection, function(value, index, collection) {
return (result = !!callback(value, index, collection));
});
}
return result;
}
/**
* Iterates over elements of a collection, returning an array of all elements
* the callback returns truey for. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias select
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that passed the callback check.
* @example
*
* var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [2, 4, 6]
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.filter(characters, 'blocked');
* // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
*
* // using "_.where" callback shorthand
* _.filter(characters, { 'age': 36 });
* // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
*/
function filter(collection, callback, thisArg) {
var result = [];
callback = lodash.createCallback(callback, thisArg, 3);
var index = -1,
length = collection ? collection.length : 0;
if (typeof length == 'number') {
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
result.push(value);
}
}
} else {
forOwn(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result.push(value);
}
});
}
return result;
}
/**
* Iterates over elements of a collection, returning the first element that
* the callback returns truey for. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias detect, findWhere
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the found element, else `undefined`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true },
* { 'name': 'pebbles', 'age': 1, 'blocked': false }
* ];
*
* _.find(characters, function(chr) {
* return chr.age < 40;
* });
* // => { 'name': 'barney', 'age': 36, 'blocked': false }
*
* // using "_.where" callback shorthand
* _.find(characters, { 'age': 1 });
* // => { 'name': 'pebbles', 'age': 1, 'blocked': false }
*
* // using "_.pluck" callback shorthand
* _.find(characters, 'blocked');
* // => { 'name': 'fred', 'age': 40, 'blocked': true }
*/
function find(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg, 3);
var index = -1,
length = collection ? collection.length : 0;
if (typeof length == 'number') {
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
return value;
}
}
} else {
var result;
forOwn(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result = value;
return false;
}
});
return result;
}
}
/**
* This method is like `_.find` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the found element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(num) {
* return num % 2 == 1;
* });
* // => 3
*/
function findLast(collection, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forEachRight(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result = value;
return false;
}
});
return result;
}
/**
* Iterates over elements of a collection, executing the callback for each
* element. The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection). Callbacks 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 Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
* // => logs each number and returns '1,2,3'
*
* _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
* // => logs each number and returns the object (property order is not guaranteed across environments)
*/
function forEach(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0;
callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
if (typeof length == 'number') {
while (++index < length) {
if (callback(collection[index], index, collection) === false) {
break;
}
}
} else {
forOwn(collection, callback);
}
return collection;
}
/**
* This method is like `_.forEach` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @alias eachRight
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
* // => logs each number from right to left and returns '3,2,1'
*/
function forEachRight(collection, callback, thisArg) {
var length = collection ? collection.length : 0;
callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
if (typeof length == 'number') {
while (length--) {
if (callback(collection[length], length, collection) === false) {
break;
}
}
} else {
var props = keys(collection);
length = props.length;
forOwn(collection, function(value, key, collection) {
key = props ? props[--length] : --length;
return callback(collection[key], key, collection);
});
}
return collection;
}
/**
* Creates an object composed of keys generated from the results of running
* each element of a collection through the callback. The corresponding value
* of each key is an array of the elements responsible for generating the key.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* // using "_.pluck" callback shorthand
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
(hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
});
/**
* Creates an object composed of keys generated from the results of running
* each element of the collection through the given callback. The corresponding
* value of each key is the last element responsible for generating the key.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var keys = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.indexBy(keys, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(characters, function(key) { this.fromCharCode(key.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 named by `methodName` on each element in the `collection`
* returning an array of the results of each invoked method. Additional arguments
* will be provided to each invoked method. If `methodName` is a function it
* will be invoked for, and `this` bound to, each element in the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|string} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {...*} [arg] Arguments to invoke the method with.
* @returns {Array} Returns a new array of the results of each invoked method.
* @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']]
*/
function invoke(collection, methodName) {
var args = slice(arguments, 2),
index = -1,
isFunc = typeof methodName == 'function',
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
forEach(collection, function(value) {
result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
});
return result;
}
/**
* Creates an array of values by running each element in the collection
* through the callback. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of the results of each `callback` execution.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (property order is not guaranteed across environments)
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(characters, 'name');
* // => ['barney', 'fred']
*/
function map(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
if (typeof length == 'number') {
var result = Array(length);
while (++index < length) {
result[index] = callback(collection[index], index, collection);
}
} else {
result = [];
forOwn(collection, function(value, key, collection) {
result[++index] = callback(value, key, collection);
});
}
return result;
}
/**
* Retrieves the maximum value of a collection. If the collection is empty or
* falsey `-Infinity` is returned. If a callback is provided it will be executed
* for each value in the collection to generate the criterion by which the value
* is ranked. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.max(characters, function(chr) { return chr.age; });
* // => { 'name': 'fred', 'age': 40 };
*
* // using "_.pluck" callback shorthand
* _.max(characters, 'age');
* // => { 'name': 'fred', 'age': 40 };
*/
function max(collection, callback, thisArg) {
var computed = -Infinity,
result = computed;
// allows working with functions like `_.map` without using
// their `index` argument as a callback
if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
callback = null;
}
if (callback == null && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (value > result) {
result = value;
}
}
} else {
callback = (callback == null && isString(collection))
? charAtCallback
: lodash.createCallback(callback, thisArg, 3);
forEach(collection, function(value, index, collection) {
var current = callback(value, index, collection);
if (current > computed) {
computed = current;
result = value;
}
});
}
return result;
}
/**
* Retrieves the minimum value of a collection. If the collection is empty or
* falsey `Infinity` is returned. If a callback is provided it will be executed
* for each value in the collection to generate the criterion by which the value
* is ranked. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.min(characters, function(chr) { return chr.age; });
* // => { 'name': 'barney', 'age': 36 };
*
* // using "_.pluck" callback shorthand
* _.min(characters, 'age');
* // => { 'name': 'barney', 'age': 36 };
*/
function min(collection, callback, thisArg) {
var computed = Infinity,
result = computed;
// allows working with functions like `_.map` without using
// their `index` argument as a callback
if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
callback = null;
}
if (callback == null && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (value < result) {
result = value;
}
}
} else {
callback = (callback == null && isString(collection))
? charAtCallback
: lodash.createCallback(callback, thisArg, 3);
forEach(collection, function(value, index, collection) {
var current = callback(value, index, collection);
if (current < computed) {
computed = current;
result = value;
}
});
}
return result;
}
/**
* Retrieves the value of a specified property from all elements in the collection.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {string} property The name of the property to pluck.
* @returns {Array} Returns a new array of property values.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.pluck(characters, 'name');
* // => ['barney', 'fred']
*/
var pluck = map;
/**
* Reduces a collection to a value which is the accumulated result of running
* each element in the collection through the callback, where each successive
* callback execution consumes the return value of the previous execution. If
* `accumulator` is not provided the first element of the collection will be
* used as the initial `accumulator` value. The callback is bound to `thisArg`
* and invoked with four arguments; (accumulator, value, index|key, collection).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] Initial value of the accumulator.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(sum, num) {
* return sum + num;
* });
* // => 6
*
* var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
* result[key] = num * 3;
* return result;
* }, {});
* // => { 'a': 3, 'b': 6, 'c': 9 }
*/
function reduce(collection, callback, accumulator, thisArg) {
if (!collection) return accumulator;
var noaccum = arguments.length < 3;
callback = lodash.createCallback(callback, thisArg, 4);
var index = -1,
length = collection.length;
if (typeof length == 'number') {
if (noaccum) {
accumulator = collection[++index];
}
while (++index < length) {
accumulator = callback(accumulator, collection[index], index, collection);
}
} else {
forOwn(collection, function(value, index, collection) {
accumulator = noaccum
? (noaccum = false, value)
: callback(accumulator, value, index, collection)
});
}
return accumulator;
}
/**
* This method is like `_.reduce` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @alias foldr
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] Initial value of the accumulator.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var list = [[0, 1], [2, 3], [4, 5]];
* var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, callback, accumulator, thisArg) {
var noaccum = arguments.length < 3;
callback = lodash.createCallback(callback, thisArg, 4);
forEachRight(collection, function(value, index, collection) {
accumulator = noaccum
? (noaccum = false, value)
: callback(accumulator, value, index, collection);
});
return accumulator;
}
/**
* The opposite of `_.filter` this method returns the elements of a
* collection that the callback does **not** return truey for.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that failed the callback check.
* @example
*
* var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [1, 3, 5]
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.reject(characters, 'blocked');
* // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
*
* // using "_.where" callback shorthand
* _.reject(characters, { 'age': 36 });
* // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
*/
function reject(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg, 3);
return filter(collection, function(value, index, collection) {
return !callback(value, index, collection);
});
}
/**
* Retrieves a random element or `n` random elements from a collection.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to sample.
* @param {number} [n] The number of elements to sample.
* @param- {Object} [guard] Allows working with functions like `_.map`
* without using their `index` arguments as `n`.
* @returns {Array} Returns the random sample(s) of `collection`.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*
* _.sample([1, 2, 3, 4], 2);
* // => [3, 1]
*/
function sample(collection, n, guard) {
if (collection && typeof collection.length != 'number') {
collection = values(collection);
}
if (n == null || guard) {
return collection ? collection[baseRandom(0, collection.length - 1)] : undefined;
}
var result = shuffle(collection);
result.length = nativeMin(nativeMax(0, n), result.length);
return result;
}
/**
* Creates an array of shuffled values, using a version of the Fisher-Yates
* shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to shuffle.
* @returns {Array} Returns a new shuffled collection.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(collection) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
forEach(collection, function(value) {
var rand = baseRandom(0, ++index);
result[index] = result[rand];
result[rand] = value;
});
return result;
}
/**
* Gets the size of the `collection` by returning `collection.length` for arrays
* and array-like objects or the number of own enumerable properties for objects.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns `collection.length` or number of own enumerable properties.
* @example
*
* _.size([1, 2]);
* // => 2
*
* _.size({ 'one': 1, 'two': 2, 'three': 3 });
* // => 3
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
var length = collection ? collection.length : 0;
return typeof length == 'number' ? length : keys(collection).length;
}
/**
* Checks if the callback returns a truey value for **any** element of a
* collection. The function returns as soon as it finds a passing value and
* does not iterate over the entire collection. The callback is bound to
* `thisArg` and invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias any
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if any element passed the callback check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.some(characters, 'blocked');
* // => true
*
* // using "_.where" callback shorthand
* _.some(characters, { 'age': 1 });
* // => false
*/
function some(collection, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
var index = -1,
length = collection ? collection.length : 0;
if (typeof length == 'number') {
while (++index < length) {
if ((result = callback(collection[index], index, collection))) {
break;
}
}
} else {
forOwn(collection, function(value, index, collection) {
return !(result = callback(value, index, collection));
});
}
return !!result;
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection through the callback. This method
* performs a stable sort, that is, it will preserve the original sort order
* of equal elements. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an array of property names is provided for `callback` the collection
* will be sorted by each property value.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Array|Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of sorted elements.
* @example
*
* _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
* // => [3, 1, 2]
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 },
* { 'name': 'barney', 'age': 26 },
* { 'name': 'fred', 'age': 30 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(_.sortBy(characters, 'age'), _.values);
* // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]]
*
* // sorting by multiple properties
* _.map(_.sortBy(characters, ['name', 'age']), _.values);
* // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
*/
function sortBy(collection, callback, thisArg) {
var index = -1,
isArr = isArray(callback),
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
if (!isArr) {
callback = lodash.createCallback(callback, thisArg, 3);
}
forEach(collection, function(value, key, collection) {
var object = result[++index] = getObject();
if (isArr) {
object.criteria = map(callback, function(key) { return value[key]; });
} else {
(object.criteria = getArray())[0] = callback(value, key, collection);
}
object.index = index;
object.value = value;
});
length = result.length;
result.sort(compareAscending);
while (length--) {
var object = result[length];
result[length] = object.value;
if (!isArr) {
releaseArray(object.criteria);
}
releaseObject(object);
}
return result;
}
/**
* Converts the `collection` to an array.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to convert.
* @returns {Array} Returns the new converted array.
* @example
*
* (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
* // => [2, 3, 4]
*/
function toArray(collection) {
if (collection && typeof collection.length == 'number') {
return slice(collection);
}
return values(collection);
}
/**
* Performs a deep comparison of each element in a `collection` to the given
* `properties` object, returning an array of all elements that have equivalent
* property values.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Object} props The object of property values to filter by.
* @returns {Array} Returns a new array of elements that have the given properties.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
* { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
* ];
*
* _.where(characters, { 'age': 36 });
* // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
*
* _.where(characters, { 'pets': ['dino'] });
* // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
*/
var where = filter;
/*--------------------------------------------------------------------------*/
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are all falsey.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @returns {Array} Returns a 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,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result.push(value);
}
}
return result;
}
/**
* Creates an array excluding all values of the provided arrays using strict
* equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @param {...Array} [values] The arrays of values to exclude.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
* // => [1, 3, 4]
*/
function difference(array) {
return baseDifference(array, baseFlatten(arguments, true, true, 1));
}
/**
* This method is like `_.find` except that it returns the index of the first
* element that passes the callback check, instead of the element itself.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true },
* { 'name': 'pebbles', 'age': 1, 'blocked': false }
* ];
*
* _.findIndex(characters, function(chr) {
* return chr.age < 20;
* });
* // => 2
*
* // using "_.where" callback shorthand
* _.findIndex(characters, { 'age': 36 });
* // => 0
*
* // using "_.pluck" callback shorthand
* _.findIndex(characters, 'blocked');
* // => 1
*/
function findIndex(array, callback, thisArg) {
var index = -1,
length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length) {
if (callback(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of a `collection` from right to left.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': true },
* { 'name': 'fred', 'age': 40, 'blocked': false },
* { 'name': 'pebbles', 'age': 1, 'blocked': true }
* ];
*
* _.findLastIndex(characters, function(chr) {
* return chr.age > 30;
* });
* // => 1
*
* // using "_.where" callback shorthand
* _.findLastIndex(characters, { 'age': 36 });
* // => 0
*
* // using "_.pluck" callback shorthand
* _.findLastIndex(characters, 'blocked');
* // => 2
*/
function findLastIndex(array, callback, thisArg) {
var length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (length--) {
if (callback(array[length], length, array)) {
return length;
}
}
return -1;
}
/**
* Gets the first element or first `n` elements of an array. If a callback
* is provided elements at the beginning of the array are returned as long
* as the callback returns truey. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias head, take
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback] The function called
* per element or the number of elements to return. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the first element(s) of `array`.
* @example
*
* _.first([1, 2, 3]);
* // => 1
*
* _.first([1, 2, 3], 2);
* // => [1, 2]
*
* _.first([1, 2, 3], function(num) {
* return num < 3;
* });
* // => [1, 2]
*
* var characters = [
* { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.first(characters, 'blocked');
* // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }]
*
* // using "_.where" callback shorthand
* _.pluck(_.first(characters, { 'employer': 'slate' }), 'name');
* // => ['barney', 'fred']
*/
function first(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = -1;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length && callback(array[index], index, array)) {
n++;
}
} else {
n = callback;
if (n == null || thisArg) {
return array ? array[0] : undefined;
}
}
return slice(array, 0, nativeMin(nativeMax(0, n), length));
}
/**
* Flattens a nested array (the nesting can be to any depth). If `isShallow`
* is truey, the array will only be flattened a single level. If a callback
* is provided each element of the array is passed through the callback before
* flattening. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to flatten.
* @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, [[4]]];
*
* var characters = [
* { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] },
* { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
* ];
*
* // using "_.pluck" callback shorthand
* _.flatten(characters, 'pets');
* // => ['hoppy', 'baby puss', 'dino']
*/
function flatten(array, isShallow, callback, thisArg) {
// juggle arguments
if (typeof isShallow != 'boolean' && isShallow != null) {
thisArg = callback;
callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow;
isShallow = false;
}
if (callback != null) {
array = map(array, callback, thisArg);
}
return baseFlatten(array, isShallow);
}
/**
* Gets the index at which the first occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`. If the array is already sorted
* providing `true` for `fromIndex` will run a faster binary search.
*
* @static
* @memberOf _
* @category Arrays
* @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 or `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
*
* _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
if (typeof fromIndex == 'number') {
var length = array ? array.length : 0;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
} else if (fromIndex) {
var index = sortedIndex(array, value);
return array[index] === value ? index : -1;
}
return baseIndexOf(array, value, fromIndex);
}
/**
* Gets all but the last element or last `n` elements of an array. If a
* callback is provided elements at the end of the array are excluded from
* the result as long as the callback returns truey. The callback is bound
* to `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback=1] The function called
* per element or the number of elements to exclude. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*
* _.initial([1, 2, 3], 2);
* // => [1]
*
* _.initial([1, 2, 3], function(num) {
* return num > 1;
* });
* // => [1]
*
* var characters = [
* { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.initial(characters, 'blocked');
* // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }]
*
* // using "_.where" callback shorthand
* _.pluck(_.initial(characters, { 'employer': 'na' }), 'name');
* // => ['barney', 'fred']
*/
function initial(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = length;
callback = lodash.createCallback(callback, thisArg, 3);
while (index-- && callback(array[index], index, array)) {
n++;
}
} else {
n = (callback == null || thisArg) ? 1 : callback || n;
}
return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
}
/**
* Creates an array of unique values present in all provided arrays using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of shared values.
* @example
*
* _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
* // => [1, 2]
*/
function intersection() {
var args = [],
argsIndex = -1,
argsLength = arguments.length,
caches = getArray(),
indexOf = getIndexOf(),
trustIndexOf = indexOf === baseIndexOf,
seen = getArray();
while (++argsIndex < argsLength) {
var value = arguments[argsIndex];
if (isArray(value) || isArguments(value)) {
args.push(value);
caches.push(trustIndexOf && value.length >= largeArraySize &&
createCache(argsIndex ? args[argsIndex] : seen));
}
}
var array = args[0],
index = -1,
length = array ? array.length : 0,
result = [];
outer:
while (++index < length) {
var cache = caches[0];
value = array[index];
if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
argsIndex = argsLength;
(cache || seen).push(value);
while (--argsIndex) {
cache = caches[argsIndex];
if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
continue outer;
}
}
result.push(value);
}
}
while (argsLength--) {
cache = caches[argsLength];
if (cache) {
releaseObject(cache);
}
}
releaseArray(caches);
releaseArray(seen);
return result;
}
/**
* Gets the last element or last `n` elements of an array. If a callback is
* provided elements at the end of the array are returned as long as the
* callback returns truey. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback] The function called
* per element or the number of elements to return. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the last element(s) of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*
* _.last([1, 2, 3], 2);
* // => [2, 3]
*
* _.last([1, 2, 3], function(num) {
* return num > 1;
* });
* // => [2, 3]
*
* var characters = [
* { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.pluck(_.last(characters, 'blocked'), 'name');
* // => ['fred', 'pebbles']
*
* // using "_.where" callback shorthand
* _.last(characters, { 'employer': 'na' });
* // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
*/
function last(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = length;
callback = lodash.createCallback(callback, thisArg, 3);
while (index-- && callback(array[index], index, array)) {
n++;
}
} else {
n = callback;
if (n == null || thisArg) {
return array ? array[length - 1] : undefined;
}
}
return slice(array, nativeMax(0, length - n));
}
/**
* Gets the index at which the last occurrence of `value` is found using strict
* equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
* as the offset from the end of the collection.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value or `-1`.
* @example
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
* // => 4
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var index = array ? array.length : 0;
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Removes all provided values from the given array using strict equality for
* comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to modify.
* @param {...*} [value] 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(array) {
var args = arguments,
argsIndex = 0,
argsLength = args.length,
length = array ? array.length : 0;
while (++argsIndex < argsLength) {
var index = -1,
value = args[argsIndex];
while (++index < length) {
if (array[index] === value) {
splice.call(array, index--, 1);
length--;
}
}
}
return array;
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to but not including `end`. If `start` is less than `stop` a
* zero-length range is created unless a negative `step` is specified.
*
* @static
* @memberOf _
* @category Arrays
* @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 a new range array.
* @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) {
start = +start || 0;
step = typeof step == 'number' ? step : (+step || 1);
if (end == null) {
end = start;
start = 0;
}
// use `Array(length)` so engines like Chakra and V8 avoid slower modes
// http://youtu.be/XAqIpGU8ZZk#t=17m25s
var index = -1,
length = nativeMax(0, ceil((end - start) / (step || 1))),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
/**
* Removes all elements from an array that the callback returns truey for
* and returns an array of removed elements. The callback is bound to `thisArg`
* and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to modify.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4, 5, 6];
* var evens = _.remove(array, function(num) { return num % 2 == 0; });
*
* console.log(array);
* // => [1, 3, 5]
*
* console.log(evens);
* // => [2, 4, 6]
*/
function remove(array, callback, thisArg) {
var index = -1,
length = array ? array.length : 0,
result = [];
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length) {
var value = array[index];
if (callback(value, index, array)) {
result.push(value);
splice.call(array, index--, 1);
length--;
}
}
return result;
}
/**
* The opposite of `_.initial` this method gets all but the first element or
* first `n` elements of an array. If a callback function is provided elements
* at the beginning of the array are excluded from the result as long as the
* callback returns truey. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias drop, tail
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback=1] The function called
* per element or the number of elements to exclude. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a slice of `array`.
* @example
*
* _.rest([1, 2, 3]);
* // => [2, 3]
*
* _.rest([1, 2, 3], 2);
* // => [3]
*
* _.rest([1, 2, 3], function(num) {
* return num < 3;
* });
* // => [3]
*
* var characters = [
* { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.pluck(_.rest(characters, 'blocked'), 'name');
* // => ['fred', 'pebbles']
*
* // using "_.where" callback shorthand
* _.rest(characters, { 'employer': 'slate' });
* // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
*/
function rest(array, callback, thisArg) {
if (typeof callback != 'number' && callback != null) {
var n = 0,
index = -1,
length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length && callback(array[index], index, array)) {
n++;
}
} else {
n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
}
return slice(array, n);
}
/**
* Uses a binary search to determine the smallest index at which a value
* should be inserted into a given sorted array in order to maintain the sort
* order of the array. If a callback is provided it will be executed for
* `value` and each element of `array` to compute their sort ranking. The
* callback is bound to `thisArg` and invoked with one argument; (value).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to inspect.
* @param {*} value The value to evaluate.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([20, 30, 50], 40);
* // => 2
*
* // using "_.pluck" callback shorthand
* _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
* // => 2
*
* var dict = {
* 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
* };
*
* _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
* return dict.wordToNumber[word];
* });
* // => 2
*
* _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
* return this.wordToNumber[word];
* }, dict);
* // => 2
*/
function sortedIndex(array, value, callback, thisArg) {
var low = 0,
high = array ? array.length : low;
// explicitly reference `identity` for better inlining in Firefox
callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
value = callback(value);
while (low < high) {
var mid = (low + high) >>> 1;
(callback(array[mid]) < value)
? low = mid + 1
: high = mid;
}
return low;
}
/**
* Creates an array of unique values, in order, of the provided arrays using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of combined values.
* @example
*
* _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
* // => [1, 2, 3, 5, 4]
*/
function union() {
return baseUniq(baseFlatten(arguments, true, true));
}
/**
* Creates a duplicate-value-free version of an array using strict equality
* for comparisons, i.e. `===`. If the array is sorted, providing
* `true` for `isSorted` will use a faster algorithm. If a callback is provided
* each element of `array` is passed through the callback before uniqueness
* is computed. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias unique
* @category Arrays
* @param {Array} array The array to process.
* @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a duplicate-value-free array.
* @example
*
* _.uniq([1, 2, 1, 3, 1]);
* // => [1, 2, 3]
*
* _.uniq([1, 1, 2, 2, 3], true);
* // => [1, 2, 3]
*
* _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
* // => ['A', 'b', 'C']
*
* _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
* // => [1, 2.5, 3]
*
* // using "_.pluck" callback shorthand
* _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniq(array, isSorted, callback, thisArg) {
// juggle arguments
if (typeof isSorted != 'boolean' && isSorted != null) {
thisArg = callback;
callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted;
isSorted = false;
}
if (callback != null) {
callback = lodash.createCallback(callback, thisArg, 3);
}
return baseUniq(array, isSorted, callback);
}
/**
* Creates an array excluding all provided values using strict equality for
* comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to filter.
* @param {...*} [value] The values to exclude.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
* // => [2, 3, 4]
*/
function without(array) {
return baseDifference(array, slice(arguments, 1));
}
/**
* Creates an array that is the symmetric difference of the provided arrays.
* See http://en.wikipedia.org/wiki/Symmetric_difference.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of values.
* @example
*
* _.xor([1, 2, 3], [5, 2, 1, 4]);
* // => [3, 5, 4]
*
* _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
* // => [1, 4, 5]
*/
function xor() {
var index = -1,
length = arguments.length;
while (++index < length) {
var array = arguments[index];
if (isArray(array) || isArguments(array)) {
var result = result
? baseUniq(baseDifference(result, array).concat(baseDifference(array, result)))
: array;
}
}
return 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 _
* @alias unzip
* @category Arrays
* @param {...Array} [array] Arrays to process.
* @returns {Array} Returns a new array of grouped elements.
* @example
*
* _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*/
function zip() {
var array = arguments.length > 1 ? arguments : arguments[0],
index = -1,
length = array ? max(pluck(array, 'length')) : 0,
result = Array(length < 0 ? 0 : length);
while (++index < length) {
result[index] = pluck(array, index);
}
return result;
}
/**
* Creates an object composed from arrays of `keys` and `values`. Provide
* either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
* or two arrays, one of `keys` and one of corresponding `values`.
*
* @static
* @memberOf _
* @alias object
* @category Arrays
* @param {Array} keys The array of keys.
* @param {Array} [values=[]] The array of values.
* @returns {Object} Returns an object composed of the given keys and
* corresponding values.
* @example
*
* _.zipObject(['fred', 'barney'], [30, 40]);
* // => { 'fred': 30, 'barney': 40 }
*/
function zipObject(keys, values) {
var index = -1,
length = keys ? keys.length : 0,
result = {};
if (!values && length && !isArray(keys[0])) {
values = [];
}
while (++index < length) {
var key = keys[index];
if (values) {
result[key] = values[index];
} else if (key) {
result[key[0]] = key[1];
}
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a function that executes `func`, with the `this` binding and
* arguments of the created function, only after being called `n` times.
*
* @static
* @memberOf _
* @category Functions
* @param {number} n The number of times the function must be called before
* `func` is executed.
* @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 all saves have completed
*/
function after(n, func) {
if (!isFunction(func)) {
throw new TypeError;
}
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that, when called, invokes `func` with the `this`
* binding of `thisArg` and prepends any additional `bind` arguments to those
* provided to the bound function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to bind.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var func = function(greeting) {
* return greeting + ' ' + this.name;
* };
*
* func = _.bind(func, { 'name': 'fred' }, 'hi');
* func();
* // => 'hi fred'
*/
function bind(func, thisArg) {
return arguments.length > 2
? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
: createWrapper(func, 1, null, null, thisArg);
}
/**
* 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 the function properties
* of `object` will be bound.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...string} [methodName] 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 button is clicked
*/
function bindAll(object) {
var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
index = -1,
length = funcs.length;
while (++index < length) {
var key = funcs[index];
object[key] = createWrapper(object[key], 1, null, null, object);
}
return object;
}
/**
* Creates a function that, when called, 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 will be redefined or don't yet exist.
* See http://michaux.ca/articles/lazy-function-definition-pattern.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object the method belongs to.
* @param {string} key The key of the method.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'name': 'fred',
* 'greet': function(greeting) {
* return greeting + ' ' + this.name;
* }
* };
*
* var func = _.bindKey(object, 'greet', 'hi');
* func();
* // => 'hi fred'
*
* object.greet = function(greeting) {
* return greeting + 'ya ' + this.name + '!';
* };
*
* func();
* // => 'hiya fred!'
*/
function bindKey(object, key) {
return arguments.length > 2
? createWrapper(key, 19, slice(arguments, 2), null, object)
: createWrapper(key, 3, null, null, object);
}
/**
* Creates a function that is the composition of the provided functions,
* where each function consumes the return value of the function that follows.
* For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
* Each function is executed with the `this` binding of the composed function.
*
* @static
* @memberOf _
* @category Functions
* @param {...Function} [func] Functions to compose.
* @returns {Function} Returns the new composed function.
* @example
*
* var realNameMap = {
* 'pebbles': 'penelope'
* };
*
* var format = function(name) {
* name = realNameMap[name.toLowerCase()] || name;
* return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
* };
*
* var greet = function(formatted) {
* return 'Hiya ' + formatted + '!';
* };
*
* var welcome = _.compose(greet, format);
* welcome('pebbles');
* // => 'Hiya Penelope!'
*/
function compose() {
var funcs = arguments,
length = funcs.length;
while (length--) {
if (!isFunction(funcs[length])) {
throw new TypeError;
}
}
return function() {
var args = arguments,
length = funcs.length;
while (length--) {
args = [funcs[length].apply(this, args)];
}
return args[0];
};
}
/**
* Creates a function which accepts one or more arguments of `func` that when
* invoked either executes `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` can be specified
* if `func.length` is not sufficient.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @returns {Function} Returns the new curried function.
* @example
*
* var curried = _.curry(function(a, b, c) {
* console.log(a + b + c);
* });
*
* curried(1)(2)(3);
* // => 6
*
* curried(1, 2)(3);
* // => 6
*
* curried(1, 2, 3);
* // => 6
*/
function curry(func, arity) {
arity = typeof arity == 'number' ? arity : (+arity || func.length);
return createWrapper(func, 4, null, null, null, arity);
}
/**
* Creates a function that will delay the execution of `func` until after
* `wait` milliseconds have elapsed since the last time it was invoked.
* 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 will return the result of the last `func` call.
*
* Note: If `leading` and `trailing` options are `true` `func` will be called
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to debounce.
* @param {number} wait The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
* @param {boolean} [options.trailing=true] Specify execution 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
* var lazyLayout = _.debounce(calculateLayout, 150);
* jQuery(window).on('resize', lazyLayout);
*
* // execute `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* });
*
* // ensure `batchLog` is executed once after 1 second of debounced calls
* var source = new EventSource('/stream');
* source.addEventListener('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }, false);
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (!isFunction(func)) {
throw new TypeError;
}
wait = nativeMax(0, wait) || 0;
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = options.leading;
maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
trailing = 'trailing' in options ? options.trailing : trailing;
}
var delayed = function() {
var remaining = wait - (now() - stamp);
if (remaining <= 0) {
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);
}
};
var maxDelayed = function() {
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;
}
}
};
return function() {
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;
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;
};
}
/**
* Defers executing the `func` function until the current call stack has cleared.
* Additional arguments will be provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to defer.
* @param {...*} [arg] 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
*/
function defer(func) {
if (!isFunction(func)) {
throw new TypeError;
}
var args = slice(arguments, 1);
return setTimeout(function() { func.apply(undefined, args); }, 1);
}
/**
* Executes the `func` function after `wait` milliseconds. Additional arguments
* will be provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay execution.
* @param {...*} [arg] 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
*/
function delay(func, wait) {
if (!isFunction(func)) {
throw new TypeError;
}
var args = slice(arguments, 2);
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided it will be used to determine 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 used as the cache key.
* The `func` is executed with the `this` binding of the memoized function.
* The result cache is exposed as the `cache` property on the memoized function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] A function used to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var fibonacci = _.memoize(function(n) {
* return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
* });
*
* fibonacci(9)
* // => 34
*
* var data = {
* 'fred': { 'name': 'fred', 'age': 40 },
* 'pebbles': { 'name': 'pebbles', 'age': 1 }
* };
*
* // modifying the result cache
* var get = _.memoize(function(name) { return data[name]; }, _.identity);
* get('pebbles');
* // => { 'name': 'pebbles', 'age': 1 }
*
* get.cache.pebbles.name = 'penelope';
* get('pebbles');
* // => { 'name': 'penelope', 'age': 1 }
*/
function memoize(func, resolver) {
if (!isFunction(func)) {
throw new TypeError;
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
return hasOwnProperty.call(cache, key)
? cache[key]
: (cache[key] = func.apply(this, arguments));
}
memoized.cache = {};
return memoized;
}
/**
* Creates a function that is restricted to execute `func` once. Repeat calls to
* the function will return the value of the first call. The `func` is executed
* with the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // `initialize` executes `createApplication` once
*/
function once(func) {
var ran,
result;
if (!isFunction(func)) {
throw new TypeError;
}
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
// clear the `func` variable so the function may be garbage collected
func = null;
return result;
};
}
/**
* Creates a function that, when called, invokes `func` with any additional
* `partial` arguments prepended to those provided to the new function. This
* method is similar to `_.bind` except it does **not** alter the `this` binding.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) { return greeting + ' ' + name; };
* var hi = _.partial(greet, 'hi');
* hi('fred');
* // => 'hi fred'
*/
function partial(func) {
return createWrapper(func, 16, slice(arguments, 1));
}
/**
* This method is like `_.partial` except that `partial` arguments are
* appended to those provided to the new function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var defaultsDeep = _.partialRight(_.merge, _.defaults);
*
* var options = {
* 'variable': 'data',
* 'imports': { 'jq': $ }
* };
*
* defaultsDeep(options, _.templateSettings);
*
* options.variable
* // => 'data'
*
* options.imports
* // => { '_': _, 'jq': $ }
*/
function partialRight(func) {
return createWrapper(func, 32, null, slice(arguments, 1));
}
/**
* Creates a function that, when executed, will only call the `func` function
* at most once per every `wait` milliseconds. 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 will
* return the result of the last `func` call.
*
* Note: If `leading` and `trailing` options are `true` `func` will be called
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to throttle.
* @param {number} wait The number of milliseconds to throttle executions to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
* @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* var throttled = _.throttle(updatePosition, 100);
* jQuery(window).on('scroll', throttled);
*
* // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
* 'trailing': false
* }));
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (!isFunction(func)) {
throw new TypeError;
}
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. Additional arguments provided to the function are appended
* to those provided to the wrapper function. The wrapper is executed with
* the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @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 '' + func(text) + '
';
* });
*
* p('Fred, Wilma, & Pebbles');
* // => 'Fred, Wilma, & Pebbles
'
*/
function wrap(value, wrapper) {
return createWrapper(wrapper, 16, [value]);
}
/*--------------------------------------------------------------------------*/
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new function.
* @example
*
* var object = { 'name': 'fred' };
* var getter = _.constant(object);
* getter() === object;
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* Produces a callback bound to an optional `thisArg`. If `func` is a property
* name the created callback will return the property value for a given element.
* If `func` is an object the created callback will return `true` for elements
* that contain the equivalent object properties, otherwise it will return `false`.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} [func=identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of the created callback.
* @param {number} [argCount] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // wrap to create custom callback shorthands
* _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
* var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
* return !match ? func(callback, thisArg) : function(object) {
* return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
* };
* });
*
* _.filter(characters, 'age__gt38');
* // => [{ 'name': 'fred', 'age': 40 }]
*/
function createCallback(func, thisArg, argCount) {
var type = typeof func;
if (func == null || type == 'function') {
return baseCreateCallback(func, thisArg, argCount);
}
// handle "_.pluck" style callback shorthands
if (type != 'object') {
return property(func);
}
var props = keys(func),
key = props[0],
a = func[key];
// handle "_.where" style callback shorthands
if (props.length == 1 && a === a && !isObject(a)) {
// fast path the common case of providing an object with a single
// property containing a primitive value
return function(object) {
var b = object[key];
return a === b && (a !== 0 || (1 / a == 1 / b));
};
}
return function(object) {
var length = props.length,
result = false;
while (length--) {
if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
break;
}
}
return result;
};
}
/**
* Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
* corresponding HTML entities.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} string The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('Fred, Wilma, & Pebbles');
* // => 'Fred, Wilma, & Pebbles'
*/
function escape(string) {
return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'name': 'fred' };
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Adds function properties of a source object to the destination object.
* If `object` is a function methods will be added to its prototype as well.
*
* @static
* @memberOf _
* @category Utilities
* @param {Function|Object} [object=lodash] object 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.
* @example
*
* function capitalize(string) {
* return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
* }
*
* _.mixin({ 'capitalize': capitalize });
* _.capitalize('fred');
* // => 'Fred'
*
* _('fred').capitalize().value();
* // => 'Fred'
*
* _.mixin({ 'capitalize': capitalize }, { 'chain': false });
* _('fred').capitalize();
* // => 'Fred'
*/
function mixin(object, source, options) {
var chain = true,
methodNames = source && functions(source);
if (!source || (!options && !methodNames.length)) {
if (options == null) {
options = source;
}
ctor = lodashWrapper;
source = object;
object = lodash;
methodNames = functions(source);
}
if (options === false) {
chain = false;
} else if (isObject(options) && 'chain' in options) {
chain = options.chain;
}
var ctor = object,
isFunc = isFunction(ctor);
forEach(methodNames, function(methodName) {
var func = object[methodName] = source[methodName];
if (isFunc) {
ctor.prototype[methodName] = function() {
var chainAll = this.__chain__,
value = this.__wrapped__,
args = [value];
push.apply(args, arguments);
var result = func.apply(object, args);
if (chain || chainAll) {
if (value === result && isObject(result)) {
return this;
}
result = new ctor(result);
result.__chain__ = chainAll;
}
return result;
};
}
});
}
/**
* Reverts the '_' variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @memberOf _
* @category Utilities
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
context._ = oldDash;
return this;
}
/**
* A no-operation function.
*
* @static
* @memberOf _
* @category Utilities
* @example
*
* var object = { 'name': 'fred' };
* _.noop(object) === undefined;
* // => true
*/
function noop() {
// no operation performed
}
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Utilities
* @example
*
* var stamp = _.now();
* _.defer(function() { console.log(_.now() - stamp); });
* // => logs the number of milliseconds it took for the deferred function to be called
*/
var now = isNative(now = Date.now) && now || function() {
return new Date().getTime();
};
/**
* Converts the given value into an integer of the specified radix.
* If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
* `value` is a hexadecimal, in which case a `radix` of `16` is used.
*
* Note: This method avoids differences in native ES3 and ES5 `parseInt`
* implementations. See http://es5.github.io/#E.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} value The value to parse.
* @param {number} [radix] The radix used to interpret the value to parse.
* @returns {number} Returns the new integer value.
* @example
*
* _.parseInt('08');
* // => 8
*/
var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
// Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt`
return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
};
/**
* Creates a "_.pluck" style function, which returns the `key` value of a
* given object.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} key The name of the property to retrieve.
* @returns {Function} Returns the new function.
* @example
*
* var characters = [
* { 'name': 'fred', 'age': 40 },
* { 'name': 'barney', 'age': 36 }
* ];
*
* var getName = _.property('name');
*
* _.map(characters, getName);
* // => ['barney', 'fred']
*
* _.sortBy(characters, getName);
* // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
*/
function property(key) {
return function(object) {
return object[key];
};
}
/**
* Produces a random number between `min` and `max` (inclusive). If only one
* argument is provided a number between `0` and the given number will be
* returned. If `floating` is truey or either `min` or `max` are floats a
* floating-point number will be returned instead of an integer.
*
* @static
* @memberOf _
* @category Utilities
* @param {number} [min=0] The minimum possible value.
* @param {number} [max=1] The maximum possible value.
* @param {boolean} [floating=false] Specify returning a floating-point number.
* @returns {number} Returns a 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) {
var noMin = min == null,
noMax = max == null;
if (floating == null) {
if (typeof min == 'boolean' && noMax) {
floating = min;
min = 1;
}
else if (!noMax && typeof max == 'boolean') {
floating = max;
noMax = true;
}
}
if (noMin && noMax) {
max = 1;
}
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);
}
/**
* Resolves the value of property `key` on `object`. If `key` is a function
* it will be invoked with the `this` binding of `object` and its result returned,
* else the property value is returned. If `object` is falsey then `undefined`
* is returned.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object to inspect.
* @param {string} key The name of the property to resolve.
* @returns {*} Returns the resolved value.
* @example
*
* var object = {
* 'cheese': 'crumpets',
* 'stuff': function() {
* return 'nonsense';
* }
* };
*
* _.result(object, 'cheese');
* // => 'crumpets'
*
* _.result(object, 'stuff');
* // => 'nonsense'
*/
function result(object, key) {
if (object) {
var value = object[key];
return isFunction(value) ? object[key]() : value;
}
}
/**
* A micro-templating method that handles arbitrary delimiters, preserves
* whitespace, and correctly escapes quotes within interpolated code.
*
* Note: In the development build, `_.template` utilizes sourceURLs for easier
* debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
*
* For more information on precompiling templates see:
* https://lodash.com/custom-builds
*
* For more information on Chrome extension sandboxes see:
* http://developer.chrome.com/stable/extensions/sandboxingEval.html
*
* @static
* @memberOf _
* @category Utilities
* @param {string} text The template text.
* @param {Object} data The data object used to populate the text.
* @param {Object} [options] The options object.
* @param {RegExp} [options.escape] The "escape" delimiter.
* @param {RegExp} [options.evaluate] The "evaluate" delimiter.
* @param {Object} [options.imports] An object to import into the template as local variables.
* @param {RegExp} [options.interpolate] The "interpolate" delimiter.
* @param {string} [sourceURL] The sourceURL of the template's compiled source.
* @param {string} [variable] The data object variable name.
* @returns {Function|string} Returns a compiled function when no `data` object
* is given, else it returns the interpolated text.
* @example
*
* // using the "interpolate" delimiter to create a compiled template
* var compiled = _.template('hello <%= name %>');
* compiled({ 'name': 'fred' });
* // => 'hello fred'
*
* // using the "escape" delimiter to escape HTML in data property values
* _.template('<%- value %>', { 'value': '", 'Script');
};
WYMeditor.XhtmlLexer.prototype.addCssTokens = function(scope) {
this.addEntryPattern("