code stringlengths 2 1.05M |
|---|
module.exports = {
options: {
filepathTransform: function(filepath) {
filepath.replace('ember-model', 'ember-model/lib');
return 'packages/' + filepath.replace('ember-model', 'ember-model/lib');
}
},
'dist/ember-model.js': 'packages/ember-model/lib/main.js'
};
|
// DATA_TEMPLATE: empty_table
oTest.fnStart( "Custom data source property - array only" );
$(document).ready( function () {
var oInit = {
"sAjaxSource": "../../../examples/ajax/sources/array_only.txt",
"bDeferRender": true,
"sAjaxDataProp": ""
};
$('#example').dataTable( oInit );
oTest.fnWaitTest(
"10 rows shown on the first page",
null,
function () { return $('#example tbody tr').length == 10; }
);
oTest.fnTest(
"Initial sort occured",
null,
function () { return $('#example tbody td:eq(0)').html() == "Gecko"; }
);
/* Need to use the WaitTest for sorting due to the setTimeout datatables uses */
oTest.fnTest(
"Sorting (first click) on second column",
function () { $('#example thead th:eq(1)').click(); },
function () { return $('#example tbody td:eq(1)').html() == "All others"; }
);
oTest.fnTest(
"Sorting (second click) on second column",
function () { $('#example thead th:eq(1)').click(); },
function () { return $('#example tbody td:eq(1)').html() == "Seamonkey 1.1"; }
);
oTest.fnTest(
"Sorting (third click) on second column",
function () { $('#example thead th:eq(1)').click(); },
function () { return $('#example tbody td:eq(1)').html() == "All others"; }
);
oTest.fnTest(
"Sorting (first click) on numeric column",
function () { $('#example thead th:eq(3)').click(); },
function () { return $('#example tbody td:eq(3)').html() == "-"; }
);
oTest.fnTest(
"Sorting (second click) on numeric column",
function () { $('#example thead th:eq(3)').click(); },
function () { return $('#example tbody td:eq(3)').html() == "522.1"; }
);
oTest.fnTest(
"Sorting multi-column (first click)",
function () {
$('#example thead th:eq(0)').click();
oDispacher.click( $('#example thead th:eq(1)')[0], { 'shift': true } ); },
function () { var b =
$('#example tbody td:eq(0)').html() == "Gecko" &&
$('#example tbody td:eq(1)').html() == "Camino 1.0"; return b; }
);
oTest.fnTest(
"Sorting multi-column - sorting second column only",
function () {
$('#example thead th:eq(1)').click(); },
function () { return $('#example tbody td:eq(1)').html() == "All others"; }
);
/* Basic paging */
oTest.fnTest(
"Paging to second page",
function () { $('#example_next').click(); },
function () { return $('#example tbody td:eq(1)').html() == "IE Mobile"; }
);
oTest.fnTest(
"Paging to first page",
function () { $('#example_previous').click(); },
function () { return $('#example tbody td:eq(1)').html() == "All others"; }
);
oTest.fnTest(
"Attempting to page back beyond the first page",
function () { $('#example_previous').click(); },
function () { return $('#example tbody td:eq(1)').html() == "All others"; }
);
/* Changing length */
oTest.fnTest(
"Changing table length to 25 records",
function () { $("select[name=example_length]").val('25').change(); },
function () { return $('#example tbody tr').length == 25; }
);
oTest.fnTest(
"Changing table length to 50 records",
function () { $("select[name=example_length]").val('50').change(); },
function () { return $('#example tbody tr').length == 50; }
);
oTest.fnTest(
"Changing table length to 100 records",
function () { $("select[name=example_length]").val('100').change(); },
function () { return $('#example tbody tr').length == 57; }
);
oTest.fnTest(
"Changing table length to 10 records",
function () { $("select[name=example_length]").val('10').change(); },
function () { return $('#example tbody tr').length == 10; }
);
/*
* Information element
*/
oTest.fnTest(
"Information on zero config",
null,
function () { return document.getElementById('example_info').innerHTML == "Showing 1 to 10 of 57 entries"; }
);
oTest.fnTest(
"Information on second page",
function () { $('#example_next').click(); },
function () { return document.getElementById('example_info').innerHTML == "Showing 11 to 20 of 57 entries"; }
);
oTest.fnTest(
"Information on third page",
function () { $('#example_next').click(); },
function () { return document.getElementById('example_info').innerHTML == "Showing 21 to 30 of 57 entries"; }
);
oTest.fnComplete();
} ); |
version https://git-lfs.github.com/spec/v1
oid sha256:eb0c3092c0ce1efef8f00af22725ffa9b58617a078063ee9e157ff2045cc170c
size 2806
|
module.exports={title:"Odnoklassniki",hex:"F4731C",source:"http://v.ok.ru/logo.html",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Odnoklassniki icon</title><path d="M14.505 17.44c1.275-.29 2.493-.794 3.6-1.49.834-.558 1.058-1.686.5-2.52-.536-.802-1.604-1.044-2.435-.553-2.55 1.595-5.79 1.595-8.34 0-.847-.534-1.965-.28-2.5.565 0 .002 0 .004-.002.005-.534.847-.28 1.966.567 2.5l.002.002c1.105.695 2.322 1.2 3.596 1.488l-3.465 3.465c-.707.695-.72 1.83-.028 2.537l.03.03c.344.354.81.53 1.274.53.465 0 .93-.176 1.275-.53L12 20.065l3.404 3.406c.72.695 1.87.676 2.566-.045.678-.703.678-1.818 0-2.52l-3.465-3.466zM12 12.388c3.42-.004 6.19-2.774 6.195-6.193C18.195 2.78 15.415 0 12 0S5.805 2.78 5.805 6.197c.005 3.42 2.776 6.19 6.195 6.192zm0-8.757c1.416.002 2.563 1.15 2.564 2.565 0 1.416-1.148 2.563-2.564 2.565-1.415-.002-2.562-1.148-2.565-2.564C9.437 4.78 10.585 3.633 12 3.63z"/></svg>'}; |
/*************************************************************
*
* MathJax/localization/uk/TeX.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("uk","TeX",{
version: "2.7.2",
isLoaded: true,
strings: {
ExtraOpenMissingClose: "\u0417\u0430\u0439\u0432\u0430 \u0432\u0456\u0434\u043A\u0440\u0438\u0442\u0430 \u0444\u0456\u0433\u0443\u0440\u043D\u0430 \u0434\u0443\u0436\u043A\u0430 \u0430\u0431\u043E \u0432\u0456\u0434\u0441\u0443\u0442\u043D\u044F \u0437\u0430\u043A\u0440\u0438\u0442\u0430 \u0444\u0456\u0433\u0443\u0440\u043D\u0430 \u0434\u0443\u0436\u043A\u0430",
ExtraCloseMissingOpen: "\u0417\u0430\u0439\u0432\u0430 \u0437\u0430\u043A\u0440\u0438\u0442\u0430 \u0444\u0456\u0433\u0443\u0440\u043D\u0430 \u0434\u0443\u0436\u043A\u0430 \u0430\u0431\u043E \u0432\u0456\u0434\u0441\u0443\u0442\u043D\u044F \u0432\u0456\u0434\u043A\u0440\u0438\u0442\u0430 \u0444\u0456\u0433\u0443\u0440\u043D\u0430 \u0434\u0443\u0436\u043A\u0430",
MissingLeftExtraRight: "\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 \\left \u0430\u0431\u043E \u0437\u0430\u0439\u0432\u0438\u0439 \\right",
MissingScript: "\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442\u0438 \u0432\u0435\u0440\u0445\u043D\u044C\u043E\u0433\u043E \u0456 \u043D\u0438\u0436\u043D\u044C\u043E\u0433\u043E \u0456\u043D\u0434\u0435\u043A\u0441\u0456\u0432",
ExtraLeftMissingRight: "\u0417\u0430\u0439\u0432\u0438\u0439 \\left \u0430\u0431\u043E \u0432\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 \\right",
Misplaced: "\u041D\u0435\u0432\u0456\u0440\u043D\u0438\u0439 %1",
MissingOpenForSub: "\u0411\u0440\u0430\u043A\u0443\u0454 \u0432\u0456\u0434\u043A\u0440\u0438\u0432\u0430\u044E\u0447\u043E\u0457 \u0434\u0443\u0436\u043A\u0438 \u0434\u043B\u044F \u043D\u0438\u0436\u043D\u044C\u043E\u0433\u043E \u0456\u043D\u0434\u0435\u043A\u0441\u0443",
MissingOpenForSup: "\u0411\u0440\u0430\u043A\u0443\u0454 \u0432\u0456\u0434\u043A\u0440\u0438\u0432\u0430\u044E\u0447\u043E\u0457 \u0434\u0443\u0436\u043A\u0438 \u0434\u043B\u044F \u0432\u0435\u0440\u0445\u043D\u044C\u043E\u0433\u043E \u0456\u043D\u0434\u0435\u043A\u0441\u0443",
AmbiguousUseOf: "\u041D\u0435\u043E\u0434\u043D\u043E\u0437\u043D\u0430\u0447\u043D\u0435 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u0430\u043D\u043D\u044F %1",
EnvBadEnd: "\\begin{%1} \u0437\u0430\u043A\u0456\u043D\u0447\u0438\u0432\u0441\u044F \\end{%2}",
EnvMissingEnd: "\u0411\u0440\u0430\u043A\u0443\u0454 \\end{%1}",
MissingBoxFor: "\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0454 \u043F\u043E\u043B\u0435 \u0434\u043B\u044F %1",
MissingCloseBrace: "\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u044F \u0437\u0430\u043A\u0440\u0438\u0432\u0430\u044E\u0447\u0430 \u0434\u0443\u0436\u043A\u0430",
UndefinedControlSequence: "\u041D\u0435\u0432\u0438\u0437\u043D\u0430\u0447\u0435\u043D\u0430 \u043A\u043E\u043C\u0430\u043D\u0434\u0430 %1",
DoubleExponent: "\u041F\u043E\u0434\u0432\u0456\u0439\u043D\u0438\u0439 \u0441\u0442\u0435\u043F\u0456\u043D\u044C: \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0439\u0442\u0435 \u0434\u0443\u0436\u043A\u0438 \u0434\u043B\u044F \u0443\u0442\u043E\u0447\u043D\u0435\u043D\u043D\u044F",
DoubleSubscripts: "\u041F\u043E\u0434\u0432\u0456\u0439\u043D\u0438\u0439 \u043D\u0438\u0436\u043D\u0456\u0439 \u0456\u043D\u0434\u0435\u043A\u0441: \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0439\u0442\u0435 \u0434\u0443\u0436\u043A\u0438 \u0443\u0442\u043E\u0447\u0435\u043D\u043D\u044F",
DoubleExponentPrime: "\u0417\u043D\u0430\u043A \u0448\u0442\u0440\u0438\u0445\u0430 \u0441\u043F\u0440\u0438\u0447\u0438\u043D\u0438\u0432 \u043F\u043E\u0434\u0432\u0456\u0439\u043D\u0438\u0439 \u0441\u0442\u0435\u043F\u0456\u043D\u044C: \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u0430\u0439\u0442\u0435 \u0434\u0443\u0436\u043A\u0438 \u0434\u043B\u044F \u0443\u0442\u043E\u0447\u043D\u0435\u043D\u043D\u044F",
CantUseHash1: "\u041D\u0435 \u043C\u043E\u0436\u043D\u0430 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0432\u0430\u0442\u0438 \u0441\u0438\u043C\u0432\u043E\u043B \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430 \u043C\u0430\u043A\u0440\u043E\u0441\u0443 # \u0443 \u043C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u0447\u043D\u043E\u043C\u0443 \u0440\u0435\u0436\u0438\u043C\u0456",
MisplacedMiddle: "%1 \u043C\u0430\u0454 \u0431\u0443\u0442\u0438 \u0432 \u043C\u0435\u0436\u0430\u0445 \\left \u0456 \\right",
MisplacedLimits: "%1 \u0434\u043E\u0437\u0432\u043E\u043B\u0435\u043D\u043E \u0442\u0456\u043B\u044C\u043A\u0438 \u043D\u0430 \u043E\u043F\u0435\u0440\u0430\u0442\u043E\u0440\u0430\u0445",
MisplacedMoveRoot: "%1 \u043C\u043E\u0436\u0435 \u0437'\u044F\u0432\u0438\u0442\u0438\u0441\u044F \u043B\u0438\u0448\u0435 \u043F\u0456\u0434 \u043A\u043E\u0440\u0435\u043D\u0435\u043C",
MultipleCommand: "\u041A\u0456\u043B\u044C\u043A\u0430 %1",
IntegerArg: "\u0410\u0440\u0433\u0443\u043C\u0435\u043D\u0442 \u0434\u043B\u044F %1 \u043C\u0430\u0454 \u0431\u0443\u0442\u0438 \u0446\u0456\u043B\u0438\u043C \u0447\u0438\u0441\u043B\u043E\u043C",
NotMathMLToken: "%1 \u043D\u0435 \u0435\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u043C \u043C\u0430\u0440\u043A\u0435\u0440\u0430",
InvalidMathMLAttr: "\u041D\u0435\u043F\u0440\u0438\u043F\u0443\u0441\u0442\u0438\u043C\u0438\u0439 \u0430\u0442\u0440\u0438\u0431\u0443\u0442 MathML: %1",
UnknownAttrForElement: "%1 \u043D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u0430\u0442\u0440\u0438\u0431\u0443\u0442 \u0434\u043B\u044F %2",
MaxMacroSub1: "\u041F\u0435\u0440\u0435\u0432\u0438\u0449\u0435\u043D\u043E \u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u0443 \u043A\u0456\u043B\u044C\u043A\u0456\u0441\u0442\u044C \u0432\u0438\u043A\u043B\u0438\u043A\u0456\u0432 \u043C\u0430\u043A\u0440\u043E\u0441\u0456\u0432; \u0430\u0431\u043E \u0432\u0456\u0434\u0431\u0443\u0432\u0430\u0454\u0442\u044C\u0441\u044F \u0440\u0435\u043A\u0443\u0440\u0441\u0438\u0432\u043D\u0438\u0439 \u0432\u0438\u043A\u043B\u0438\u043A \u043C\u0430\u043A\u0440\u043E\u0441\u0443?",
MaxMacroSub2: "\u041F\u0435\u0440\u0435\u0432\u0438\u0449\u0435\u043D\u043E \u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u0443 \u043A\u0456\u043B\u044C\u043A\u0456\u0441\u0442\u044C \u043F\u0456\u0434\u0441\u0442\u0430\u043D\u043E\u0432\u043E\u043A MathJax; \u041C\u043E\u0436\u043B\u0438\u0432\u043E, \u0440\u0435\u043A\u0443\u0440\u0441\u0456\u044F \u0432 \u0441\u0435\u0440\u0435\u0434\u043E\u0432\u0438\u0449\u0456 LaTeX?",
MissingArgFor: "\u041F\u0440\u043E\u043F\u0443\u0449\u0435\u043D\u0438\u0439 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442 \u0434\u043B\u044F %1",
ExtraAlignTab: "\u0417\u0430\u0439\u0432\u0438\u0439 \u0442\u0430\u0431\u0443\u043B\u044F\u0442\u043E\u0440 \u0442\u0435\u043A\u0441\u0442\u0443 \u0443 \\cases",
BracketMustBeDimension: "\u0410\u0440\u0433\u0443\u043C\u0435\u043D\u0442 \u0443 \u0434\u0443\u0436\u043A\u0430\u0445 \u0434\u043B\u044F %1 \u043C\u0430\u0454 \u0431\u0443\u0442\u0438 \u0440\u043E\u0437\u043C\u0456\u0440\u043E\u043C",
InvalidEnv: "\u041D\u0435\u0432\u0456\u0440\u043D\u0435 \u0456\u043C'\u044F \u0441\u0435\u0440\u0435\u0434\u043E\u0432\u0438\u0449\u0430 '%1'",
UnknownEnv: "\u041D\u0435\u0432\u0456\u0434\u043E\u043C\u0435 \u0441\u0435\u0440\u0435\u0434\u043E\u0432\u0438\u0449\u0435 '%1'",
ExtraCloseLooking: "\u0417\u0430\u0439\u0432\u0430 \u0437\u0430\u043A\u0440\u0438\u0432\u0430\u044E\u0447\u0430 \u0434\u0443\u0436\u043A\u0430 \u0432\u0438\u043D\u0438\u043A\u043B\u0430 \u043F\u0456\u0434 \u0447\u0430\u0441 \u043F\u043E\u0448\u0443\u043A\u0443 %1",
MissingCloseBracket: "\u041D\u0435 \u043C\u043E\u0436\u043B\u0438\u0432\u043E \u0437\u043D\u0430\u0439\u0442\u0438 \u0437\u0430\u043A\u0440\u0438\u0432\u0430\u044E\u0447\u0443 ']' \u0434\u043B\u044F \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442\u0443 \u0434\u043E %1",
MissingOrUnrecognizedDelim: "\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 \u0430\u0431\u043E \u043D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u0440\u043E\u0437\u0434\u0456\u043B\u044C\u043D\u0438\u043A \u0434\u043B\u044F %1",
MissingDimOrUnits: "\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 \u0440\u043E\u0437\u043C\u0456\u0440 \u0430\u0431\u043E \u0439\u043E\u0433\u043E \u043E\u0434\u0438\u043D\u0438\u0446\u0456 \u0434\u043B\u044F %1",
TokenNotFoundForCommand: "\u041D\u0435 \u043C\u043E\u0436\u043B\u0438\u0432\u043E \u0437\u043D\u0430\u0439\u0442\u0438 %1 \u0434\u043B\u044F %2",
MathNotTerminated: "\u041C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u043A\u0430 \u043D\u0435 \u0437\u0430\u0432\u0435\u0440\u0448\u0443\u0454\u0442\u044C\u0441\u044F \u0432 \u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u043C\u0443 \u043F\u043E\u043B\u0456",
IllegalMacroParam: "\u041D\u0435\u0437\u0430\u043A\u043E\u043D\u043D\u0435 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F \u043D\u0430 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 \u043C\u0430\u043A\u0440\u043E\u0441\u0443",
MaxBufferSize: "\u041F\u0435\u0440\u0435\u0432\u0438\u0449\u0435\u043D\u043E \u0440\u043E\u0437\u043C\u0456\u0440 \u0432\u043D\u0443\u0442\u0440\u0456\u0448\u043D\u044C\u043E\u0433\u043E \u0431\u0443\u0444\u0435\u0440\u0430 MathJax; \u0442\u0430\u043C \u0454 \u0440\u0435\u043A\u0443\u0440\u0441\u0438\u0432\u043D\u0438\u0439 \u0432\u0438\u043A\u043B\u0438\u043A \u043C\u0430\u043A\u0440\u043E\u0441\u0443?",
CommandNotAllowedInEnv: "%1 \u043D\u0435 \u0434\u043E\u043F\u0443\u0441\u043A\u0430\u0454\u0442\u044C\u0441\u044F \u0432 \u0441\u0435\u0440\u0435\u0434\u043E\u0432\u0438\u0449\u0456 %2",
MultipleLabel: "\u041C\u0456\u0442\u043A\u0430 '%1' \u0432\u0438\u0437\u043D\u0430\u0447\u0435\u043D\u0430 \u043A\u0456\u043B\u044C\u043A\u0430 \u0440\u0430\u0437\u0456\u0432",
CommandAtTheBeginingOfLine: "%1 \u043C\u0430\u0454 \u0437\u043D\u0430\u0445\u043E\u0434\u0438\u0442\u0438\u0441\u044F \u043D\u0430 \u043F\u043E\u0447\u0430\u0442\u043A\u0443 \u0440\u044F\u0434\u043A\u0430",
IllegalAlign: "\u041D\u0435\u0437\u0430\u043A\u043E\u043D\u043D\u0435 \u0432\u0438\u0440\u0456\u0432\u043D\u044E\u0432\u0430\u043D\u043D\u044F \u0432\u043A\u0430\u0437\u0430\u043D\u0435 \u0443 %1",
BadMathStyleFor: "\u041D\u0435\u0432\u0456\u0440\u043D\u0438\u0439 \u0441\u0438\u043D\u0442\u0430\u043A\u0441\u0438\u0441 \u0434\u043B\u044F %1",
PositiveIntegerArg: "\u0410\u0440\u0433\u0443\u043C\u0435\u043D\u0442 \u0434\u043B\u044F %1 \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0431\u0443\u0442\u0438 \u0434\u043E\u0434\u0430\u0442\u043D\u0438\u043C \u0446\u0456\u043B\u0438\u043C \u0447\u0438\u0441\u043B\u043E\u043C",
ErroneousNestingEq: "\u041F\u043E\u043C\u0438\u043B\u043A\u043E\u0432\u0456 \u0432\u043A\u043B\u0430\u0434\u0435\u043D\u043E\u0441\u0442\u0456 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440 \u0440\u0456\u0432\u043D\u044F\u043D\u043D\u044F",
MultlineRowsOneCol: "\u0420\u044F\u0434\u043A\u0438 \u0443 \u0441\u0435\u0440\u0435\u0434\u043E\u0432\u0438\u0449\u0456 %1 \u043C\u0443\u0441\u044F\u0442\u044C \u043C\u0430\u0442\u0438 \u043B\u0438\u0448\u0435 \u043E\u0434\u0438\u043D \u0441\u0442\u043E\u0432\u043F\u0435\u0446\u044C",
MultipleBBoxProperty: "%1 \u0432\u043A\u0430\u0437\u0430\u043D\u043E \u0434\u0432\u0456\u0447\u0456 \u0432 %2",
InvalidBBoxProperty: "'%1' \u0437\u043E\u0432\u0441\u0456\u043C \u043D\u0435 \u0441\u0445\u043E\u0436\u0438\u0439 \u043D\u0430 \u043A\u043E\u043B\u0456\u0440, \u0434\u043E\u0434\u0430\u0442\u043A\u043E\u0432\u0438\u0439 \u0440\u043E\u0437\u043C\u0456\u0440 \u0430\u0431\u043E \u0441\u0442\u0438\u043B\u044C",
ExtraEndMissingBegin: "\u0417\u0430\u0439\u0432\u0430 %1 \u0430\u0431\u043E \u0432\u0456\u0434\u0441\u0443\u0442\u043D\u044F \\begingroup",
GlobalNotFollowedBy: "%1 \u043D\u0435 \u0441\u043B\u0456\u0434\u0443\u0454 \u043F\u0456\u0441\u043B\u044F \\let, \\def \u0430\u0431\u043E \\newcommand",
UndefinedColorModel: "\u041A\u043E\u043B\u0456\u0440\u043D\u0430 \u043C\u043E\u0434\u0435\u043B\u044C '%1' \u043D\u0435 \u0432\u0438\u0437\u043D\u0430\u0447\u0435\u043D\u0430",
ModelArg1: "\u0417\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u043A\u043E\u043B\u044C\u043E\u0440\u0443 \u0434\u043B\u044F \u043C\u043E\u0434\u0435\u043B\u0456 %1 \u0432\u0438\u043C\u0430\u0433\u0430\u044E\u0442\u044C 3 \u0446\u0438\u0444\u0440\u0438",
InvalidDecimalNumber: "\u041D\u0435\u0432\u0456\u0440\u043D\u0435 \u0434\u0435\u0441\u044F\u0442\u043A\u043E\u0432\u0435 \u0447\u0438\u0441\u043B\u043E",
ModelArg2: "\u0417\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u043A\u043E\u043B\u044C\u043E\u0440\u0443 \u0434\u043B\u044F \u043C\u043E\u0434\u0435\u043B\u0456 %1 \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043C\u0456\u0436 \u0442\u0435\u0433\u0430\u043C\u0438 %2 \u0456 %3",
InvalidNumber: "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E",
NewextarrowArg1: "\u041F\u0435\u0440\u0448\u0438\u0439 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442 %1 \u043C\u0430\u0454 \u0431\u0443\u0442\u0438 \u043D\u0430\u0437\u0432\u043E\u044E \u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u043A\u0435\u0440\u0456\u0432\u043D\u043E\u0457 \u043F\u043E\u0441\u043B\u0456\u0434\u043E\u0432\u043D\u043E\u0441\u0442\u0456",
NewextarrowArg2: "\u0414\u0440\u0443\u0433\u0438\u0439 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442 \u0434\u043B\u044F %1 \u043C\u0430\u0454 \u0431\u0443\u0442\u0438 \u0434\u0432\u043E\u043C\u0430 \u0446\u0456\u043B\u0438\u043C\u0438 \u0447\u0438\u0441\u043B\u0430\u043C\u0438, \u0440\u043E\u0437\u0434\u0456\u043B\u0435\u043D\u0438\u043C\u0438 \u043A\u043E\u043C\u0430\u043C\u0438",
NewextarrowArg3: "\u0422\u0440\u0435\u0442\u0456\u0439 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442 \u0434\u043B\u044F %1 \u043C\u0430\u0454 \u0431\u0443\u0442\u0438 \u0447\u0438\u0441\u043B\u043E\u0432\u0438\u043C \u044E\u043D\u0456\u043A\u043E\u0434\u043D\u0438\u043C \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u043C",
NoClosingChar: "\u041D\u0435 \u043C\u043E\u0436\u043B\u0438\u0432\u043E \u0437\u043D\u0430\u0439\u0442\u0438 \u0432\u0456\u0434\u043A\u0440\u0438\u0432\u0430\u044E\u0447\u043E\u0457 %1",
IllegalControlSequenceName: "\u041D\u0435\u0432\u0456\u0440\u043D\u0435 \u0456\u043C'\u044F \u043A\u0435\u0440\u0456\u0432\u043D\u043E\u0457 \u043F\u043E\u0441\u043B\u0456\u0434\u043E\u0432\u043D\u043E\u0441\u0442\u0456 \u0434\u043B\u044F %1",
IllegalParamNumber: "\u041D\u0435\u0432\u0456\u0440\u043D\u0435 \u0447\u0438\u0441\u043B\u043E \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0456\u0432, \u0437\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0445 \u0443 %1",
MissingCS: "\u041F\u0456\u0441\u043B\u044F %1 \u043C\u0443\u0441\u0438\u0442\u044C \u0441\u043B\u0456\u0434\u0443\u0432\u0430\u0442\u0438 \u043A\u0435\u0440\u0456\u0432\u043D\u0430 \u043F\u043E\u0441\u043B\u0456\u0434\u043E\u0432\u043D\u0456\u0441\u0442\u044C",
CantUseHash2: "\u041D\u0435\u0437\u0430\u043A\u043E\u043D\u043D\u0435 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u0430\u043D\u043D\u044F # \u0443 \u0448\u0430\u0431\u043B\u043E\u043D\u0456 \u0434\u043B\u044F %1",
SequentialParam: "\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0438 \u0434\u043B\u044F %1 \u043F\u043E\u0432\u0438\u043D\u043D\u0456 \u0431\u0443\u0442\u0438 \u043F\u0440\u043E\u043D\u0443\u043C\u0435\u0440\u043E\u0432\u0430\u043D\u0456 \u043F\u043E\u0441\u043B\u0456\u0434\u043E\u0432\u043D\u043E",
MissingReplacementString: "\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 \u0440\u044F\u0434\u043E\u043A \u0437\u0430\u043C\u0456\u043D\u0438 \u0434\u043B\u044F \u0432\u0438\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F %1",
MismatchUseDef: "\u0412\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u0430\u043D\u043D\u044F %1 \u043D\u0435 \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0454 \u0439\u043E\u0433\u043E \u0432\u0438\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044E",
RunawayArgument: "\u0412\u0442\u0440\u0430\u0447\u0435\u043D\u0438\u0439 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442 \u0434\u043B\u044F %1?",
NoClosingDelim: "\u041D\u0435 \u0432\u0434\u0430\u043B\u043E\u0441\u044F \u0437\u043D\u0430\u0439\u0442\u0438 \u0437\u0430\u043A\u0440\u0438\u0432\u0430\u044E\u0447\u043E\u0433\u043E \u0440\u043E\u0437\u0434\u0456\u043B\u044C\u043D\u0438\u043A\u0430 \u0434\u043B\u044F%1"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/uk/TeX.js");
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
cache: true,
entry: path.join(__dirname, '/modules/index.js'),
externals: [
{
"react": {
root: "React",
commonjs2: "react",
commonjs: "react",
amd: "react"
}
}
],
output: {
path: path.join(__dirname, '/dist'),
filename: 'radium.js',
library: 'Radium',
libraryTarget: 'umd'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader?stage=0'
}
]
}
}
|
"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var React=_interopRequireWildcard(require("react")),AccordionContext=React.createContext({});"production"!==process.env.NODE_ENV&&(AccordionContext.displayName="AccordionContext");var _default=AccordionContext;exports.default=AccordionContext; |
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/STIX/General/Regular/GreekItalic.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Hub.Insert(
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral'],
{
0x1D6E2: [667,0,717,35,685], // MATHEMATICAL ITALIC CAPITAL ALPHA
0x1D6E3: [653,0,696,38,686], // MATHEMATICAL ITALIC CAPITAL BETA
0x1D6E4: [653,0,616,38,721], // MATHEMATICAL ITALIC CAPITAL GAMMA
0x1D6E5: [667,0,596,30,556], // MATHEMATICAL ITALIC CAPITAL DELTA
0x1D6E6: [653,0,714,38,734], // MATHEMATICAL ITALIC CAPITAL EPSILON
0x1D6E7: [653,0,772,60,802], // MATHEMATICAL ITALIC CAPITAL ZETA
0x1D6E8: [653,0,873,38,923], // MATHEMATICAL ITALIC CAPITAL ETA
0x1D6E9: [669,11,737,50,712], // MATHEMATICAL ITALIC CAPITAL THETA
0x1D6EA: [653,0,480,38,530], // MATHEMATICAL ITALIC CAPITAL IOTA
0x1D6EB: [653,0,762,38,802], // MATHEMATICAL ITALIC CAPITAL KAPPA
0x1D6EC: [667,0,718,35,686], // MATHEMATICAL ITALIC CAPITAL LAMDA
0x1D6ED: [653,0,1005,38,1055], // MATHEMATICAL ITALIC CAPITAL MU
0x1D6EE: [653,0,851,38,901], // MATHEMATICAL ITALIC CAPITAL NU
0x1D6EF: [653,0,706,52,741], // MATHEMATICAL ITALIC CAPITAL XI
0x1D6F0: [669,11,732,50,712], // MATHEMATICAL ITALIC CAPITAL OMICRON
0x1D6F1: [653,0,873,38,923], // MATHEMATICAL ITALIC CAPITAL PI
0x1D6F2: [653,0,594,38,704], // MATHEMATICAL ITALIC CAPITAL RHO
0x1D6F3: [669,11,737,50,712], // MATHEMATICAL ITALIC CAPITAL THETA SYMBOL
0x1D6F4: [653,0,735,58,760], // MATHEMATICAL ITALIC CAPITAL SIGMA
0x1D6F5: [653,0,550,25,670], // MATHEMATICAL ITALIC CAPITAL TAU
0x1D6F6: [668,0,613,28,743], // MATHEMATICAL ITALIC CAPITAL UPSILON
0x1D6F7: [653,0,772,25,747], // MATHEMATICAL ITALIC CAPITAL PHI
0x1D6F8: [653,0,790,25,810], // MATHEMATICAL ITALIC CAPITAL CHI
0x1D6F9: [667,0,670,28,743], // MATHEMATICAL ITALIC CAPITAL PSI
0x1D6FA: [666,0,800,32,777], // MATHEMATICAL ITALIC CAPITAL OMEGA
0x1D6FB: [653,15,627,42,600], // MATHEMATICAL ITALIC NABLA
0x1D6FC: [441,10,524,40,529], // MATHEMATICAL ITALIC SMALL ALPHA
0x1D6FD: [668,183,493,25,518], // MATHEMATICAL ITALIC SMALL BETA
0x1D6FE: [441,187,428,35,458], // MATHEMATICAL ITALIC SMALL GAMMA
0x1D6FF: [668,11,463,40,451], // MATHEMATICAL ITALIC SMALL DELTA
0x1D700: [441,11,484,25,444], // MATHEMATICAL ITALIC SMALL EPSILON
0x1D701: [668,183,435,40,480], // MATHEMATICAL ITALIC SMALL ZETA
0x1D702: [441,183,460,30,455], // MATHEMATICAL ITALIC SMALL ETA
0x1D703: [668,11,484,40,474], // MATHEMATICAL ITALIC SMALL THETA
0x1D704: [441,11,267,50,227], // MATHEMATICAL ITALIC SMALL IOTA
0x1D705: [441,0,534,50,549], // MATHEMATICAL ITALIC SMALL KAPPA
0x1D706: [668,16,541,50,511], // MATHEMATICAL ITALIC SMALL LAMDA
0x1D707: [428,183,579,30,549], // MATHEMATICAL ITALIC SMALL MU
0x1D708: [446,9,452,50,462], // MATHEMATICAL ITALIC SMALL NU
0x1D709: [668,183,433,25,443], // MATHEMATICAL ITALIC SMALL XI
0x1D70A: [441,11,458,40,438], // MATHEMATICAL ITALIC SMALL OMICRON
0x1D70B: [428,13,558,35,568], // MATHEMATICAL ITALIC SMALL PI
0x1D70C: [441,183,502,30,472], // MATHEMATICAL ITALIC SMALL RHO
0x1D70D: [490,183,439,35,464], // MATHEMATICAL ITALIC SMALL FINAL SIGMA
0x1D70E: [428,11,537,40,547], // MATHEMATICAL ITALIC SMALL SIGMA
0x1D70F: [428,5,442,30,472], // MATHEMATICAL ITALIC SMALL TAU
0x1D710: [439,11,460,30,445], // MATHEMATICAL ITALIC SMALL UPSILON
0x1D711: [441,183,666,50,631], // MATHEMATICAL ITALIC SMALL PHI
0x1D712: [441,202,595,30,645], // MATHEMATICAL ITALIC SMALL CHI
0x1D713: [441,183,661,30,711], // MATHEMATICAL ITALIC SMALL PSI
0x1D714: [441,11,681,20,661], // MATHEMATICAL ITALIC SMALL OMEGA
0x1D715: [668,11,471,40,471], // MATHEMATICAL ITALIC PARTIAL DIFFERENTIAL
0x1D716: [441,11,430,40,430], // MATHEMATICAL ITALIC EPSILON SYMBOL
0x1D717: [678,10,554,20,507], // MATHEMATICAL ITALIC THETA SYMBOL
0x1D718: [441,13,561,12,587], // MATHEMATICAL ITALIC KAPPA SYMBOL
0x1D719: [668,183,645,40,620], // MATHEMATICAL ITALIC PHI SYMBOL
0x1D71A: [441,187,509,40,489], // MATHEMATICAL ITALIC RHO SYMBOL
0x1D71B: [428,11,856,30,866] // MATHEMATICAL ITALIC PI SYMBOL
}
);
MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Regular/GreekItalic.js");
|
/* flatpickr v4.0.6, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.pt = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined
? window.flatpickr
: {
l10ns: {},
};
var Portuguese = {
weekdays: {
shorthand: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"],
longhand: [
"Domingo",
"Segunda-feira",
"Terça-feira",
"Quarta-feira",
"Quinta-feira",
"Sexta-feira",
"Sábado",
],
},
months: {
shorthand: [
"Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez",
],
longhand: [
"Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro",
],
},
rangeSeparator: " até ",
};
fp.l10ns.pt = Portuguese;
var pt = fp.l10ns;
exports.Portuguese = Portuguese;
exports['default'] = pt;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
// Copyright (c) 2017, Frappe Technologies and contributors
// For license information, please see license.txt
frappe.ui.form.on('Salutation', {
refresh: function() {
}
});
|
/*!
* froala_editor v2.6.2 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2017 Froala Labs
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function( root, jQuery ) {
if ( jQuery === undefined ) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if ( typeof window !== 'undefined' ) {
jQuery = require('jquery');
}
else {
jQuery = require('jquery')(root);
}
}
return factory(jQuery);
};
} else {
// Browser globals
factory(window.jQuery);
}
}(function ($) {
/**
* Bosnian
*/
$.FE.LANGUAGE['bs'] = {
translation: {
// Place holder
"Type something": "Ukucajte ne\u0161tp",
// Basic formatting
"Bold": "Bold",
"Italic": "Italic",
"Underline": "Podvu\u010deno",
"Strikethrough": "Precrtano",
// Main buttons
"Insert": "Umetni",
"Delete": "Obri\u0161i",
"Cancel": "Otka\u017ei",
"OK": "U redu",
"Back": "Natrag",
"Remove": "Ukloni",
"More": "Vi\u0161e",
"Update": "A\u017euriranje",
"Style": "Stil",
// Font
"Font Family": "Odaberi font",
"Font Size": "Veli\u010dina fonta",
// Colors
"Colors": "Boje",
"Background": "Pozadine",
"Text": "Teksta",
// Paragraphs
"Paragraph Format": "Paragraf formatu",
"Normal": "Normalno",
"Code": "Izvorni kod",
"Heading 1": "Naslov 1",
"Heading 2": "Naslov 2",
"Heading 3": "Naslov 3",
"Heading 4": "Naslov 4",
// Style
"Paragraph Style": "Paragraf stil",
"Inline Style": "Inline stil",
// Alignment
"Alignment": "Poravnanje",
"Align Left": "Poravnaj lijevo",
"Align Center": "Poravnaj po sredini",
"Align Right": "Poravnaj desno",
"Align Justify": "Obostrano poravnanje",
"None": "Nijedan",
// Lists
"Ordered List": "Ure\u0111ena lista",
"Unordered List": "Nesre\u0111ene lista",
// Indent
"Decrease Indent": "Smanjenje alineja",
"Increase Indent": "Pove\u0107anje alineja",
// Links
"Insert Link": "Umetni link",
"Open in new tab": "Otvori u novom prozoru",
"Open Link": "Otvori link",
"Edit Link": "Uredi link",
"Unlink": "Ukloni link",
"Choose Link": "Izabrati link",
// Images
"Insert Image": "Umetni sliku",
"Upload Image": "Upload sliku",
"By URL": "Preko URL",
"Browse": "Pregledaj",
"Drop image": "Izbaci sliku",
"or click": "ili odaberi",
"Manage Images": "Upravljanje ilustracijama",
"Loading": "Koji tovari",
"Deleting": "Brisanje",
"Tags": "Oznake",
"Are you sure? Image will be deleted.": "Da li ste sigurni da \u017eelite da obri\u0161ete ovu ilustraciju?",
"Replace": "Zamijenite",
"Uploading": "Uploading",
"Loading image": "Koji tovari sliku",
"Display": "Prikaz",
"Inline": "Inline",
"Break Text": "Break tekst",
"Alternate Text": "Alternativna tekst",
"Change Size": "Promijeni veli\u010dinu",
"Width": "\u0161irina",
"Height": "Visina",
"Something went wrong. Please try again.": "Ne\u0161to je po\u0161lo po zlu. Molimo vas da poku\u0161ate ponovo.",
// Video
"Insert Video": "Umetni video",
"Embedded Code": "Embedded kod",
// Tables
"Insert Table": "Umetni tabelu",
"Table Header": "Tabelu zaglavlja",
"Remove Table": "Uklonite tabelu",
"Table Style": "Tabela stil",
"Horizontal Align": "Horizontalno poravnaj",
"Row": "Red",
"Insert row above": "Umetni red iznad",
"Insert row below": "Umetni red ispod",
"Delete row": "Obri\u0161i red",
"Column": "Kolona",
"Insert column before": "Umetni kolonu prije",
"Insert column after": "Umetni kolonu poslije",
"Delete column": "Obri\u0161i kolonu",
"Cell": "\u0106elija",
"Merge cells": "Spoji \u0107elija",
"Horizontal split": "Horizontalno razdvajanje polja",
"Vertical split": "Vertikalno razdvajanje polja",
"Cell Background": "\u0106elija pozadini",
"Vertical Align": "Vertikalni poravnaj",
"Top": "Vrh",
"Middle": "Srednji",
"Bottom": "Dno",
"Align Top": "Poravnaj vrh",
"Align Middle": "Poravnaj srednji",
"Align Bottom": "Poravnaj dno",
"Cell Style": "\u0106elija stil",
// Files
"Upload File": "Upload datoteke",
"Drop file": "Drop datoteke",
// Emoticons
"Emoticons": "Emotikona",
"Grinning face": "Cere\u0107i lice",
"Grinning face with smiling eyes": "Cere\u0107i lice nasmijana o\u010dima",
"Face with tears of joy": "Lice sa suze radosnice",
"Smiling face with open mouth": "Nasmijana lica s otvorenih usta",
"Smiling face with open mouth and smiling eyes": "Nasmijana lica s otvorenih usta i nasmijana o\u010di",
"Smiling face with open mouth and cold sweat": "Nasmijana lica s otvorenih usta i hladan znoj",
"Smiling face with open mouth and tightly-closed eyes": "Nasmijana lica s otvorenih usta i \u010dvrsto-zatvorenih o\u010diju",
"Smiling face with halo": "Nasmijana lica sa halo",
"Smiling face with horns": "Nasmijana lica s rogovima",
"Winking face": "Namigivanje lice",
"Smiling face with smiling eyes": "Nasmijana lica sa nasmijana o\u010dima",
"Face savoring delicious food": "Suo\u010davaju u\u017eivaju\u0107i ukusna hrana",
"Relieved face": "Laknulo lice",
"Smiling face with heart-shaped eyes": "Nasmijana lica sa obliku srca o\u010di",
"Smiling face with sunglasses": "Nasmijana lica sa sun\u010dane nao\u010dare",
"Smirking face": "Namr\u0161tena lica",
"Neutral face": "Neutral lice",
"Expressionless face": "Bezizra\u017eajno lice",
"Unamused face": "Nije zabavno lice",
"Face with cold sweat": "Lice s hladnim znojem",
"Pensive face": "Zami\u0161ljen lice",
"Confused face": "Zbunjen lice",
"Confounded face": "Uzbu\u0111en lice",
"Kissing face": "Ljubakanje lice",
"Face throwing a kiss": "Suo\u010davaju bacanje poljubac",
"Kissing face with smiling eyes": "Ljubljenje lice nasmijana o\u010dima",
"Kissing face with closed eyes": "Ljubljenje lice sa zatvorenim o\u010dima",
"Face with stuck out tongue": "Lice sa ispru\u017eio jezik",
"Face with stuck out tongue and winking eye": "Lice sa ispru\u017eio jezik i trep\u0107u\u0107e \u0107e oko",
"Face with stuck out tongue and tightly-closed eyes": "Lice sa ispru\u017eio jezik i \u010dvrsto zatvorene o\u010di",
"Disappointed face": "Razo\u010daran lice",
"Worried face": "Zabrinuti lice",
"Angry face": "Ljut lice",
"Pouting face": "Napu\u0107enim lice",
"Crying face": "Plakanje lice",
"Persevering face": "Istrajan lice",
"Face with look of triumph": "Lice s pogledom trijumfa",
"Disappointed but relieved face": "Razo\u010daran, ali olak\u0161anje lice",
"Frowning face with open mouth": "Namr\u0161tiv\u0161i lice s otvorenih usta",
"Anguished face": "Bolnom lice",
"Fearful face": "Pla\u0161ljiv lice",
"Weary face": "Umoran lice",
"Sleepy face": "Pospan lice",
"Tired face": "Umorno lice",
"Grimacing face": "Grimase lice",
"Loudly crying face": "Glasno pla\u010de lice",
"Face with open mouth": "Lice s otvorenih usta",
"Hushed face": "Smiren lice",
"Face with open mouth and cold sweat": "Lice s otvorenih usta i hladan znoj",
"Face screaming in fear": "Suo\u010davaju vri\u0161ti u strahu",
"Astonished face": "Zapanjen lice",
"Flushed face": "Rumeno lice",
"Sleeping face": "Usnulo lice",
"Dizzy face": "O\u0161amu\u0107en lice",
"Face without mouth": "Lice bez usta",
"Face with medical mask": "Lice sa medicinskom maskom",
// Line breaker
"Break": "Slomiti",
// Math
"Subscript": "Potpisan",
"Superscript": "Natpis",
// Full screen
"Fullscreen": "Preko cijelog zaslona",
// Horizontal line
"Insert Horizontal Line": "Umetni vodoravna liniju",
// Clear formatting
"Clear Formatting": "Izbrisati formatiranje",
// Undo, redo
"Undo": "Korak nazad",
"Redo": "Korak naprijed",
// Select all
"Select All": "Ozna\u010di sve",
// Code view
"Code View": "Kod pogled",
// Quote
"Quote": "Citat",
"Increase": "Pove\u0107ati",
"Decrease": "Smanjenje",
// Quick Insert
"Quick Insert": "Brzo umetak"
},
direction: "ltr"
};
}));
|
/**
* Entry point for the Firebase functions of the Screenshot tool. Firebase functions only support
* JavaScript files and therefore the TypeScript files needs to be transpiled. Using ts-node
* seems to be more elegant for now, because Firebase requires the `node_modules` to be copied
* to the output directory and when using TSC the `node_modules` won't be copied to the destination.
*/
'use strict';
const path = require('path');
// Enable TypeScript compilation at runtime using ts-node.
require('ts-node').register({
project: path.join(__dirname, 'tsconfig.json')
});
const functionExports = require('./screenshot-functions');
// Re-export every firebase function from TypeScript
Object.keys(functionExports).forEach(fnName => {
module.exports[fnName] = functionExports[fnName];
});
|
// File: chapter13/directive-no-transclusion/directive.js
angular.module('stockMarketApp')
.directive('stockWidget', [function() {
return {
templateUrl: 'stock.html',
restrict: 'A',
scope: {
stockData: '='
},
link: function($scope, $element, $attrs) {
$scope.getChange = function(stock) {
return Math.ceil(((stock.price - stock.previous) /
stock.previous) * 100);
};
}
};
}]);
|
var punycode = {};
try { punycode = require("punycode"); } catch (e) { }
module.exports = punycode; |
var miniSurvey ={
bid:0,
serviceURL: $("input[name=miniSurveyServices]").val() + '?block=form&',
init: function(){
this.tabSetup();
/*
for(var i=0;i<this.answerTypes.length;i++){
this.answerTypes[i].onclick=function(){miniSurvey.optionsCheck(this);miniSurvey.settingsCheck(this);}
this.answerTypes[i].onchange=function(){miniSurvey.optionsCheck(this);miniSurvey.settingsCheck(this);}
}
for(var i=0;i<this.answerTypesEdit.length;i++){
this.answerTypesEdit[i].onclick=function(){miniSurvey.optionsCheck(this,'Edit');miniSurvey.settingsCheck(this,'Edit');}
this.answerTypesEdit[i].onchange=function(){miniSurvey.optionsCheck(this,'Edit');miniSurvey.settingsCheck(this,'Edit');}
}
*/
$("#answerType").change(function(r) {
miniSurvey.optionsCheck($('#answerType').get(0));
miniSurvey.settingsCheck($('#answerType').get(0));
});
$("#answerTypeEdit").change(function(r) {
miniSurvey.optionsCheck($('#answerTypeEdit').get(0), 'Edit');
miniSurvey.settingsCheck($('#answerTypeEdit').get(0), 'Edit');
});
$('#refreshButton').click( function(){ miniSurvey.refreshSurvey(); return false; } );
$('#addQuestion').click( function(){ miniSurvey.addQuestion(); return false; } );
$('#editQuestion').click( function(){ miniSurvey.addQuestion('Edit'); return false; } );
$('#cancelEditQuestion').click( function(){ $('#editQuestionForm').css('display','none') } );
this.serviceURL+='cID='+this.cID+'&arHandle='+this.arHandle+'&bID='+this.bID+'&btID='+this.btID+'&';
miniSurvey.refreshSurvey();
$('#emailSettings').hide();
},
tabSetup: function(){
$('ul#ccm-formblock-tabs li a').each( function(num,el){
el.onclick=function(){
var pane=this.id.replace('ccm-formblock-tab-','');
miniSurvey.showPane(pane);
}
});
},
showPane:function(pane){
$('ul#ccm-formblock-tabs li').each(function(num,el){ $(el).removeClass('active') });
$(document.getElementById('ccm-formblock-tab-'+pane).parentNode).addClass('active');
$('div.ccm-formBlockPane').each(function(num,el){ el.style.display='none'; });
$('#ccm-formBlockPane-'+pane).css('display','block');
},
refreshSurvey : function(){
$.ajax({
url: this.serviceURL+'mode=refreshSurvey&qsID='+parseInt(this.qsID)+'&hide='+miniSurvey.hideQuestions.join(','),
success: function(msg){ $('#miniSurveyPreviewWrap').html(msg); }
});
$.ajax({
url: this.serviceURL+'mode=refreshSurvey&qsID='+parseInt(this.qsID)+'&showEdit=1&hide='+miniSurvey.hideQuestions.join(','),
success: function(msg){ $('#miniSurveyWrap').html(msg); }
});
},
optionsCheck : function(radioButton,mode){
if(mode!='Edit') mode='';
if( radioButton.value=='select' || radioButton.value=='radios' || radioButton.value=='checkboxlist'){
$('#answerOptionsArea'+mode).css('display','block');
}else $('#answerOptionsArea'+mode).css('display','none');
if( radioButton.value=='email') {
$('#emailSettings'+mode).show();
} else {
$('#emailSettings'+mode).hide();
}
},
settingsCheck : function(radioButton,mode){
if(mode!='Edit') mode='';
if( radioButton.value=='text'){
$('#answerSettings'+mode).css('display','block');
}else {
$('#answerSettings'+mode).css('display','none');
}
},
addQuestion : function(mode){
var msqID=0;
if(mode!='Edit') {
mode='';
} else {
msqID=parseInt($('#msqID').val(), 10);
}
var formID = '#answerType'+mode;
answerType = $(formID).val();
var options = encodeURIComponent($('#answerOptions'+mode).val());
var postStr='question='+encodeURIComponent($('#question'+mode).val())+'&options='+options;
postStr+='&width='+escape($('#width'+mode).val());
postStr+='&height='+escape($('#height'+mode).val());
var req = $('#required'+mode+' input[value=1]').prop('checked') ? 1 : 0;
postStr+='&required='+req;
postStr+='&position='+escape($('#position'+mode).val());
var form=document.getElementById('ccm-block-form');
postStr+='&inputType='+answerType;//$('input[name=answerType'+mode+']:checked').val()
postStr+='&msqID='+msqID+'&qsID='+parseInt(this.qsID);
if(answerType == 'email') {
postStr+='&send_notification_from=';
if (mode == 'Edit') {
fieldID = "#send_notification_from_edit";
}
else {
fieldID = "#send_notification_from";
}
postStr+= $(fieldID).is(':checked') ? "1" : "0"
}
$.ajax({
type: "POST",
data: postStr,
url: this.serviceURL+'mode=addQuestion&qsID='+parseInt(this.qsID),
success: function(msg){
eval('var jsonObj='+msg);
if(!jsonObj){
alert(ccm_t('ajax-error'));
}else if(jsonObj.noRequired){
alert(ccm_t('complete-required'));
}else{
if(jsonObj.mode=='Edit'){
var questionMsg = $('#questionEditedMsg');
questionMsg.fadeIn();
setTimeout(function(){
questionMsg.fadeOut();
}, 5000);
if(jsonObj.hideQID){
miniSurvey.hideQuestions.push( miniSurvey.edit_qID ); //jsonObj.hideQID);
miniSurvey.edit_qID=0;
}
}else{
var questionMsg = $('#questionAddedMsg');
questionMsg.fadeIn();
setTimeout(function(){
questionMsg.fadeOut();
}, 5000);
//miniSurvey.saveOrder();
}
$('#editQuestionForm').css('display','none');
miniSurvey.qsID=jsonObj.qsID;
miniSurvey.ignoreQuestionId(jsonObj.msqID);
$('#qsID').val(jsonObj.qsID);
miniSurvey.resetQuestion();
miniSurvey.refreshSurvey();
//miniSurvey.showPane('preview');
}
}
});
},
//prevent duplication of these questions, for block question versioning
ignoreQuestionId:function(msqID){
var msqID, ignoreEl=$('#ccm-ignoreQuestionIDs');
if(ignoreEl.val()) msqIDs=ignoreEl.val().split(',');
else msqIDs=[];
msqIDs.push( parseInt(msqID, 10) );
ignoreEl.val( msqIDs.join(',') );
},
reloadQuestion : function(qID){
$.ajax({
url: this.serviceURL+"mode=getQuestion&qsID="+parseInt(this.qsID)+'&qID='+parseInt(qID),
success: function(msg){
eval('var jsonObj='+msg);
$('#editQuestionForm').css('display','block')
$('#questionEdit').val(jsonObj.question);
$('#answerOptionsEdit').val(jsonObj.optionVals.replace(/%%/g,"\r\n") );
$('#widthEdit').val(jsonObj.width);
$('#heightEdit').val(jsonObj.height);
$('#positionEdit').val(jsonObj.position);
if (parseInt(jsonObj.required, 10) == 1) {
$('#requiredEdit input[value=1]').prop('checked', true);
$('#requiredEdit input[value=0]').prop('checked', false);
} else {
$('#requiredEdit input[value=1]').prop('checked', false);
$('#requiredEdit input[value=0]').prop('checked', true);
}
if(jsonObj.inputType == 'email') {
var options = jsonObj.optionVals.split(";");
for (var i = 0; i < options.length; i++) {
key_val = options[i].split('::');
if(key_val.length == 2) {
if (key_val[0] == 'send_notification_from') {
if (key_val[1] == 1) {
$('.send_notification_from input').prop('checked', true);
} else {
$('.send_notification_from input').prop('checked', false);
}
}
}
}
}
$('#msqID').val(jsonObj.msqID);
$('#answerTypeEdit').val(jsonObj.inputType);
miniSurvey.optionsCheck($('#answerTypeEdit').get(0), 'Edit');
miniSurvey.settingsCheck($('#answerTypeEdit').get(0), 'Edit');
if(parseInt(jsonObj.bID)>0)
miniSurvey.edit_qID = parseInt(qID) ;
$('.miniSurveyOptions').first().closest('.ui-dialog-content').get(0).scrollTop = 0;
}
});
},
//prevent duplication of these questions, for block question versioning
pendingDeleteQuestionId:function(msqID){
var msqID, el=$('#ccm-pendingDeleteIDs');
if(el.val()) msqIDs=el.val().split(',');
else msqIDs=[];
msqIDs.push( parseInt(msqID, 10) );
el.val( msqIDs.join(',') );
},
hideQuestions : [],
deleteQuestion : function(el,msqID,qID){
if(confirm(ccm_t('delete-question'))) {
$.ajax({
url: this.serviceURL+"mode=delQuestion&qsID="+parseInt(this.qsID)+'&msqID='+parseInt(msqID),
success: function(msg){ miniSurvey.resetQuestion(); miniSurvey.refreshSurvey(); }
});
miniSurvey.ignoreQuestionId(msqID);
miniSurvey.hideQuestions.push(qID);
miniSurvey.pendingDeleteQuestionId(msqID)
}
},
resetQuestion : function(){
$('#question').val('');
$('#answerOptions').val('');
$('#width').val('50');
$('#height').val('3');
$('#msqID').val('');
$('#answerType').val('field').change();
$('#answerOptionsArea').hide();
$('#answerSettings').hide();
$('#required input').prop('checked', false);
},
validate:function(){
var failed=0;
var n=$('#surveyName');
if( !n || parseInt(n.val().length, 10)==0 ){
alert(ccm_t('form-name'));
this.showPane('options');
n.focus();
failed=1;
}
var Qs=$('.miniSurveyQuestionRow');
if( !Qs || parseInt(Qs.length, 10)<1 ){
alert(ccm_t('form-min-1'));
failed=1;
}
if(failed){
ccm_isBlockError=1;
return false;
}
return true;
},
moveUp:function(el,thisQID){
var qIDs=this.serialize();
var previousQID=0;
for(var i=0;i<qIDs.length;i++){
if(qIDs[i]==thisQID){
if(previousQID==0) break;
$('#miniSurveyQuestionRow'+thisQID).after($('#miniSurveyQuestionRow'+previousQID));
break;
}
previousQID=qIDs[i];
}
this.saveOrder();
},
moveDown:function(el,thisQID){
var qIDs=this.serialize();
var thisQIDfound=0;
for(var i=0;i<qIDs.length;i++){
if(qIDs[i]==thisQID){
thisQIDfound=1;
continue;
}
if(thisQIDfound){
$('#miniSurveyQuestionRow'+qIDs[i]).after($('#miniSurveyQuestionRow'+thisQID));
break;
}
}
this.saveOrder();
},
serialize:function(){
var t = document.getElementById("miniSurveyPreviewTable");
var qIDs=[];
for(var i=0;i<t.childNodes.length;i++){
if( t.childNodes[i].className && t.childNodes[i].className.indexOf('miniSurveyQuestionRow')>=0 ){
var qID=t.childNodes[i].id.substr('miniSurveyQuestionRow'.length);
qIDs.push(qID);
}
}
return qIDs;
},
saveOrder:function(){
var postStr='qIDs='+this.serialize().join(',')+'&qsID='+parseInt(this.qsID);
$.ajax({
type: "POST",
data: postStr,
url: this.serviceURL+"mode=reorderQuestions",
success: function(msg){
miniSurvey.refreshSurvey();
}
});
}
};
ccmValidateBlockForm = function() { return miniSurvey.validate(); };
$(document).ready(function(){
//miniSurvey.init();
/* TODO hackzors, this shouldnt be necessary */
$('#ccm-block-form').closest('div').addClass('ccm-ui');
});
|
/*
YUI 3.18.1 (build f7e7bcb)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('event-synthetic', function (Y, NAME) {
/**
* Define new DOM events that can be subscribed to from Nodes.
*
* @module event
* @submodule event-synthetic
*/
var CustomEvent = Y.CustomEvent,
DOMMap = Y.Env.evt.dom_map,
toArray = Y.Array,
YLang = Y.Lang,
isObject = YLang.isObject,
isString = YLang.isString,
isArray = YLang.isArray,
query = Y.Selector.query,
noop = function () {};
/**
* <p>The triggering mechanism used by SyntheticEvents.</p>
*
* <p>Implementers should not instantiate these directly. Use the Notifier
* provided to the event's implemented <code>on(node, sub, notifier)</code> or
* <code>delegate(node, sub, notifier, filter)</code> methods.</p>
*
* @class SyntheticEvent.Notifier
* @constructor
* @param handle {EventHandle} the detach handle for the subscription to an
* internal custom event used to execute the callback passed to
* on(..) or delegate(..)
* @param emitFacade {Boolean} take steps to ensure the first arg received by
* the subscription callback is an event facade
* @private
* @since 3.2.0
*/
function Notifier(handle, emitFacade) {
this.handle = handle;
this.emitFacade = emitFacade;
}
/**
* <p>Executes the subscription callback, passing the firing arguments as the
* first parameters to that callback. For events that are configured with
* emitFacade=true, it is common practice to pass the triggering DOMEventFacade
* as the first parameter. Barring a proper DOMEventFacade or EventFacade
* (from a CustomEvent), a new EventFacade will be generated. In that case, if
* fire() is called with a simple object, it will be mixed into the facade.
* Otherwise, the facade will be prepended to the callback parameters.</p>
*
* <p>For notifiers provided to delegate logic, the first argument should be an
* object with a "currentTarget" property to identify what object to
* default as 'this' in the callback. Typically this is gleaned from the
* DOMEventFacade or EventFacade, but if configured with emitFacade=false, an
* object must be provided. In that case, the object will be removed from the
* callback parameters.</p>
*
* <p>Additional arguments passed during event subscription will be
* automatically added after those passed to fire().</p>
*
* @method fire
* @param {EventFacade|DOMEventFacade|any} e (see description)
* @param {any[]} [arg*] additional arguments received by all subscriptions
* @private
*/
Notifier.prototype.fire = function (e) {
// first arg to delegate notifier should be an object with currentTarget
var args = toArray(arguments, 0, true),
handle = this.handle,
ce = handle.evt,
sub = handle.sub,
thisObj = sub.context,
delegate = sub.filter,
event = e || {},
ret;
if (this.emitFacade) {
if (!e || !e.preventDefault) {
event = ce._getFacade();
if (isObject(e) && !e.preventDefault) {
Y.mix(event, e, true);
args[0] = event;
} else {
args.unshift(event);
}
}
event.type = ce.type;
event.details = args.slice();
if (delegate) {
event.container = ce.host;
}
} else if (delegate && isObject(e) && e.currentTarget) {
args.shift();
}
sub.context = thisObj || event.currentTarget || ce.host;
ret = ce.fire.apply(ce, args);
// have to handle preventedFn and stoppedFn manually because
// Notifier CustomEvents are forced to emitFacade=false
if (e.prevented && ce.preventedFn) {
ce.preventedFn.apply(ce, args);
}
if (e.stopped && ce.stoppedFn) {
ce.stoppedFn.apply(ce, args);
}
sub.context = thisObj; // reset for future firing
// to capture callbacks that return false to stopPropagation.
// Useful for delegate implementations
return ret;
};
/**
* Manager object for synthetic event subscriptions to aggregate multiple synths on the
* same node without colliding with actual DOM subscription entries in the global map of
* DOM subscriptions. Also facilitates proper cleanup on page unload.
*
* @class SynthRegistry
* @constructor
* @param el {HTMLElement} the DOM element
* @param yuid {String} the yuid stamp for the element
* @param key {String} the generated id token used to identify an event type +
* element in the global DOM subscription map.
* @private
*/
function SynthRegistry(el, yuid, key) {
this.handles = [];
this.el = el;
this.key = key;
this.domkey = yuid;
}
SynthRegistry.prototype = {
constructor: SynthRegistry,
// A few object properties to fake the CustomEvent interface for page
// unload cleanup. DON'T TOUCH!
type : '_synth',
fn : noop,
capture : false,
/**
* Adds a subscription from the Notifier registry.
*
* @method register
* @param handle {EventHandle} the subscription
* @since 3.4.0
*/
register: function (handle) {
handle.evt.registry = this;
this.handles.push(handle);
},
/**
* Removes the subscription from the Notifier registry.
*
* @method _unregisterSub
* @param sub {Subscription} the subscription
* @since 3.4.0
*/
unregister: function (sub) {
var handles = this.handles,
events = DOMMap[this.domkey],
i;
for (i = handles.length - 1; i >= 0; --i) {
if (handles[i].sub === sub) {
handles.splice(i, 1);
break;
}
}
// Clean up left over objects when there are no more subscribers.
if (!handles.length) {
delete events[this.key];
if (!Y.Object.size(events)) {
delete DOMMap[this.domkey];
}
}
},
/**
* Used by the event system's unload cleanup process. When navigating
* away from the page, the event system iterates the global map of element
* subscriptions and detaches everything using detachAll(). Normally,
* the map is populated with custom events, so this object needs to
* at least support the detachAll method to duck type its way to
* cleanliness.
*
* @method detachAll
* @private
* @since 3.4.0
*/
detachAll : function () {
var handles = this.handles,
i = handles.length;
while (--i >= 0) {
handles[i].detach();
}
}
};
/**
* <p>Wrapper class for the integration of new events into the YUI event
* infrastructure. Don't instantiate this object directly, use
* <code>Y.Event.define(type, config)</code>. See that method for details.</p>
*
* <p>Properties that MAY or SHOULD be specified in the configuration are noted
* below and in the description of <code>Y.Event.define</code>.</p>
*
* @class SyntheticEvent
* @constructor
* @param cfg {Object} Implementation pieces and configuration
* @since 3.1.0
* @in event-synthetic
*/
function SyntheticEvent() {
this._init.apply(this, arguments);
}
Y.mix(SyntheticEvent, {
Notifier: Notifier,
SynthRegistry: SynthRegistry,
/**
* Returns the array of subscription handles for a node for the given event
* type. Passing true as the third argument will create a registry entry
* in the event system's DOM map to host the array if one doesn't yet exist.
*
* @method getRegistry
* @param node {Node} the node
* @param type {String} the event
* @param create {Boolean} create a registration entry to host a new array
* if one doesn't exist.
* @return {Array}
* @static
* @protected
* @since 3.2.0
*/
getRegistry: function (node, type, create) {
var el = node._node,
yuid = Y.stamp(el),
key = 'event:' + yuid + type + '_synth',
events = DOMMap[yuid];
if (create) {
if (!events) {
events = DOMMap[yuid] = {};
}
if (!events[key]) {
events[key] = new SynthRegistry(el, yuid, key);
}
}
return (events && events[key]) || null;
},
/**
* Alternate <code>_delete()</code> method for the CustomEvent object
* created to manage SyntheticEvent subscriptions.
*
* @method _deleteSub
* @param sub {Subscription} the subscription to clean up
* @private
* @since 3.2.0
*/
_deleteSub: function (sub) {
if (sub && sub.fn) {
var synth = this.eventDef,
method = (sub.filter) ? 'detachDelegate' : 'detach';
this._subscribers = [];
if (CustomEvent.keepDeprecatedSubs) {
this.subscribers = {};
}
synth[method](sub.node, sub, this.notifier, sub.filter);
this.registry.unregister(sub);
delete sub.fn;
delete sub.node;
delete sub.context;
}
},
prototype: {
constructor: SyntheticEvent,
/**
* Construction logic for the event.
*
* @method _init
* @protected
*/
_init: function () {
var config = this.publishConfig || (this.publishConfig = {});
// The notification mechanism handles facade creation
this.emitFacade = ('emitFacade' in config) ?
config.emitFacade :
true;
config.emitFacade = false;
},
/**
* <p>Implementers MAY provide this method definition.</p>
*
* <p>Implement this function if the event supports a different
* subscription signature. This function is used by both
* <code>on()</code> and <code>delegate()</code>. The second parameter
* indicates that the event is being subscribed via
* <code>delegate()</code>.</p>
*
* <p>Implementations must remove extra arguments from the args list
* before returning. The required args for <code>on()</code>
* subscriptions are</p>
* <pre><code>[type, callback, target, context, argN...]</code></pre>
*
* <p>The required args for <code>delegate()</code>
* subscriptions are</p>
*
* <pre><code>[type, callback, target, filter, context, argN...]</code></pre>
*
* <p>The return value from this function will be stored on the
* subscription in the '_extra' property for reference elsewhere.</p>
*
* @method processArgs
* @param args {Array} parmeters passed to Y.on(..) or Y.delegate(..)
* @param delegate {Boolean} true if the subscription is from Y.delegate
* @return {any}
*/
processArgs: noop,
/**
* <p>Implementers MAY override this property.</p>
*
* <p>Whether to prevent multiple subscriptions to this event that are
* classified as being the same. By default, this means the subscribed
* callback is the same function. See the <code>subMatch</code>
* method. Setting this to true will impact performance for high volume
* events.</p>
*
* @property preventDups
* @type {Boolean}
* @default false
*/
//preventDups : false,
/**
* <p>Implementers SHOULD provide this method definition.</p>
*
* Implementation logic for subscriptions done via <code>node.on(type,
* fn)</code> or <code>Y.on(type, fn, target)</code>. This
* function should set up the monitor(s) that will eventually fire the
* event. Typically this involves subscribing to at least one DOM
* event. It is recommended to store detach handles from any DOM
* subscriptions to make for easy cleanup in the <code>detach</code>
* method. Typically these handles are added to the <code>sub</code>
* object. Also for SyntheticEvents that leverage a single DOM
* subscription under the hood, it is recommended to pass the DOM event
* object to <code>notifier.fire(e)</code>. (The event name on the
* object will be updated).
*
* @method on
* @param node {Node} the node the subscription is being applied to
* @param sub {Subscription} the object to track this subscription
* @param notifier {SyntheticEvent.Notifier} call notifier.fire(..) to
* trigger the execution of the subscribers
*/
on: noop,
/**
* <p>Implementers SHOULD provide this method definition.</p>
*
* <p>Implementation logic for detaching subscriptions done via
* <code>node.on(type, fn)</code>. This function should clean up any
* subscriptions made in the <code>on()</code> phase.</p>
*
* @method detach
* @param node {Node} the node the subscription was applied to
* @param sub {Subscription} the object tracking this subscription
* @param notifier {SyntheticEvent.Notifier} the Notifier used to
* trigger the execution of the subscribers
*/
detach: noop,
/**
* <p>Implementers SHOULD provide this method definition.</p>
*
* <p>Implementation logic for subscriptions done via
* <code>node.delegate(type, fn, filter)</code> or
* <code>Y.delegate(type, fn, container, filter)</code>. Like with
* <code>on()</code> above, this function should monitor the environment
* for the event being fired, and trigger subscription execution by
* calling <code>notifier.fire(e)</code>.</p>
*
* <p>This function receives a fourth argument, which is the filter
* used to identify which Node's are of interest to the subscription.
* The filter will be either a boolean function that accepts a target
* Node for each hierarchy level as the event bubbles, or a selector
* string. To translate selector strings into filter functions, use
* <code>Y.delegate.compileFilter(filter)</code>.</p>
*
* @method delegate
* @param node {Node} the node the subscription is being applied to
* @param sub {Subscription} the object to track this subscription
* @param notifier {SyntheticEvent.Notifier} call notifier.fire(..) to
* trigger the execution of the subscribers
* @param filter {String|Function} Selector string or function that
* accepts an event object and returns null, a Node, or an
* array of Nodes matching the criteria for processing.
* @since 3.2.0
*/
delegate : noop,
/**
* <p>Implementers SHOULD provide this method definition.</p>
*
* <p>Implementation logic for detaching subscriptions done via
* <code>node.delegate(type, fn, filter)</code> or
* <code>Y.delegate(type, fn, container, filter)</code>. This function
* should clean up any subscriptions made in the
* <code>delegate()</code> phase.</p>
*
* @method detachDelegate
* @param node {Node} the node the subscription was applied to
* @param sub {Subscription} the object tracking this subscription
* @param notifier {SyntheticEvent.Notifier} the Notifier used to
* trigger the execution of the subscribers
* @param filter {String|Function} Selector string or function that
* accepts an event object and returns null, a Node, or an
* array of Nodes matching the criteria for processing.
* @since 3.2.0
*/
detachDelegate : noop,
/**
* Sets up the boilerplate for detaching the event and facilitating the
* execution of subscriber callbacks.
*
* @method _on
* @param args {Array} array of arguments passed to
* <code>Y.on(...)</code> or <code>Y.delegate(...)</code>
* @param delegate {Boolean} true if called from
* <code>Y.delegate(...)</code>
* @return {EventHandle} the detach handle for this subscription
* @private
* since 3.2.0
*/
_on: function (args, delegate) {
var handles = [],
originalArgs = args.slice(),
extra = this.processArgs(args, delegate),
selector = args[2],
method = delegate ? 'delegate' : 'on',
nodes, handle;
// Can't just use Y.all because it doesn't support window (yet?)
nodes = (isString(selector)) ?
query(selector) :
toArray(selector || Y.one(Y.config.win));
if (!nodes.length && isString(selector)) {
handle = Y.on('available', function () {
Y.mix(handle, Y[method].apply(Y, originalArgs), true);
}, selector);
return handle;
}
Y.Array.each(nodes, function (node) {
var subArgs = args.slice(),
filter;
node = Y.one(node);
if (node) {
if (delegate) {
filter = subArgs.splice(3, 1)[0];
}
// (type, fn, el, thisObj, ...) => (fn, thisObj, ...)
subArgs.splice(0, 4, subArgs[1], subArgs[3]);
if (!this.preventDups ||
!this.getSubs(node, args, null, true))
{
handles.push(this._subscribe(node, method, subArgs, extra, filter));
}
}
}, this);
return (handles.length === 1) ?
handles[0] :
new Y.EventHandle(handles);
},
/**
* Creates a new Notifier object for use by this event's
* <code>on(...)</code> or <code>delegate(...)</code> implementation
* and register the custom event proxy in the DOM system for cleanup.
*
* @method _subscribe
* @param node {Node} the Node hosting the event
* @param method {String} "on" or "delegate"
* @param args {Array} the subscription arguments passed to either
* <code>Y.on(...)</code> or <code>Y.delegate(...)</code>
* after running through <code>processArgs(args)</code> to
* normalize the argument signature
* @param extra {any} Extra data parsed from
* <code>processArgs(args)</code>
* @param filter {String|Function} the selector string or function
* filter passed to <code>Y.delegate(...)</code> (not
* present when called from <code>Y.on(...)</code>)
* @return {EventHandle}
* @private
* @since 3.2.0
*/
_subscribe: function (node, method, args, extra, filter) {
var dispatcher = new Y.CustomEvent(this.type, this.publishConfig),
handle = dispatcher.on.apply(dispatcher, args),
notifier = new Notifier(handle, this.emitFacade),
registry = SyntheticEvent.getRegistry(node, this.type, true),
sub = handle.sub;
sub.node = node;
sub.filter = filter;
if (extra) {
this.applyArgExtras(extra, sub);
}
Y.mix(dispatcher, {
eventDef : this,
notifier : notifier,
host : node, // I forget what this is for
currentTarget: node, // for generating facades
target : node, // for generating facades
el : node._node, // For category detach
_delete : SyntheticEvent._deleteSub
}, true);
handle.notifier = notifier;
registry.register(handle);
// Call the implementation's "on" or "delegate" method
this[method](node, sub, notifier, filter);
return handle;
},
/**
* <p>Implementers MAY provide this method definition.</p>
*
* <p>Implement this function if you want extra data extracted during
* processArgs to be propagated to subscriptions on a per-node basis.
* That is to say, if you call <code>Y.on('xyz', fn, xtra, 'div')</code>
* the data returned from processArgs will be shared
* across the subscription objects for all the divs. If you want each
* subscription to receive unique information, do that processing
* here.</p>
*
* <p>The default implementation adds the data extracted by processArgs
* to the subscription object as <code>sub._extra</code>.</p>
*
* @method applyArgExtras
* @param extra {any} Any extra data extracted from processArgs
* @param sub {Subscription} the individual subscription
*/
applyArgExtras: function (extra, sub) {
sub._extra = extra;
},
/**
* Removes the subscription(s) from the internal subscription dispatch
* mechanism. See <code>SyntheticEvent._deleteSub</code>.
*
* @method _detach
* @param args {Array} The arguments passed to
* <code>node.detach(...)</code>
* @private
* @since 3.2.0
*/
_detach: function (args) {
// Can't use Y.all because it doesn't support window (yet?)
// TODO: Does Y.all support window now?
var target = args[2],
els = (isString(target)) ?
query(target) : toArray(target),
node, i, len, handles, j;
// (type, fn, el, context, filter?) => (type, fn, context, filter?)
args.splice(2, 1);
for (i = 0, len = els.length; i < len; ++i) {
node = Y.one(els[i]);
if (node) {
handles = this.getSubs(node, args);
if (handles) {
for (j = handles.length - 1; j >= 0; --j) {
handles[j].detach();
}
}
}
}
},
/**
* Returns the detach handles of subscriptions on a node that satisfy a
* search/filter function. By default, the filter used is the
* <code>subMatch</code> method.
*
* @method getSubs
* @param node {Node} the node hosting the event
* @param args {Array} the array of original subscription args passed
* to <code>Y.on(...)</code> (before
* <code>processArgs</code>
* @param filter {Function} function used to identify a subscription
* for inclusion in the returned array
* @param first {Boolean} stop after the first match (used to check for
* duplicate subscriptions)
* @return {EventHandle[]} detach handles for the matching subscriptions
*/
getSubs: function (node, args, filter, first) {
var registry = SyntheticEvent.getRegistry(node, this.type),
handles = [],
allHandles, i, len, handle;
if (registry) {
allHandles = registry.handles;
if (!filter) {
filter = this.subMatch;
}
for (i = 0, len = allHandles.length; i < len; ++i) {
handle = allHandles[i];
if (filter.call(this, handle.sub, args)) {
if (first) {
return handle;
} else {
handles.push(allHandles[i]);
}
}
}
}
return handles.length && handles;
},
/**
* <p>Implementers MAY override this to define what constitutes a
* "same" subscription. Override implementations should
* consider the lack of a comparator as a match, so calling
* <code>getSubs()</code> with no arguments will return all subs.</p>
*
* <p>Compares a set of subscription arguments against a Subscription
* object to determine if they match. The default implementation
* compares the callback function against the second argument passed to
* <code>Y.on(...)</code> or <code>node.detach(...)</code> etc.</p>
*
* @method subMatch
* @param sub {Subscription} the existing subscription
* @param args {Array} the calling arguments passed to
* <code>Y.on(...)</code> etc.
* @return {Boolean} true if the sub can be described by the args
* present
* @since 3.2.0
*/
subMatch: function (sub, args) {
// Default detach cares only about the callback matching
return !args[1] || sub.fn === args[1];
}
}
}, true);
Y.SyntheticEvent = SyntheticEvent;
/**
* <p>Defines a new event in the DOM event system. Implementers are
* responsible for monitoring for a scenario whereby the event is fired. A
* notifier object is provided to the functions identified below. When the
* criteria defining the event are met, call notifier.fire( [args] ); to
* execute event subscribers.</p>
*
* <p>The first parameter is the name of the event. The second parameter is a
* configuration object which define the behavior of the event system when the
* new event is subscribed to or detached from. The methods that should be
* defined in this configuration object are <code>on</code>,
* <code>detach</code>, <code>delegate</code>, and <code>detachDelegate</code>.
* You are free to define any other methods or properties needed to define your
* event. Be aware, however, that since the object is used to subclass
* SyntheticEvent, you should avoid method names used by SyntheticEvent unless
* your intention is to override the default behavior.</p>
*
* <p>This is a list of properties and methods that you can or should specify
* in the configuration object:</p>
*
* <dl>
* <dt><code>on</code></dt>
* <dd><code>function (node, subscription, notifier)</code> The
* implementation logic for subscription. Any special setup you need to
* do to create the environment for the event being fired--E.g. native
* DOM event subscriptions. Store subscription related objects and
* state on the <code>subscription</code> object. When the
* criteria have been met to fire the synthetic event, call
* <code>notifier.fire(e)</code>. See Notifier's <code>fire()</code>
* method for details about what to pass as parameters.</dd>
*
* <dt><code>detach</code></dt>
* <dd><code>function (node, subscription, notifier)</code> The
* implementation logic for cleaning up a detached subscription. E.g.
* detach any DOM subscriptions added in <code>on</code>.</dd>
*
* <dt><code>delegate</code></dt>
* <dd><code>function (node, subscription, notifier, filter)</code> The
* implementation logic for subscription via <code>Y.delegate</code> or
* <code>node.delegate</code>. The filter is typically either a selector
* string or a function. You can use
* <code>Y.delegate.compileFilter(selectorString)</code> to create a
* filter function from a selector string if needed. The filter function
* expects an event object as input and should output either null, a
* matching Node, or an array of matching Nodes. Otherwise, this acts
* like <code>on</code> DOM event subscriptions. Store subscription
* related objects and information on the <code>subscription</code>
* object. When the criteria have been met to fire the synthetic event,
* call <code>notifier.fire(e)</code> as noted above.</dd>
*
* <dt><code>detachDelegate</code></dt>
* <dd><code>function (node, subscription, notifier)</code> The
* implementation logic for cleaning up a detached delegate subscription.
* E.g. detach any DOM delegate subscriptions added in
* <code>delegate</code>.</dd>
*
* <dt><code>publishConfig</code></dt>
* <dd>(Object) The configuration object that will be used to instantiate
* the underlying CustomEvent. See Notifier's <code>fire</code> method
* for details.</dd>
*
* <dt><code>processArgs</code></dt
* <dd>
* <p><code>function (argArray, fromDelegate)</code> Optional method
* to extract any additional arguments from the subscription
* signature. Using this allows <code>on</code> or
* <code>delegate</code> signatures like
* <code>node.on("hover", overCallback,
* outCallback)</code>.</p>
* <p>When processing an atypical argument signature, make sure the
* args array is returned to the normal signature before returning
* from the function. For example, in the "hover" example
* above, the <code>outCallback</code> needs to be <code>splice</code>d
* out of the array. The expected signature of the args array for
* <code>on()</code> subscriptions is:</p>
* <pre>
* <code>[type, callback, target, contextOverride, argN...]</code>
* </pre>
* <p>And for <code>delegate()</code>:</p>
* <pre>
* <code>[type, callback, target, filter, contextOverride, argN...]</code>
* </pre>
* <p>where <code>target</code> is the node the event is being
* subscribed for. You can see these signatures documented for
* <code>Y.on()</code> and <code>Y.delegate()</code> respectively.</p>
* <p>Whatever gets returned from the function will be stored on the
* <code>subscription</code> object under
* <code>subscription._extra</code>.</p></dd>
* <dt><code>subMatch</code></dt>
* <dd>
* <p><code>function (sub, args)</code> Compares a set of
* subscription arguments against a Subscription object to determine
* if they match. The default implementation compares the callback
* function against the second argument passed to
* <code>Y.on(...)</code> or <code>node.detach(...)</code> etc.</p>
* </dd>
* </dl>
*
* @method define
* @param type {String} the name of the event
* @param config {Object} the prototype definition for the new event (see above)
* @param force {Boolean} override an existing event (use with caution)
* @return {SyntheticEvent} the subclass implementation instance created to
* handle event subscriptions of this type
* @static
* @for Event
* @since 3.1.0
* @in event-synthetic
*/
Y.Event.define = function (type, config, force) {
var eventDef, Impl, synth;
if (type && type.type) {
eventDef = type;
force = config;
} else if (config) {
eventDef = Y.merge({ type: type }, config);
}
if (eventDef) {
if (force || !Y.Node.DOM_EVENTS[eventDef.type]) {
Impl = function () {
SyntheticEvent.apply(this, arguments);
};
Y.extend(Impl, SyntheticEvent, eventDef);
synth = new Impl();
type = synth.type;
Y.Node.DOM_EVENTS[type] = Y.Env.evt.plugins[type] = {
eventDef: synth,
on: function () {
return synth._on(toArray(arguments));
},
delegate: function () {
return synth._on(toArray(arguments), true);
},
detach: function () {
return synth._detach(toArray(arguments));
}
};
}
} else if (isString(type) || isArray(type)) {
Y.Array.each(toArray(type), function (t) {
Y.Node.DOM_EVENTS[t] = 1;
});
}
return synth;
};
}, '3.18.1', {"requires": ["node-base", "event-custom-complex"]});
|
loadIonicon('<svg width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><path d="M405.34 405.332H106.66V106.668H240V64H106.66C83.19 64 64 83.197 64 106.668v298.664C64 428.802 83.19 448 106.66 448h298.68c23.47 0 42.66-19.197 42.66-42.668V272h-42.66v133.332zM288 64v42.668h87.474L160 322.133 189.864 352 405.34 136.53V224H448V64H288z"/></svg>','md-open'); |
describe('tooltip template', function() {
var elm,
elmBody,
scope,
elmScope,
tooltipScope;
// load the popover code
beforeEach(module('ui.bootstrap.tooltip'));
// load the template
beforeEach(module('template/tooltip/tooltip-template-popup.html'));
beforeEach(inject(function($templateCache) {
$templateCache.put('myUrl', [200, '<span>{{ myTemplateText }}</span>', {}]);
}));
beforeEach(inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><span tooltip-template="templateUrl">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.templateUrl = 'myUrl';
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
function trigger(element, evt) {
evt = new Event(evt);
element[0].dispatchEvent(evt);
}
it('should open on mouseenter', inject(function() {
trigger(elm, 'mouseenter');
expect( tooltipScope.isOpen ).toBe( true );
expect( elmBody.children().length ).toBe( 2 );
}));
it('should not open on mouseenter if templateUrl is empty', inject(function() {
scope.templateUrl = null;
scope.$digest();
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(false);
expect(elmBody.children().length).toBe(1);
}));
it('should show updated text', inject(function() {
scope.myTemplateText = 'some text';
scope.$digest();
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
expect(elmBody.children().eq(1).text().trim()).toBe('some text');
scope.myTemplateText = 'new text';
scope.$digest();
expect(elmBody.children().eq(1).text().trim()).toBe('new text');
}));
it('should hide tooltip when template becomes empty', inject(function($timeout) {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
scope.templateUrl = '';
scope.$digest();
expect(tooltipScope.isOpen).toBe(false);
$timeout.flush();
expect(elmBody.children().length).toBe(1);
}));
});
|
/*!
* jQuery JavaScript Library v1.3.2
*
* Copyright (c) 2009 John Resig, http://jquery.com/
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
* Revision: 6246
*/
(function(){
var
// Will speed up references to window, and allows munging its name.
window = this,
// Will speed up references to undefined, and allows munging its name.
undefined,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/;
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// Make sure that a selection was provided
selector = selector || document;
// Handle $(DOMElement)
if ( selector.nodeType ) {
this[0] = selector;
this.length = 1;
this.context = selector;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
var match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] )
selector = jQuery.clean( [ match[1] ], context );
// HANDLE: $("#id")
else {
var elem = document.getElementById( match[3] );
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem && elem.id != match[3] )
return jQuery().find( selector );
// Otherwise, we inject the element directly into the jQuery object
var ret = jQuery( elem || [] );
ret.context = document;
ret.selector = selector;
return ret;
}
// HANDLE: $(expr, [context])
// (which is just equivalent to: $(content).find(expr)
} else
return jQuery( context ).find( selector );
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) )
return jQuery( document ).ready( selector );
// Make sure that old selector state is passed along
if ( selector.selector && selector.context ) {
this.selector = selector.selector;
this.context = selector.context;
}
return this.setArray(jQuery.isArray( selector ) ?
selector :
jQuery.makeArray(selector));
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.3.2",
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num === undefined ?
// Return a 'clean' array
Array.prototype.slice.call( this ) :
// Return just the object
this[ num ];
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery( elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" )
ret.selector = this.selector + (this.selector ? " " : "") + selector;
else if ( name )
ret.selector = this.selector + "." + name + "(" + selector + ")";
// Return the newly-formed element set
return ret;
},
// Force the current matched set of elements to become
// the specified array of elements (destroying the stack in the process)
// You should use pushStack() in order to do this, but maintain the stack
setArray: function( elems ) {
// Resetting the length to 0, then using the native Array push
// is a super-fast way to populate an object with array-like properties
this.length = 0;
Array.prototype.push.apply( this, elems );
return this;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem && elem.jquery ? elem[0] : elem
, this );
},
attr: function( name, value, type ) {
var options = name;
// Look for the case where we're accessing a style value
if ( typeof name === "string" )
if ( value === undefined )
return this[0] && jQuery[ type || "attr" ]( this[0], name );
else {
options = {};
options[ name ] = value;
}
// Check to see if we're setting style values
return this.each(function(i){
// Set all the styles
for ( name in options )
jQuery.attr(
type ?
this.style :
this,
name, jQuery.prop( this, options[ name ], type, i, name )
);
});
},
css: function( key, value ) {
// ignore negative width and height values
if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
value = undefined;
return this.attr( key, value, "curCSS" );
},
text: function( text ) {
if ( typeof text !== "object" && text != null )
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
var ret = "";
jQuery.each( text || this, function(){
jQuery.each( this.childNodes, function(){
if ( this.nodeType != 8 )
ret += this.nodeType != 1 ?
this.nodeValue :
jQuery.fn.text( [ this ] );
});
});
return ret;
},
wrapAll: function( html ) {
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).clone();
if ( this[0].parentNode )
wrap.insertBefore( this[0] );
wrap.map(function(){
var elem = this;
while ( elem.firstChild )
elem = elem.firstChild;
return elem;
}).append(this);
}
return this;
},
wrapInner: function( html ) {
return this.each(function(){
jQuery( this ).contents().wrapAll( html );
});
},
wrap: function( html ) {
return this.each(function(){
jQuery( this ).wrapAll( html );
});
},
append: function() {
return this.domManip(arguments, true, function(elem){
if (this.nodeType == 1)
this.appendChild( elem );
});
},
prepend: function() {
return this.domManip(arguments, true, function(elem){
if (this.nodeType == 1)
this.insertBefore( elem, this.firstChild );
});
},
before: function() {
return this.domManip(arguments, false, function(elem){
this.parentNode.insertBefore( elem, this );
});
},
after: function() {
return this.domManip(arguments, false, function(elem){
this.parentNode.insertBefore( elem, this.nextSibling );
});
},
end: function() {
return this.prevObject || jQuery( [] );
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: [].push,
sort: [].sort,
splice: [].splice,
find: function( selector ) {
if ( this.length === 1 ) {
var ret = this.pushStack( [], "find", selector );
ret.length = 0;
jQuery.find( selector, this[0], ret );
return ret;
} else {
return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
return jQuery.find( selector, elem );
})), "find", selector );
}
},
clone: function( events ) {
// Do the clone
var ret = this.map(function(){
if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
// IE copies events bound via attachEvent when
// using cloneNode. Calling detachEvent on the
// clone will also remove the events from the orignal
// In order to get around this, we use innerHTML.
// Unfortunately, this means some modifications to
// attributes in IE that are actually only stored
// as properties will not be copied (such as the
// the name attribute on an input).
var html = this.outerHTML;
if ( !html ) {
var div = this.ownerDocument.createElement("div");
div.appendChild( this.cloneNode(true) );
html = div.innerHTML;
}
return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
} else
return this.cloneNode(true);
});
// Copy the events from the original to the clone
if ( events === true ) {
var orig = this.find("*").andSelf(), i = 0;
ret.find("*").andSelf().each(function(){
if ( this.nodeName !== orig[i].nodeName )
return;
var events = jQuery.data( orig[i], "events" );
for ( var type in events ) {
for ( var handler in events[ type ] ) {
jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
}
}
i++;
});
}
// Return the cloned set
return ret;
},
filter: function( selector ) {
return this.pushStack(
jQuery.isFunction( selector ) &&
jQuery.grep(this, function(elem, i){
return selector.call( elem, i );
}) ||
jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
return elem.nodeType === 1;
}) ), "filter", selector );
},
closest: function( selector ) {
var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
closer = 0;
return this.map(function(){
var cur = this;
while ( cur && cur.ownerDocument ) {
if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
jQuery.data(cur, "closest", closer);
return cur;
}
cur = cur.parentNode;
closer++;
}
});
},
not: function( selector ) {
if ( typeof selector === "string" )
// test special case where just one selector is passed in
if ( isSimple.test( selector ) )
return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
else
selector = jQuery.multiFilter( selector, this );
var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
return this.filter(function() {
return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
});
},
add: function( selector ) {
return this.pushStack( jQuery.unique( jQuery.merge(
this.get(),
typeof selector === "string" ?
jQuery( selector ) :
jQuery.makeArray( selector )
)));
},
is: function( selector ) {
return !!selector && jQuery.multiFilter( selector, this ).length > 0;
},
hasClass: function( selector ) {
return !!selector && this.is( "." + selector );
},
val: function( value ) {
if ( value === undefined ) {
var elem = this[0];
if ( elem ) {
if( jQuery.nodeName( elem, 'option' ) )
return (elem.attributes.value || {}).specified ? elem.value : elem.text;
// We need to handle select boxes special
if ( jQuery.nodeName( elem, "select" ) ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type == "select-one";
// Nothing was selected
if ( index < 0 )
return null;
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
if ( option.selected ) {
// Get the specifc value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if ( one )
return value;
// Multi-Selects return an array
values.push( value );
}
}
return values;
}
// Everything else, we just grab the value
return (elem.value || "").replace(/\r/g, "");
}
return undefined;
}
if ( typeof value === "number" )
value += '';
return this.each(function(){
if ( this.nodeType != 1 )
return;
if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
this.checked = (jQuery.inArray(this.value, value) >= 0 ||
jQuery.inArray(this.name, value) >= 0);
else if ( jQuery.nodeName( this, "select" ) ) {
var values = jQuery.makeArray(value);
jQuery( "option", this ).each(function(){
this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
jQuery.inArray( this.text, values ) >= 0);
});
if ( !values.length )
this.selectedIndex = -1;
} else
this.value = value;
});
},
html: function( value ) {
return value === undefined ?
(this[0] ?
this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
null) :
this.empty().append( value );
},
replaceWith: function( value ) {
return this.after( value ).remove();
},
eq: function( i ) {
return this.slice( i, +i + 1 );
},
slice: function() {
return this.pushStack( Array.prototype.slice.apply( this, arguments ),
"slice", Array.prototype.slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function(elem, i){
return callback.call( elem, i, elem );
}));
},
andSelf: function() {
return this.add( this.prevObject );
},
domManip: function( args, table, callback ) {
if ( this[0] ) {
var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
first = fragment.firstChild;
if ( first )
for ( var i = 0, l = this.length; i < l; i++ )
callback.call( root(this[i], first), this.length > 1 || i > 0 ?
fragment.cloneNode(true) : fragment );
if ( scripts )
jQuery.each( scripts, evalScript );
}
return this;
function root( elem, cur ) {
return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
}
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
function evalScript( i, elem ) {
if ( elem.src )
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
else
jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
if ( elem.parentNode )
elem.parentNode.removeChild( elem );
}
function now(){
return +new Date;
}
jQuery.extend = jQuery.fn.extend = function() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) )
target = {};
// extend jQuery itself if only one argument is passed
if ( length == i ) {
target = this;
--i;
}
for ( ; i < length; i++ )
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null )
// Extend the base object
for ( var name in options ) {
var src = target[ name ], copy = options[ name ];
// Prevent never-ending loop
if ( target === copy )
continue;
// Recurse if we're merging object values
if ( deep && copy && typeof copy === "object" && !copy.nodeType )
target[ name ] = jQuery.extend( deep,
// Never move original objects, clone them
src || ( copy.length != null ? [ ] : { } )
, copy );
// Don't bring in undefined values
else if ( copy !== undefined )
target[ name ] = copy;
}
// Return the modified object
return target;
};
// exclude the following css properties to add px
var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
// cache defaultView
defaultView = document.defaultView || {},
toString = Object.prototype.toString;
jQuery.extend({
noConflict: function( deep ) {
window.$ = _$;
if ( deep )
window.jQuery = _jQuery;
return jQuery;
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return toString.call(obj) === "[object Function]";
},
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
// check if an element is in a (or is an) XML document
isXMLDoc: function( elem ) {
return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
!!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
},
// Evalulates a script in a global context
globalEval: function( data ) {
if ( data && /\S/.test(data) ) {
// Inspired by code by Andrea Giammarchi
// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
if ( jQuery.support.scriptEval )
script.appendChild( document.createTextNode( data ) );
else
script.text = data;
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ], args ) === false )
break;
} else
for ( ; i < length; )
if ( callback.apply( object[ i++ ], args ) === false )
break;
// A special, fast, case for the most common use of each
} else {
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
},
prop: function( elem, value, type, i, name ) {
// Handle executable functions
if ( jQuery.isFunction( value ) )
value = value.call( elem, i );
// Handle passing in a number to a CSS property
return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
value + "px" :
value;
},
className: {
// internal only, use addClass("class")
add: function( elem, classNames ) {
jQuery.each((classNames || "").split(/\s+/), function(i, className){
if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
elem.className += (elem.className ? " " : "") + className;
});
},
// internal only, use removeClass("class")
remove: function( elem, classNames ) {
if (elem.nodeType == 1)
elem.className = classNames !== undefined ?
jQuery.grep(elem.className.split(/\s+/), function(className){
return !jQuery.className.has( classNames, className );
}).join(" ") :
"";
},
// internal only, use hasClass("class")
has: function( elem, className ) {
return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( var name in options )
elem.style[ name ] = old[ name ];
},
css: function( elem, name, force, extra ) {
if ( name == "width" || name == "height" ) {
var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
function getWH() {
val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" )
return;
jQuery.each( which, function() {
if ( !extra )
val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
if ( extra === "margin" )
val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
else
val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
});
}
if ( elem.offsetWidth !== 0 )
getWH();
else
jQuery.swap( elem, props, getWH );
return Math.max(0, Math.round(val));
}
return jQuery.curCSS( elem, name, force );
},
curCSS: function( elem, name, force ) {
var ret, style = elem.style;
// We need to handle opacity special in IE
if ( name == "opacity" && !jQuery.support.opacity ) {
ret = jQuery.attr( style, "opacity" );
return ret == "" ?
"1" :
ret;
}
// Make sure we're using the right name for getting the float value
if ( name.match( /float/i ) )
name = styleFloat;
if ( !force && style && style[ name ] )
ret = style[ name ];
else if ( defaultView.getComputedStyle ) {
// Only "float" is needed here
if ( name.match( /float/i ) )
name = "float";
name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
var computedStyle = defaultView.getComputedStyle( elem, null );
if ( computedStyle )
ret = computedStyle.getPropertyValue( name );
// We should always get a number back from opacity
if ( name == "opacity" && ret == "" )
ret = "1";
} else if ( elem.currentStyle ) {
var camelCase = name.replace(/\-(\w)/g, function(all, letter){
return letter.toUpperCase();
});
ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
// Remember the original values
var left = style.left, rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
elem.runtimeStyle.left = elem.currentStyle.left;
style.left = ret || 0;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
elem.runtimeStyle.left = rsLeft;
}
}
return ret;
},
clean: function( elems, context, fragment ) {
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" )
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
if ( match )
return [ context.createElement( match[1] ) ];
}
var ret = [], scripts = [], div = context.createElement("div");
jQuery.each(elems, function(i, elem){
if ( typeof elem === "number" )
elem += '';
if ( !elem )
return;
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
all :
front + "></" + tag + ">";
});
// Trim whitespace, otherwise indexOf won't work as expected
var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();
var wrap =
// option or optgroup
!tags.indexOf("<opt") &&
[ 1, "<select multiple='multiple'>", "</select>" ] ||
!tags.indexOf("<leg") &&
[ 1, "<fieldset>", "</fieldset>" ] ||
tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
[ 1, "<table>", "</table>" ] ||
!tags.indexOf("<tr") &&
[ 2, "<table><tbody>", "</tbody></table>" ] ||
// <thead> matched above
(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
!tags.indexOf("<col") &&
[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
// IE can't serialize <link> and <script> tags normally
!jQuery.support.htmlSerialize &&
[ 1, "div<div>", "</div>" ] ||
[ 0, "", "" ];
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( wrap[0]-- )
div = div.lastChild;
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = /<tbody/i.test(elem),
tbody = !tags.indexOf("<table") && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] == "<table>" && !hasBody ?
div.childNodes :
[];
for ( var j = tbody.length - 1; j >= 0 ; --j )
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
elem = jQuery.makeArray( div.childNodes );
}
if ( elem.nodeType )
ret.push( elem );
else
ret = jQuery.merge( ret, elem );
});
if ( fragment ) {
for ( var i = 0; ret[i]; i++ ) {
if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 )
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
fragment.appendChild( ret[i] );
}
}
return scripts;
}
return ret;
},
attr: function( elem, name, value ) {
// don't set attributes on text and comment nodes
if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
return undefined;
var notxml = !jQuery.isXMLDoc( elem ),
// Whether we are setting (or getting)
set = value !== undefined;
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
// Only do all the following if this is a node (faster for style)
// IE elem.getAttribute passes even for style
if ( elem.tagName ) {
// These attributes require special treatment
var special = /href|src|style/.test( name );
// Safari mis-reports the default selected property of a hidden option
// Accessing the parent's selectedIndex property fixes it
if ( name == "selected" && elem.parentNode )
elem.parentNode.selectedIndex;
// If applicable, access the attribute via the DOM 0 way
if ( name in elem && notxml && !special ) {
if ( set ){
// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
throw "type property can't be changed";
elem[ name ] = value;
}
// browsers index elements by id/name on forms, give priority to attributes.
if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
return elem.getAttributeNode( name ).nodeValue;
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
if ( name == "tabIndex" ) {
var attributeNode = elem.getAttributeNode( "tabIndex" );
return attributeNode && attributeNode.specified
? attributeNode.value
: elem.nodeName.match(/(button|input|object|select|textarea)/i)
? 0
: elem.nodeName.match(/^(a|area)$/i) && elem.href
? 0
: undefined;
}
return elem[ name ];
}
if ( !jQuery.support.style && notxml && name == "style" )
return jQuery.attr( elem.style, "cssText", value );
if ( set )
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
var attr = !jQuery.support.hrefNormalized && notxml && special
// Some attributes require a special call on IE
? elem.getAttribute( name, 2 )
: elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return attr === null ? undefined : attr;
}
// elem is actually elem.style ... set the style
// IE uses filters for opacity
if ( !jQuery.support.opacity && name == "opacity" ) {
if ( set ) {
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
elem.zoom = 1;
// Set the alpha filter to set the opacity
elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
(parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
}
return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
"";
}
name = name.replace(/-([a-z])/ig, function(all, letter){
return letter.toUpperCase();
});
if ( set )
elem[ name ] = value;
return elem[ name ];
},
trim: function( text ) {
return (text || "").replace( /^\s+|\s+$/g, "" );
},
makeArray: function( array ) {
var ret = [];
if( array != null ){
var i = array.length;
// The window, strings (and functions) also have 'length'
if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
ret[0] = array;
else
while( i )
ret[--i] = array[i];
}
return ret;
},
inArray: function( elem, array ) {
for ( var i = 0, length = array.length; i < length; i++ )
// Use === because on IE, window == document
if ( array[ i ] === elem )
return i;
return -1;
},
merge: function( first, second ) {
// We have to loop this way because IE & Opera overwrite the length
// expando of getElementsByTagName
var i = 0, elem, pos = first.length;
// Also, we need to make sure that the correct elements are being returned
// (IE returns comment nodes in a '*' query)
if ( !jQuery.support.getAll ) {
while ( (elem = second[ i++ ]) != null )
if ( elem.nodeType != 8 )
first[ pos++ ] = elem;
} else
while ( (elem = second[ i++ ]) != null )
first[ pos++ ] = elem;
return first;
},
unique: function( array ) {
var ret = [], done = {};
try {
for ( var i = 0, length = array.length; i < length; i++ ) {
var id = jQuery.data( array[ i ] );
if ( !done[ id ] ) {
done[ id ] = true;
ret.push( array[ i ] );
}
}
} catch( e ) {
ret = array;
}
return ret;
},
grep: function( elems, callback, inv ) {
var ret = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ )
if ( !inv != !callback( elems[ i ], i ) )
ret.push( elems[ i ] );
return ret;
},
map: function( elems, callback ) {
var ret = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
var value = callback( elems[ i ], i );
if ( value != null )
ret[ ret.length ] = value;
}
return ret.concat.apply( [], ret );
}
});
// Use of jQuery.browser is deprecated.
// It's included for backwards compatibility and plugins,
// although they should work to migrate away.
var userAgent = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
jQuery.browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
jQuery.each({
parent: function(elem){return elem.parentNode;},
parents: function(elem){return jQuery.dir(elem,"parentNode");},
next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
children: function(elem){return jQuery.sibling(elem.firstChild);},
contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
}, function(name, fn){
jQuery.fn[ name ] = function( selector ) {
var ret = jQuery.map( this, fn );
if ( selector && typeof selector == "string" )
ret = jQuery.multiFilter( selector, ret );
return this.pushStack( jQuery.unique( ret ), name, selector );
};
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(name, original){
jQuery.fn[ name ] = function( selector ) {
var ret = [], insert = jQuery( selector );
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, selector );
};
});
jQuery.each({
removeAttr: function( name ) {
jQuery.attr( this, name, "" );
if (this.nodeType == 1)
this.removeAttribute( name );
},
addClass: function( classNames ) {
jQuery.className.add( this, classNames );
},
removeClass: function( classNames ) {
jQuery.className.remove( this, classNames );
},
toggleClass: function( classNames, state ) {
if( typeof state !== "boolean" )
state = !jQuery.className.has( this, classNames );
jQuery.className[ state ? "add" : "remove" ]( this, classNames );
},
remove: function( selector ) {
if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
// Prevent memory leaks
jQuery( "*", this ).add([this]).each(function(){
jQuery.event.remove(this);
jQuery.removeData(this);
});
if (this.parentNode)
this.parentNode.removeChild( this );
}
},
empty: function() {
// Remove element nodes and prevent memory leaks
jQuery(this).children().remove();
// Remove any remaining nodes
while ( this.firstChild )
this.removeChild( this.firstChild );
}
}, function(name, fn){
jQuery.fn[ name ] = function(){
return this.each( fn, arguments );
};
});
// Helper function used by the dimensions and offset modules
function num(elem, prop) {
return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}
var expando = "jQuery" + now(), uuid = 0, windowData = {};
jQuery.extend({
cache: {},
data: function( elem, name, data ) {
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ];
// Compute a unique ID for the element
if ( !id )
id = elem[ expando ] = ++uuid;
// Only generate the data cache if we're
// trying to access or manipulate it
if ( name && !jQuery.cache[ id ] )
jQuery.cache[ id ] = {};
// Prevent overriding the named cache with undefined values
if ( data !== undefined )
jQuery.cache[ id ][ name ] = data;
// Return the named cache data, or the ID for the element
return name ?
jQuery.cache[ id ][ name ] :
id;
},
removeData: function( elem, name ) {
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ];
// If we want to remove a specific section of the element's data
if ( name ) {
if ( jQuery.cache[ id ] ) {
// Remove the section of cache data
delete jQuery.cache[ id ][ name ];
// If we've removed all the data, remove the element's cache
name = "";
for ( name in jQuery.cache[ id ] )
break;
if ( !name )
jQuery.removeData( elem );
}
// Otherwise, we want to remove all of the element's data
} else {
// Clean up the element expando
try {
delete elem[ expando ];
} catch(e){
// IE has trouble directly removing the expando
// but it's ok with using removeAttribute
if ( elem.removeAttribute )
elem.removeAttribute( expando );
}
// Completely remove the data cache
delete jQuery.cache[ id ];
}
},
queue: function( elem, type, data ) {
if ( elem ){
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type );
if ( !q || jQuery.isArray(data) )
q = jQuery.data( elem, type, jQuery.makeArray(data) );
else if( data )
q.push( data );
}
return q;
},
dequeue: function( elem, type ){
var queue = jQuery.queue( elem, type ),
fn = queue.shift();
if( !type || type === "fx" )
fn = queue[0];
if( fn !== undefined )
fn.call(elem);
}
});
jQuery.fn.extend({
data: function( key, value ){
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
if ( data === undefined && this.length )
data = jQuery.data( this[0], key );
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else
return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
jQuery.data( this, key, value );
});
},
removeData: function( key ){
return this.each(function(){
jQuery.removeData( this, key );
});
},
queue: function(type, data){
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined )
return jQuery.queue( this[0], type );
return this.each(function(){
var queue = jQuery.queue( this, type, data );
if( type == "fx" && queue.length == 1 )
queue[0].call(this);
});
},
dequeue: function(type){
return this.each(function(){
jQuery.dequeue( this, type );
});
}
});/*!
* Sizzle CSS Selector Engine - v0.9.3
* Copyright 2009, The Dojo Foundation
* More information: http://sizzlejs.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
done = 0,
toString = Object.prototype.toString;
var Sizzle = function(selector, context, results, seed) {
results = results || [];
context = context || document;
if ( context.nodeType !== 1 && context.nodeType !== 9 )
return [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
var parts = [], m, set, checkSet, check, mode, extra, prune = true;
// Reset the position of the chunker regexp (start from head)
chunker.lastIndex = 0;
while ( (m = chunker.exec(selector)) !== null ) {
parts.push( m[1] );
if ( m[2] ) {
extra = RegExp.rightContext;
break;
}
}
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] )
selector += parts.shift();
set = posProcess( selector, set );
}
}
} else {
var ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
set = Sizzle.filter( ret.expr, ret.set );
if ( parts.length > 0 ) {
checkSet = makeArray(set);
} else {
prune = false;
}
while ( parts.length ) {
var cur = parts.pop(), pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, isXML(context) );
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
throw "Syntax error, unrecognized expression: " + (cur || selector);
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context.nodeType === 1 ) {
for ( var i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( var i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, context, results, seed );
if ( sortOrder ) {
hasDuplicate = false;
results.sort(sortOrder);
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[i-1] ) {
results.splice(i--, 1);
}
}
}
}
}
return results;
};
Sizzle.matches = function(expr, set){
return Sizzle(expr, null, null, set);
};
Sizzle.find = function(expr, context, isXML){
var set, match;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var type = Expr.order[i], match;
if ( (match = Expr.match[ type ].exec( expr )) ) {
var left = RegExp.leftContext;
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName("*");
}
return {set: set, expr: expr};
};
Sizzle.filter = function(expr, set, inplace, not){
var old = expr, result = [], curLoop = set, match, anyFound,
isXMLFilter = set && set[0] && isXML(set[0]);
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.match[ type ].exec( expr )) != null ) {
var filter = Expr.filter[ type ], found, item;
anyFound = false;
if ( curLoop == result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr == old ) {
if ( anyFound == null ) {
throw "Syntax error, unrecognized expression: " + expr;
} else {
break;
}
}
old = expr;
}
return curLoop;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function(elem){
return elem.getAttribute("href");
}
},
relative: {
"+": function(checkSet, part, isXML){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test(part),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag && !isXML ) {
part = part.toUpperCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function(checkSet, part, isXML){
var isPartStr = typeof part === "string";
if ( isPartStr && !/\W/.test(part) ) {
part = isXML ? part : part.toUpperCase();
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName === part ? parent : false;
}
}
} else {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck;
if ( !part.match(/\W/) ) {
var nodeCheck = part = isXML ? part : part.toUpperCase();
checkFn = dirNodeCheck;
}
checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
},
"~": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck;
if ( typeof part === "string" && !part.match(/\W/) ) {
var nodeCheck = part = isXML ? part : part.toUpperCase();
checkFn = dirNodeCheck;
}
checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
}
},
find: {
ID: function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? [m] : [];
}
},
NAME: function(match, context, isXML){
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [], results = context.getElementsByName(match[1]);
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function(match, context){
return context.getElementsByTagName(match[1]);
}
},
preFilter: {
CLASS: function(match, curLoop, inplace, result, not, isXML){
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
if ( !inplace )
result.push( elem );
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function(match){
return match[1].replace(/\\/g, "");
},
TAG: function(match, curLoop){
for ( var i = 0; curLoop[i] === false; i++ ){}
return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
},
CHILD: function(match){
if ( match[1] == "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function(match, curLoop, inplace, result, not, isXML){
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function(match, curLoop, inplace, result, not){
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( match[3].match(chunker).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function(match){
match.unshift( true );
return match;
}
},
filters: {
enabled: function(elem){
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function(elem){
return elem.disabled === true;
},
checked: function(elem){
return elem.checked === true;
},
selected: function(elem){
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function(elem){
return !!elem.firstChild;
},
empty: function(elem){
return !elem.firstChild;
},
has: function(elem, i, match){
return !!Sizzle( match[3], elem ).length;
},
header: function(elem){
return /h\d/i.test( elem.nodeName );
},
text: function(elem){
return "text" === elem.type;
},
radio: function(elem){
return "radio" === elem.type;
},
checkbox: function(elem){
return "checkbox" === elem.type;
},
file: function(elem){
return "file" === elem.type;
},
password: function(elem){
return "password" === elem.type;
},
submit: function(elem){
return "submit" === elem.type;
},
image: function(elem){
return "image" === elem.type;
},
reset: function(elem){
return "reset" === elem.type;
},
button: function(elem){
return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
},
input: function(elem){
return /input|select|textarea|button/i.test(elem.nodeName);
}
},
setFilters: {
first: function(elem, i){
return i === 0;
},
last: function(elem, i, match, array){
return i === array.length - 1;
},
even: function(elem, i){
return i % 2 === 0;
},
odd: function(elem, i){
return i % 2 === 1;
},
lt: function(elem, i, match){
return i < match[3] - 0;
},
gt: function(elem, i, match){
return i > match[3] - 0;
},
nth: function(elem, i, match){
return match[3] - 0 == i;
},
eq: function(elem, i, match){
return match[3] - 0 == i;
}
},
filter: {
PSEUDO: function(elem, match, i, array){
var name = match[1], filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var i = 0, l = not.length; i < l; i++ ) {
if ( not[i] === elem ) {
return false;
}
}
return true;
}
},
CHILD: function(elem, match){
var type = match[1], node = elem;
switch (type) {
case 'only':
case 'first':
while (node = node.previousSibling) {
if ( node.nodeType === 1 ) return false;
}
if ( type == 'first') return true;
node = elem;
case 'last':
while (node = node.nextSibling) {
if ( node.nodeType === 1 ) return false;
}
return true;
case 'nth':
var first = match[2], last = match[3];
if ( first == 1 && last == 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first == 0 ) {
return diff == 0;
} else {
return ( diff % first == 0 && diff / first >= 0 );
}
}
},
ID: function(elem, match){
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function(elem, match){
return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
},
CLASS: function(elem, match){
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function(elem, match){
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value != check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function(elem, match, i, array){
var name = match[2], filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS;
for ( var type in Expr.match ) {
Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
}
var makeArray = function(array, results) {
array = Array.prototype.slice.call( array );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
try {
Array.prototype.slice.call( document.documentElement.childNodes );
// Provide a fallback method if it does not work
} catch(e){
makeArray = function(array, results) {
var ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var i = 0, l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( var i = 0; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( "sourceIndex" in document.documentElement ) {
sortOrder = function( a, b ) {
var ret = a.sourceIndex - b.sourceIndex;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( document.createRange ) {
sortOrder = function( a, b ) {
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.selectNode(a);
aRange.collapse(true);
bRange.selectNode(b);
bRange.collapse(true);
var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("form"),
id = "script" + (new Date).getTime();
form.innerHTML = "<input name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
var root = document.documentElement;
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( !!document.getElementById( id ) ) {
Expr.find.ID = function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
}
};
Expr.filter.ID = function(elem, match){
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function(match, context){
var results = context.getElementsByTagName(match[1]);
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function(elem){
return elem.getAttribute("href", 2);
};
}
})();
if ( document.querySelectorAll ) (function(){
var oldSizzle = Sizzle, div = document.createElement("div");
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function(query, context, extra, seed){
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && context.nodeType === 9 && !isXML(context) ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(e){}
}
return oldSizzle(query, context, extra, seed);
};
Sizzle.find = oldSizzle.find;
Sizzle.filter = oldSizzle.filter;
Sizzle.selectors = oldSizzle.selectors;
Sizzle.matches = oldSizzle.matches;
})();
if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
if ( div.getElementsByClassName("e").length === 0 )
return;
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 )
return;
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function(match, context, isXML) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
var sibDir = dir == "previousSibling" && !isXML;
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
if ( sibDir && elem.nodeType === 1 ){
elem.sizcache = doneName;
elem.sizset = i;
}
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
var sibDir = dir == "previousSibling" && !isXML;
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
if ( sibDir && elem.nodeType === 1 ) {
elem.sizcache = doneName;
elem.sizset = i;
}
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
var contains = document.compareDocumentPosition ? function(a, b){
return a.compareDocumentPosition(b) & 16;
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
var isXML = function(elem){
return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
!!elem.ownerDocument && isXML( elem.ownerDocument );
};
var posProcess = function(selector, context){
var tmpSet = [], later = "", match,
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.filter = Sizzle.filter;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
Sizzle.selectors.filters.hidden = function(elem){
return elem.offsetWidth === 0 || elem.offsetHeight === 0;
};
Sizzle.selectors.filters.visible = function(elem){
return elem.offsetWidth > 0 || elem.offsetHeight > 0;
};
Sizzle.selectors.filters.animated = function(elem){
return jQuery.grep(jQuery.timers, function(fn){
return elem === fn.elem;
}).length;
};
jQuery.multiFilter = function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return Sizzle.matches(expr, elems);
};
jQuery.dir = function( elem, dir ){
var matched = [], cur = elem[dir];
while ( cur && cur != document ) {
if ( cur.nodeType == 1 )
matched.push( cur );
cur = cur[dir];
}
return matched;
};
jQuery.nth = function(cur, result, dir, elem){
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] )
if ( cur.nodeType == 1 && ++num == result )
break;
return cur;
};
jQuery.sibling = function(n, elem){
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && n != elem )
r.push( n );
}
return r;
};
return;
window.Sizzle = Sizzle;
})();
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function(elem, types, handler, data) {
if ( elem.nodeType == 3 || elem.nodeType == 8 )
return;
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( elem.setInterval && elem != window )
elem = window;
// Make sure that the function being executed has a unique ID
if ( !handler.guid )
handler.guid = this.guid++;
// if data is passed, bind to handler
if ( data !== undefined ) {
// Create temporary function pointer to original handler
var fn = handler;
// Create unique handler function, wrapped around original handler
handler = this.proxy( fn );
// Store data in unique handler
handler.data = data;
}
// Init the element's event structure
var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
jQuery.event.handle.apply(arguments.callee.elem, arguments) :
undefined;
});
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native
// event in IE.
handle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
jQuery.each(types.split(/\s+/), function(index, type) {
// Namespaced event handlers
var namespaces = type.split(".");
type = namespaces.shift();
handler.type = namespaces.slice().sort().join(".");
// Get the current list of functions bound to this event
var handlers = events[type];
if ( jQuery.event.specialAll[type] )
jQuery.event.specialAll[type].setup.call(elem, data, namespaces);
// Init the event handler queue
if (!handlers) {
handlers = events[type] = {};
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
// Bind the global event handler to the element
if (elem.addEventListener)
elem.addEventListener(type, handle, false);
else if (elem.attachEvent)
elem.attachEvent("on" + type, handle);
}
}
// Add the function to the element's handler list
handlers[handler.guid] = handler;
// Keep track of which events have been used, for global triggering
jQuery.event.global[type] = true;
});
// Nullify elem to prevent memory leaks in IE
elem = null;
},
guid: 1,
global: {},
// Detach an event or set of events from an element
remove: function(elem, types, handler) {
// don't do events on text and comment nodes
if ( elem.nodeType == 3 || elem.nodeType == 8 )
return;
var events = jQuery.data(elem, "events"), ret, index;
if ( events ) {
// Unbind all events for the element
if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
for ( var type in events )
this.remove( elem, type + (types || "") );
else {
// types is actually an event object here
if ( types.type ) {
handler = types.handler;
types = types.type;
}
// Handle multiple events seperated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
jQuery.each(types.split(/\s+/), function(index, type){
// Namespaced event handlers
var namespaces = type.split(".");
type = namespaces.shift();
var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
if ( events[type] ) {
// remove the given handler for the given type
if ( handler )
delete events[type][handler.guid];
// remove all handlers for the given type
else
for ( var handle in events[type] )
// Handle the removal of namespaced events
if ( namespace.test(events[type][handle].type) )
delete events[type][handle];
if ( jQuery.event.specialAll[type] )
jQuery.event.specialAll[type].teardown.call(elem, namespaces);
// remove generic event handler if no more handlers exist
for ( ret in events[type] ) break;
if ( !ret ) {
if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
if (elem.removeEventListener)
elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
else if (elem.detachEvent)
elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
}
ret = null;
delete events[type];
}
}
});
}
// Remove the expando if it's no longer used
for ( ret in events ) break;
if ( !ret ) {
var handle = jQuery.data( elem, "handle" );
if ( handle ) handle.elem = null;
jQuery.removeData( elem, "events" );
jQuery.removeData( elem, "handle" );
}
}
},
// bubbling is internal
trigger: function( event, data, elem, bubbling ) {
// Event object or event type
var type = event.type || event;
if( !bubbling ){
event = typeof event === "object" ?
// jQuery.Event object
event[expando] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( this.global[type] )
jQuery.each( jQuery.cache, function(){
if ( this.events && this.events[type] )
jQuery.event.trigger( event, data, this.handle.elem );
});
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
return undefined;
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray(data);
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = jQuery.data(elem, "handle");
if ( handle )
handle.apply( elem, data );
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
event.result = false;
// Trigger the native events (except for clicks on links)
if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
this.triggered = true;
try {
elem[ type ]();
// prevent IE from throwing an error for some hidden elements
} catch (e) {}
}
this.triggered = false;
if ( !event.isPropagationStopped() ) {
var parent = elem.parentNode || elem.ownerDocument;
if ( parent )
jQuery.event.trigger(event, data, parent, true);
}
},
handle: function(event) {
// returned undefined or false
var all, handlers;
event = arguments[0] = jQuery.event.fix( event || window.event );
event.currentTarget = this;
// Namespaced event handlers
var namespaces = event.type.split(".");
event.type = namespaces.shift();
// Cache this now, all = true means, any handler
all = !namespaces.length && !event.exclusive;
var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
handlers = ( jQuery.data(this, "events") || {} )[event.type];
for ( var j in handlers ) {
var handler = handlers[j];
// Filter the functions by class
if ( all || namespace.test(handler.type) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handler;
event.data = handler.data;
var ret = handler.apply(this, arguments);
if( ret !== undefined ){
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if( event.isImmediatePropagationStopped() )
break;
}
}
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function(event) {
if ( event[expando] )
return event;
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ){
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target )
event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
// check if target is a textnode (safari)
if ( event.target.nodeType == 3 )
event.target = event.target.parentNode;
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement )
event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement, body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
}
// Add which for key events
if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
event.which = event.charCode || event.keyCode;
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey )
event.metaKey = event.ctrlKey;
// Add which for click: 1 == left; 2 == middle; 3 == right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button )
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
return event;
},
proxy: function( fn, proxy ){
proxy = proxy || function(){ return fn.apply(this, arguments); };
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
// So proxy can be declared as an argument
return proxy;
},
special: {
ready: {
// Make sure the ready event is setup
setup: bindReady,
teardown: function() {}
}
},
specialAll: {
live: {
setup: function( selector, namespaces ){
jQuery.event.add( this, namespaces[0], liveHandler );
},
teardown: function( namespaces ){
if ( namespaces.length ) {
var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
jQuery.each( (jQuery.data(this, "events").live || {}), function(){
if ( name.test(this.type) )
remove++;
});
if ( remove < 1 )
jQuery.event.remove( this, namespaces[0], liveHandler );
}
}
}
}
};
jQuery.Event = function( src ){
// Allow instantiation without the 'new' keyword
if( !this.preventDefault )
return new jQuery.Event(src);
// Event object
if( src && src.type ){
this.originalEvent = src;
this.type = src.type;
// Event type
}else
this.type = src;
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = now();
// Mark it as fixed
this[expando] = true;
};
function returnFalse(){
return false;
}
function returnTrue(){
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if( !e )
return;
// if preventDefault exists run it on the original event
if (e.preventDefault)
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
e.returnValue = false;
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if( !e )
return;
// if stopPropagation exists run it on the original event
if (e.stopPropagation)
e.stopPropagation();
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation:function(){
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Traverse up the tree
while ( parent && parent != this )
try { parent = parent.parentNode; }
catch(e) { parent = this; }
if( parent != this ){
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
};
jQuery.each({
mouseover: 'mouseenter',
mouseout: 'mouseleave'
}, function( orig, fix ){
jQuery.event.special[ fix ] = {
setup: function(){
jQuery.event.add( this, orig, withinElement, fix );
},
teardown: function(){
jQuery.event.remove( this, orig, withinElement );
}
};
});
jQuery.fn.extend({
bind: function( type, data, fn ) {
return type == "unload" ? this.one(type, data, fn) : this.each(function(){
jQuery.event.add( this, type, fn || data, fn && data );
});
},
one: function( type, data, fn ) {
var one = jQuery.event.proxy( fn || data, function(event) {
jQuery(this).unbind(event, one);
return (fn || data).apply( this, arguments );
});
return this.each(function(){
jQuery.event.add( this, type, one, fn && data);
});
},
unbind: function( type, fn ) {
return this.each(function(){
jQuery.event.remove( this, type, fn );
});
},
trigger: function( type, data ) {
return this.each(function(){
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if( this[0] ){
var event = jQuery.Event(type);
event.preventDefault();
event.stopPropagation();
jQuery.event.trigger( event, data, this[0] );
return event.result;
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments, i = 1;
// link all the functions, so any of them can unbind this click handler
while( i < args.length )
jQuery.event.proxy( fn, args[i++] );
return this.click( jQuery.event.proxy( fn, function(event) {
// Figure out which function to execute
this.lastToggle = ( this.lastToggle || 0 ) % i;
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ this.lastToggle++ ].apply( this, arguments ) || false;
}));
},
hover: function(fnOver, fnOut) {
return this.mouseenter(fnOver).mouseleave(fnOut);
},
ready: function(fn) {
// Attach the listeners
bindReady();
// If the DOM is already ready
if ( jQuery.isReady )
// Execute the function immediately
fn.call( document, jQuery );
// Otherwise, remember the function for later
else
// Add the function to the wait list
jQuery.readyList.push( fn );
return this;
},
live: function( type, fn ){
var proxy = jQuery.event.proxy( fn );
proxy.guid += this.selector + type;
jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );
return this;
},
die: function( type, fn ){
jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
return this;
}
});
function liveHandler( event ){
var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
stop = true,
elems = [];
jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
if ( check.test(fn.type) ) {
var elem = jQuery(event.target).closest(fn.data)[0];
if ( elem )
elems.push({ elem: elem, fn: fn });
}
});
elems.sort(function(a,b) {
return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
});
jQuery.each(elems, function(){
if ( this.fn.call(this.elem, event, this.fn.data) === false )
return (stop = false);
});
return stop;
}
function liveConvert(type, selector){
return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
}
jQuery.extend({
isReady: false,
readyList: [],
// Handle when the DOM is ready
ready: function() {
// Make sure that the DOM is not already loaded
if ( !jQuery.isReady ) {
// Remember that the DOM is ready
jQuery.isReady = true;
// If there are functions bound, to execute
if ( jQuery.readyList ) {
// Execute all of them
jQuery.each( jQuery.readyList, function(){
this.call( document, jQuery );
});
// Reset the list of functions
jQuery.readyList = null;
}
// Trigger any bound ready events
jQuery(document).triggerHandler("ready");
}
}
});
var readyBound = false;
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
jQuery.ready();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
if ( jQuery.isReady ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
"mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
"change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
// Handle event binding
jQuery.fn[name] = function(fn){
return fn ? this.bind(name, fn) : this.trigger(name);
};
});
// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery( window ).bind( 'unload', function(){
for ( var id in jQuery.cache )
// Skip the window
if ( id != 1 && jQuery.cache[ id ].handle )
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
});
(function(){
jQuery.support = {};
var root = document.documentElement,
script = document.createElement("script"),
div = document.createElement("div"),
id = "script" + (new Date).getTime();
div.style.display = "none";
div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';
var all = div.getElementsByTagName("*"),
a = div.getElementsByTagName("a")[0];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return;
}
jQuery.support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType == 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that you can get all elements in an <object> element
// IE 7 always returns no results
objectAll: !!div.getElementsByTagName("object")[0]
.getElementsByTagName("*").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText insted)
style: /red/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
opacity: a.style.opacity === "0.5",
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Will be defined later
scriptEval: false,
noCloneEvent: true,
boxModel: null
};
script.type = "text/javascript";
try {
script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
} catch(e){}
root.insertBefore( script, root.firstChild );
// Make sure that the execution of code works by injecting a script
// tag with appendChild/createTextNode
// (IE doesn't support this, fails, and uses .text instead)
if ( window[ id ] ) {
jQuery.support.scriptEval = true;
delete window[ id ];
}
root.removeChild( script );
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function(){
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
jQuery.support.noCloneEvent = false;
div.detachEvent("onclick", arguments.callee);
});
div.cloneNode(true).fireEvent("onclick");
}
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function(){
var div = document.createElement("div");
div.style.width = div.style.paddingLeft = "1px";
document.body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
document.body.removeChild( div ).style.display = 'none';
});
})();
var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";
jQuery.props = {
"for": "htmlFor",
"class": "className",
"float": styleFloat,
cssFloat: styleFloat,
styleFloat: styleFloat,
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
tabindex: "tabIndex"
};
jQuery.fn.extend({
// Keep a copy of the old load
_load: jQuery.fn.load,
load: function( url, params, callback ) {
if ( typeof url !== "string" )
return this._load( url );
var off = url.indexOf(" ");
if ( off >= 0 ) {
var selector = url.slice(off, url.length);
url = url.slice(0, off);
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params )
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else if( typeof params === "object" ) {
params = jQuery.param( params );
type = "POST";
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function(res, status){
// If successful, inject the HTML into all the matched elements
if ( status == "success" || status == "notmodified" )
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div/>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
if( callback )
self.each( callback, [res.responseText, status, res] );
}
});
return this;
},
serialize: function() {
return jQuery.param(this.serializeArray());
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray(this.elements) : this;
})
.filter(function(){
return this.name && !this.disabled &&
(this.checked || /select|textarea/i.test(this.nodeName) ||
/text|hidden|password|search/i.test(this.type));
})
.map(function(i, elem){
var val = jQuery(this).val();
return val == null ? null :
jQuery.isArray(val) ?
jQuery.map( val, function(val, i){
return {name: elem.name, value: val};
}) :
{name: elem.name, value: val};
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
jQuery.fn[o] = function(f){
return this.bind(o, f);
};
});
var jsc = now();
jQuery.extend({
get: function( url, data, callback, type ) {
// shift arguments if data argument was ommited
if ( jQuery.isFunction( data ) ) {
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
username: null,
password: null,
*/
// Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
// This function can be overriden by calling jQuery.ajaxSetup
xhr:function(){
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
},
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
script: "text/javascript, application/javascript",
json: "application/json, text/javascript",
text: "text/plain",
_default: "*/*"
}
},
// Last-Modified header cache for next request
lastModified: {},
ajax: function( s ) {
// Extend the settings, but re-extend 's' so that it can be
// checked again later (in the test suite, specifically)
s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
var jsonp, jsre = /=\?(&|$)/g, status, data,
type = s.type.toUpperCase();
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" )
s.data = jQuery.param(s.data);
// Handle JSONP Parameter Callbacks
if ( s.dataType == "jsonp" ) {
if ( type == "GET" ) {
if ( !s.url.match(jsre) )
s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
} else if ( !s.data || !s.data.match(jsre) )
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
jsonp = "jsonp" + jsc++;
// Replace the =? sequence both in the query string and the data
if ( s.data )
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
window[ jsonp ] = function(tmp){
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;
try{ delete window[ jsonp ]; } catch(e){}
if ( head )
head.removeChild( script );
};
}
if ( s.dataType == "script" && s.cache == null )
s.cache = false;
if ( s.cache === false && type == "GET" ) {
var ts = now();
// try replacing _= if it is there
var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
// if nothing was replaced, add timestamp to the end
s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
}
// If data is available, append data to url for get requests
if ( s.data && type == "GET" ) {
s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
// IE likes to send both get and post data, prevent this
s.data = null;
}
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
jQuery.event.trigger( "ajaxStart" );
// Matches an absolute URL, and saves the domain
var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType == "script" && type == "GET" && parts
&& ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = s.url;
if (s.scriptCharset)
script.charset = s.scriptCharset;
// Handle Script loading
if ( !jsonp ) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
success();
complete();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
}
head.appendChild(script);
// We handle everything using the script element injection
return undefined;
}
var requestDone = false;
// Create the request object
var xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if( s.username )
xhr.open(type, s.url, s.async, s.username, s.password);
else
xhr.open(type, s.url, s.async);
// Need an extra try/catch for cross domain requests in Firefox 3
try {
// Set the correct header, if data is being sent
if ( s.data )
xhr.setRequestHeader("Content-Type", s.contentType);
// Set the If-Modified-Since header, if ifModified mode.
if ( s.ifModified )
xhr.setRequestHeader("If-Modified-Since",
jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
// Set header so the called script knows that it's an XMLHttpRequest
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Set the Accepts header for the server, depending on the dataType
xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
s.accepts[ s.dataType ] + ", */*" :
s.accepts._default );
} catch(e){}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// close opended socket
xhr.abort();
return false;
}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xhr, s]);
// Wait for a response to come back
var onreadystatechange = function(isTimeout){
// The request was aborted, clear the interval and decrement jQuery.active
if (xhr.readyState == 0) {
if (ival) {
// clear poll interval
clearInterval(ival);
ival = null;
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
}
// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
requestDone = true;
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
status = isTimeout == "timeout" ? "timeout" :
!jQuery.httpSuccess( xhr ) ? "error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
"success";
if ( status == "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch(e) {
status = "parsererror";
}
}
// Make sure that the request was successful or notmodified
if ( status == "success" ) {
// Cache Last-Modified header, if ifModified mode.
var modRes;
try {
modRes = xhr.getResponseHeader("Last-Modified");
} catch(e) {} // swallow exception thrown by FF if header is not available
if ( s.ifModified && modRes )
jQuery.lastModified[s.url] = modRes;
// JSONP handles its own success callback
if ( !jsonp )
success();
} else
jQuery.handleError(s, xhr, status);
// Fire the complete handlers
complete();
if ( isTimeout )
xhr.abort();
// Stop memory leaks
if ( s.async )
xhr = null;
}
};
if ( s.async ) {
// don't attach the handler to the request, just poll it instead
var ival = setInterval(onreadystatechange, 13);
// Timeout checker
if ( s.timeout > 0 )
setTimeout(function(){
// Check to see if the request is still happening
if ( xhr && !requestDone )
onreadystatechange( "timeout" );
}, s.timeout);
}
// Send the data
try {
xhr.send(s.data);
} catch(e) {
jQuery.handleError(s, xhr, null, e);
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async )
onreadystatechange();
function success(){
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
}
function complete(){
// Process result
if ( s.complete )
s.complete(xhr, status);
// The request was completed
if ( s.global )
jQuery.event.trigger( "ajaxComplete", [xhr, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
}
// return XMLHttpRequest to allow aborting the request etc.
return xhr;
},
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) s.error( xhr, status, e );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxError", [xhr, s, e] );
},
// Counter for holding the number of active queries
active: 0,
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol == "file:" ||
( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
} catch(e){}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xhr, url ) {
try {
var xhrRes = xhr.getResponseHeader("Last-Modified");
// Firefox always returns 200. check Last-Modified date
return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
} catch(e){}
return false;
},
httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type"),
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.tagName == "parsererror" )
throw "parsererror";
// Allow a pre-filtering function to sanitize the response
// s != null is checked to keep backwards compatibility
if( s && s.dataFilter )
data = s.dataFilter( data, type );
// The filter can actually parse the response
if( typeof data === "string" ){
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
data = window["eval"]("(" + data + ")");
}
return data;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a ) {
var s = [ ];
function add( key, value ){
s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
};
// If an array was passed in, assume that it is an array
// of form elements
if ( jQuery.isArray(a) || a.jquery )
// Serialize the form elements
jQuery.each( a, function(){
add( this.name, this.value );
});
// Otherwise, assume that it's an object of key/value pairs
else
// Serialize the key/values
for ( var j in a )
// If the value is an array then the key names need to be repeated
if ( jQuery.isArray(a[j]) )
jQuery.each( a[j], function(){
add( j, this );
});
else
add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
// Return the resulting serialization
return s.join("&").replace(/%20/g, "+");
}
});
var elemdisplay = {},
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
function genFx( type, num ){
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
obj[ this ] = type;
});
return obj;
}
jQuery.fn.extend({
show: function(speed,callback){
if ( speed ) {
return this.animate( genFx("show", 3), speed, callback);
} else {
for ( var i = 0, l = this.length; i < l; i++ ){
var old = jQuery.data(this[i], "olddisplay");
this[i].style.display = old || "";
if ( jQuery.css(this[i], "display") === "none" ) {
var tagName = this[i].tagName, display;
if ( elemdisplay[ tagName ] ) {
display = elemdisplay[ tagName ];
} else {
var elem = jQuery("<" + tagName + " />").appendTo("body");
display = elem.css("display");
if ( display === "none" )
display = "block";
elem.remove();
elemdisplay[ tagName ] = display;
}
jQuery.data(this[i], "olddisplay", display);
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var i = 0, l = this.length; i < l; i++ ){
this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
}
return this;
}
},
hide: function(speed,callback){
if ( speed ) {
return this.animate( genFx("hide", 3), speed, callback);
} else {
for ( var i = 0, l = this.length; i < l; i++ ){
var old = jQuery.data(this[i], "olddisplay");
if ( !old && old !== "none" )
jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var i = 0, l = this.length; i < l; i++ ){
this[i].style.display = "none";
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2 ){
var bool = typeof fn === "boolean";
return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
this._toggle.apply( this, arguments ) :
fn == null || bool ?
this.each(function(){
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
}) :
this.animate(genFx("toggle", 3), fn, fn2);
},
fadeTo: function(speed,to,callback){
return this.animate({opacity: to}, speed, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
return this[ optall.queue === false ? "each" : "queue" ](function(){
var opt = jQuery.extend({}, optall), p,
hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
self = this;
for ( p in prop ) {
if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
return opt.complete.call(this);
if ( ( p == "height" || p == "width" ) && this.style ) {
// Store display property
opt.display = jQuery.css(this, "display");
// Make sure that nothing sneaks out
opt.overflow = this.style.overflow;
}
}
if ( opt.overflow != null )
this.style.overflow = "hidden";
opt.curAnim = jQuery.extend({}, prop);
jQuery.each( prop, function(name, val){
var e = new jQuery.fx( self, opt, name );
if ( /toggle|show|hide/.test(val) )
e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
else {
var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
start = e.cur(true) || 0;
if ( parts ) {
var end = parseFloat(parts[2]),
unit = parts[3] || "px";
// We need to compute starting value
if ( unit != "px" ) {
self.style[ name ] = (end || 1) + unit;
start = ((end || 1) / e.cur(true)) * start;
self.style[ name ] = start + unit;
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] )
end = ((parts[1] == "-=" ? -1 : 1) * end) + start;
e.custom( start, end, unit );
} else
e.custom( start, val, "" );
}
});
// For JS strict compliance
return true;
});
},
stop: function(clearQueue, gotoEnd){
var timers = jQuery.timers;
if (clearQueue)
this.queue([]);
this.each(function(){
// go in reverse order so anything added to the queue during the loop is ignored
for ( var i = timers.length - 1; i >= 0; i-- )
if ( timers[i].elem == this ) {
if (gotoEnd)
// force the next step to be the last
timers[i](true);
timers.splice(i, 1);
}
});
// start the next in the queue if the last step wasn't forced
if (!gotoEnd)
this.dequeue();
return this;
}
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show", 1),
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" }
}, function( name, props ){
jQuery.fn[ name ] = function( speed, callback ){
return this.animate( props, speed, callback );
};
});
jQuery.extend({
speed: function(speed, easing, fn) {
var opt = typeof speed === "object" ? speed : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function(){
if ( opt.queue !== false )
jQuery(this).dequeue();
if ( jQuery.isFunction( opt.old ) )
opt.old.call( this );
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ){
this.options = options;
this.elem = elem;
this.prop = prop;
if ( !options.orig )
options.orig = {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function(){
if ( this.options.step )
this.options.step.call( this.elem, this.now, this );
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
// Set display property to block for height/width animations
if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
this.elem.style.display = "block";
},
// Get the current size
cur: function(force){
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
return this.elem[ this.prop ];
var r = parseFloat(jQuery.css(this.elem, this.prop, force));
return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
},
// Start an animation from one number to another
custom: function(from, to, unit){
this.startTime = now();
this.start = from;
this.end = to;
this.unit = unit || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
var self = this;
function t(gotoEnd){
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval(function(){
var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length ) {
clearInterval( timerId );
timerId = undefined;
}
}, 13);
}
},
// Simple 'show' function
show: function(){
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any
// flash of content
this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());
// Start by showing the element
jQuery(this.elem).show();
},
// Simple 'hide' function
hide: function(){
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function(gotoEnd){
var t = now();
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
var done = true;
for ( var i in this.options.curAnim )
if ( this.options.curAnim[i] !== true )
done = false;
if ( done ) {
if ( this.options.display != null ) {
// Reset the overflow
this.elem.style.overflow = this.options.overflow;
// Reset the display
this.elem.style.display = this.options.display;
if ( jQuery.css(this.elem, "display") == "none" )
this.elem.style.display = "block";
}
// Hide the element if the "hide" operation was done
if ( this.options.hide )
jQuery(this.elem).hide();
// Reset the properties, if the item has been hidden or shown
if ( this.options.hide || this.options.show )
for ( var p in this.options.curAnim )
jQuery.attr(this.elem.style, p, this.options.orig[p]);
// Execute the complete function
this.options.complete.call( this.elem );
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
speeds:{
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function(fx){
jQuery.attr(fx.elem.style, "opacity", fx.now);
},
_default: function(fx){
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
else
fx.elem[ fx.prop ] = fx.now;
}
}
});
if ( document.documentElement["getBoundingClientRect"] )
jQuery.fn.offset = function() {
if ( !this[0] ) return { top: 0, left: 0 };
if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
var box = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop,
left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
return { top: top, left: left };
};
else
jQuery.fn.offset = function() {
if ( !this[0] ) return { top: 0, left: 0 };
if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
jQuery.offset.initialized || jQuery.offset.initialize();
var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
body = doc.body, defaultView = doc.defaultView,
prevComputedStyle = defaultView.getComputedStyle(elem, null),
top = elem.offsetTop, left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
computedStyle = defaultView.getComputedStyle(elem, null);
top -= elem.scrollTop, left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop, left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
top += parseInt( computedStyle.borderTopWidth, 10) || 0,
left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
top += parseInt( computedStyle.borderTopWidth, 10) || 0,
left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
top += body.offsetTop,
left += body.offsetLeft;
if ( prevComputedStyle.position === "fixed" )
top += Math.max(docElem.scrollTop, body.scrollTop),
left += Math.max(docElem.scrollLeft, body.scrollLeft);
return { top: top, left: left };
};
jQuery.offset = {
initialize: function() {
if ( this.initialized ) return;
var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';
rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
for ( prop in rules ) container.style[prop] = rules[prop];
container.innerHTML = html;
body.insertBefore(container, body.firstChild);
innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
body.style.marginTop = '1px';
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
body.style.marginTop = bodyMarginTop;
body.removeChild(container);
this.initialized = true;
},
bodyOffset: function(body) {
jQuery.offset.initialized || jQuery.offset.initialize();
var top = body.offsetTop, left = body.offsetLeft;
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
top += parseInt( jQuery.curCSS(body, 'marginTop', true), 10 ) || 0,
left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
return { top: top, left: left };
}
};
jQuery.fn.extend({
position: function() {
var left = 0, top = 0, results;
if ( this[0] ) {
// Get *real* offsetParent
var offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= num( this, 'marginTop' );
offset.left -= num( this, 'marginLeft' );
// Add offsetParent borders
parentOffset.top += num( offsetParent, 'borderTopWidth' );
parentOffset.left += num( offsetParent, 'borderLeftWidth' );
// Subtract the two offsets
results = {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
}
return results;
},
offsetParent: function() {
var offsetParent = this[0].offsetParent || document.body;
while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
offsetParent = offsetParent.offsetParent;
return jQuery(offsetParent);
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
var method = 'scroll' + name;
jQuery.fn[ method ] = function(val) {
if (!this[0]) return null;
return val !== undefined ?
// Set the scroll offset
this.each(function() {
this == window || this == document ?
window.scrollTo(
!i ? val : jQuery(window).scrollLeft(),
i ? val : jQuery(window).scrollTop()
) :
this[ method ] = val;
}) :
// Return the scroll offset
this[0] == window || this[0] == document ?
self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
jQuery.boxModel && document.documentElement[ method ] ||
document.body[ method ] :
this[0][ method ];
};
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function(i, name){
var tl = i ? "Left" : "Top", // top or left
br = i ? "Right" : "Bottom", // bottom or right
lower = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function(){
return this[0] ?
jQuery.css( this[0], lower, false, "padding" ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function(margin) {
return this[0] ?
jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) :
null;
};
var type = name.toLowerCase();
jQuery.fn[ type ] = function( size ) {
// Get window width or height
return this[0] == window ?
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
document.body[ "client" + name ] :
// Get document width or height
this[0] == document ?
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
Math.max(
document.documentElement["client" + name],
document.body["scroll" + name], document.documentElement["scroll" + name],
document.body["offset" + name], document.documentElement["offset" + name]
) :
// Get or set width or height on the element
size === undefined ?
// Get width or height on the element
(this.length ? jQuery.css( this[0], type ) : null) :
// Set the width or height on the element (default to pixels if value is unitless)
this.css( type, typeof size === "string" ? size : size + "px" );
};
});
})();
|
/**
* @license Highcharts JS v6.0.1 (2017-10-05)
*
* Indicator series type for Highstock
*
* (c) 2010-2017 Sebastian Bochan
*
* License: www.highcharts.com/license
*/
'use strict';
(function(factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function(Highcharts) {
(function(H) {
var isArray = H.isArray,
seriesType = H.seriesType;
// Utils:
function sumArray(array) {
return H.reduce(array, function(prev, cur) {
return prev + cur;
}, 0);
}
function meanDeviation(arr, sma) {
var len = arr.length,
sum = 0,
i;
for (i = 0; i < len; i++) {
sum += Math.abs(sma - (arr[i]));
}
return sum;
}
/**
* The CCI series type.
*
* @constructor seriesTypes.cci
* @augments seriesTypes.sma
*/
seriesType('cci', 'sma',
/**
* Commodity Channel Index (CCI). This series requires `linkedTo` option to be set.
*
* @extends {plotOptions.sma}
* @product highstock
* @sample {highstock} stock/indicators/cci Exponential moving average indicator
* @since 6.0.0
* @optionparent plotOptions.cci
*/
{
name: 'CCI (14)',
params: {
period: 14
}
}, {
getValues: function(series, params) {
var period = params.period,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
TP = [],
periodTP = [],
range = 1,
CCI = [],
xData = [],
yData = [],
CCIPoint, p, len, smaTP, TPtemp, meanDev, i;
// CCI requires close value
if (xVal.length <= period || !isArray(yVal[0]) || yVal[0].length !== 4) {
return false;
}
// accumulate first N-points
while (range < period) {
p = yVal[range - 1];
TP.push((p[1] + p[2] + p[3]) / 3);
range++;
}
for (i = period; i <= yValLen; i++) {
p = yVal[i - 1];
TPtemp = (p[1] + p[2] + p[3]) / 3;
len = TP.push(TPtemp);
periodTP = TP.slice(len - period);
smaTP = sumArray(periodTP) / period;
meanDev = meanDeviation(periodTP, smaTP) / period;
CCIPoint = ((TPtemp - smaTP) / (0.015 * meanDev));
CCI.push([xVal[i - 1], CCIPoint]);
xData.push(xVal[i - 1]);
yData.push(CCIPoint);
}
return {
values: CCI,
xData: xData,
yData: yData
};
}
});
/**
* A `CCI` series. If the [type](#series.cci.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* For options that apply to multiple series, it is recommended to add
* them to the [plotOptions.series](#plotOptions.series) options structure.
* To apply to all series of this specific type, apply it to
* [plotOptions.cci](#plotOptions.cci).
*
* @type {Object}
* @since 6.0.0
* @extends series,plotOptions.cci
* @excluding data,dataParser,dataURL
* @product highstock
* @apioption series.cci
*/
/**
* @type {Array<Object|Array>}
* @since 6.0.0
* @extends series.sma.data
* @product highstock
* @apioption series.cci.data
*/
}(Highcharts));
}));
|
/*
Highcharts JS v6.0.0 (2017-10-04)
Money Flow Index indicator for Highstock
(c) 2010-2017 Grzegorz Blachliski
License: www.highcharts.com/license
*/
(function(e){"object"===typeof module&&module.exports?module.exports=e:e(Highcharts)})(function(e){(function(e){function p(b){return b.reduce(function(c,b){return c+b})}function m(b){return(b[1]+b[2]+b[3])/3}var u=e.isArray;e.seriesType("mfi","sma",{name:"Money Flow Index (14)",params:{period:14,volumeSeriesID:"volume",decimals:4}},{getValues:function(b,c){var d=c.period,n=b.xData,g=b.yData,v=g?g.length:0,w=c.decimals,h=1,a=b.chart.get(c.volumeSeriesID);b=a&&a.yData;var q=[],r=[],t=[],k=[],l=[],f;
if(!a)return e.error("Series "+c.volumeSeriesID+" not found! Check `volumeSeriesID`.",!0);if(n.length<=d||!u(g[0])||4!==g[0].length||!b)return!1;for(c=m(g[h]);h<d+1;)a=c,c=m(g[h]),a=c>=a?!0:!1,f=c*b[h],k.push(a?f:0),l.push(a?0:f),h++;for(d=h-1;d<v;d++)d>h-1&&(k.shift(),l.shift(),a=c,c=m(g[d]),a=c>a?!0:!1,f=c*b[d],k.push(a?f:0),l.push(a?0:f)),a=p(l),f=p(k),a=f/a,a=parseFloat((100-100/(1+a)).toFixed(w)),q.push([n[d],a]),r.push(n[d]),t.push(a);return{values:q,xData:r,yData:t}}})})(e)});
|
window.addEventListener("load", function() {
console.log("Hello World!");
});
|
IntlMessageFormat.__addLocaleData({locale:"to", messageformat:{pluralFunction:function (n) { return"other"; }}}); |
describe('$meteorStopper service', function() {
var $meteorStopper;
var $rootScope;
var $scope;
var $mock;
var $meteorMock = function() {
return {
stop: function() {}
};
};
beforeEach(angular.mock.module('angular-meteor.stopper'));
beforeEach(angular.mock.inject(function(_$meteorStopper_, _$rootScope_) {
$meteorStopper = _$meteorStopper_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$scope.$meteorMock = $meteorStopper($meteorMock);
$mock = $scope.$meteorMock();
}));
describe('#subscribe()', function() {
beforeEach(function() {
spyOn(Meteor, 'subscribe').and.callThrough();
});
it('should call meteor subscription with scope as the context', function() {
$mock.subscribe();
expect(Meteor.subscribe.calls.mostRecent().object).toEqual($scope);
});
});
describe('scope destruction', function() {
beforeEach(function() {
spyOn($mock, 'stop');
});
it('should stop meteor entity listeners on scope destruction', function() {
$scope.$destroy();
expect($mock.stop.calls.count()).toEqual(1);
});
});
}); |
/* Highcharts plugin to handle text symbols */
(function (H) {
function symbolWrap(proceed, symbol, x, y, w, h, options) {
if (symbol.indexOf('text:') === 0) {
var text = unescape(JSON.parse('"\\u' + symbol.split(':')[1] + '"')),
svgElem = this.text(text, x, y)
.attr({
translateY: h,
translateX: -1
})
.css({
fontFamily: 'FontAwesome',
fontSize: h * 2
});
if (svgElem.renderer.isVML) {
svgElem.fillSetter = function (value, key, element) {
element.style.color = H.Color(value).get('rgb');
};
}
return svgElem;
}
return proceed.apply(this, [].slice.call(arguments, 1));
}
H.wrap(H.SVGRenderer.prototype, 'symbol', symbolWrap);
if (H.VMLRenderer) {
H.wrap(H.VMLRenderer.prototype, 'symbol', symbolWrap);
}
// Load the font for SVG files also
/*
H.wrap(H.Chart.prototype, 'getSVG', function (proceed) {
var svg = proceed.call(this);
svg = '<?xml-stylesheet type="text/css" ' +
'href="http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" ?>' +
svg;
return svg;
});
*/
}(Highcharts));
|
'use strict';
var angular = require('angular');
angular
.module('mwl.calendar')
.filter('calendarTruncateEventTitle', function() {
return function(string, length, boxHeight) {
if (!string) {
return '';
}
//Only truncate if if actually needs truncating
if (string.length >= length && string.length / 20 > boxHeight / 30) {
return string.substr(0, length) + '...';
} else {
return string;
}
};
});
|
/*
* Sugar Library v1.3.6
*
* Freely distributable and licensed under the MIT-style license.
* Copyright (c) 2012 Andrew Plummer
* http://sugarjs.com/
*
* ---------------------------- */
(function(){
/***
* @package Core
* @description Internal utility and common methods.
***/
// A few optimizations for Google Closure Compiler will save us a couple kb in the release script.
var object = Object, array = Array, regexp = RegExp, date = Date, string = String, number = Number, math = Math, Undefined;
// The global context
var globalContext = typeof global !== 'undefined' ? global : this;
// defineProperty exists in IE8 but will error when trying to define a property on
// native objects. IE8 does not have defineProperies, however, so this check saves a try/catch block.
var definePropertySupport = object.defineProperty && object.defineProperties;
// Class initializers and class helpers
var ClassNames = 'Array,Boolean,Date,Function,Number,String,RegExp'.split(',');
var isArray = buildClassCheck(ClassNames[0]);
var isBoolean = buildClassCheck(ClassNames[1]);
var isDate = buildClassCheck(ClassNames[2]);
var isFunction = buildClassCheck(ClassNames[3]);
var isNumber = buildClassCheck(ClassNames[4]);
var isString = buildClassCheck(ClassNames[5]);
var isRegExp = buildClassCheck(ClassNames[6]);
function buildClassCheck(type) {
return function(obj) {
return className(obj) === '[object '+type+']';
}
}
function className(obj) {
return object.prototype.toString.call(obj);
}
function initializeClasses() {
initializeClass(object);
iterateOverObject(ClassNames, function(i,name) {
initializeClass(globalContext[name]);
});
}
function initializeClass(klass) {
if(klass['SugarMethods']) return;
defineProperty(klass, 'SugarMethods', {});
extend(klass, false, false, {
'restore': function() {
var all = arguments.length === 0, methods = multiArgs(arguments);
iterateOverObject(klass['SugarMethods'], function(name, m) {
if(all || methods.indexOf(name) > -1) {
defineProperty(m.instance ? klass.prototype : klass, name, m.method);
}
});
},
'extend': function(methods, override, instance) {
extend(klass, instance !== false, override, methods);
}
});
}
// Class extending methods
function extend(klass, instance, override, methods) {
var extendee = instance ? klass.prototype : klass, original;
initializeClass(klass);
iterateOverObject(methods, function(name, method) {
original = extendee[name];
if(typeof override === 'function') {
method = wrapNative(extendee[name], method, override);
}
if(override !== false || !extendee[name]) {
defineProperty(extendee, name, method);
}
// If the method is internal to Sugar, then store a reference so it can be restored later.
klass['SugarMethods'][name] = { instance: instance, method: method, original: original };
});
}
function extendSimilar(klass, instance, override, set, fn) {
var methods = {};
set = isString(set) ? set.split(',') : set;
set.forEach(function(name, i) {
fn(methods, name, i);
});
extend(klass, instance, override, methods);
}
function wrapNative(nativeFn, extendedFn, condition) {
return function() {
if(nativeFn && (condition === true || !condition.apply(this, arguments))) {
return nativeFn.apply(this, arguments);
} else {
return extendedFn.apply(this, arguments);
}
}
}
function defineProperty(target, name, method) {
if(definePropertySupport) {
object.defineProperty(target, name, { 'value': method, 'configurable': true, 'enumerable': false, 'writable': true });
} else {
target[name] = method;
}
}
// Argument helpers
function multiArgs(args, fn) {
var result = [], i;
for(i = 0; i < args.length; i++) {
result.push(args[i]);
if(fn) fn.call(args, args[i], i);
}
return result;
}
function checkCallback(fn) {
if(!fn || !fn.call) {
throw new TypeError('Callback is not callable');
}
}
// General helpers
function isDefined(o) {
return o !== Undefined;
}
function isUndefined(o) {
return o === Undefined;
}
// Object helpers
function isObjectPrimitive(obj) {
// Check for null
return obj && typeof obj === 'object';
}
function isObject(obj) {
// === on the constructor is not safe across iframes
// 'hasOwnProperty' ensures that the object also inherits
// from Object, which is false for DOMElements in IE.
return !!obj && className(obj) === '[object Object]' && 'hasOwnProperty' in obj;
}
function hasOwnProperty(obj, key) {
return object['hasOwnProperty'].call(obj, key);
}
function iterateOverObject(obj, fn) {
var key;
for(key in obj) {
if(!hasOwnProperty(obj, key)) continue;
if(fn.call(obj, key, obj[key], obj) === false) break;
}
}
function simpleMerge(target, source) {
iterateOverObject(source, function(key) {
target[key] = source[key];
});
return target;
}
// Hash definition
function Hash(obj) {
simpleMerge(this, obj);
};
Hash.prototype.constructor = object;
// Number helpers
function getRange(start, stop, fn, step) {
var arr = [], i = parseInt(start), down = step < 0;
while((!down && i <= stop) || (down && i >= stop)) {
arr.push(i);
if(fn) fn.call(this, i);
i += step || 1;
}
return arr;
}
function round(val, precision, method) {
var fn = math[method || 'round'];
var multiplier = math.pow(10, math.abs(precision || 0));
if(precision < 0) multiplier = 1 / multiplier;
return fn(val * multiplier) / multiplier;
}
function ceil(val, precision) {
return round(val, precision, 'ceil');
}
function floor(val, precision) {
return round(val, precision, 'floor');
}
function padNumber(num, place, sign, base) {
var str = math.abs(num).toString(base || 10);
str = repeatString(place - str.replace(/\.\d+/, '').length, '0') + str;
if(sign || num < 0) {
str = (num < 0 ? '-' : '+') + str;
}
return str;
}
function getOrdinalizedSuffix(num) {
if(num >= 11 && num <= 13) {
return 'th';
} else {
switch(num % 10) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
default: return 'th';
}
}
}
// String helpers
// WhiteSpace/LineTerminator as defined in ES5.1 plus Unicode characters in the Space, Separator category.
function getTrimmableCharacters() {
return '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
}
function repeatString(times, str) {
return array(math.max(0, isDefined(times) ? times : 1) + 1).join(str || '');
}
// RegExp helpers
function getRegExpFlags(reg, add) {
var flags = reg.toString().match(/[^/]*$/)[0];
if(add) {
flags = (flags + add).split('').sort().join('').replace(/([gimy])\1+/g, '$1');
}
return flags;
}
function escapeRegExp(str) {
if(!isString(str)) str = string(str);
return str.replace(/([\\/'*+?|()\[\]{}.^$])/g,'\\$1');
}
// Specialized helpers
// Used by Array#unique and Object.equal
function stringify(thing, stack) {
var type = typeof thing,
thingIsObject,
thingIsArray,
klass, value,
arr, key, i;
// Return quickly if string to save cycles
if(type === 'string') return thing;
klass = object.prototype.toString.call(thing)
thingIsObject = isObject(thing);
thingIsArray = klass === '[object Array]';
if(thing != null && thingIsObject || thingIsArray) {
// This method for checking for cyclic structures was egregiously stolen from
// the ingenious method by @kitcambridge from the Underscore script:
// https://github.com/documentcloud/underscore/issues/240
if(!stack) stack = [];
// Allowing a step into the structure before triggering this
// script to save cycles on standard JSON structures and also to
// try as hard as possible to catch basic properties that may have
// been modified.
if(stack.length > 1) {
i = stack.length;
while (i--) {
if (stack[i] === thing) {
return 'CYC';
}
}
}
stack.push(thing);
value = string(thing.constructor);
arr = thingIsArray ? thing : object.keys(thing).sort();
for(i = 0; i < arr.length; i++) {
key = thingIsArray ? i : arr[i];
value += key + stringify(thing[key], stack);
}
stack.pop();
} else if(1 / thing === -Infinity) {
value = '-0';
} else {
value = string(thing && thing.valueOf ? thing.valueOf() : thing);
}
return type + klass + value;
}
function isEqual(a, b) {
if(objectIsMatchedByValue(a) && objectIsMatchedByValue(b)) {
return stringify(a) === stringify(b);
} else {
return a === b;
}
}
function objectIsMatchedByValue(obj) {
var klass = className(obj);
return klass === '[object Date]' ||
klass === '[object Array]' ||
klass === '[object String]' ||
klass === '[object Number]' ||
klass === '[object RegExp]' ||
klass === '[object Boolean]' ||
klass === '[object Arguments]' ||
isObject(obj);
}
// Used by Array#at and String#at
function entryAtIndex(arr, args, str) {
var result = [], length = arr.length, loop = args[args.length - 1] !== false, r;
multiArgs(args, function(index) {
if(isBoolean(index)) return false;
if(loop) {
index = index % length;
if(index < 0) index = length + index;
}
r = str ? arr.charAt(index) || '' : arr[index];
result.push(r);
});
return result.length < 2 ? result[0] : result;
}
// Object class methods implemented as instance methods
function buildObjectInstanceMethods(set, target) {
extendSimilar(target, true, false, set, function(methods, name) {
methods[name + (name === 'equal' ? 's' : '')] = function() {
return object[name].apply(null, [this].concat(multiArgs(arguments)));
}
});
}
initializeClasses();
/***
* @package ES5
* @description Shim methods that provide ES5 compatible functionality. This package can be excluded if you do not require legacy browser support (IE8 and below).
*
***/
/***
* Object module
*
***/
extend(object, false, false, {
'keys': function(obj) {
var keys = [];
if(!isObjectPrimitive(obj) && !isRegExp(obj) && !isFunction(obj)) {
throw new TypeError('Object required');
}
iterateOverObject(obj, function(key, value) {
keys.push(key);
});
return keys;
}
});
/***
* Array module
*
***/
// ECMA5 methods
function arrayIndexOf(arr, search, fromIndex, increment) {
var length = arr.length,
fromRight = increment == -1,
start = fromRight ? length - 1 : 0,
index = toIntegerWithDefault(fromIndex, start);
if(index < 0) {
index = length + index;
}
if((!fromRight && index < 0) || (fromRight && index >= length)) {
index = start;
}
while((fromRight && index >= 0) || (!fromRight && index < length)) {
if(arr[index] === search) {
return index;
}
index += increment;
}
return -1;
}
function arrayReduce(arr, fn, initialValue, fromRight) {
var length = arr.length, count = 0, defined = isDefined(initialValue), result, index;
checkCallback(fn);
if(length == 0 && !defined) {
throw new TypeError('Reduce called on empty array with no initial value');
} else if(defined) {
result = initialValue;
} else {
result = arr[fromRight ? length - 1 : count];
count++;
}
while(count < length) {
index = fromRight ? length - count - 1 : count;
if(index in arr) {
result = fn(result, arr[index], index, arr);
}
count++;
}
return result;
}
function toIntegerWithDefault(i, d) {
if(isNaN(i)) {
return d;
} else {
return parseInt(i >> 0);
}
}
function checkFirstArgumentExists(args) {
if(args.length === 0) {
throw new TypeError('First argument must be defined');
}
}
extend(array, false, false, {
/***
*
* @method Array.isArray(<obj>)
* @returns Boolean
* @short Returns true if <obj> is an Array.
* @extra This method is provided for browsers that don't support it internally.
* @example
*
* Array.isArray(3) -> false
* Array.isArray(true) -> false
* Array.isArray('wasabi') -> false
* Array.isArray([1,2,3]) -> true
*
***/
'isArray': function(obj) {
return isArray(obj);
}
});
extend(array, true, false, {
/***
* @method every(<f>, [scope])
* @returns Boolean
* @short Returns true if all elements in the array match <f>.
* @extra [scope] is the %this% object. %all% is provided an alias. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ ['a','a','a'].every(function(n) {
* return n == 'a';
* });
* ['a','a','a'].every('a') -> true
* [{a:2},{a:2}].every({a:2}) -> true
***/
'every': function(fn, scope) {
var length = this.length, index = 0;
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && !fn.call(scope, this[index], index, this)) {
return false;
}
index++;
}
return true;
},
/***
* @method some(<f>, [scope])
* @returns Boolean
* @short Returns true if any element in the array matches <f>.
* @extra [scope] is the %this% object. %any% is provided as an alias. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ ['a','b','c'].some(function(n) {
* return n == 'a';
* });
+ ['a','b','c'].some(function(n) {
* return n == 'd';
* });
* ['a','b','c'].some('a') -> true
* [{a:2},{b:5}].some({a:2}) -> true
***/
'some': function(fn, scope) {
var length = this.length, index = 0;
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && fn.call(scope, this[index], index, this)) {
return true;
}
index++;
}
return false;
},
/***
* @method map(<map>, [scope])
* @returns Array
* @short Maps the array to another array containing the values that are the result of calling <map> on each element.
* @extra [scope] is the %this% object. In addition to providing this method for browsers that don't support it natively, this enhanced method also directly accepts a string, which is a shortcut for a function that gets that property (or invokes a function) on each element.
* @example
*
+ [1,2,3].map(function(n) {
* return n * 3;
* }); -> [3,6,9]
* ['one','two','three'].map(function(n) {
* return n.length;
* }); -> [3,3,5]
* ['one','two','three'].map('length') -> [3,3,5]
***/
'map': function(fn, scope) {
var length = this.length, index = 0, result = new Array(length);
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this) {
result[index] = fn.call(scope, this[index], index, this);
}
index++;
}
return result;
},
/***
* @method filter(<f>, [scope])
* @returns Array
* @short Returns any elements in the array that match <f>.
* @extra [scope] is the %this% object. In addition to providing this method for browsers that don't support it natively, this method also implements @array_matching.
* @example
*
+ [1,2,3].filter(function(n) {
* return n > 1;
* });
* [1,2,2,4].filter(2) -> 2
*
***/
'filter': function(fn, scope) {
var length = this.length, index = 0, result = [];
checkFirstArgumentExists(arguments);
while(index < length) {
if(index in this && fn.call(scope, this[index], index, this)) {
result.push(this[index]);
}
index++;
}
return result;
},
/***
* @method indexOf(<search>, [fromIndex])
* @returns Number
* @short Searches the array and returns the first index where <search> occurs, or -1 if the element is not found.
* @extra [fromIndex] is the index from which to begin the search. This method performs a simple strict equality comparison on <search>. It does not support enhanced functionality such as searching the contents against a regex, callback, or deep comparison of objects. For such functionality, use the %findIndex% method instead.
* @example
*
* [1,2,3].indexOf(3) -> 1
* [1,2,3].indexOf(7) -> -1
*
***/
'indexOf': function(search, fromIndex) {
if(isString(this)) return this.indexOf(search, fromIndex);
return arrayIndexOf(this, search, fromIndex, 1);
},
/***
* @method lastIndexOf(<search>, [fromIndex])
* @returns Number
* @short Searches the array and returns the last index where <search> occurs, or -1 if the element is not found.
* @extra [fromIndex] is the index from which to begin the search. This method performs a simple strict equality comparison on <search>.
* @example
*
* [1,2,1].lastIndexOf(1) -> 2
* [1,2,1].lastIndexOf(7) -> -1
*
***/
'lastIndexOf': function(search, fromIndex) {
if(isString(this)) return this.lastIndexOf(search, fromIndex);
return arrayIndexOf(this, search, fromIndex, -1);
},
/***
* @method forEach([fn], [scope])
* @returns Nothing
* @short Iterates over the array, calling [fn] on each loop.
* @extra This method is only provided for those browsers that do not support it natively. [scope] becomes the %this% object.
* @example
*
* ['a','b','c'].forEach(function(a) {
* // Called 3 times: 'a','b','c'
* });
*
***/
'forEach': function(fn, scope) {
var length = this.length, index = 0;
checkCallback(fn);
while(index < length) {
if(index in this) {
fn.call(scope, this[index], index, this);
}
index++;
}
},
/***
* @method reduce(<fn>, [init])
* @returns Mixed
* @short Reduces the array to a single result.
* @extra If [init] is passed as a starting value, that value will be passed as the first argument to the callback. The second argument will be the first element in the array. From that point, the result of the callback will then be used as the first argument of the next iteration. This is often refered to as "accumulation", and [init] is often called an "accumulator". If [init] is not passed, then <fn> will be called n - 1 times, where n is the length of the array. In this case, on the first iteration only, the first argument will be the first element of the array, and the second argument will be the second. After that callbacks work as normal, using the result of the previous callback as the first argument of the next. This method is only provided for those browsers that do not support it natively.
*
* @example
*
+ [1,2,3,4].reduce(function(a, b) {
* return a - b;
* });
+ [1,2,3,4].reduce(function(a, b) {
* return a - b;
* }, 100);
*
***/
'reduce': function(fn, init) {
return arrayReduce(this, fn, init);
},
/***
* @method reduceRight([fn], [init])
* @returns Mixed
* @short Identical to %Array#reduce%, but operates on the elements in reverse order.
* @extra This method is only provided for those browsers that do not support it natively.
*
*
*
*
* @example
*
+ [1,2,3,4].reduceRight(function(a, b) {
* return a - b;
* });
*
***/
'reduceRight': function(fn, init) {
return arrayReduce(this, fn, init, true);
}
});
/***
* String module
*
***/
function buildTrim() {
var support = getTrimmableCharacters().match(/^\s+$/);
try { string.prototype.trim.call([1]); } catch(e) { support = false; }
extend(string, true, !support, {
/***
* @method trim[Side]()
* @returns String
* @short Removes leading and/or trailing whitespace from the string.
* @extra Whitespace is defined as line breaks, tabs, and any character in the "Space, Separator" Unicode category, conforming to the the ES5 spec. The standard %trim% method is only added when not fully supported natively.
*
* @set
* trim
* trimLeft
* trimRight
*
* @example
*
* ' wasabi '.trim() -> 'wasabi'
* ' wasabi '.trimLeft() -> 'wasabi '
* ' wasabi '.trimRight() -> ' wasabi'
*
***/
'trim': function() {
return this.toString().trimLeft().trimRight();
},
'trimLeft': function() {
return this.replace(regexp('^['+getTrimmableCharacters()+']+'), '');
},
'trimRight': function() {
return this.replace(regexp('['+getTrimmableCharacters()+']+$'), '');
}
});
}
/***
* Function module
*
***/
extend(Function, true, false, {
/***
* @method bind(<scope>, [arg1], ...)
* @returns Function
* @short Binds <scope> as the %this% object for the function when it is called. Also allows currying an unlimited number of parameters.
* @extra "currying" means setting parameters ([arg1], [arg2], etc.) ahead of time so that they are passed when the function is called later. If you pass additional parameters when the function is actually called, they will be added will be added to the end of the curried parameters. This method is provided for browsers that don't support it internally.
* @example
*
+ (function() {
* return this;
* }).bind('woof')(); -> returns 'woof'; function is bound with 'woof' as the this object.
* (function(a) {
* return a;
* }).bind(1, 2)(); -> returns 2; function is bound with 1 as the this object and 2 curried as the first parameter
* (function(a, b) {
* return a + b;
* }).bind(1, 2)(3); -> returns 5; function is bound with 1 as the this object, 2 curied as the first parameter and 3 passed as the second when calling the function
*
***/
'bind': function(scope) {
var fn = this, args = multiArgs(arguments).slice(1), nop, bound;
if(!isFunction(this)) {
throw new TypeError('Function.prototype.bind called on a non-function');
}
bound = function() {
return fn.apply(fn.prototype && this instanceof fn ? this : scope, args.concat(multiArgs(arguments)));
}
bound.prototype = this.prototype;
return bound;
}
});
/***
* Date module
*
***/
/***
* @method toISOString()
* @returns String
* @short Formats the string to ISO8601 format.
* @extra This will always format as UTC time. Provided for browsers that do not support this method.
* @example
*
* Date.create().toISOString() -> ex. 2011-07-05 12:24:55.528Z
*
***
* @method toJSON()
* @returns String
* @short Returns a JSON representation of the date.
* @extra This is effectively an alias for %toISOString%. Will always return the date in UTC time. Provided for browsers that do not support this method.
* @example
*
* Date.create().toJSON() -> ex. 2011-07-05 12:24:55.528Z
*
***/
extend(date, false, false, {
/***
* @method Date.now()
* @returns String
* @short Returns the number of milliseconds since January 1st, 1970 00:00:00 (UTC time).
* @extra Provided for browsers that do not support this method.
* @example
*
* Date.now() -> ex. 1311938296231
*
***/
'now': function() {
return new date().getTime();
}
});
function buildISOString() {
var d = new date(date.UTC(1999, 11, 31)), target = '1999-12-31T00:00:00.000Z';
var support = d.toISOString && d.toISOString() === target;
extendSimilar(date, true, !support, 'toISOString,toJSON', function(methods, name) {
methods[name] = function() {
return padNumber(this.getUTCFullYear(), 4) + '-' +
padNumber(this.getUTCMonth() + 1, 2) + '-' +
padNumber(this.getUTCDate(), 2) + 'T' +
padNumber(this.getUTCHours(), 2) + ':' +
padNumber(this.getUTCMinutes(), 2) + ':' +
padNumber(this.getUTCSeconds(), 2) + '.' +
padNumber(this.getUTCMilliseconds(), 3) + 'Z';
}
});
}
// Initialize
buildTrim();
buildISOString();
/***
* @package Array
* @dependency core
* @description Array manipulation and traversal, "fuzzy matching" against elements, alphanumeric sorting and collation, enumerable methods on Object.
*
***/
function multiMatch(el, match, scope, params) {
var result = true;
if(el === match) {
// Match strictly equal values up front.
return true;
} else if(isRegExp(match) && isString(el)) {
// Match against a regexp
return regexp(match).test(el);
} else if(isFunction(match)) {
// Match against a filtering function
return match.apply(scope, params);
} else if(isObject(match) && isObjectPrimitive(el)) {
// Match against a hash or array.
iterateOverObject(match, function(key, value) {
if(!multiMatch(el[key], match[key], scope, [el[key], el])) {
result = false;
}
});
return result;
} else {
return isEqual(el, match);
}
}
function transformArgument(el, map, context, mapArgs) {
if(isUndefined(map)) {
return el;
} else if(isFunction(map)) {
return map.apply(context, mapArgs || []);
} else if(isFunction(el[map])) {
return el[map].call(el);
} else {
return el[map];
}
}
// Basic array internal methods
function arrayEach(arr, fn, startIndex, loop) {
var length, index, i;
if(startIndex < 0) startIndex = arr.length + startIndex;
i = isNaN(startIndex) ? 0 : startIndex;
length = loop === true ? arr.length + i : arr.length;
while(i < length) {
index = i % arr.length;
if(!(index in arr)) {
return iterateOverSparseArray(arr, fn, i, loop);
} else if(fn.call(arr, arr[index], index, arr) === false) {
break;
}
i++;
}
}
function iterateOverSparseArray(arr, fn, fromIndex, loop) {
var indexes = [], i;
for(i in arr) {
if(isArrayIndex(arr, i) && i >= fromIndex) {
indexes.push(parseInt(i));
}
}
indexes.sort().each(function(index) {
return fn.call(arr, arr[index], index, arr);
});
return arr;
}
function isArrayIndex(arr, i) {
return i in arr && toUInt32(i) == i && i != 0xffffffff;
}
function toUInt32(i) {
return i >>> 0;
}
function arrayFind(arr, f, startIndex, loop, returnIndex) {
var result, index;
arrayEach(arr, function(el, i, arr) {
if(multiMatch(el, f, arr, [el, i, arr])) {
result = el;
index = i;
return false;
}
}, startIndex, loop);
return returnIndex ? index : result;
}
function arrayUnique(arr, map) {
var result = [], o = {}, transformed;
arrayEach(arr, function(el, i) {
transformed = map ? transformArgument(el, map, arr, [el, i, arr]) : el;
if(!checkForElementInHashAndSet(o, transformed)) {
result.push(el);
}
})
return result;
}
function arrayIntersect(arr1, arr2, subtract) {
var result = [], o = {};
arr2.each(function(el) {
checkForElementInHashAndSet(o, el);
});
arr1.each(function(el) {
var stringified = stringify(el),
isReference = !objectIsMatchedByValue(el);
// Add the result to the array if:
// 1. We're subtracting intersections or it doesn't already exist in the result and
// 2. It exists in the compared array and we're adding, or it doesn't exist and we're removing.
if(elementExistsInHash(o, stringified, el, isReference) != subtract) {
discardElementFromHash(o, stringified, el, isReference);
result.push(el);
}
});
return result;
}
function arrayFlatten(arr, level, current) {
level = level || Infinity;
current = current || 0;
var result = [];
arrayEach(arr, function(el) {
if(isArray(el) && current < level) {
result = result.concat(arrayFlatten(el, level, current + 1));
} else {
result.push(el);
}
});
return result;
}
function flatArguments(args) {
var result = [];
multiArgs(args, function(arg) {
result = result.concat(arg);
});
return result;
}
function elementExistsInHash(hash, key, element, isReference) {
var exists = key in hash;
if(isReference) {
if(!hash[key]) {
hash[key] = [];
}
exists = hash[key].indexOf(element) !== -1;
}
return exists;
}
function checkForElementInHashAndSet(hash, element) {
var stringified = stringify(element),
isReference = !objectIsMatchedByValue(element),
exists = elementExistsInHash(hash, stringified, element, isReference);
if(isReference) {
hash[stringified].push(element);
} else {
hash[stringified] = element;
}
return exists;
}
function discardElementFromHash(hash, key, element, isReference) {
var arr, i = 0;
if(isReference) {
arr = hash[key];
while(i < arr.length) {
if(arr[i] === element) {
arr.splice(i, 1);
} else {
i += 1;
}
}
} else {
delete hash[key];
}
}
// Support methods
function getMinOrMax(obj, map, which, all) {
var edge,
result = [],
max = which === 'max',
min = which === 'min',
isArray = Array.isArray(obj);
iterateOverObject(obj, function(key) {
var el = obj[key];
var test = transformArgument(el, map, obj, isArray ? [el, parseInt(key), obj] : []);
if(test === edge) {
result.push(el);
} else if(isUndefined(edge) || (max && test > edge) || (min && test < edge)) {
result = [el];
edge = test;
}
});
if(!isArray) result = arrayFlatten(result, 1);
return all ? result : result[0];
}
// Alphanumeric collation helpers
function collateStrings(a, b) {
var aValue, bValue, aChar, bChar, aEquiv, bEquiv, index = 0, tiebreaker = 0;
a = getCollationReadyString(a);
b = getCollationReadyString(b);
do {
aChar = getCollationCharacter(a, index);
bChar = getCollationCharacter(b, index);
aValue = getCollationValue(aChar);
bValue = getCollationValue(bChar);
if(aValue === -1 || bValue === -1) {
aValue = a.charCodeAt(index) || null;
bValue = b.charCodeAt(index) || null;
}
aEquiv = aChar !== a.charAt(index);
bEquiv = bChar !== b.charAt(index);
if(aEquiv !== bEquiv && tiebreaker === 0) {
tiebreaker = aEquiv - bEquiv;
}
index += 1;
} while(aValue != null && bValue != null && aValue === bValue);
if(aValue === bValue) return tiebreaker;
return aValue < bValue ? -1 : 1;
}
function getCollationReadyString(str) {
if(array[AlphanumericSortIgnoreCase]) {
str = str.toLowerCase();
}
return str.replace(array[AlphanumericSortIgnore], '');
}
function getCollationCharacter(str, index) {
var chr = str.charAt(index), eq = array[AlphanumericSortEquivalents] || {};
return eq[chr] || chr;
}
function getCollationValue(chr) {
var order = array[AlphanumericSortOrder];
if(!chr) {
return null;
} else {
return order.indexOf(chr);
}
}
var AlphanumericSortOrder = 'AlphanumericSortOrder';
var AlphanumericSortIgnore = 'AlphanumericSortIgnore';
var AlphanumericSortIgnoreCase = 'AlphanumericSortIgnoreCase';
var AlphanumericSortEquivalents = 'AlphanumericSortEquivalents';
function buildEnhancements() {
var callbackCheck = function() { var a = arguments; return a.length > 0 && !isFunction(a[0]); };
extendSimilar(array, true, callbackCheck, 'map,every,all,some,any,none,filter', function(methods, name) {
methods[name] = function(f) {
return this[name](function(el, index) {
if(name === 'map') {
return transformArgument(el, f, this, [el, index, this]);
} else {
return multiMatch(el, f, this, [el, index, this]);
}
});
}
});
}
function buildAlphanumericSort() {
var order = 'AÁÀÂÃĄBCĆČÇDĎÐEÉÈĚÊËĘFGĞHıIÍÌİÎÏJKLŁMNŃŇÑOÓÒÔPQRŘSŚŠŞTŤUÚÙŮÛÜVWXYÝZŹŻŽÞÆŒØÕÅÄÖ';
var equiv = 'AÁÀÂÃÄ,CÇ,EÉÈÊË,IÍÌİÎÏ,OÓÒÔÕÖ,Sß,UÚÙÛÜ';
array[AlphanumericSortOrder] = order.split('').map(function(str) {
return str + str.toLowerCase();
}).join('');
var equivalents = {};
arrayEach(equiv.split(','), function(set) {
var equivalent = set.charAt(0);
arrayEach(set.slice(1).split(''), function(chr) {
equivalents[chr] = equivalent;
equivalents[chr.toLowerCase()] = equivalent.toLowerCase();
});
});
array[AlphanumericSortIgnoreCase] = true;
array[AlphanumericSortEquivalents] = equivalents;
}
extend(array, false, false, {
/***
*
* @method Array.create(<obj1>, <obj2>, ...)
* @returns Array
* @short Alternate array constructor.
* @extra This method will create a single array by calling %concat% on all arguments passed. In addition to ensuring that an unknown variable is in a single, flat array (the standard constructor will create nested arrays, this one will not), it is also a useful shorthand to convert a function's arguments object into a standard array.
* @example
*
* Array.create('one', true, 3) -> ['one', true, 3]
* Array.create(['one', true, 3]) -> ['one', true, 3]
+ Array.create(function(n) {
* return arguments;
* }('howdy', 'doody'));
*
***/
'create': function() {
var result = [], tmp;
multiArgs(arguments, function(a) {
if(isObjectPrimitive(a)) {
try {
tmp = array.prototype.slice.call(a, 0);
if(tmp.length > 0) {
a = tmp;
}
} catch(e) {}
}
result = result.concat(a);
});
return result;
}
});
extend(array, true, false, {
/***
* @method find(<f>, [index] = 0, [loop] = false)
* @returns Mixed
* @short Returns the first element that matches <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. Starts at [index], and will continue once from index = 0 if [loop] is true. This method implements @array_matching.
* @example
*
+ [{a:1,b:2},{a:1,b:3},{a:1,b:4}].find(function(n) {
* return n['a'] == 1;
* }); -> {a:1,b:3}
* ['cuba','japan','canada'].find(/^c/, 2) -> 'canada'
*
***/
'find': function(f, index, loop) {
return arrayFind(this, f, index, loop);
},
/***
* @method findAll(<f>, [index] = 0, [loop] = false)
* @returns Array
* @short Returns all elements that match <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. Starts at [index], and will continue once from index = 0 if [loop] is true. This method implements @array_matching.
* @example
*
+ [{a:1,b:2},{a:1,b:3},{a:2,b:4}].findAll(function(n) {
* return n['a'] == 1;
* }); -> [{a:1,b:3},{a:1,b:4}]
* ['cuba','japan','canada'].findAll(/^c/) -> 'cuba','canada'
* ['cuba','japan','canada'].findAll(/^c/, 2) -> 'canada'
*
***/
'findAll': function(f, index, loop) {
var result = [];
arrayEach(this, function(el, i, arr) {
if(multiMatch(el, f, arr, [el, i, arr])) {
result.push(el);
}
}, index, loop);
return result;
},
/***
* @method findIndex(<f>, [startIndex] = 0, [loop] = false)
* @returns Number
* @short Returns the index of the first element that matches <f> or -1 if not found.
* @extra This method has a few notable differences to native %indexOf%. Although <f> will similarly match a primitive such as a string or number, it will also match deep objects and arrays that are not equal by reference (%===%). Additionally, if a function is passed it will be run as a matching function (similar to the behavior of %Array#filter%) rather than attempting to find that function itself by reference in the array. Starts at [index], and will continue once from index = 0 if [loop] is true. This method implements @array_matching.
* @example
*
+ [1,2,3,4].findIndex(3); -> 2
+ [1,2,3,4].findIndex(function(n) {
* return n % 2 == 0;
* }); -> 1
+ ['one','two','three'].findIndex(/th/); -> 2
*
***/
'findIndex': function(f, startIndex, loop) {
var index = arrayFind(this, f, startIndex, loop, true);
return isUndefined(index) ? -1 : index;
},
/***
* @method count(<f>)
* @returns Number
* @short Counts all elements in the array that match <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. This method implements @array_matching.
* @example
*
* [1,2,3,1].count(1) -> 2
* ['a','b','c'].count(/b/) -> 1
+ [{a:1},{b:2}].count(function(n) {
* return n['a'] > 1;
* }); -> 0
*
***/
'count': function(f) {
if(isUndefined(f)) return this.length;
return this.findAll(f).length;
},
/***
* @method removeAt(<start>, [end])
* @returns Array
* @short Removes element at <start>. If [end] is specified, removes the range between <start> and [end]. This method will change the array! If you don't intend the array to be changed use %clone% first.
* @example
*
* ['a','b','c'].removeAt(0) -> ['b','c']
* [1,2,3,4].removeAt(1, 3) -> [1]
*
***/
'removeAt': function(start, end) {
if(isUndefined(start)) return this;
if(isUndefined(end)) end = start;
for(var i = 0; i <= (end - start); i++) {
this.splice(start, 1);
}
return this;
},
/***
* @method include(<el>, [index])
* @returns Array
* @short Adds <el> to the array.
* @extra This is a non-destructive alias for %add%. It will not change the original array.
* @example
*
* [1,2,3,4].include(5) -> [1,2,3,4,5]
* [1,2,3,4].include(8, 1) -> [1,8,2,3,4]
* [1,2,3,4].include([5,6,7]) -> [1,2,3,4,5,6,7]
*
***/
'include': function(el, index) {
return this.clone().add(el, index);
},
/***
* @method exclude([f1], [f2], ...)
* @returns Array
* @short Removes any element in the array that matches [f1], [f2], etc.
* @extra This is a non-destructive alias for %remove%. It will not change the original array. This method implements @array_matching.
* @example
*
* [1,2,3].exclude(3) -> [1,2]
* ['a','b','c'].exclude(/b/) -> ['a','c']
+ [{a:1},{b:2}].exclude(function(n) {
* return n['a'] == 1;
* }); -> [{b:2}]
*
***/
'exclude': function() {
return array.prototype.remove.apply(this.clone(), arguments);
},
/***
* @method clone()
* @returns Array
* @short Clones the array.
* @example
*
* [1,2,3].clone() -> [1,2,3]
*
***/
'clone': function() {
return simpleMerge([], this);
},
/***
* @method unique([map] = null)
* @returns Array
* @short Removes all duplicate elements in the array.
* @extra [map] may be a function mapping the value to be uniqued on or a string acting as a shortcut. This is most commonly used when you have a key that ensures the object's uniqueness, and don't need to check all fields. This method will also correctly operate on arrays of objects.
* @example
*
* [1,2,2,3].unique() -> [1,2,3]
* [{foo:'bar'},{foo:'bar'}].unique() -> [{foo:'bar'}]
+ [{foo:'bar'},{foo:'bar'}].unique(function(obj){
* return obj.foo;
* }); -> [{foo:'bar'}]
* [{foo:'bar'},{foo:'bar'}].unique('foo') -> [{foo:'bar'}]
*
***/
'unique': function(map) {
return arrayUnique(this, map);
},
/***
* @method flatten([limit] = Infinity)
* @returns Array
* @short Returns a flattened, one-dimensional copy of the array.
* @extra You can optionally specify a [limit], which will only flatten that depth.
* @example
*
* [[1], 2, [3]].flatten() -> [1,2,3]
* [['a'],[],'b','c'].flatten() -> ['a','b','c']
*
***/
'flatten': function(limit) {
return arrayFlatten(this, limit);
},
/***
* @method union([a1], [a2], ...)
* @returns Array
* @short Returns an array containing all elements in all arrays with duplicates removed.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].union([5,7,9]) -> [1,3,5,7,9]
* ['a','b'].union(['b','c']) -> ['a','b','c']
*
***/
'union': function() {
return arrayUnique(this.concat(flatArguments(arguments)));
},
/***
* @method intersect([a1], [a2], ...)
* @returns Array
* @short Returns an array containing the elements all arrays have in common.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].intersect([5,7,9]) -> [5]
* ['a','b'].intersect('b','c') -> ['b']
*
***/
'intersect': function() {
return arrayIntersect(this, flatArguments(arguments), false);
},
/***
* @method subtract([a1], [a2], ...)
* @returns Array
* @short Subtracts from the array all elements in [a1], [a2], etc.
* @extra This method will also correctly operate on arrays of objects.
* @example
*
* [1,3,5].subtract([5,7,9]) -> [1,3]
* [1,3,5].subtract([3],[5]) -> [1]
* ['a','b'].subtract('b','c') -> ['a']
*
***/
'subtract': function(a) {
return arrayIntersect(this, flatArguments(arguments), true);
},
/***
* @method at(<index>, [loop] = true)
* @returns Mixed
* @short Gets the element(s) at a given index.
* @extra When [loop] is true, overshooting the end of the array (or the beginning) will begin counting from the other end. As an alternate syntax, passing multiple indexes will get the elements at those indexes.
* @example
*
* [1,2,3].at(0) -> 1
* [1,2,3].at(2) -> 3
* [1,2,3].at(4) -> 2
* [1,2,3].at(4, false) -> null
* [1,2,3].at(-1) -> 3
* [1,2,3].at(0,1) -> [1,2]
*
***/
'at': function() {
return entryAtIndex(this, arguments);
},
/***
* @method first([num] = 1)
* @returns Mixed
* @short Returns the first element(s) in the array.
* @extra When <num> is passed, returns the first <num> elements in the array.
* @example
*
* [1,2,3].first() -> 1
* [1,2,3].first(2) -> [1,2]
*
***/
'first': function(num) {
if(isUndefined(num)) return this[0];
if(num < 0) num = 0;
return this.slice(0, num);
},
/***
* @method last([num] = 1)
* @returns Mixed
* @short Returns the last element(s) in the array.
* @extra When <num> is passed, returns the last <num> elements in the array.
* @example
*
* [1,2,3].last() -> 3
* [1,2,3].last(2) -> [2,3]
*
***/
'last': function(num) {
if(isUndefined(num)) return this[this.length - 1];
var start = this.length - num < 0 ? 0 : this.length - num;
return this.slice(start);
},
/***
* @method from(<index>)
* @returns Array
* @short Returns a slice of the array from <index>.
* @example
*
* [1,2,3].from(1) -> [2,3]
* [1,2,3].from(2) -> [3]
*
***/
'from': function(num) {
return this.slice(num);
},
/***
* @method to(<index>)
* @returns Array
* @short Returns a slice of the array up to <index>.
* @example
*
* [1,2,3].to(1) -> [1]
* [1,2,3].to(2) -> [1,2]
*
***/
'to': function(num) {
if(isUndefined(num)) num = this.length;
return this.slice(0, num);
},
/***
* @method min([map], [all] = false)
* @returns Mixed
* @short Returns the element in the array with the lowest value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all min values in an array.
* @example
*
* [1,2,3].min() -> 1
* ['fee','fo','fum'].min('length') -> 'fo'
* ['fee','fo','fum'].min('length', true) -> ['fo']
+ ['fee','fo','fum'].min(function(n) {
* return n.length;
* }); -> ['fo']
+ [{a:3,a:2}].min(function(n) {
* return n['a'];
* }); -> [{a:2}]
*
***/
'min': function(map, all) {
return getMinOrMax(this, map, 'min', all);
},
/***
* @method max([map], [all] = false)
* @returns Mixed
* @short Returns the element in the array with the greatest value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut. If [all] is true, will return all max values in an array.
* @example
*
* [1,2,3].max() -> 3
* ['fee','fo','fum'].max('length') -> 'fee'
* ['fee','fo','fum'].max('length', true) -> ['fee']
+ [{a:3,a:2}].max(function(n) {
* return n['a'];
* }); -> {a:3}
*
***/
'max': function(map, all) {
return getMinOrMax(this, map, 'max', all);
},
/***
* @method least([map])
* @returns Array
* @short Returns the elements in the array with the least commonly occuring value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut.
* @example
*
* [3,2,2].least() -> [3]
* ['fe','fo','fum'].least('length') -> ['fum']
+ [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].least(function(n) {
* return n.age;
* }); -> [{age:35,name:'ken'}]
*
***/
'least': function(map, all) {
return getMinOrMax(this.groupBy.apply(this, [map]), 'length', 'min', all);
},
/***
* @method most([map])
* @returns Array
* @short Returns the elements in the array with the most commonly occuring value.
* @extra [map] may be a function mapping the value to be checked or a string acting as a shortcut.
* @example
*
* [3,2,2].most() -> [2]
* ['fe','fo','fum'].most('length') -> ['fe','fo']
+ [{age:35,name:'ken'},{age:12,name:'bob'},{age:12,name:'ted'}].most(function(n) {
* return n.age;
* }); -> [{age:12,name:'bob'},{age:12,name:'ted'}]
*
***/
'most': function(map, all) {
return getMinOrMax(this.groupBy.apply(this, [map]), 'length', 'max', all);
},
/***
* @method sum([map])
* @returns Number
* @short Sums all values in the array.
* @extra [map] may be a function mapping the value to be summed or a string acting as a shortcut.
* @example
*
* [1,2,2].sum() -> 5
+ [{age:35},{age:12},{age:12}].sum(function(n) {
* return n.age;
* }); -> 59
* [{age:35},{age:12},{age:12}].sum('age') -> 59
*
***/
'sum': function(map) {
var arr = map ? this.map(map) : this;
return arr.length > 0 ? arr.reduce(function(a,b) { return a + b; }) : 0;
},
/***
* @method average([map])
* @returns Number
* @short Averages all values in the array.
* @extra [map] may be a function mapping the value to be averaged or a string acting as a shortcut.
* @example
*
* [1,2,3].average() -> 2
+ [{age:35},{age:11},{age:11}].average(function(n) {
* return n.age;
* }); -> 19
* [{age:35},{age:11},{age:11}].average('age') -> 19
*
***/
'average': function(map) {
var arr = map ? this.map(map) : this;
return arr.length > 0 ? arr.sum() / arr.length : 0;
},
/***
* @method inGroups(<num>, [padding])
* @returns Array
* @short Groups the array into <num> arrays.
* @extra [padding] specifies a value with which to pad the last array so that they are all equal length.
* @example
*
* [1,2,3,4,5,6,7].inGroups(3) -> [ [1,2,3], [4,5,6], [7] ]
* [1,2,3,4,5,6,7].inGroups(3, 'none') -> [ [1,2,3], [4,5,6], [7,'none','none'] ]
*
***/
'inGroups': function(num, padding) {
var pad = arguments.length > 1;
var arr = this;
var result = [];
var divisor = ceil(this.length / num);
getRange(0, num - 1, function(i) {
var index = i * divisor;
var group = arr.slice(index, index + divisor);
if(pad && group.length < divisor) {
getRange(1, divisor - group.length, function() {
group = group.add(padding);
});
}
result.push(group);
});
return result;
},
/***
* @method inGroupsOf(<num>, [padding] = null)
* @returns Array
* @short Groups the array into arrays of <num> elements each.
* @extra [padding] specifies a value with which to pad the last array so that they are all equal length.
* @example
*
* [1,2,3,4,5,6,7].inGroupsOf(4) -> [ [1,2,3,4], [5,6,7] ]
* [1,2,3,4,5,6,7].inGroupsOf(4, 'none') -> [ [1,2,3,4], [5,6,7,'none'] ]
*
***/
'inGroupsOf': function(num, padding) {
var result = [], len = this.length, arr = this, group;
if(len === 0 || num === 0) return arr;
if(isUndefined(num)) num = 1;
if(isUndefined(padding)) padding = null;
getRange(0, ceil(len / num) - 1, function(i) {
group = arr.slice(num * i, num * i + num);
while(group.length < num) {
group.push(padding);
}
result.push(group);
});
return result;
},
/***
* @method isEmpty()
* @returns Boolean
* @short Returns true if the array is empty.
* @extra This is true if the array has a length of zero, or contains only %undefined%, %null%, or %NaN%.
* @example
*
* [].isEmpty() -> true
* [null,undefined].isEmpty() -> true
*
***/
'isEmpty': function() {
return this.compact().length == 0;
},
/***
* @method sortBy(<map>, [desc] = false)
* @returns Array
* @short Sorts the array by <map>.
* @extra <map> may be a function, a string acting as a shortcut, or blank (direct comparison of array values). [desc] will sort the array in descending order. When the field being sorted on is a string, the resulting order will be determined by an internal collation algorithm that is optimized for major Western languages, but can be customized. For more information see @array_sorting.
* @example
*
* ['world','a','new'].sortBy('length') -> ['a','new','world']
* ['world','a','new'].sortBy('length', true) -> ['world','new','a']
+ [{age:72},{age:13},{age:18}].sortBy(function(n) {
* return n.age;
* }); -> [{age:13},{age:18},{age:72}]
*
***/
'sortBy': function(map, desc) {
var arr = this.clone();
arr.sort(function(a, b) {
var aProperty, bProperty, comp;
aProperty = transformArgument(a, map, arr, [a]);
bProperty = transformArgument(b, map, arr, [b]);
if(isString(aProperty) && isString(bProperty)) {
comp = collateStrings(aProperty, bProperty);
} else if(aProperty < bProperty) {
comp = -1;
} else if(aProperty > bProperty) {
comp = 1;
} else {
comp = 0;
}
return comp * (desc ? -1 : 1);
});
return arr;
},
/***
* @method randomize()
* @returns Array
* @short Returns a copy of the array with the elements randomized.
* @extra Uses Fisher-Yates algorithm.
* @example
*
* [1,2,3,4].randomize() -> [?,?,?,?]
*
***/
'randomize': function() {
var a = this.concat();
for(var j, x, i = a.length; i; j = parseInt(math.random() * i), x = a[--i], a[i] = a[j], a[j] = x) {};
return a;
},
/***
* @method zip([arr1], [arr2], ...)
* @returns Array
* @short Merges multiple arrays together.
* @extra This method "zips up" smaller arrays into one large whose elements are "all elements at index 0", "all elements at index 1", etc. Useful when you have associated data that is split over separated arrays. If the arrays passed have more elements than the original array, they will be discarded. If they have fewer elements, the missing elements will filled with %null%.
* @example
*
* [1,2,3].zip([4,5,6]) -> [[1,2], [3,4], [5,6]]
* ['Martin','John'].zip(['Luther','F.'], ['King','Kennedy']) -> [['Martin','Luther','King'], ['John','F.','Kennedy']]
*
***/
'zip': function() {
var args = multiArgs(arguments);
return this.map(function(el, i) {
return [el].concat(args.map(function(k) {
return (i in k) ? k[i] : null;
}));
});
},
/***
* @method sample([num])
* @returns Mixed
* @short Returns a random element from the array.
* @extra If [num] is passed, will return [num] samples from the array.
* @example
*
* [1,2,3,4,5].sample() -> // Random element
* [1,2,3,4,5].sample(3) -> // Array of 3 random elements
*
***/
'sample': function(num) {
var arr = this.randomize();
return arguments.length > 0 ? arr.slice(0, num) : arr[0];
},
/***
* @method each(<fn>, [index] = 0, [loop] = false)
* @returns Array
* @short Runs <fn> against each element in the array. Enhanced version of %Array#forEach%.
* @extra Parameters passed to <fn> are identical to %forEach%, ie. the first parameter is the current element, second parameter is the current index, and third parameter is the array itself. If <fn> returns %false% at any time it will break out of the loop. Once %each% finishes, it will return the array. If [index] is passed, <fn> will begin at that index and work its way to the end. If [loop] is true, it will then start over from the beginning of the array and continue until it reaches [index] - 1.
* @example
*
* [1,2,3,4].each(function(n) {
* // Called 4 times: 1, 2, 3, 4
* });
* [1,2,3,4].each(function(n) {
* // Called 4 times: 3, 4, 1, 2
* }, 2, true);
*
***/
'each': function(fn, index, loop) {
arrayEach(this, fn, index, loop);
return this;
},
/***
* @method add(<el>, [index])
* @returns Array
* @short Adds <el> to the array.
* @extra If [index] is specified, it will add at [index], otherwise adds to the end of the array. %add% behaves like %concat% in that if <el> is an array it will be joined, not inserted. This method will change the array! Use %include% for a non-destructive alias. Also, %insert% is provided as an alias that reads better when using an index.
* @example
*
* [1,2,3,4].add(5) -> [1,2,3,4,5]
* [1,2,3,4].add([5,6,7]) -> [1,2,3,4,5,6,7]
* [1,2,3,4].insert(8, 1) -> [1,8,2,3,4]
*
***/
'add': function(el, index) {
if(!isNumber(number(index)) || isNaN(index)) index = this.length;
array.prototype.splice.apply(this, [index, 0].concat(el));
return this;
},
/***
* @method remove([f1], [f2], ...)
* @returns Array
* @short Removes any element in the array that matches [f1], [f2], etc.
* @extra Will match a string, number, array, object, or alternately test against a function or regex. This method will change the array! Use %exclude% for a non-destructive alias. This method implements @array_matching.
* @example
*
* [1,2,3].remove(3) -> [1,2]
* ['a','b','c'].remove(/b/) -> ['a','c']
+ [{a:1},{b:2}].remove(function(n) {
* return n['a'] == 1;
* }); -> [{b:2}]
*
***/
'remove': function() {
var i, arr = this;
multiArgs(arguments, function(f) {
i = 0;
while(i < arr.length) {
if(multiMatch(arr[i], f, arr, [arr[i], i, arr])) {
arr.splice(i, 1);
} else {
i++;
}
}
});
return arr;
},
/***
* @method compact([all] = false)
* @returns Array
* @short Removes all instances of %undefined%, %null%, and %NaN% from the array.
* @extra If [all] is %true%, all "falsy" elements will be removed. This includes empty strings, 0, and false.
* @example
*
* [1,null,2,undefined,3].compact() -> [1,2,3]
* [1,'',2,false,3].compact() -> [1,'',2,false,3]
* [1,'',2,false,3].compact(true) -> [1,2,3]
*
***/
'compact': function(all) {
var result = [];
arrayEach(this, function(el, i) {
if(isArray(el)) {
result.push(el.compact());
} else if(all && el) {
result.push(el);
} else if(!all && el != null && el.valueOf() === el.valueOf()) {
result.push(el);
}
});
return result;
},
/***
* @method groupBy(<map>, [fn])
* @returns Object
* @short Groups the array by <map>.
* @extra Will return an object with keys equal to the grouped values. <map> may be a mapping function, or a string acting as a shortcut. Optionally calls [fn] for each group.
* @example
*
* ['fee','fi','fum'].groupBy('length') -> { 2: ['fi'], 3: ['fee','fum'] }
+ [{age:35,name:'ken'},{age:15,name:'bob'}].groupBy(function(n) {
* return n.age;
* }); -> { 35: [{age:35,name:'ken'}], 15: [{age:15,name:'bob'}] }
*
***/
'groupBy': function(map, fn) {
var arr = this, result = {}, key;
arrayEach(arr, function(el, index) {
key = transformArgument(el, map, arr, [el, index, arr]);
if(!result[key]) result[key] = [];
result[key].push(el);
});
if(fn) {
iterateOverObject(result, fn);
}
return result;
},
/***
* @method none(<f>)
* @returns Boolean
* @short Returns true if none of the elements in the array match <f>.
* @extra <f> will match a string, number, array, object, or alternately test against a function or regex. This method implements @array_matching.
* @example
*
* [1,2,3].none(5) -> true
* ['a','b','c'].none(/b/) -> false
+ [{a:1},{b:2}].none(function(n) {
* return n['a'] > 1;
* }); -> true
*
***/
'none': function() {
return !this.any.apply(this, arguments);
}
});
// Aliases
extend(array, true, false, {
/***
* @method all()
* @alias every
*
***/
'all': array.prototype.every,
/*** @method any()
* @alias some
*
***/
'any': array.prototype.some,
/***
* @method insert()
* @alias add
*
***/
'insert': array.prototype.add
});
/***
* Object module
* Enumerable methods on objects
*
***/
function keysWithCoercion(obj) {
if(obj && obj.valueOf) {
obj = obj.valueOf();
}
return object.keys(obj);
}
/***
* @method [enumerable](<obj>)
* @returns Boolean
* @short Enumerable methods in the Array package are also available to the Object class. They will perform their normal operations for every property in <obj>.
* @extra In cases where a callback is used, instead of %element, index%, the callback will instead be passed %key, value%. Enumerable methods are also available to extended objects as instance methods.
*
* @set
* each
* map
* any
* all
* none
* count
* find
* findAll
* reduce
* isEmpty
* sum
* average
* min
* max
* least
* most
*
* @example
*
* Object.any({foo:'bar'}, 'bar') -> true
* Object.extended({foo:'bar'}).any('bar') -> true
* Object.isEmpty({}) -> true
+ Object.map({ fred: { age: 52 } }, 'age'); -> { fred: 52 }
*
***/
function buildEnumerableMethods(names, mapping) {
extendSimilar(object, false, false, names, function(methods, name) {
methods[name] = function(obj, arg1, arg2) {
var result;
var x = keysWithCoercion(obj);
result = array.prototype[name].call(x, function(key) {
if(mapping) {
return transformArgument(obj[key], arg1, obj, [key, obj[key], obj]);
} else {
return multiMatch(obj[key], arg1, obj, [key, obj[key], obj]);
}
}, arg2);
if(isArray(result)) {
// The method has returned an array of keys so use this array
// to build up the resulting object in the form we want it in.
result = result.reduce(function(o, key, i) {
o[key] = obj[key];
return o;
}, {});
}
return result;
};
});
buildObjectInstanceMethods(names, Hash);
}
extend(object, false, false, {
'map': function(obj, map) {
return keysWithCoercion(obj).reduce(function(result, key) {
result[key] = transformArgument(obj[key], map, obj, [key, obj[key], obj]);
return result;
}, {});
},
'reduce': function(obj) {
var values = keysWithCoercion(obj).map(function(key) {
return obj[key];
});
return values.reduce.apply(values, multiArgs(arguments).slice(1));
},
'each': function(obj, fn) {
checkCallback(fn);
iterateOverObject(obj, fn);
return obj;
},
/***
* @method size(<obj>)
* @returns Number
* @short Returns the number of properties in <obj>.
* @extra %size% is available as an instance method on extended objects.
* @example
*
* Object.size({ foo: 'bar' }) -> 1
*
***/
'size': function (obj) {
return keysWithCoercion(obj).length;
}
});
buildEnhancements();
buildAlphanumericSort();
buildEnumerableMethods('any,all,none,count,find,findAll,isEmpty');
buildEnumerableMethods('sum,average,min,max,least,most', true);
buildObjectInstanceMethods('map,reduce,size', Hash);
/***
* @package Date
* @dependency core
* @description Date parsing and formatting, relative formats like "1 minute ago", Number methods like "daysAgo", localization support with default English locale definition.
*
***/
var English;
var CurrentLocalization;
var TimeFormat = ['ampm','hour','minute','second','ampm','utc','offset_sign','offset_hours','offset_minutes','ampm']
var DecimalReg = '(?:[,.]\\d+)?';
var HoursReg = '\\d{1,2}' + DecimalReg;
var SixtyReg = '[0-5]\\d' + DecimalReg;
var RequiredTime = '({t})?\\s*('+HoursReg+')(?:{h}('+SixtyReg+')?{m}(?::?('+SixtyReg+'){s})?\\s*(?:({t})|(Z)|(?:([+-])(\\d{2,2})(?::?(\\d{2,2}))?)?)?|\\s*({t}))';
var KanjiDigits = '〇一二三四五六七八九十百千万';
var FullWidthDigits = '0123456789';
var AsianDigitMap = {};
var AsianDigitReg;
var DateArgumentUnits;
var DateUnitsReversed;
var CoreDateFormats = [];
var DateOutputFormats = [
{
token: 'f{1,4}|ms|milliseconds',
format: function(d) {
return callDateGet(d, 'Milliseconds');
}
},
{
token: 'ss?|seconds',
format: function(d, len) {
return callDateGet(d, 'Seconds');
}
},
{
token: 'mm?|minutes',
format: function(d, len) {
return callDateGet(d, 'Minutes');
}
},
{
token: 'hh?|hours|12hr',
format: function(d) {
return getShortHour(d);
}
},
{
token: 'HH?|24hr',
format: function(d) {
return callDateGet(d, 'Hours');
}
},
{
token: 'dd?|date|day',
format: function(d) {
return callDateGet(d, 'Date');
}
},
{
token: 'dow|weekday',
word: true,
format: function(d, loc, n, t) {
var dow = callDateGet(d, 'Day');
return loc['weekdays'][dow + (n - 1) * 7];
}
},
{
token: 'MM?',
format: function(d) {
return callDateGet(d, 'Month') + 1;
}
},
{
token: 'mon|month',
word: true,
format: function(d, loc, n, len) {
var month = callDateGet(d, 'Month');
return loc['months'][month + (n - 1) * 12];
}
},
{
token: 'y{2,4}|year',
format: function(d) {
return callDateGet(d, 'FullYear');
}
},
{
token: '[Tt]{1,2}',
format: function(d, loc, n, format) {
if(loc['ampm'].length == 0) return '';
var hours = callDateGet(d, 'Hours');
var str = loc['ampm'][floor(hours / 12)];
if(format.length === 1) str = str.slice(0,1);
if(format.slice(0,1) === 'T') str = str.toUpperCase();
return str;
}
},
{
token: 'z{1,4}|tz|timezone',
text: true,
format: function(d, loc, n, format) {
var tz = d.getUTCOffset();
if(format == 'z' || format == 'zz') {
tz = tz.replace(/(\d{2})(\d{2})/, function(f,h,m) {
return padNumber(h, format.length);
});
}
return tz;
}
},
{
token: 'iso(tz|timezone)',
format: function(d) {
return d.getUTCOffset(true);
}
},
{
token: 'ord',
format: function(d) {
var date = callDateGet(d, 'Date');
return date + getOrdinalizedSuffix(date);
}
}
];
var DateUnits = [
{
unit: 'year',
method: 'FullYear',
ambiguous: true,
multiplier: function(d) {
var adjust = d ? (d.isLeapYear() ? 1 : 0) : 0.25;
return (365 + adjust) * 24 * 60 * 60 * 1000;
}
},
{
unit: 'month',
method: 'Month',
ambiguous: true,
multiplier: function(d, ms) {
var days = 30.4375, inMonth;
if(d) {
inMonth = d.daysInMonth();
if(ms <= inMonth.days()) {
days = inMonth;
}
}
return days * 24 * 60 * 60 * 1000;
}
},
{
unit: 'week',
method: 'Week',
multiplier: function() {
return 7 * 24 * 60 * 60 * 1000;
}
},
{
unit: 'day',
method: 'Date',
ambiguous: true,
multiplier: function() {
return 24 * 60 * 60 * 1000;
}
},
{
unit: 'hour',
method: 'Hours',
multiplier: function() {
return 60 * 60 * 1000;
}
},
{
unit: 'minute',
method: 'Minutes',
multiplier: function() {
return 60 * 1000;
}
},
{
unit: 'second',
method: 'Seconds',
multiplier: function() {
return 1000;
}
},
{
unit: 'millisecond',
method: 'Milliseconds',
multiplier: function() {
return 1;
}
}
];
// Date Localization
var Localizations = {};
// Localization object
function Localization(l) {
simpleMerge(this, l);
this.compiledFormats = CoreDateFormats.concat();
}
Localization.prototype = {
getMonth: function(n) {
if(isNumber(n)) {
return n - 1;
} else {
return this['months'].indexOf(n) % 12;
}
},
getWeekday: function(n) {
return this['weekdays'].indexOf(n) % 7;
},
getNumber: function(n) {
var i;
if(isNumber(n)) {
return n;
} else if(n && (i = this['numbers'].indexOf(n)) !== -1) {
return (i + 1) % 10;
} else {
return 1;
}
},
getNumericDate: function(n) {
var self = this;
return n.replace(regexp(this['num'], 'g'), function(d) {
var num = self.getNumber(d);
return num || '';
});
},
getEnglishUnit: function(n) {
return English['units'][this['units'].indexOf(n) % 8];
},
getRelativeFormat: function(adu) {
return this.convertAdjustedToFormat(adu, adu[2] > 0 ? 'future' : 'past');
},
getDuration: function(ms) {
return this.convertAdjustedToFormat(getAdjustedUnit(ms), 'duration');
},
hasVariant: function(code) {
code = code || this.code;
return code === 'en' || code === 'en-US' ? true : this['variant'];
},
matchAM: function(str) {
return str === this['ampm'][0];
},
matchPM: function(str) {
return str && str === this['ampm'][1];
},
convertAdjustedToFormat: function(adu, mode) {
var sign, unit, mult,
num = adu[0],
u = adu[1],
ms = adu[2],
format = this[mode] || this['relative'];
if(isFunction(format)) {
return format.call(this, num, u, ms, mode);
}
mult = this['plural'] && num > 1 ? 1 : 0;
unit = this['units'][mult * 8 + u] || this['units'][u];
if(this['capitalizeUnit']) unit = simpleCapitalize(unit);
sign = this['modifiers'].filter(function(m) { return m.name == 'sign' && m.value == (ms > 0 ? 1 : -1); })[0];
return format.replace(/\{(.*?)\}/g, function(full, match) {
switch(match) {
case 'num': return num;
case 'unit': return unit;
case 'sign': return sign.src;
}
});
},
getFormats: function() {
return this.cachedFormat ? [this.cachedFormat].concat(this.compiledFormats) : this.compiledFormats;
},
addFormat: function(src, allowsTime, match, variant, iso) {
var to = match || [], loc = this, time, timeMarkers, lastIsNumeral;
src = src.replace(/\s+/g, '[-,. ]*');
src = src.replace(/\{([^,]+?)\}/g, function(all, k) {
var value, arr, result,
opt = k.match(/\?$/),
nc = k.match(/^(\d+)\??$/),
slice = k.match(/(\d)(?:-(\d))?/),
key = k.replace(/[^a-z]+$/, '');
if(nc) {
value = loc['tokens'][nc[1]];
} else if(loc[key]) {
value = loc[key];
} else if(loc[key + 's']) {
value = loc[key + 's'];
if(slice) {
// Can't use filter here as Prototype hijacks the method and doesn't
// pass an index, so use a simple loop instead!
arr = [];
value.forEach(function(m, i) {
var mod = i % (loc['units'] ? 8 : value.length);
if(mod >= slice[1] && mod <= (slice[2] || slice[1])) {
arr.push(m);
}
});
value = arr;
}
value = arrayToAlternates(value);
}
if(nc) {
result = '(?:' + value + ')';
} else {
if(!match) {
to.push(key);
}
result = '(' + value + ')';
}
if(opt) {
result += '?';
}
return result;
});
if(allowsTime) {
time = prepareTime(RequiredTime, loc, iso);
timeMarkers = ['t','[\\s\\u3000]'].concat(loc['timeMarker']);
lastIsNumeral = src.match(/\\d\{\d,\d\}\)+\??$/);
addDateInputFormat(loc, '(?:' + time + ')[,\\s\\u3000]+?' + src, TimeFormat.concat(to), variant);
addDateInputFormat(loc, src + '(?:[,\\s]*(?:' + timeMarkers.join('|') + (lastIsNumeral ? '+' : '*') +')' + time + ')?', to.concat(TimeFormat), variant);
} else {
addDateInputFormat(loc, src, to, variant);
}
}
};
// Localization helpers
function getLocalization(localeCode, fallback) {
var loc;
if(!isString(localeCode)) localeCode = '';
loc = Localizations[localeCode] || Localizations[localeCode.slice(0,2)];
if(fallback === false && !loc) {
throw new Error('Invalid locale.');
}
return loc || CurrentLocalization;
}
function setLocalization(localeCode, set) {
var loc, canAbbreviate;
function initializeField(name) {
var val = loc[name];
if(isString(val)) {
loc[name] = val.split(',');
} else if(!val) {
loc[name] = [];
}
}
function eachAlternate(str, fn) {
str = str.split('+').map(function(split) {
return split.replace(/(.+):(.+)$/, function(full, base, suffixes) {
return suffixes.split('|').map(function(suffix) {
return base + suffix;
}).join('|');
});
}).join('|');
return str.split('|').forEach(fn);
}
function setArray(name, abbreviate, multiple) {
var arr = [];
loc[name].forEach(function(full, i) {
if(abbreviate) {
full += '+' + full.slice(0,3);
}
eachAlternate(full, function(day, j) {
arr[j * multiple + i] = day.toLowerCase();
});
});
loc[name] = arr;
}
function getDigit(start, stop, allowNumbers) {
var str = '\\d{' + start + ',' + stop + '}';
if(allowNumbers) str += '|(?:' + arrayToAlternates(loc['numbers']) + ')+';
return str;
}
function getNum() {
var arr = ['\\d+'].concat(loc['articles']);
if(loc['numbers']) arr = arr.concat(loc['numbers']);
return arrayToAlternates(arr);
}
function setDefault(name, value) {
loc[name] = loc[name] || value;
}
function setModifiers() {
var arr = [];
loc.modifiersByName = {};
loc['modifiers'].forEach(function(modifier) {
var name = modifier.name;
eachAlternate(modifier.src, function(t) {
var locEntry = loc[name];
loc.modifiersByName[t] = modifier;
arr.push({ name: name, src: t, value: modifier.value });
loc[name] = locEntry ? locEntry + '|' + t : t;
});
});
loc['day'] += '|' + arrayToAlternates(loc['weekdays']);
loc['modifiers'] = arr;
}
// Initialize the locale
loc = new Localization(set);
initializeField('modifiers');
'months,weekdays,units,numbers,articles,tokens,timeMarker,ampm,timeSuffixes,dateParse,timeParse'.split(',').forEach(initializeField);
canAbbreviate = !loc['monthSuffix'];
setArray('months', canAbbreviate, 12);
setArray('weekdays', canAbbreviate, 7);
setArray('units', false, 8);
setArray('numbers', false, 10);
setDefault('code', localeCode);
setDefault('date', getDigit(1,2, loc['digitDate']));
setDefault('year', "'\\d{2}|" + getDigit(4,4));
setDefault('num', getNum());
setModifiers();
if(loc['monthSuffix']) {
loc['month'] = getDigit(1,2);
loc['months'] = getRange(1, 12).map(function(n) { return n + loc['monthSuffix']; });
}
loc['full_month'] = getDigit(1,2) + '|' + arrayToAlternates(loc['months']);
// The order of these formats is very important. Order is reversed so formats that come
// later will take precedence over formats that come before. This generally means that
// more specific formats should come later, however, the {year} format should come before
// {day}, as 2011 needs to be parsed as a year (2011) and not date (20) + hours (11)
// If the locale has time suffixes then add a time only format for that locale
// that is separate from the core English-based one.
if(loc['timeSuffixes'].length > 0) {
loc.addFormat(prepareTime(RequiredTime, loc), false, TimeFormat)
}
loc.addFormat('{day}', true);
loc.addFormat('{month}' + (loc['monthSuffix'] || ''));
loc.addFormat('{year}' + (loc['yearSuffix'] || ''));
loc['timeParse'].forEach(function(src) {
loc.addFormat(src, true);
});
loc['dateParse'].forEach(function(src) {
loc.addFormat(src);
});
return Localizations[localeCode] = loc;
}
// General helpers
function addDateInputFormat(locale, format, match, variant) {
locale.compiledFormats.unshift({
variant: variant,
locale: locale,
reg: regexp('^' + format + '$', 'i'),
to: match
});
}
function simpleCapitalize(str) {
return str.slice(0,1).toUpperCase() + str.slice(1);
}
function arrayToAlternates(arr) {
return arr.filter(function(el) {
return !!el;
}).join('|');
}
// Date argument helpers
function collectDateArguments(args, allowDuration) {
var obj, arr;
if(isObject(args[0])) {
return args;
} else if (isNumber(args[0]) && !isNumber(args[1])) {
return [args[0]];
} else if (isString(args[0]) && allowDuration) {
return [getDateParamsFromString(args[0]), args[1]];
}
obj = {};
DateArgumentUnits.forEach(function(u,i) {
obj[u.unit] = args[i];
});
return [obj];
}
function getDateParamsFromString(str, num) {
var params = {};
match = str.match(/^(\d+)?\s?(\w+?)s?$/i);
if(match) {
if(isUndefined(num)) {
num = parseInt(match[1]) || 1;
}
params[match[2].toLowerCase()] = num;
}
return params;
}
// Date parsing helpers
function getFormatMatch(match, arr) {
var obj = {}, value, num;
arr.forEach(function(key, i) {
value = match[i + 1];
if(isUndefined(value) || value === '') return;
if(key === 'year') {
obj.yearAsString = value.replace(/'/, '');
}
num = parseFloat(value.replace(/'/, '').replace(/,/, '.'));
obj[key] = !isNaN(num) ? num : value.toLowerCase();
});
return obj;
}
function cleanDateInput(str) {
str = str.trim().replace(/^(just )?now|\.+$/i, '');
return convertAsianDigits(str);
}
function convertAsianDigits(str) {
return str.replace(AsianDigitReg, function(full, disallowed, match) {
var sum = 0, place = 1, lastWasHolder, lastHolder;
if(disallowed) return full;
match.split('').reverse().forEach(function(letter) {
var value = AsianDigitMap[letter], holder = value > 9;
if(holder) {
if(lastWasHolder) sum += place;
place *= value / (lastHolder || 1);
lastHolder = value;
} else {
if(lastWasHolder === false) {
place *= 10;
}
sum += place * value;
}
lastWasHolder = holder;
});
if(lastWasHolder) sum += place;
return sum;
});
}
function getExtendedDate(f, localeCode, prefer, forceUTC) {
var d = new date(), relative = false, baseLocalization, loc, format, set, unit, weekday, num, tmp, after;
d.utc(forceUTC);
if(isDate(f)) {
d = new date(f.getTime());
} else if(isNumber(f)) {
d = new date(f);
} else if(isObject(f)) {
d.set(f, true);
set = f;
} else if(isString(f)) {
// The act of getting the localization will pre-initialize
// if it is missing and add the required formats.
baseLocalization = getLocalization(localeCode);
// Clean the input and convert Kanji based numerals if they exist.
f = cleanDateInput(f);
if(baseLocalization) {
iterateOverObject(baseLocalization.getFormats(), function(i, dif) {
var match = f.match(dif.reg);
if(match) {
format = dif;
loc = format.locale;
set = getFormatMatch(match, format.to, loc);
if(set['utc']) {
d.utc();
}
loc.cachedFormat = format;
if(set.timestamp) {
set = set.timestamp;
return false;
}
// If there's a variant (crazy Endian American format), swap the month and day.
if(format.variant && !isString(set['month']) && (isString(set['date']) || baseLocalization.hasVariant(localeCode))) {
tmp = set['month'];
set['month'] = set['date'];
set['date'] = tmp;
}
// If the year is 2 digits then get the implied century.
if(set['year'] && set.yearAsString.length === 2) {
set['year'] = getYearFromAbbreviation(set['year']);
}
// Set the month which may be localized.
if(set['month']) {
set['month'] = loc.getMonth(set['month']);
if(set['shift'] && !set['unit']) set['unit'] = loc['units'][7];
}
// If there is both a weekday and a date, the date takes precedence.
if(set['weekday'] && set['date']) {
delete set['weekday'];
// Otherwise set a localized weekday.
} else if(set['weekday']) {
set['weekday'] = loc.getWeekday(set['weekday']);
if(set['shift'] && !set['unit']) set['unit'] = loc['units'][5];
}
// Relative day localizations such as "today" and "tomorrow".
if(set['day'] && (tmp = loc.modifiersByName[set['day']])) {
set['day'] = tmp.value;
d.reset();
relative = true;
// If the day is a weekday, then set that instead.
} else if(set['day'] && (weekday = loc.getWeekday(set['day'])) > -1) {
delete set['day'];
if(set['num'] && set['month']) {
// If we have "the 2nd tuesday of June", set the day to the beginning of the month, then
// look ahead to set the weekday after all other properties have been set. The weekday needs
// to be set after the actual set because it requires overriding the "prefer" argument which
// could unintentionally send the year into the future, past, etc.
after = function() {
var w = d.getWeekday();
d.setWeekday((7 * (set['num'] - 1)) + (w > weekday ? weekday + 7 : weekday));
}
set['day'] = 1;
} else {
set['weekday'] = weekday;
}
}
if(set['date'] && !isNumber(set['date'])) {
set['date'] = loc.getNumericDate(set['date']);
}
// If the time is 1pm-11pm advance the time by 12 hours.
if(loc.matchPM(set['ampm']) && set['hour'] < 12) {
set['hour'] += 12;
} else if(loc.matchAM(set['ampm']) && set['hour'] === 12) {
set['hour'] = 0;
}
// Adjust for timezone offset
if('offset_hours' in set || 'offset_minutes' in set) {
d.utc();
set['offset_minutes'] = set['offset_minutes'] || 0;
set['offset_minutes'] += set['offset_hours'] * 60;
if(set['offset_sign'] === '-') {
set['offset_minutes'] *= -1;
}
set['minute'] -= set['offset_minutes'];
}
// Date has a unit like "days", "months", etc. are all relative to the current date.
if(set['unit']) {
relative = true;
num = loc.getNumber(set['num']);
unit = loc.getEnglishUnit(set['unit']);
// Shift and unit, ie "next month", "last week", etc.
if(set['shift'] || set['edge']) {
num *= (tmp = loc.modifiersByName[set['shift']]) ? tmp.value : 0;
// Relative month and static date: "the 15th of last month"
if(unit === 'month' && isDefined(set['date'])) {
d.set({ 'day': set['date'] }, true);
delete set['date'];
}
// Relative year and static month/date: "June 15th of last year"
if(unit === 'year' && isDefined(set['month'])) {
d.set({ 'month': set['month'], 'day': set['date'] }, true);
delete set['month'];
delete set['date'];
}
}
// Unit and sign, ie "months ago", "weeks from now", etc.
if(set['sign'] && (tmp = loc.modifiersByName[set['sign']])) {
num *= tmp.value;
}
// Units can be with non-relative dates, set here. ie "the day after monday"
if(isDefined(set['weekday'])) {
d.set({'weekday': set['weekday'] }, true);
delete set['weekday'];
}
// Finally shift the unit.
set[unit] = (set[unit] || 0) + num;
}
if(set['year_sign'] === '-') {
set['year'] *= -1;
}
DateUnitsReversed.slice(1,4).forEach(function(u, i) {
var value = set[u.unit], fraction = value % 1;
if(fraction) {
set[DateUnitsReversed[i].unit] = round(fraction * (u.unit === 'second' ? 1000 : 60));
set[u.unit] = floor(value);
}
});
return false;
}
});
}
if(!format) {
// The Date constructor does something tricky like checking the number
// of arguments so simply passing in undefined won't work.
d = f ? new date(f) : new date();
} else if(relative) {
d.advance(set);
} else {
if(d._utc) {
// UTC times can traverse into other days or even months,
// so preemtively reset the time here to prevent this.
d.reset();
}
updateDate(d, set, true, false, prefer);
}
// If there is an "edge" it needs to be set after the
// other fields are set. ie "the end of February"
if(set && set['edge']) {
tmp = loc.modifiersByName[set['edge']];
iterateOverObject(DateUnitsReversed.slice(4), function(i, u) {
if(isDefined(set[u.unit])) {
unit = u.unit;
return false;
}
});
if(unit === 'year') set.specificity = 'month';
else if(unit === 'month' || unit === 'week') set.specificity = 'day';
d[(tmp.value < 0 ? 'endOf' : 'beginningOf') + simpleCapitalize(unit)]();
// This value of -2 is arbitrary but it's a nice clean way to hook into this system.
if(tmp.value === -2) d.reset();
}
if(after) {
after();
}
}
d.utc(false);
return {
date: d,
set: set
}
}
// If the year is two digits, add the most appropriate century prefix.
function getYearFromAbbreviation(year) {
return round(callDateGet(new date(), 'FullYear') / 100) * 100 - round(year / 100) * 100 + year;
}
function getShortHour(d) {
var hours = callDateGet(d, 'Hours');
return hours === 0 ? 12 : hours - (floor(hours / 13) * 12);
}
// weeksSince won't work here as the result needs to be floored, not rounded.
function getWeekNumber(date) {
date = date.clone();
var dow = callDateGet(date, 'Day') || 7;
date.addDays(4 - dow).reset();
return 1 + floor(date.daysSince(date.clone().beginningOfYear()) / 7);
}
function getAdjustedUnit(ms) {
var next, ams = math.abs(ms), value = ams, unit = 0;
DateUnitsReversed.slice(1).forEach(function(u, i) {
next = floor(round(ams / u.multiplier() * 10) / 10);
if(next >= 1) {
value = next;
unit = i + 1;
}
});
return [value, unit, ms];
}
// Date formatting helpers
function formatDate(date, format, relative, localeCode) {
var adu, loc = getLocalization(localeCode), caps = regexp(/^[A-Z]/), value, shortcut;
if(!date.isValid()) {
return 'Invalid Date';
} else if(Date[format]) {
format = Date[format];
} else if(isFunction(format)) {
adu = getAdjustedUnit(date.millisecondsFromNow());
format = format.apply(date, adu.concat(loc));
}
if(!format && relative) {
adu = adu || getAdjustedUnit(date.millisecondsFromNow());
// Adjust up if time is in ms, as this doesn't
// look very good for a standard relative date.
if(adu[1] === 0) {
adu[1] = 1;
adu[0] = 1;
}
return loc.getRelativeFormat(adu);
}
format = format || 'long';
format = loc[format] || format;
DateOutputFormats.forEach(function(dof) {
format = format.replace(regexp('\\{('+dof.token+')(\\d)?\\}', dof.word ? 'i' : ''), function(m,t,d) {
var val = dof.format(date, loc, d || 1, t), l = t.length, one = t.match(/^(.)\1+$/);
if(dof.word) {
if(l === 3) val = val.slice(0,3);
if(one || t.match(caps)) val = simpleCapitalize(val);
} else if(one && !dof.text) {
val = (isNumber(val) ? padNumber(val, l) : val.toString()).slice(-l);
}
return val;
});
});
return format;
}
// Date comparison helpers
function compareDate(d, find, buffer, forceUTC) {
var p, t, min, max, minOffset, maxOffset, override, capitalized, accuracy = 0, loBuffer = 0, hiBuffer = 0;
p = getExtendedDate(find, null, null, forceUTC);
if(buffer > 0) {
loBuffer = hiBuffer = buffer;
override = true;
}
if(!p.date.isValid()) return false;
if(p.set && p.set.specificity) {
DateUnits.forEach(function(u, i) {
if(u.unit === p.set.specificity) {
accuracy = u.multiplier(p.date, d - p.date) - 1;
}
});
capitalized = simpleCapitalize(p.set.specificity);
if(p.set['edge'] || p.set['shift']) {
p.date['beginningOf' + capitalized]();
}
if(p.set.specificity === 'month') {
max = p.date.clone()['endOf' + capitalized]().getTime();
}
if(!override && p.set['sign'] && p.set.specificity != 'millisecond') {
// If the time is relative, there can occasionally be an disparity between the relative date
// and "now", which it is being compared to, so set an extra buffer to account for this.
loBuffer = 50;
hiBuffer = -50;
}
}
t = d.getTime();
min = p.date.getTime();
max = max || (min + accuracy);
max = compensateForTimezoneTraversal(d, min, max);
return t >= (min - loBuffer) && t <= (max + hiBuffer);
}
function compensateForTimezoneTraversal(d, min, max) {
var dMin, dMax, minOffset, maxOffset;
dMin = new Date(min);
dMax = new Date(max).utc(d.isUTC());
if(callDateGet(dMax, 'Hours') !== 23) {
minOffset = dMin.getTimezoneOffset();
maxOffset = dMax.getTimezoneOffset();
if(minOffset !== maxOffset) {
max += (maxOffset - minOffset).minutes();
}
}
return max;
}
function updateDate(d, params, reset, advance, prefer) {
var weekday, specificityIndex;
function getParam(key) {
return isDefined(params[key]) ? params[key] : params[key + 's'];
}
function paramExists(key) {
return isDefined(getParam(key));
}
function uniqueParamExists(key, isDay) {
return paramExists(key) || (isDay && paramExists('weekday'));
}
function canDisambiguate() {
var now = new date;
return (prefer === -1 && d > now) || (prefer === 1 && d < now);
}
if(isNumber(params) && advance) {
// If param is a number and we're advancing, the number is presumed to be milliseconds.
params = { 'milliseconds': params };
} else if(isNumber(params)) {
// Otherwise just set the timestamp and return.
d.setTime(params);
return d;
}
// "date" can also be passed for the day
if(isDefined(params['date'])) {
params['day'] = params['date'];
}
// Reset any unit lower than the least specific unit set. Do not do this for weeks
// or for years. This needs to be performed before the acutal setting of the date
// because the order needs to be reversed in order to get the lowest specificity,
// also because higher order units can be overwritten by lower order units, such
// as setting hour: 3, minute: 345, etc.
iterateOverObject(DateUnitsReversed, function(i,u) {
var isDay = u.unit === 'day';
if(uniqueParamExists(u.unit, isDay)) {
params.specificity = u.unit;
specificityIndex = +i;
return false;
} else if(reset && u.unit !== 'week' && (!isDay || !paramExists('week'))) {
// Days are relative to months, not weeks, so don't reset if a week exists.
callDateSet(d, u.method, (isDay ? 1 : 0));
}
});
// Now actually set or advance the date in order, higher units first.
DateUnits.forEach(function(u,i) {
var unit = u.unit, method = u.method, higherUnit = DateUnits[i - 1], value;
value = getParam(unit)
if(isUndefined(value)) return;
if(advance) {
if(unit === 'week') {
value = (params['day'] || 0) + (value * 7);
method = 'Date';
}
value = (value * advance) + callDateGet(d, method);
} else if(unit === 'month' && paramExists('day')) {
// When setting the month, there is a chance that we will traverse into a new month.
// This happens in DST shifts, for example June 1st DST jumping to January 1st
// (non-DST) will have a shift of -1:00 which will traverse into the previous year.
// Prevent this by proactively setting the day when we know it will be set again anyway.
// It can also happen when there are not enough days in the target month. This second
// situation is identical to checkMonthTraversal below, however when we are advancing
// we want to reset the date to "the last date in the target month". In the case of
// DST shifts, however, we want to avoid the "edges" of months as that is where this
// unintended traversal can happen. This is the reason for the different handling of
// two similar but slightly different situations.
//
// TL;DR This method avoids the edges of a month IF not advancing and the date is going
// to be set anyway, while checkMonthTraversal resets the date to the last day if advancing.
//
callDateSet(d, 'Date', 15);
}
callDateSet(d, method, value);
if(advance && unit === 'month') {
checkMonthTraversal(d, value);
}
});
// If a weekday is included in the params, set it ahead of time and set the params
// to reflect the updated date so that resetting works properly.
if(!advance && !paramExists('day') && paramExists('weekday')) {
var weekday = getParam('weekday'), isAhead, futurePreferred;
d.setWeekday(weekday);
}
if(canDisambiguate()) {
iterateOverObject(DateUnitsReversed.slice(specificityIndex + 1), function(i,u) {
var ambiguous = u.ambiguous || (u.unit === 'week' && paramExists('weekday'));
if(ambiguous && !uniqueParamExists(u.unit, u.unit === 'day')) {
d[u.addMethod](prefer);
return false;
}
});
}
return d;
}
function callDateGet(d, method) {
return d['get' + (d._utc ? 'UTC' : '') + method]();
}
function callDateSet(d, method, value) {
return d['set' + (d._utc ? 'UTC' : '') + method](value);
}
// The ISO format allows times strung together without a demarcating ":", so make sure
// that these markers are now optional.
function prepareTime(format, loc, iso) {
var timeSuffixMapping = {'h':0,'m':1,'s':2}, add;
loc = loc || English;
return format.replace(/{([a-z])}/g, function(full, token) {
var separators = [],
isHours = token === 'h',
tokenIsRequired = isHours && !iso;
if(token === 't') {
return loc['ampm'].join('|');
} else {
if(isHours) {
separators.push(':');
}
if(add = loc['timeSuffixes'][timeSuffixMapping[token]]) {
separators.push(add + '\\s*');
}
return separators.length === 0 ? '' : '(?:' + separators.join('|') + ')' + (tokenIsRequired ? '' : '?');
}
});
}
// If the month is being set, then we don't want to accidentally
// traverse into a new month just because the target month doesn't have enough
// days. In other words, "5 months ago" from July 30th is still February, even
// though there is no February 30th, so it will of necessity be February 28th
// (or 29th in the case of a leap year).
function checkMonthTraversal(date, targetMonth) {
if(targetMonth < 0) {
targetMonth = targetMonth % 12 + 12;
}
if(targetMonth % 12 != callDateGet(date, 'Month')) {
callDateSet(date, 'Date', 0);
}
}
function createDate(args, prefer, forceUTC) {
var f, localeCode;
if(isNumber(args[1])) {
// If the second argument is a number, then we have an enumerated constructor type as in "new Date(2003, 2, 12);"
f = collectDateArguments(args)[0];
} else {
f = args[0];
localeCode = args[1];
}
return getExtendedDate(f, localeCode, prefer, forceUTC).date;
}
function buildDateUnits() {
DateUnitsReversed = DateUnits.concat().reverse();
DateArgumentUnits = DateUnits.concat();
DateArgumentUnits.splice(2,1);
}
/***
* @method [units]Since([d], [locale] = currentLocale)
* @returns Number
* @short Returns the time since [d] in the appropriate unit.
* @extra [d] will accept a date object, timestamp, or text format. If not specified, [d] is assumed to be now. [locale] can be passed to specify the locale that the date is in. %[unit]Ago% is provided as an alias to make this more readable when [d] is assumed to be the current date. For more see @date_format.
*
* @set
* millisecondsSince
* secondsSince
* minutesSince
* hoursSince
* daysSince
* weeksSince
* monthsSince
* yearsSince
*
* @example
*
* Date.create().millisecondsSince('1 hour ago') -> 3,600,000
* Date.create().daysSince('1 week ago') -> 7
* Date.create().yearsSince('15 years ago') -> 15
* Date.create('15 years ago').yearsAgo() -> 15
*
***
* @method [units]Ago()
* @returns Number
* @short Returns the time ago in the appropriate unit.
*
* @set
* millisecondsAgo
* secondsAgo
* minutesAgo
* hoursAgo
* daysAgo
* weeksAgo
* monthsAgo
* yearsAgo
*
* @example
*
* Date.create('last year').millisecondsAgo() -> 3,600,000
* Date.create('last year').daysAgo() -> 7
* Date.create('last year').yearsAgo() -> 15
*
***
* @method [units]Until([d], [locale] = currentLocale)
* @returns Number
* @short Returns the time until [d] in the appropriate unit.
* @extra [d] will accept a date object, timestamp, or text format. If not specified, [d] is assumed to be now. [locale] can be passed to specify the locale that the date is in. %[unit]FromNow% is provided as an alias to make this more readable when [d] is assumed to be the current date. For more see @date_format.
*
* @set
* millisecondsUntil
* secondsUntil
* minutesUntil
* hoursUntil
* daysUntil
* weeksUntil
* monthsUntil
* yearsUntil
*
* @example
*
* Date.create().millisecondsUntil('1 hour from now') -> 3,600,000
* Date.create().daysUntil('1 week from now') -> 7
* Date.create().yearsUntil('15 years from now') -> 15
* Date.create('15 years from now').yearsFromNow() -> 15
*
***
* @method [units]FromNow()
* @returns Number
* @short Returns the time from now in the appropriate unit.
*
* @set
* millisecondsFromNow
* secondsFromNow
* minutesFromNow
* hoursFromNow
* daysFromNow
* weeksFromNow
* monthsFromNow
* yearsFromNow
*
* @example
*
* Date.create('next year').millisecondsFromNow() -> 3,600,000
* Date.create('next year').daysFromNow() -> 7
* Date.create('next year').yearsFromNow() -> 15
*
***
* @method add[Units](<num>, [reset] = false)
* @returns Date
* @short Adds <num> of the unit to the date. If [reset] is true, all lower units will be reset.
* @extra Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Don't use %addMonths% if you need precision.
*
* @set
* addMilliseconds
* addSeconds
* addMinutes
* addHours
* addDays
* addWeeks
* addMonths
* addYears
*
* @example
*
* Date.create().addMilliseconds(5) -> current time + 5 milliseconds
* Date.create().addDays(5) -> current time + 5 days
* Date.create().addYears(5) -> current time + 5 years
*
***
* @method isLast[Unit]()
* @returns Boolean
* @short Returns true if the date is last week/month/year.
*
* @set
* isLastWeek
* isLastMonth
* isLastYear
*
* @example
*
* Date.create('yesterday').isLastWeek() -> true or false?
* Date.create('yesterday').isLastMonth() -> probably not...
* Date.create('yesterday').isLastYear() -> even less likely...
*
***
* @method isThis[Unit]()
* @returns Boolean
* @short Returns true if the date is this week/month/year.
*
* @set
* isThisWeek
* isThisMonth
* isThisYear
*
* @example
*
* Date.create('tomorrow').isThisWeek() -> true or false?
* Date.create('tomorrow').isThisMonth() -> probably...
* Date.create('tomorrow').isThisYear() -> signs point to yes...
*
***
* @method isNext[Unit]()
* @returns Boolean
* @short Returns true if the date is next week/month/year.
*
* @set
* isNextWeek
* isNextMonth
* isNextYear
*
* @example
*
* Date.create('tomorrow').isNextWeek() -> true or false?
* Date.create('tomorrow').isNextMonth() -> probably not...
* Date.create('tomorrow').isNextYear() -> even less likely...
*
***
* @method beginningOf[Unit]()
* @returns Date
* @short Sets the date to the beginning of the appropriate unit.
*
* @set
* beginningOfDay
* beginningOfWeek
* beginningOfMonth
* beginningOfYear
*
* @example
*
* Date.create().beginningOfDay() -> the beginning of today (resets the time)
* Date.create().beginningOfWeek() -> the beginning of the week
* Date.create().beginningOfMonth() -> the beginning of the month
* Date.create().beginningOfYear() -> the beginning of the year
*
***
* @method endOf[Unit]()
* @returns Date
* @short Sets the date to the end of the appropriate unit.
*
* @set
* endOfDay
* endOfWeek
* endOfMonth
* endOfYear
*
* @example
*
* Date.create().endOfDay() -> the end of today (sets the time to 23:59:59.999)
* Date.create().endOfWeek() -> the end of the week
* Date.create().endOfMonth() -> the end of the month
* Date.create().endOfYear() -> the end of the year
*
***/
function buildDateMethods() {
extendSimilar(date, true, false, DateUnits, function(methods, u, i) {
var unit = u.unit, caps = simpleCapitalize(unit), multiplier = u.multiplier(), since, until;
u.addMethod = 'add' + caps + 's';
since = function(f, localeCode) {
return round((this.getTime() - date.create(f, localeCode).getTime()) / multiplier);
};
until = function(f, localeCode) {
return round((date.create(f, localeCode).getTime() - this.getTime()) / multiplier);
};
methods[unit+'sAgo'] = until;
methods[unit+'sUntil'] = until;
methods[unit+'sSince'] = since;
methods[unit+'sFromNow'] = since;
methods[u.addMethod] = function(num, reset) {
var set = {};
set[unit] = num;
return this.advance(set, reset);
};
buildNumberToDateAlias(u, multiplier);
if(i < 3) {
['Last','This','Next'].forEach(function(shift) {
methods['is' + shift + caps] = function() {
return this.is(shift + ' ' + unit);
};
});
}
if(i < 4) {
methods['beginningOf' + caps] = function() {
var set = {};
switch(unit) {
case 'year': set['year'] = callDateGet(this, 'FullYear'); break;
case 'month': set['month'] = callDateGet(this, 'Month'); break;
case 'day': set['day'] = callDateGet(this, 'Date'); break;
case 'week': set['weekday'] = 0; break;
}
return this.set(set, true);
};
methods['endOf' + caps] = function() {
var set = { 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 999 };
switch(unit) {
case 'year': set['month'] = 11; set['day'] = 31; break;
case 'month': set['day'] = this.daysInMonth(); break;
case 'week': set['weekday'] = 6; break;
}
return this.set(set, true);
};
}
});
}
function buildCoreInputFormats() {
English.addFormat('([+-])?(\\d{4,4})[-.]?{full_month}[-.]?(\\d{1,2})?', true, ['year_sign','year','month','date'], false, true);
English.addFormat('(\\d{1,2})[-.\\/]{full_month}(?:[-.\\/](\\d{2,4}))?', true, ['date','month','year'], true);
English.addFormat('{full_month}[-.](\\d{4,4})', false, ['month','year']);
English.addFormat('\\/Date\\((\\d+(?:\\+\\d{4,4})?)\\)\\/', false, ['timestamp'])
English.addFormat(prepareTime(RequiredTime, English), false, TimeFormat)
// When a new locale is initialized it will have the CoreDateFormats initialized by default.
// From there, adding new formats will push them in front of the previous ones, so the core
// formats will be the last to be reached. However, the core formats themselves have English
// months in them, which means that English needs to first be initialized and creates a race
// condition. I'm getting around this here by adding these generalized formats in the order
// specific -> general, which will mean they will be added to the English localization in
// general -> specific order, then chopping them off the front and reversing to get the correct
// order. Note that there are 7 formats as 2 have times which adds a front and a back format.
CoreDateFormats = English.compiledFormats.slice(0,7).reverse();
English.compiledFormats = English.compiledFormats.slice(7).concat(CoreDateFormats);
}
function buildDateOutputShortcuts() {
extendSimilar(date, true, false, 'short,long,full', function(methods, name) {
methods[name] = function(localeCode) {
return formatDate(this, name, false, localeCode);
}
});
}
function buildAsianDigits() {
KanjiDigits.split('').forEach(function(digit, value) {
var holder;
if(value > 9) {
value = math.pow(10, value - 9);
}
AsianDigitMap[digit] = value;
});
FullWidthDigits.split('').forEach(function(digit, value) {
AsianDigitMap[digit] = value;
});
// Kanji numerals may also be included in phrases which are text-based rather
// than actual numbers such as Chinese weekdays (上周三), and "the day before
// yesterday" (一昨日) in Japanese, so don't match these.
AsianDigitReg = regexp('([期週周])?([' + KanjiDigits + FullWidthDigits + ']+)(?!昨)', 'g');
}
/***
* @method is[Day]()
* @returns Boolean
* @short Returns true if the date falls on that day.
* @extra Also available: %isYesterday%, %isToday%, %isTomorrow%, %isWeekday%, and %isWeekend%.
*
* @set
* isToday
* isYesterday
* isTomorrow
* isWeekday
* isWeekend
* isSunday
* isMonday
* isTuesday
* isWednesday
* isThursday
* isFriday
* isSaturday
*
* @example
*
* Date.create('tomorrow').isToday() -> false
* Date.create('thursday').isTomorrow() -> ?
* Date.create('yesterday').isWednesday() -> ?
* Date.create('today').isWeekend() -> ?
*
***
* @method isFuture()
* @returns Boolean
* @short Returns true if the date is in the future.
* @example
*
* Date.create('next week').isFuture() -> true
* Date.create('last week').isFuture() -> false
*
***
* @method isPast()
* @returns Boolean
* @short Returns true if the date is in the past.
* @example
*
* Date.create('last week').isPast() -> true
* Date.create('next week').isPast() -> false
*
***/
function buildRelativeAliases() {
var special = 'today,yesterday,tomorrow,weekday,weekend,future,past'.split(',');
var weekdays = English['weekdays'].slice(0,7);
var months = English['months'].slice(0,12);
extendSimilar(date, true, false, special.concat(weekdays).concat(months), function(methods, name) {
methods['is'+ simpleCapitalize(name)] = function(utc) {
return this.is(name, 0, utc);
};
});
}
function buildUTCAliases() {
date.extend({
'utc': {
'create': function() {
return createDate(arguments, 0, true);
},
'past': function() {
return createDate(arguments, -1, true);
},
'future': function() {
return createDate(arguments, 1, true);
}
}
}, false, false);
}
function setDateProperties() {
date.extend({
'RFC1123': '{Dow}, {dd} {Mon} {yyyy} {HH}:{mm}:{ss} {tz}',
'RFC1036': '{Weekday}, {dd}-{Mon}-{yy} {HH}:{mm}:{ss} {tz}',
'ISO8601_DATE': '{yyyy}-{MM}-{dd}',
'ISO8601_DATETIME': '{yyyy}-{MM}-{dd}T{HH}:{mm}:{ss}.{fff}{isotz}'
}, false, false);
}
date.extend({
/***
* @method Date.create(<d>, [locale] = currentLocale)
* @returns Date
* @short Alternate Date constructor which understands many different text formats, a timestamp, or another date.
* @extra If no argument is given, date is assumed to be now. %Date.create% additionally can accept enumerated parameters as with the standard date constructor. [locale] can be passed to specify the locale that the date is in. When unspecified, the current locale (default is English) is assumed. UTC-based dates can be created through the %utc% object. For more see @date_format.
* @set
* Date.utc.create
*
* @example
*
* Date.create('July') -> July of this year
* Date.create('1776') -> 1776
* Date.create('today') -> today
* Date.create('wednesday') -> This wednesday
* Date.create('next friday') -> Next friday
* Date.create('July 4, 1776') -> July 4, 1776
* Date.create(-446806800000) -> November 5, 1955
* Date.create(1776, 6, 4) -> July 4, 1776
* Date.create('1776年07月04日', 'ja') -> July 4, 1776
* Date.utc.create('July 4, 1776', 'en') -> July 4, 1776
*
***/
'create': function() {
return createDate(arguments);
},
/***
* @method Date.past(<d>, [locale] = currentLocale)
* @returns Date
* @short Alternate form of %Date.create% with any ambiguity assumed to be the past.
* @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" depending on context. Note that dates explicitly in the future ("next Sunday") will remain in the future. This method simply provides a hint when ambiguity exists. UTC-based dates can be created through the %utc% object. For more, see @date_format.
* @set
* Date.utc.past
* @example
*
* Date.past('July') -> July of this year or last depending on the current month
* Date.past('Wednesday') -> This wednesday or last depending on the current weekday
*
***/
'past': function() {
return createDate(arguments, -1);
},
/***
* @method Date.future(<d>, [locale] = currentLocale)
* @returns Date
* @short Alternate form of %Date.create% with any ambiguity assumed to be the future.
* @extra For example %"Sunday"% can be either "the Sunday coming up" or "the Sunday last" depending on context. Note that dates explicitly in the past ("last Sunday") will remain in the past. This method simply provides a hint when ambiguity exists. UTC-based dates can be created through the %utc% object. For more, see @date_format.
* @set
* Date.utc.future
*
* @example
*
* Date.future('July') -> July of this year or next depending on the current month
* Date.future('Wednesday') -> This wednesday or next depending on the current weekday
*
***/
'future': function() {
return createDate(arguments, 1);
},
/***
* @method Date.addLocale(<code>, <set>)
* @returns Locale
* @short Adds a locale <set> to the locales understood by Sugar.
* @extra For more see @date_format.
*
***/
'addLocale': function(localeCode, set) {
return setLocalization(localeCode, set);
},
/***
* @method Date.setLocale(<code>)
* @returns Locale
* @short Sets the current locale to be used with dates.
* @extra Sugar has support for 13 locales that are available through the "Date Locales" package. In addition you can define a new locale with %Date.addLocale%. For more see @date_format.
*
***/
'setLocale': function(localeCode, set) {
var loc = getLocalization(localeCode, false);
CurrentLocalization = loc;
// The code is allowed to be more specific than the codes which are required:
// i.e. zh-CN or en-US. Currently this only affects US date variants such as 8/10/2000.
if(localeCode && localeCode != loc['code']) {
loc['code'] = localeCode;
}
return loc;
},
/***
* @method Date.getLocale([code] = current)
* @returns Locale
* @short Gets the locale for the given code, or the current locale.
* @extra The resulting locale object can be manipulated to provide more control over date localizations. For more about locales, see @date_format.
*
***/
'getLocale': function(localeCode) {
return !localeCode ? CurrentLocalization : getLocalization(localeCode, false);
},
/**
* @method Date.addFormat(<format>, <match>, [code] = null)
* @returns Nothing
* @short Manually adds a new date input format.
* @extra This method allows fine grained control for alternate formats. <format> is a string that can have regex tokens inside. <match> is an array of the tokens that each regex capturing group will map to, for example %year%, %date%, etc. For more, see @date_format.
*
**/
'addFormat': function(format, match, localeCode) {
addDateInputFormat(getLocalization(localeCode), format, match);
}
}, false, false);
date.extend({
/***
* @method set(<set>, [reset] = false)
* @returns Date
* @short Sets the date object.
* @extra This method can accept multiple formats including a single number as a timestamp, an object, or enumerated parameters (as with the Date constructor). If [reset] is %true%, any units more specific than those passed will be reset.
*
* @example
*
* new Date().set({ year: 2011, month: 11, day: 31 }) -> December 31, 2011
* new Date().set(2011, 11, 31) -> December 31, 2011
* new Date().set(86400000) -> 1 day after Jan 1, 1970
* new Date().set({ year: 2004, month: 6 }, true) -> June 1, 2004, 00:00:00.000
*
***/
'set': function() {
var args = collectDateArguments(arguments);
return updateDate(this, args[0], args[1])
},
/***
* @method setWeekday()
* @returns Nothing
* @short Sets the weekday of the date.
*
* @example
*
* d = new Date(); d.setWeekday(1); d; -> Monday of this week
* d = new Date(); d.setWeekday(6); d; -> Saturday of this week
*
***/
'setWeekday': function(dow) {
if(isUndefined(dow)) return;
return callDateSet(this, 'Date', callDateGet(this, 'Date') + dow - callDateGet(this, 'Day'));
},
/***
* @method setWeek()
* @returns Nothing
* @short Sets the week (of the year).
*
* @example
*
* d = new Date(); d.setWeek(15); d; -> 15th week of the year
*
***/
'setWeek': function(week) {
if(isUndefined(week)) return;
var date = callDateGet(this, 'Date');
callDateSet(this, 'Month', 0);
callDateSet(this, 'Date', (week * 7) + 1);
return this.getTime();
},
/***
* @method getWeek()
* @returns Number
* @short Gets the date's week (of the year).
* @extra If %utc% is set on the date, the week will be according to UTC time.
*
* @example
*
* new Date().getWeek() -> today's week of the year
*
***/
'getWeek': function() {
return getWeekNumber(this);
},
/***
* @method getUTCOffset([iso])
* @returns String
* @short Returns a string representation of the offset from UTC time. If [iso] is true the offset will be in ISO8601 format.
* @example
*
* new Date().getUTCOffset() -> "+0900"
* new Date().getUTCOffset(true) -> "+09:00"
*
***/
'getUTCOffset': function(iso) {
var offset = this._utc ? 0 : this.getTimezoneOffset();
var colon = iso === true ? ':' : '';
if(!offset && iso) return 'Z';
return padNumber(round(-offset / 60), 2, true) + colon + padNumber(offset % 60, 2);
},
/***
* @method utc([on] = true)
* @returns Date
* @short Sets the internal utc flag for the date. When on, UTC-based methods will be called internally.
* @extra For more see @date_format.
* @example
*
* new Date().utc(true)
* new Date().utc(false)
*
***/
'utc': function(set) {
this._utc = set === true || arguments.length === 0;
return this;
},
/***
* @method isUTC()
* @returns Boolean
* @short Returns true if the date has no timezone offset.
* @extra This will also return true for a date that has had %toUTC% called on it. This is intended to help approximate shifting timezones which is not possible in client-side Javascript. Note that the native method %getTimezoneOffset% will always report the same thing, even if %isUTC% becomes true.
* @example
*
* new Date().isUTC() -> true or false?
* new Date().toUTC().isUTC() -> true
*
***/
'isUTC': function() {
return !!this._utc || this.getTimezoneOffset() === 0;
},
/***
* @method advance(<set>, [reset] = false)
* @returns Date
* @short Sets the date forward.
* @extra This method can accept multiple formats including an object, a string in the format %3 days%, a single number as milliseconds, or enumerated parameters (as with the Date constructor). If [reset] is %true%, any units more specific than those passed will be reset. For more see @date_format.
* @example
*
* new Date().advance({ year: 2 }) -> 2 years in the future
* new Date().advance('2 days') -> 2 days in the future
* new Date().advance(0, 2, 3) -> 2 months 3 days in the future
* new Date().advance(86400000) -> 1 day in the future
*
***/
'advance': function() {
var args = collectDateArguments(arguments, true);
return updateDate(this, args[0], args[1], 1);
},
/***
* @method rewind(<set>, [reset] = false)
* @returns Date
* @short Sets the date back.
* @extra This method can accept multiple formats including a single number as a timestamp, an object, or enumerated parameters (as with the Date constructor). If [reset] is %true%, any units more specific than those passed will be reset. For more see @date_format.
* @example
*
* new Date().rewind({ year: 2 }) -> 2 years in the past
* new Date().rewind(0, 2, 3) -> 2 months 3 days in the past
* new Date().rewind(86400000) -> 1 day in the past
*
***/
'rewind': function() {
var args = collectDateArguments(arguments, true);
return updateDate(this, args[0], args[1], -1);
},
/***
* @method isValid()
* @returns Boolean
* @short Returns true if the date is valid.
* @example
*
* new Date().isValid() -> true
* new Date('flexor').isValid() -> false
*
***/
'isValid': function() {
return !isNaN(this.getTime());
},
/***
* @method isAfter(<d>, [margin] = 0)
* @returns Boolean
* @short Returns true if the date is after the <d>.
* @extra [margin] is to allow extra margin of error (in ms). <d> will accept a date object, timestamp, or text format. If not specified, <d> is assumed to be now. See @date_format for more.
* @example
*
* new Date().isAfter('tomorrow') -> false
* new Date().isAfter('yesterday') -> true
*
***/
'isAfter': function(d, margin, utc) {
return this.getTime() > date.create(d).getTime() - (margin || 0);
},
/***
* @method isBefore(<d>, [margin] = 0)
* @returns Boolean
* @short Returns true if the date is before <d>.
* @extra [margin] is to allow extra margin of error (in ms). <d> will accept a date object, timestamp, or text format. If not specified, <d> is assumed to be now. See @date_format for more.
* @example
*
* new Date().isBefore('tomorrow') -> true
* new Date().isBefore('yesterday') -> false
*
***/
'isBefore': function(d, margin) {
return this.getTime() < date.create(d).getTime() + (margin || 0);
},
/***
* @method isBetween(<d1>, <d2>, [margin] = 0)
* @returns Boolean
* @short Returns true if the date falls between <d1> and <d2>.
* @extra [margin] is to allow extra margin of error (in ms). <d1> and <d2> will accept a date object, timestamp, or text format. If not specified, they are assumed to be now. See @date_format for more.
* @example
*
* new Date().isBetween('yesterday', 'tomorrow') -> true
* new Date().isBetween('last year', '2 years ago') -> false
*
***/
'isBetween': function(d1, d2, margin) {
var t = this.getTime();
var t1 = date.create(d1).getTime();
var t2 = date.create(d2).getTime();
var lo = math.min(t1, t2);
var hi = math.max(t1, t2);
margin = margin || 0;
return (lo - margin < t) && (hi + margin > t);
},
/***
* @method isLeapYear()
* @returns Boolean
* @short Returns true if the date is a leap year.
* @example
*
* Date.create('2000').isLeapYear() -> true
*
***/
'isLeapYear': function() {
var year = callDateGet(this, 'FullYear');
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
},
/***
* @method daysInMonth()
* @returns Number
* @short Returns the number of days in the date's month.
* @example
*
* Date.create('May').daysInMonth() -> 31
* Date.create('February, 2000').daysInMonth() -> 29
*
***/
'daysInMonth': function() {
return 32 - callDateGet(new date(callDateGet(this, 'FullYear'), callDateGet(this, 'Month'), 32), 'Date');
},
/***
* @method format(<format>, [locale] = currentLocale)
* @returns String
* @short Formats and outputs the date.
* @extra <format> can be a number of pre-determined formats or a string of tokens. Locale-specific formats are %short%, %long%, and %full% which have their own aliases and can be called with %date.short()%, etc. If <format> is not specified the %long% format is assumed. [locale] specifies a locale code to use (if not specified the current locale is used). See @date_format for more details.
*
* @set
* short
* long
* full
*
* @example
*
* Date.create().format() -> ex. July 4, 2003
* Date.create().format('{Weekday} {d} {Month}, {yyyy}') -> ex. Monday July 4, 2003
* Date.create().format('{hh}:{mm}') -> ex. 15:57
* Date.create().format('{12hr}:{mm}{tt}') -> ex. 3:57pm
* Date.create().format(Date.ISO8601_DATETIME) -> ex. 2011-07-05 12:24:55.528Z
* Date.create('last week').format('short', 'ja') -> ex. 先週
* Date.create('yesterday').format(function(value,unit,ms,loc) {
* // value = 1, unit = 3, ms = -86400000, loc = [current locale object]
* }); -> ex. 1 day ago
*
***/
'format': function(f, localeCode) {
return formatDate(this, f, false, localeCode);
},
/***
* @method relative([fn], [locale] = currentLocale)
* @returns String
* @short Returns a relative date string offset to the current time.
* @extra [fn] can be passed to provide for more granular control over the resulting string. [fn] is passed 4 arguments: the adjusted value, unit, offset in milliseconds, and a localization object. As an alternate syntax, [locale] can also be passed as the first (and only) parameter. For more, see @date_format.
* @example
*
* Date.create('90 seconds ago').relative() -> 1 minute ago
* Date.create('January').relative() -> ex. 5 months ago
* Date.create('January').relative('ja') -> 3ヶ月前
* Date.create('120 minutes ago').relative(function(val,unit,ms,loc) {
* // value = 2, unit = 3, ms = -7200, loc = [current locale object]
* }); -> ex. 5 months ago
*
***/
'relative': function(f, localeCode) {
if(isString(f)) {
localeCode = f;
f = null;
}
return formatDate(this, f, true, localeCode);
},
/***
* @method is(<d>, [margin] = 0)
* @returns Boolean
* @short Returns true if the date is <d>.
* @extra <d> will accept a date object, timestamp, or text format. %is% additionally understands more generalized expressions like month/weekday names, 'today', etc, and compares to the precision implied in <d>. [margin] allows an extra margin of error in milliseconds. For more, see @date_format.
* @example
*
* Date.create().is('July') -> true or false?
* Date.create().is('1776') -> false
* Date.create().is('today') -> true
* Date.create().is('weekday') -> true or false?
* Date.create().is('July 4, 1776') -> false
* Date.create().is(-6106093200000) -> false
* Date.create().is(new Date(1776, 6, 4)) -> false
*
***/
'is': function(d, margin, utc) {
var tmp, comp;
if(!this.isValid()) return;
if(isString(d)) {
d = d.trim().toLowerCase();
comp = this.clone().utc(utc);
switch(true) {
case d === 'future': return this.getTime() > new date().getTime();
case d === 'past': return this.getTime() < new date().getTime();
case d === 'weekday': return callDateGet(comp, 'Day') > 0 && callDateGet(comp, 'Day') < 6;
case d === 'weekend': return callDateGet(comp, 'Day') === 0 || callDateGet(comp, 'Day') === 6;
case (tmp = English['weekdays'].indexOf(d) % 7) > -1: return callDateGet(comp, 'Day') === tmp;
case (tmp = English['months'].indexOf(d) % 12) > -1: return callDateGet(comp, 'Month') === tmp;
}
}
return compareDate(this, d, margin, utc);
},
/***
* @method reset([unit] = 'hours')
* @returns Date
* @short Resets the unit passed and all smaller units. Default is "hours", effectively resetting the time.
* @example
*
* Date.create().reset('day') -> Beginning of today
* Date.create().reset('month') -> 1st of the month
*
***/
'reset': function(unit) {
var params = {}, recognized;
unit = unit || 'hours';
if(unit === 'date') unit = 'days';
recognized = DateUnits.some(function(u) {
return unit === u.unit || unit === u.unit + 's';
});
params[unit] = unit.match(/^days?/) ? 1 : 0;
return recognized ? this.set(params, true) : this;
},
/***
* @method clone()
* @returns Date
* @short Clones the date.
* @example
*
* Date.create().clone() -> Copy of now
*
***/
'clone': function() {
var d = new date(this.getTime());
d._utc = this._utc;
return d;
}
});
// Instance aliases
date.extend({
/***
* @method iso()
* @alias toISOString
*
***/
'iso': function() {
return this.toISOString();
},
/***
* @method getWeekday()
* @returns Number
* @short Alias for %getDay%.
* @set
* getUTCWeekday
*
* @example
*
+ Date.create().getWeekday(); -> (ex.) 3
+ Date.create().getUTCWeekday(); -> (ex.) 3
*
***/
'getWeekday': date.prototype.getDay,
'getUTCWeekday': date.prototype.getUTCDay
});
/***
* Number module
*
***/
/***
* @method [unit]()
* @returns Number
* @short Takes the number as a corresponding unit of time and converts to milliseconds.
* @extra Method names can be both singular and plural. Note that as "a month" is ambiguous as a unit of time, %months% will be equivalent to 30.4375 days, the average number in a month. Be careful using %months% if you need exact precision.
*
* @set
* millisecond
* milliseconds
* second
* seconds
* minute
* minutes
* hour
* hours
* day
* days
* week
* weeks
* month
* months
* year
* years
*
* @example
*
* (5).milliseconds() -> 5
* (10).hours() -> 36000000
* (1).day() -> 86400000
*
***
* @method [unit]Before([d], [locale] = currentLocale)
* @returns Date
* @short Returns a date that is <n> units before [d], where <n> is the number.
* @extra [d] will accept a date object, timestamp, or text format. Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Be careful using %monthsBefore% if you need exact precision. See @date_format for more.
*
* @set
* millisecondBefore
* millisecondsBefore
* secondBefore
* secondsBefore
* minuteBefore
* minutesBefore
* hourBefore
* hoursBefore
* dayBefore
* daysBefore
* weekBefore
* weeksBefore
* monthBefore
* monthsBefore
* yearBefore
* yearsBefore
*
* @example
*
* (5).daysBefore('tuesday') -> 5 days before tuesday of this week
* (1).yearBefore('January 23, 1997') -> January 23, 1996
*
***
* @method [unit]Ago()
* @returns Date
* @short Returns a date that is <n> units ago.
* @extra Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Be careful using %monthsAgo% if you need exact precision.
*
* @set
* millisecondAgo
* millisecondsAgo
* secondAgo
* secondsAgo
* minuteAgo
* minutesAgo
* hourAgo
* hoursAgo
* dayAgo
* daysAgo
* weekAgo
* weeksAgo
* monthAgo
* monthsAgo
* yearAgo
* yearsAgo
*
* @example
*
* (5).weeksAgo() -> 5 weeks ago
* (1).yearAgo() -> January 23, 1996
*
***
* @method [unit]After([d], [locale] = currentLocale)
* @returns Date
* @short Returns a date <n> units after [d], where <n> is the number.
* @extra [d] will accept a date object, timestamp, or text format. Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Be careful using %monthsAfter% if you need exact precision. See @date_format for more.
*
* @set
* millisecondAfter
* millisecondsAfter
* secondAfter
* secondsAfter
* minuteAfter
* minutesAfter
* hourAfter
* hoursAfter
* dayAfter
* daysAfter
* weekAfter
* weeksAfter
* monthAfter
* monthsAfter
* yearAfter
* yearsAfter
*
* @example
*
* (5).daysAfter('tuesday') -> 5 days after tuesday of this week
* (1).yearAfter('January 23, 1997') -> January 23, 1998
*
***
* @method [unit]FromNow()
* @returns Date
* @short Returns a date <n> units from now.
* @extra Note that "months" is ambiguous as a unit of time. If the target date falls on a day that does not exist (ie. August 31 -> February 31), the date will be shifted to the last day of the month. Be careful using %monthsFromNow% if you need exact precision.
*
* @set
* millisecondFromNow
* millisecondsFromNow
* secondFromNow
* secondsFromNow
* minuteFromNow
* minutesFromNow
* hourFromNow
* hoursFromNow
* dayFromNow
* daysFromNow
* weekFromNow
* weeksFromNow
* monthFromNow
* monthsFromNow
* yearFromNow
* yearsFromNow
*
* @example
*
* (5).weeksFromNow() -> 5 weeks ago
* (1).yearFromNow() -> January 23, 1998
*
***/
function buildNumberToDateAlias(u, multiplier) {
var unit = u.unit, methods = {};
function base() { return round(this * multiplier); }
function after() { return createDate(arguments)[u.addMethod](this); }
function before() { return createDate(arguments)[u.addMethod](-this); }
methods[unit] = base;
methods[unit + 's'] = base;
methods[unit + 'Before'] = before;
methods[unit + 'sBefore'] = before;
methods[unit + 'Ago'] = before;
methods[unit + 'sAgo'] = before;
methods[unit + 'After'] = after;
methods[unit + 'sAfter'] = after;
methods[unit + 'FromNow'] = after;
methods[unit + 'sFromNow'] = after;
number.extend(methods);
}
number.extend({
/***
* @method duration([locale] = currentLocale)
* @returns String
* @short Takes the number as milliseconds and returns a unit-adjusted localized string.
* @extra This method is the same as %Date#relative% without the localized equivalent of "from now" or "ago". [locale] can be passed as the first (and only) parameter. Note that this method is only available when the dates package is included.
* @example
*
* (500).duration() -> '500 milliseconds'
* (1200).duration() -> '1 second'
* (75).minutes().duration() -> '1 hour'
* (75).minutes().duration('es') -> '1 hora'
*
***/
'duration': function(localeCode) {
return getLocalization(localeCode).getDuration(this);
}
});
English = CurrentLocalization = date.addLocale('en', {
'plural': true,
'timeMarker': 'at',
'ampm': 'am,pm',
'months': 'January,February,March,April,May,June,July,August,September,October,November,December',
'weekdays': 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday',
'units': 'millisecond:|s,second:|s,minute:|s,hour:|s,day:|s,week:|s,month:|s,year:|s',
'numbers': 'one,two,three,four,five,six,seven,eight,nine,ten',
'articles': 'a,an,the',
'tokens': 'the,st|nd|rd|th,of',
'short': '{Month} {d}, {yyyy}',
'long': '{Month} {d}, {yyyy} {h}:{mm}{tt}',
'full': '{Weekday} {Month} {d}, {yyyy} {h}:{mm}:{ss}{tt}',
'past': '{num} {unit} {sign}',
'future': '{num} {unit} {sign}',
'duration': '{num} {unit}',
'modifiers': [
{ 'name': 'day', 'src': 'yesterday', 'value': -1 },
{ 'name': 'day', 'src': 'today', 'value': 0 },
{ 'name': 'day', 'src': 'tomorrow', 'value': 1 },
{ 'name': 'sign', 'src': 'ago|before', 'value': -1 },
{ 'name': 'sign', 'src': 'from now|after|from|in|later', 'value': 1 },
{ 'name': 'edge', 'src': 'last day', 'value': -2 },
{ 'name': 'edge', 'src': 'end', 'value': -1 },
{ 'name': 'edge', 'src': 'first day|beginning', 'value': 1 },
{ 'name': 'shift', 'src': 'last', 'value': -1 },
{ 'name': 'shift', 'src': 'the|this', 'value': 0 },
{ 'name': 'shift', 'src': 'next', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{month} {year}',
'{shift} {unit=5-7}',
'{0?} {date}{1}',
'{0?} {edge} of {shift?} {unit=4-7?}{month?}{year?}'
],
'timeParse': [
'{0} {num}{1} {day} of {month} {year?}',
'{weekday?} {month} {date}{1?} {year?}',
'{date} {month} {year}',
'{date} {month}',
'{shift} {weekday}',
'{shift} week {weekday}',
'{weekday} {2?} {shift} week',
'{num} {unit=4-5} {sign} {day}',
'{0?} {date}{1} of {month}',
'{0?}{month?} {date?}{1?} of {shift} {unit=6-7}'
]
});
buildDateUnits();
buildDateMethods();
buildCoreInputFormats();
buildDateOutputShortcuts();
buildAsianDigits();
buildRelativeAliases();
buildUTCAliases();
setDateProperties();
/***
* @package DateRange
* @dependency date
* @description Date Ranges define a range of time. They can enumerate over specific points within that range, and be manipulated and compared.
*
***/
var DateRange = function(start, end) {
this.start = date.create(start);
this.end = date.create(end);
};
// 'toString' doesn't appear in a for..in loop in IE even though
// hasOwnProperty reports true, so extend() can't be used here.
// Also tried simply setting the prototype = {} up front for all
// methods but GCC very oddly started dropping properties in the
// object randomly (maybe because of the global scope?) hence
// the need for the split logic here.
DateRange.prototype.toString = function() {
/***
* @method toString()
* @returns String
* @short Returns a string representation of the DateRange.
* @example
*
* Date.range('2003', '2005').toString() -> January 1, 2003..January 1, 2005
*
***/
return this.isValid() ? this.start.full() + '..' + this.end.full() : 'Invalid DateRange';
};
extend(DateRange, true, false, {
/***
* @method isValid()
* @returns Boolean
* @short Returns true if the DateRange is valid, false otherwise.
* @example
*
* Date.range('2003', '2005').isValid() -> true
* Date.range('2005', '2003').isValid() -> false
*
***/
'isValid': function() {
return this.start < this.end;
},
/***
* @method duration()
* @returns Number
* @short Return the duration of the DateRange in milliseconds.
* @example
*
* Date.range('2003', '2005').duration() -> 94694400000
*
***/
'duration': function() {
return this.isValid() ? this.end.getTime() - this.start.getTime() : NaN;
},
/***
* @method contains(<d>)
* @returns Boolean
* @short Returns true if <d> is contained inside the DateRange. <d> may be a date or another DateRange.
* @example
*
* Date.range('2003', '2005').contains(Date.create('2004')) -> true
*
***/
'contains': function(obj) {
var self = this, arr = obj.start && obj.end ? [obj.start, obj.end] : [obj];
return arr.every(function(d) {
return d >= self.start && d <= self.end;
});
},
/***
* @method every(<increment>, [fn])
* @returns Array
* @short Iterates through the DateRange for every <increment>, calling [fn] if it is passed. Returns an array of each increment visited.
* @extra When <increment> is a number, increments will be to the exact millisecond. <increment> can also be a string in the format %{number} {unit}s%, in which case it will increment in the unit specified. Note that a discrepancy exists in the case of months, as %(2).months()% is an approximation. Stepping through the actual months by passing %"2 months"% is usually preferable in this case.
* @example
*
* Date.range('2003-01', '2003-03').every("2 months") -> [...]
*
***/
'every': function(increment, fn) {
var current = this.start.clone(), result = [], index = 0, params, isDay;
if(isString(increment)) {
current.advance(getDateParamsFromString(increment, 0), true);
params = getDateParamsFromString(increment);
isDay = increment.toLowerCase() === 'day';
} else {
params = { 'milliseconds': increment };
}
while(current <= this.end) {
result.push(current);
if(fn) fn(current, index);
if(isDay && callDateGet(current, 'Hours') === 23) {
// When DST traversal happens at 00:00 hours, the time is effectively
// pushed back to 23:00, meaning 1) 00:00 for that day does not exist,
// and 2) there is no difference between 23:00 and 00:00, as you are
// "jumping" around in time. Hours here will be reset before the date
// is advanced and the date will never in fact advance, so set the hours
// directly ahead to the next day to avoid this problem.
current = current.clone();
callDateSet(current, 'Hours', 48);
} else {
current = current.clone().advance(params, true);
}
index++;
}
return result;
},
/***
* @method union(<range>)
* @returns DateRange
* @short Returns a new DateRange with the earliest starting point as its start, and the latest ending point as its end. If the two ranges do not intersect this will effectively remove the "gap" between them.
* @example
*
* Date.range('2003=01', '2005-01').union(Date.range('2004-01', '2006-01')) -> Jan 1, 2003..Jan 1, 2006
*
***/
'union': function(range) {
return new DateRange(
this.start < range.start ? this.start : range.start,
this.end > range.end ? this.end : range.end
);
},
/***
* @method intersect(<range>)
* @returns DateRange
* @short Returns a new DateRange with the latest starting point as its start, and the earliest ending point as its end. If the two ranges do not intersect this will effectively produce an invalid range.
* @example
*
* Date.range('2003-01', '2005-01').intersect(Date.range('2004-01', '2006-01')) -> Jan 1, 2004..Jan 1, 2005
*
***/
'intersect': function(range) {
return new DateRange(
this.start > range.start ? this.start : range.start,
this.end < range.end ? this.end : range.end
);
}
});
/***
* @method each[Unit]([fn])
* @returns Date
* @short Increments through the date range for each [unit], calling [fn] if it is passed. Returns an array of each increment visited.
*
* @set
* eachMillisecond
* eachSecond
* eachMinute
* eachHour
* eachDay
* eachWeek
* eachMonth
* eachYear
*
* @example
*
* Date.range('2003-01', '2003-02').eachMonth() -> [...]
* Date.range('2003-01-15', '2003-01-16').eachDay() -> [...]
*
***/
extendSimilar(DateRange, true, false, 'Millisecond,Second,Minute,Hour,Day,Week,Month,Year', function(methods, name) {
methods['each' + name] = function(fn) { return this.every(name, fn); }
});
/***
* Date module
***/
extend(date, false, false, {
/***
* @method Date.range([start], [end])
* @returns DateRange
* @short Creates a new date range.
* @extra If either [start] or [end] are null, they will default to the current date.
*
***/
'range': function(start, end) {
return new DateRange(start, end);
}
});
/***
* @package Function
* @dependency core
* @description Lazy, throttled, and memoized functions, delayed functions and handling of timers, argument currying.
*
***/
function setDelay(fn, ms, after, scope, args) {
var index;
if(!fn.timers) fn.timers = [];
if(!isNumber(ms)) ms = 0;
fn.timers.push(setTimeout(function(){
fn.timers.splice(index, 1);
after.apply(scope, args || []);
}, ms));
index = fn.timers.length;
}
extend(Function, true, false, {
/***
* @method lazy([ms] = 1, [limit] = Infinity)
* @returns Function
* @short Creates a lazy function that, when called repeatedly, will queue execution and wait [ms] milliseconds to execute again.
* @extra Lazy functions will always execute as many times as they are called up to [limit], after which point subsequent calls will be ignored (if it is set to a finite number). Compare this to %throttle%, which will execute only once per [ms] milliseconds. %lazy% is useful when you need to be sure that every call to a function is executed, but in a non-blocking manner. Calling %cancel% on a lazy function will clear the entire queue. Note that [ms] can also be a fraction.
* @example
*
* (function() {
* // Executes immediately.
* }).lazy()();
* (3).times(function() {
* // Executes 3 times, with each execution 20ms later than the last.
* }.lazy(20));
* (100).times(function() {
* // Executes 50 times, with each execution 20ms later than the last.
* }.lazy(20, 50));
*
***/
'lazy': function(ms, limit) {
var fn = this, queue = [], lock = false, execute, rounded, perExecution;
ms = ms || 1;
limit = limit || Infinity;
rounded = ceil(ms);
perExecution = round(rounded / ms);
execute = function() {
if(lock || queue.length == 0) return;
var max = math.max(queue.length - perExecution, 0);
while(queue.length > max) {
// Getting uber-meta here...
Function.prototype.apply.apply(fn, queue.shift());
}
setDelay(lazy, rounded, function() {
lock = false;
execute();
});
lock = true;
}
function lazy() {
// The first call is immediate, so having 1 in the queue
// implies two calls have already taken place.
if(lock && queue.length > limit - 2) return;
queue.push([this, arguments]);
execute();
}
return lazy;
},
/***
* @method delay([ms] = 0, [arg1], ...)
* @returns Function
* @short Executes the function after <ms> milliseconds.
* @extra Returns a reference to itself. %delay% is also a way to execute non-blocking operations that will wait until the CPU is free. Delayed functions can be canceled using the %cancel% method. Can also curry arguments passed in after <ms>.
* @example
*
* (function(arg1) {
* // called 1s later
* }).delay(1000, 'arg1');
*
***/
'delay': function(ms) {
var fn = this;
var args = multiArgs(arguments).slice(1);
setDelay(fn, ms, fn, fn, args);
return fn;
},
/***
* @method throttle(<ms>)
* @returns Function
* @short Creates a "throttled" version of the function that will only be executed once per <ms> milliseconds.
* @extra This is functionally equivalent to calling %lazy% with a [limit] of %1%. %throttle% is appropriate when you want to make sure a function is only executed at most once for a given duration. Compare this to %lazy%, which will queue rapid calls and execute them later.
* @example
*
* (3).times(function() {
* // called only once. will wait 50ms until it responds again
* }.throttle(50));
*
***/
'throttle': function(ms) {
return this.lazy(ms, 1);
},
/***
* @method debounce(<ms>)
* @returns Function
* @short Creates a "debounced" function that postpones its execution until after <ms> milliseconds have passed.
* @extra This method is useful to execute a function after things have "settled down". A good example of this is when a user tabs quickly through form fields, execution of a heavy operation should happen after a few milliseconds when they have "settled" on a field.
* @example
*
* var fn = (function(arg1) {
* // called once 50ms later
* }).debounce(50); fn() fn() fn();
*
***/
'debounce': function(ms) {
var fn = this;
function debounced() {
debounced.cancel();
setDelay(debounced, ms, fn, this, arguments);
};
return debounced;
},
/***
* @method cancel()
* @returns Function
* @short Cancels a delayed function scheduled to be run.
* @extra %delay%, %lazy%, %throttle%, and %debounce% can all set delays.
* @example
*
* (function() {
* alert('hay'); // Never called
* }).delay(500).cancel();
*
***/
'cancel': function() {
if(isArray(this.timers)) {
while(this.timers.length > 0) {
clearTimeout(this.timers.shift());
}
}
return this;
},
/***
* @method after([num] = 1)
* @returns Function
* @short Creates a function that will execute after [num] calls.
* @extra %after% is useful for running a final callback after a series of asynchronous operations, when the order in which the operations will complete is unknown.
* @example
*
* var fn = (function() {
* // Will be executed once only
* }).after(3); fn(); fn(); fn();
*
***/
'after': function(num) {
var fn = this, counter = 0, storedArguments = [];
if(!isNumber(num)) {
num = 1;
} else if(num === 0) {
fn.call();
return fn;
}
return function() {
var ret;
storedArguments.push(multiArgs(arguments));
counter++;
if(counter == num) {
ret = fn.call(this, storedArguments);
counter = 0;
storedArguments = [];
return ret;
}
}
},
/***
* @method once()
* @returns Function
* @short Creates a function that will execute only once and store the result.
* @extra %once% is useful for creating functions that will cache the result of an expensive operation and use it on subsequent calls. Also it can be useful for creating initialization functions that only need to be run once.
* @example
*
* var fn = (function() {
* // Will be executed once only
* }).once(); fn(); fn(); fn();
*
***/
'once': function() {
var fn = this;
return function() {
return hasOwnProperty(fn, 'memo') ? fn['memo'] : fn['memo'] = fn.apply(this, arguments);
}
},
/***
* @method fill(<arg1>, <arg2>, ...)
* @returns Function
* @short Returns a new version of the function which when called will have some of its arguments pre-emptively filled in, also known as "currying".
* @extra Arguments passed to a "filled" function are generally appended to the curried arguments. However, if %undefined% is passed as any of the arguments to %fill%, it will be replaced, when the "filled" function is executed. This allows currying of arguments even when they occur toward the end of an argument list (the example demonstrates this much more clearly).
* @example
*
* var delayOneSecond = setTimeout.fill(undefined, 1000);
* delayOneSecond(function() {
* // Will be executed 1s later
* });
*
***/
'fill': function() {
var fn = this, curried = multiArgs(arguments);
return function() {
var args = multiArgs(arguments);
curried.forEach(function(arg, index) {
if(arg != null || index >= args.length) args.splice(index, 0, arg);
});
return fn.apply(this, args);
}
}
});
/***
* @package Number
* @dependency core
* @description Number formatting, rounding (with precision), and ranges. Aliases to Math methods.
*
***/
function abbreviateNumber(num, roundTo, str, mid, limit, bytes) {
var fixed = num.toFixed(20),
decimalPlace = fixed.search(/\./),
numeralPlace = fixed.search(/[1-9]/),
significant = decimalPlace - numeralPlace,
unit, i, divisor;
if(significant > 0) {
significant -= 1;
}
i = math.max(math.min((significant / 3).floor(), limit === false ? str.length : limit), -mid);
unit = str.charAt(i + mid - 1);
if(significant < -9) {
i = -3;
roundTo = significant.abs() - 9;
unit = str.slice(0,1);
}
divisor = bytes ? (2).pow(10 * i) : (10).pow(i * 3);
return (num / divisor).round(roundTo || 0).format() + unit.trim();
}
extend(number, false, false, {
/***
* @method Number.random([n1], [n2])
* @returns Number
* @short Returns a random integer between [n1] and [n2].
* @extra If only 1 number is passed, the other will be 0. If none are passed, the number will be either 0 or 1.
* @example
*
* Number.random(50, 100) -> ex. 85
* Number.random(50) -> ex. 27
* Number.random() -> ex. 0
*
***/
'random': function(n1, n2) {
var min, max;
if(arguments.length == 1) n2 = n1, n1 = 0;
min = math.min(n1 || 0, isUndefined(n2) ? 1 : n2);
max = math.max(n1 || 0, isUndefined(n2) ? 1 : n2) + 1;
return floor((math.random() * (max - min)) + min);
}
});
extend(number, true, false, {
/***
* @method log(<base> = Math.E)
* @returns Number
* @short Returns the logarithm of the number with base <base>, or natural logarithm of the number if <base> is undefined.
* @example
*
* (64).log(2) -> 6
* (9).log(3) -> 2
* (5).log() -> 1.6094379124341003
*
***/
'log': function(base) {
return math.log(this) / (base ? math.log(base) : 1);
},
/***
* @method abbr([precision] = 0)
* @returns String
* @short Returns an abbreviated form of the number.
* @extra [precision] will round to the given precision.
* @example
*
* (1000).abbr() -> "1k"
* (1000000).abbr() -> "1m"
* (1280).abbr(1) -> "1.3k"
*
***/
'abbr': function(precision) {
return abbreviateNumber(this, precision, 'kmbt', 0, 4);
},
/***
* @method metric([precision] = 0, [limit] = 1)
* @returns String
* @short Returns the number as a string in metric notation.
* @extra [precision] will round to the given precision. Both very large numbers and very small numbers are supported. [limit] is the upper limit for the units. The default is %1%, which is "kilo". If [limit] is %false%, the upper limit will be "exa". The lower limit is "nano", and cannot be changed.
* @example
*
* (1000).metric() -> "1k"
* (1000000).metric() -> "1,000k"
* (1000000).metric(0, false) -> "1M"
* (1249).metric(2) + 'g' -> "1.25kg"
* (0.025).metric() + 'm' -> "25mm"
*
***/
'metric': function(precision, limit) {
return abbreviateNumber(this, precision, 'nμm kMGTPE', 4, isUndefined(limit) ? 1 : limit);
},
/***
* @method bytes([precision] = 0, [limit] = 4)
* @returns String
* @short Returns an abbreviated form of the number, considered to be "Bytes".
* @extra [precision] will round to the given precision. [limit] is the upper limit for the units. The default is %4%, which is "terabytes" (TB). If [limit] is %false%, the upper limit will be "exa".
* @example
*
* (1000).bytes() -> "1kB"
* (1000).bytes(2) -> "0.98kB"
* ((10).pow(20)).bytes() -> "90,949,470TB"
* ((10).pow(20)).bytes(0, false) -> "87EB"
*
***/
'bytes': function(precision, limit) {
return abbreviateNumber(this, precision, 'kMGTPE', 0, isUndefined(limit) ? 4 : limit, true) + 'B';
},
/***
* @method isInteger()
* @returns Boolean
* @short Returns true if the number has no trailing decimal.
* @example
*
* (420).isInteger() -> true
* (4.5).isInteger() -> false
*
***/
'isInteger': function() {
return this % 1 == 0;
},
/***
* @method isOdd()
* @returns Boolean
* @short Returns true if the number is odd.
* @example
*
* (3).isOdd() -> true
* (18).isOdd() -> false
*
***/
'isOdd': function() {
return !isNaN(this) && !this.isMultipleOf(2);
},
/***
* @method isEven()
* @returns Boolean
* @short Returns true if the number is even.
* @example
*
* (6).isEven() -> true
* (17).isEven() -> false
*
***/
'isEven': function() {
return this.isMultipleOf(2);
},
/***
* @method isMultipleOf(<num>)
* @returns Boolean
* @short Returns true if the number is a multiple of <num>.
* @example
*
* (6).isMultipleOf(2) -> true
* (17).isMultipleOf(2) -> false
* (32).isMultipleOf(4) -> true
* (34).isMultipleOf(4) -> false
*
***/
'isMultipleOf': function(num) {
return this % num === 0;
},
/***
* @method format([place] = 0, [thousands] = ',', [decimal] = '.')
* @returns String
* @short Formats the number to a readable string.
* @extra If [place] is %undefined%, will automatically determine the place. [thousands] is the character used for the thousands separator. [decimal] is the character used for the decimal point.
* @example
*
* (56782).format() -> '56,782'
* (56782).format(2) -> '56,782.00'
* (4388.43).format(2, ' ') -> '4 388.43'
* (4388.43).format(2, '.', ',') -> '4.388,43'
*
***/
'format': function(place, thousands, decimal) {
var i, str, split, integer, fraction, result = '';
if(isUndefined(thousands)) {
thousands = ',';
}
if(isUndefined(decimal)) {
decimal = '.';
}
str = (isNumber(place) ? round(this, place || 0).toFixed(math.max(place, 0)) : this.toString()).replace(/^-/, '');
split = str.split('.');
integer = split[0];
fraction = split[1];
for(i = integer.length; i > 0; i -= 3) {
if(i < integer.length) {
result = thousands + result;
}
result = integer.slice(math.max(0, i - 3), i) + result;
}
if(fraction) {
result += decimal + repeatString((place || 0) - fraction.length, '0') + fraction;
}
return (this < 0 ? '-' : '') + result;
},
/***
* @method hex([pad] = 1)
* @returns String
* @short Converts the number to hexidecimal.
* @extra [pad] will pad the resulting string to that many places.
* @example
*
* (255).hex() -> 'ff';
* (255).hex(4) -> '00ff';
* (23654).hex() -> '5c66';
*
***/
'hex': function(pad) {
return this.pad(pad || 1, false, 16);
},
/***
* @method upto(<num>, [fn], [step] = 1)
* @returns Array
* @short Returns an array containing numbers from the number up to <num>.
* @extra Optionally calls [fn] callback for each number in that array. [step] allows multiples greater than 1.
* @example
*
* (2).upto(6) -> [2, 3, 4, 5, 6]
* (2).upto(6, function(n) {
* // This function is called 5 times receiving n as the value.
* });
* (2).upto(8, null, 2) -> [2, 4, 6, 8]
*
***/
'upto': function(num, fn, step) {
return getRange(this, num, fn, step || 1);
},
/***
* @method downto(<num>, [fn], [step] = 1)
* @returns Array
* @short Returns an array containing numbers from the number down to <num>.
* @extra Optionally calls [fn] callback for each number in that array. [step] allows multiples greater than 1.
* @example
*
* (8).downto(3) -> [8, 7, 6, 5, 4, 3]
* (8).downto(3, function(n) {
* // This function is called 6 times receiving n as the value.
* });
* (8).downto(2, null, 2) -> [8, 6, 4, 2]
*
***/
'downto': function(num, fn, step) {
return getRange(this, num, fn, -(step || 1));
},
/***
* @method times(<fn>)
* @returns Number
* @short Calls <fn> a number of times equivalent to the number.
* @example
*
* (8).times(function(i) {
* // This function is called 8 times.
* });
*
***/
'times': function(fn) {
if(fn) {
for(var i = 0; i < this; i++) {
fn.call(this, i);
}
}
return this.toNumber();
},
/***
* @method chr()
* @returns String
* @short Returns a string at the code point of the number.
* @example
*
* (65).chr() -> "A"
* (75).chr() -> "K"
*
***/
'chr': function() {
return string.fromCharCode(this);
},
/***
* @method pad(<place> = 0, [sign] = false, [base] = 10)
* @returns String
* @short Pads a number with "0" to <place>.
* @extra [sign] allows you to force the sign as well (+05, etc). [base] can change the base for numeral conversion.
* @example
*
* (5).pad(2) -> '05'
* (-5).pad(4) -> '-0005'
* (82).pad(3, true) -> '+082'
*
***/
'pad': function(place, sign, base) {
return padNumber(this, place, sign, base);
},
/***
* @method ordinalize()
* @returns String
* @short Returns an ordinalized (English) string, i.e. "1st", "2nd", etc.
* @example
*
* (1).ordinalize() -> '1st';
* (2).ordinalize() -> '2nd';
* (8).ordinalize() -> '8th';
*
***/
'ordinalize': function() {
var suffix, num = this.abs(), last = parseInt(num.toString().slice(-2));
return this + getOrdinalizedSuffix(last);
},
/***
* @method toNumber()
* @returns Number
* @short Returns a number. This is mostly for compatibility reasons.
* @example
*
* (420).toNumber() -> 420
*
***/
'toNumber': function() {
return parseFloat(this, 10);
}
});
/***
* @method round(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.round% that also allows a <precision>.
*
* @example
*
* (3.241).round() -> 3
* (-3.841).round() -> -4
* (3.241).round(2) -> 3.24
* (3748).round(-2) -> 3800
*
***
* @method ceil(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.ceil% that also allows a <precision>.
*
* @example
*
* (3.241).ceil() -> 4
* (-3.241).ceil() -> -3
* (3.241).ceil(2) -> 3.25
* (3748).ceil(-2) -> 3800
*
***
* @method floor(<precision> = 0)
* @returns Number
* @short Shortcut for %Math.floor% that also allows a <precision>.
*
* @example
*
* (3.241).floor() -> 3
* (-3.841).floor() -> -4
* (3.241).floor(2) -> 3.24
* (3748).floor(-2) -> 3700
*
***
* @method [math]()
* @returns Number
* @short Math related functions are mapped as shortcuts to numbers and are identical. Note that %Number#log% provides some special defaults.
*
* @set
* abs
* sin
* asin
* cos
* acos
* tan
* atan
* sqrt
* exp
* pow
*
* @example
*
* (3).pow(3) -> 27
* (-3).abs() -> 3
* (1024).sqrt() -> 32
*
***/
function buildNumber() {
extendSimilar(number, true, false, 'round,floor,ceil', function(methods, name) {
methods[name] = function(precision) {
return round(this, precision, name);
}
});
extendSimilar(number, true, false, 'abs,pow,sin,asin,cos,acos,tan,atan,exp,pow,sqrt', function(methods, name) {
methods[name] = function(a, b) {
return math[name](this, a, b);
}
});
}
buildNumber();
/***
* @package Object
* @dependency core
* @description Object manipulation, type checking (isNumber, isString, ...), extended objects with hash-like methods available as instance methods.
*
* Much thanks to kangax for his informative aricle about how problems with instanceof and constructor
* http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
*
***/
var ObjectTypeMethods = 'isObject,isNaN'.split(',');
var ObjectHashMethods = 'keys,values,each,merge,clone,equal,watch,tap,has'.split(',');
function setParamsObject(obj, param, value, deep) {
var reg = /^(.+?)(\[.*\])$/, paramIsArray, match, allKeys, key;
if(deep !== false && (match = param.match(reg))) {
key = match[1];
allKeys = match[2].replace(/^\[|\]$/g, '').split('][');
allKeys.forEach(function(k) {
paramIsArray = !k || k.match(/^\d+$/);
if(!key && isArray(obj)) key = obj.length;
if(!obj[key]) {
obj[key] = paramIsArray ? [] : {};
}
obj = obj[key];
key = k;
});
if(!key && paramIsArray) key = obj.length.toString();
setParamsObject(obj, key, value);
} else if(value.match(/^[+-]?\d+(\.\d+)?$/)) {
obj[param] = parseFloat(value);
} else if(value === 'true') {
obj[param] = true;
} else if(value === 'false') {
obj[param] = false;
} else {
obj[param] = value;
}
}
/***
* @method Object.is[Type](<obj>)
* @returns Boolean
* @short Returns true if <obj> is an object of that type.
* @extra %isObject% will return false on anything that is not an object literal, including instances of inherited classes. Note also that %isNaN% will ONLY return true if the object IS %NaN%. It does not mean the same as browser native %isNaN%, which returns true for anything that is "not a number".
*
* @set
* isArray
* isObject
* isBoolean
* isDate
* isFunction
* isNaN
* isNumber
* isString
* isRegExp
*
* @example
*
* Object.isArray([1,2,3]) -> true
* Object.isDate(3) -> false
* Object.isRegExp(/wasabi/) -> true
* Object.isObject({ broken:'wear' }) -> true
*
***/
function buildTypeMethods() {
extendSimilar(object, false, false, ClassNames, function(methods, name) {
var method = 'is' + name;
ObjectTypeMethods.push(method);
methods[method] = function(obj) {
return className(obj) === '[object '+name+']';
}
});
}
function buildObjectExtend() {
extend(object, false, function(){ return arguments.length === 0; }, {
'extend': function() {
buildObjectInstanceMethods(ObjectTypeMethods.concat(ObjectHashMethods), object);
}
});
}
extend(object, false, true, {
/***
* @method watch(<obj>, <prop>, <fn>)
* @returns Nothing
* @short Watches a property of <obj> and runs <fn> when it changes.
* @extra <fn> is passed three arguments: the property <prop>, the old value, and the new value. The return value of [fn] will be set as the new value. This method is useful for things such as validating or cleaning the value when it is set. Warning: this method WILL NOT work in browsers that don't support %Object.defineProperty%. This notably includes IE 8 and below, and Opera. This is the only method in Sugar that is not fully compatible with all browsers. %watch% is available as an instance method on extended objects.
* @example
*
* Object.watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) {
* // Will be run when the property 'foo' is set on the object.
* });
* Object.extended().watch({ foo: 'bar' }, 'foo', function(prop, oldVal, newVal) {
* // Will be run when the property 'foo' is set on the object.
* });
*
***/
'watch': function(obj, prop, fn) {
if(!definePropertySupport) return;
var value = obj[prop];
object.defineProperty(obj, prop, {
'enumerable' : true,
'configurable': true,
'get': function() {
return value;
},
'set': function(to) {
value = fn.call(obj, prop, value, to);
}
});
}
});
extend(object, false, function(arg1, arg2) { return isFunction(arg2); }, {
/***
* @method keys(<obj>, [fn])
* @returns Array
* @short Returns an array containing the keys in <obj>. Optionally calls [fn] for each key.
* @extra This method is provided for browsers that don't support it natively, and additionally is enhanced to accept the callback [fn]. Returned keys are in no particular order. %keys% is available as an instance method on extended objects.
* @example
*
* Object.keys({ broken: 'wear' }) -> ['broken']
* Object.keys({ broken: 'wear' }, function(key, value) {
* // Called once for each key.
* });
* Object.extended({ broken: 'wear' }).keys() -> ['broken']
*
***/
'keys': function(obj, fn) {
var keys = object.keys(obj);
keys.forEach(function(key) {
fn.call(obj, key, obj[key]);
});
return keys;
}
});
extend(object, false, false, {
'isObject': function(obj) {
return isObject(obj);
},
'isNaN': function(obj) {
// This is only true of NaN
return isNumber(obj) && obj.valueOf() !== obj.valueOf();
},
/***
* @method equal(<a>, <b>)
* @returns Boolean
* @short Returns true if <a> and <b> are equal.
* @extra %equal% in Sugar is "egal", meaning the values are equal if they are "not observably distinguishable". Note that on extended objects the name is %equals% for readability.
* @example
*
* Object.equal({a:2}, {a:2}) -> true
* Object.equal({a:2}, {a:3}) -> false
* Object.extended({a:2}).equals({a:3}) -> false
*
***/
'equal': function(a, b) {
return isEqual(a, b);
},
/***
* @method Object.extended(<obj> = {})
* @returns Extended object
* @short Creates a new object, equivalent to %new Object()% or %{}%, but with extended methods.
* @extra See extended objects for more.
* @example
*
* Object.extended()
* Object.extended({ happy:true, pappy:false }).keys() -> ['happy','pappy']
* Object.extended({ happy:true, pappy:false }).values() -> [true, false]
*
***/
'extended': function(obj) {
return new Hash(obj);
},
/***
* @method merge(<target>, <source>, [deep] = false, [resolve] = true)
* @returns Merged object
* @short Merges all the properties of <source> into <target>.
* @extra Merges are shallow unless [deep] is %true%. Properties of <source> will win in the case of conflicts, unless [resolve] is %false%. [resolve] can also be a function that resolves the conflict. In this case it will be passed 3 arguments, %key%, %targetVal%, and %sourceVal%, with the context set to <source>. This will allow you to solve conflict any way you want, ie. adding two numbers together, etc. %merge% is available as an instance method on extended objects.
* @example
*
* Object.merge({a:1},{b:2}) -> { a:1, b:2 }
* Object.merge({a:1},{a:2}, false, false) -> { a:1 }
+ Object.merge({a:1},{a:2}, false, function(key, a, b) {
* return a + b;
* }); -> { a:3 }
* Object.extended({a:1}).merge({b:2}) -> { a:1, b:2 }
*
***/
'merge': function(target, source, deep, resolve) {
var key, val;
// Strings cannot be reliably merged thanks to
// their properties not being enumerable in < IE8.
if(target && typeof source != 'string') {
for(key in source) {
if(!hasOwnProperty(source, key) || !target) continue;
val = source[key];
// Conflict!
if(isDefined(target[key])) {
// Do not merge.
if(resolve === false) {
continue;
}
// Use the result of the callback as the result.
if(isFunction(resolve)) {
val = resolve.call(source, key, target[key], source[key])
}
}
// Deep merging.
if(deep === true && val && isObjectPrimitive(val)) {
if(isDate(val)) {
val = new date(val.getTime());
} else if(isRegExp(val)) {
val = new regexp(val.source, getRegExpFlags(val));
} else {
if(!target[key]) target[key] = array.isArray(val) ? [] : {};
object.merge(target[key], source[key], deep, resolve);
continue;
}
}
target[key] = val;
}
}
return target;
},
/***
* @method values(<obj>, [fn])
* @returns Array
* @short Returns an array containing the values in <obj>. Optionally calls [fn] for each value.
* @extra Returned values are in no particular order. %values% is available as an instance method on extended objects.
* @example
*
* Object.values({ broken: 'wear' }) -> ['wear']
* Object.values({ broken: 'wear' }, function(value) {
* // Called once for each value.
* });
* Object.extended({ broken: 'wear' }).values() -> ['wear']
*
***/
'values': function(obj, fn) {
var values = [];
iterateOverObject(obj, function(k,v) {
values.push(v);
if(fn) fn.call(obj,v);
});
return values;
},
/***
* @method clone(<obj> = {}, [deep] = false)
* @returns Cloned object
* @short Creates a clone (copy) of <obj>.
* @extra Default is a shallow clone, unless [deep] is true. %clone% is available as an instance method on extended objects.
* @example
*
* Object.clone({foo:'bar'}) -> { foo: 'bar' }
* Object.clone() -> {}
* Object.extended({foo:'bar'}).clone() -> { foo: 'bar' }
*
***/
'clone': function(obj, deep) {
if(!isObjectPrimitive(obj)) return obj;
if(array.isArray(obj)) return obj.concat();
var target = obj instanceof Hash ? new Hash() : {};
return object.merge(target, obj, deep);
},
/***
* @method Object.fromQueryString(<str>, [deep] = true)
* @returns Object
* @short Converts the query string of a URL into an object.
* @extra If [deep] is %false%, conversion will only accept shallow params (ie. no object or arrays with %[]% syntax) as these are not universally supported.
* @example
*
* Object.fromQueryString('foo=bar&broken=wear') -> { foo: 'bar', broken: 'wear' }
* Object.fromQueryString('foo[]=1&foo[]=2') -> { foo: [1,2] }
*
***/
'fromQueryString': function(str, deep) {
var result = object.extended(), split;
str = str && str.toString ? str.toString() : '';
str.replace(/^.*?\?/, '').split('&').forEach(function(p) {
var split = p.split('=');
if(split.length !== 2) return;
setParamsObject(result, split[0], decodeURIComponent(split[1]), deep);
});
return result;
},
/***
* @method tap(<obj>, <fn>)
* @returns Object
* @short Runs <fn> and returns <obj>.
* @extra A string can also be used as a shortcut to a method. This method is used to run an intermediary function in the middle of method chaining. As a standalone method on the Object class it doesn't have too much use. The power of %tap% comes when using extended objects or modifying the Object prototype with Object.extend().
* @example
*
* Object.extend();
* [2,4,6].map(Math.exp).tap(function(arr) {
* arr.pop()
* });
* [2,4,6].map(Math.exp).tap('pop').map(Math.round); -> [7,55]
*
***/
'tap': function(obj, arg) {
var fn = arg;
if(!isFunction(arg)) {
fn = function() {
if(arg) obj[arg]();
}
}
fn.call(obj, obj);
return obj;
},
/***
* @method has(<obj>, <key>)
* @returns Boolean
* @short Checks if <obj> has <key> using hasOwnProperty from Object.prototype.
* @extra This method is considered safer than %Object#hasOwnProperty% when using objects as hashes. See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ for more.
* @example
*
* Object.has({ foo: 'bar' }, 'foo') -> true
* Object.has({ foo: 'bar' }, 'baz') -> false
* Object.has({ hasOwnProperty: true }, 'foo') -> false
*
***/
'has': function (obj, key) {
return hasOwnProperty(obj, key);
}
});
buildTypeMethods();
buildObjectExtend();
buildObjectInstanceMethods(ObjectHashMethods, Hash);
/***
* @package RegExp
* @dependency core
* @description Escaping regexes and manipulating their flags.
*
* Note here that methods on the RegExp class like .exec and .test will fail in the current version of SpiderMonkey being
* used by CouchDB when using shorthand regex notation like /foo/. This is the reason for the intermixed use of shorthand
* and compiled regexes here. If you're using JS in CouchDB, it is safer to ALWAYS compile your regexes from a string.
*
***/
function uniqueRegExpFlags(flags) {
return flags.split('').sort().join('').replace(/([gimy])\1+/g, '$1');
}
extend(regexp, false, false, {
/***
* @method RegExp.escape(<str> = '')
* @returns String
* @short Escapes all RegExp tokens in a string.
* @example
*
* RegExp.escape('really?') -> 'really\?'
* RegExp.escape('yes.') -> 'yes\.'
* RegExp.escape('(not really)') -> '\(not really\)'
*
***/
'escape': function(str) {
return escapeRegExp(str);
}
});
extend(regexp, true, false, {
/***
* @method getFlags()
* @returns String
* @short Returns the flags of the regex as a string.
* @example
*
* /texty/gim.getFlags('testy') -> 'gim'
*
***/
'getFlags': function() {
return getRegExpFlags(this);
},
/***
* @method setFlags(<flags>)
* @returns RegExp
* @short Sets the flags on a regex and retuns a copy.
* @example
*
* /texty/.setFlags('gim') -> now has global, ignoreCase, and multiline set
*
***/
'setFlags': function(flags) {
return regexp(this.source, flags);
},
/***
* @method addFlag(<flag>)
* @returns RegExp
* @short Adds <flag> to the regex.
* @example
*
* /texty/.addFlag('g') -> now has global flag set
*
***/
'addFlag': function(flag) {
return this.setFlags(getRegExpFlags(this, flag));
},
/***
* @method removeFlag(<flag>)
* @returns RegExp
* @short Removes <flag> from the regex.
* @example
*
* /texty/g.removeFlag('g') -> now has global flag removed
*
***/
'removeFlag': function(flag) {
return this.setFlags(getRegExpFlags(this).replace(flag, ''));
}
});
/***
* @package String
* @dependency core
* @description String manupulation, escaping, encoding, truncation, and:conversion.
*
***/
function getAcronym(word) {
var inflector = string.Inflector;
var word = inflector && inflector.acronyms[word];
if(isString(word)) {
return word;
}
}
function padString(str, p, left, right) {
var padding = string(p);
if(padding != p) {
padding = '';
}
if(!isNumber(left)) left = 1;
if(!isNumber(right)) right = 1;
return padding.repeat(left) + str + padding.repeat(right);
}
function chr(num) {
return string.fromCharCode(num);
}
var btoa, atob;
function buildBase64(key) {
if(this.btoa) {
btoa = this.btoa;
atob = this.atob;
return;
}
var base64reg = /[^A-Za-z0-9\+\/\=]/g;
btoa = function(str) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = str.charCodeAt(i++);
chr2 = str.charCodeAt(i++);
chr3 = str.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + key.charAt(enc1) + key.charAt(enc2) + key.charAt(enc3) + key.charAt(enc4);
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < str.length);
return output;
}
atob = function(input) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
if(input.match(base64reg)) {
throw new Error('String contains invalid base64 characters');
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
do {
enc1 = key.indexOf(input.charAt(i++));
enc2 = key.indexOf(input.charAt(i++));
enc3 = key.indexOf(input.charAt(i++));
enc4 = key.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + chr(chr1);
if (enc3 != 64) {
output = output + chr(chr2);
}
if (enc4 != 64) {
output = output + chr(chr3);
}
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < input.length);
return output;
}
}
extend(string, true, false, {
/***
* @method escapeRegExp()
* @returns String
* @short Escapes all RegExp tokens in the string.
* @example
*
* 'really?'.escapeRegExp() -> 'really\?'
* 'yes.'.escapeRegExp() -> 'yes\.'
* '(not really)'.escapeRegExp() -> '\(not really\)'
*
***/
'escapeRegExp': function() {
return escapeRegExp(this);
},
/***
* @method escapeURL([param] = false)
* @returns String
* @short Escapes characters in a string to make a valid URL.
* @extra If [param] is true, it will also escape valid URL characters for use as a URL parameter.
* @example
*
* 'http://foo.com/"bar"'.escapeURL() -> 'http://foo.com/%22bar%22'
* 'http://foo.com/"bar"'.escapeURL(true) -> 'http%3A%2F%2Ffoo.com%2F%22bar%22'
*
***/
'escapeURL': function(param) {
return param ? encodeURIComponent(this) : encodeURI(this);
},
/***
* @method unescapeURL([partial] = false)
* @returns String
* @short Restores escaped characters in a URL escaped string.
* @extra If [partial] is true, it will only unescape non-valid URL characters. [partial] is included here for completeness, but should very rarely be needed.
* @example
*
* 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL() -> 'http://foo.com/the bar'
* 'http%3A%2F%2Ffoo.com%2Fthe%20bar'.unescapeURL(true) -> 'http%3A%2F%2Ffoo.com%2Fthe bar'
*
***/
'unescapeURL': function(param) {
return param ? decodeURI(this) : decodeURIComponent(this);
},
/***
* @method escapeHTML()
* @returns String
* @short Converts HTML characters to their entity equivalents.
* @example
*
* '<p>some text</p>'.escapeHTML() -> '<p>some text</p>'
* 'one & two'.escapeHTML() -> 'one & two'
*
***/
'escapeHTML': function() {
return this.replace(/&/g, '&' )
.replace(/</g, '<' )
.replace(/>/g, '>' )
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/');
},
/***
* @method unescapeHTML([partial] = false)
* @returns String
* @short Restores escaped HTML characters.
* @example
*
* '<p>some text</p>'.unescapeHTML() -> '<p>some text</p>'
* 'one & two'.unescapeHTML() -> 'one & two'
*
***/
'unescapeHTML': function() {
return this.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(///g, '/');
},
/***
* @method encodeBase64()
* @returns String
* @short Encodes the string into base64 encoding.
* @extra This method wraps the browser native %btoa% when available, and uses a custom implementation when not available.
* @example
*
* 'gonna get encoded!'.encodeBase64() -> 'Z29ubmEgZ2V0IGVuY29kZWQh'
* 'http://twitter.com/'.encodeBase64() -> 'aHR0cDovL3R3aXR0ZXIuY29tLw=='
*
***/
'encodeBase64': function() {
return btoa(this);
},
/***
* @method decodeBase64()
* @returns String
* @short Decodes the string from base64 encoding.
* @extra This method wraps the browser native %atob% when available, and uses a custom implementation when not available.
* @example
*
* 'aHR0cDovL3R3aXR0ZXIuY29tLw=='.decodeBase64() -> 'http://twitter.com/'
* 'anVzdCBnb3QgZGVjb2RlZA=='.decodeBase64() -> 'just got decoded!'
*
***/
'decodeBase64': function() {
return atob(this);
},
/***
* @method each([search] = single character, [fn])
* @returns Array
* @short Runs callback [fn] against each occurence of [search].
* @extra Returns an array of matches. [search] may be either a string or regex, and defaults to every character in the string.
* @example
*
* 'jumpy'.each() -> ['j','u','m','p','y']
* 'jumpy'.each(/[r-z]/) -> ['u','y']
* 'jumpy'.each(/[r-z]/, function(m) {
* // Called twice: "u", "y"
* });
*
***/
'each': function(search, fn) {
var match, i;
if(isFunction(search)) {
fn = search;
search = /[\s\S]/g;
} else if(!search) {
search = /[\s\S]/g
} else if(isString(search)) {
search = regexp(escapeRegExp(search), 'gi');
} else if(isRegExp(search)) {
search = regexp(search.source, getRegExpFlags(search, 'g'));
}
match = this.match(search) || [];
if(fn) {
for(i = 0; i < match.length; i++) {
match[i] = fn.call(this, match[i], i, match) || match[i];
}
}
return match;
},
/***
* @method shift(<n>)
* @returns Array
* @short Shifts each character in the string <n> places in the character map.
* @example
*
* 'a'.shift(1) -> 'b'
* 'ク'.shift(1) -> 'グ'
*
***/
'shift': function(n) {
var result = '';
n = n || 0;
this.codes(function(c) {
result += chr(c + n);
});
return result;
},
/***
* @method codes([fn])
* @returns Array
* @short Runs callback [fn] against each character code in the string. Returns an array of character codes.
* @example
*
* 'jumpy'.codes() -> [106,117,109,112,121]
* 'jumpy'.codes(function(c) {
* // Called 5 times: 106, 117, 109, 112, 121
* });
*
***/
'codes': function(fn) {
var codes = [];
for(var i=0; i<this.length; i++) {
var code = this.charCodeAt(i);
codes.push(code);
if(fn) fn.call(this, code, i);
}
return codes;
},
/***
* @method chars([fn])
* @returns Array
* @short Runs callback [fn] against each character in the string. Returns an array of characters.
* @example
*
* 'jumpy'.chars() -> ['j','u','m','p','y']
* 'jumpy'.chars(function(c) {
* // Called 5 times: "j","u","m","p","y"
* });
*
***/
'chars': function(fn) {
return this.each(fn);
},
/***
* @method words([fn])
* @returns Array
* @short Runs callback [fn] against each word in the string. Returns an array of words.
* @extra A "word" here is defined as any sequence of non-whitespace characters.
* @example
*
* 'broken wear'.words() -> ['broken','wear']
* 'broken wear'.words(function(w) {
* // Called twice: "broken", "wear"
* });
*
***/
'words': function(fn) {
return this.trim().each(/\S+/g, fn);
},
/***
* @method lines([fn])
* @returns Array
* @short Runs callback [fn] against each line in the string. Returns an array of lines.
* @example
*
* 'broken wear\nand\njumpy jump'.lines() -> ['broken wear','and','jumpy jump']
* 'broken wear\nand\njumpy jump'.lines(function(l) {
* // Called three times: "broken wear", "and", "jumpy jump"
* });
*
***/
'lines': function(fn) {
return this.trim().each(/^.*$/gm, fn);
},
/***
* @method paragraphs([fn])
* @returns Array
* @short Runs callback [fn] against each paragraph in the string. Returns an array of paragraphs.
* @extra A paragraph here is defined as a block of text bounded by two or more line breaks.
* @example
*
* 'Once upon a time.\n\nIn the land of oz...'.paragraphs() -> ['Once upon a time.','In the land of oz...']
* 'Once upon a time.\n\nIn the land of oz...'.paragraphs(function(p) {
* // Called twice: "Once upon a time.", "In teh land of oz..."
* });
*
***/
'paragraphs': function(fn) {
var paragraphs = this.trim().split(/[\r\n]{2,}/);
paragraphs = paragraphs.map(function(p) {
if(fn) var s = fn.call(p);
return s ? s : p;
});
return paragraphs;
},
/***
* @method startsWith(<find>, [case] = true)
* @returns Boolean
* @short Returns true if the string starts with <find>.
* @extra <find> may be either a string or regex. Case sensitive if [case] is true.
* @example
*
* 'hello'.startsWith('hell') -> true
* 'hello'.startsWith(/[a-h]/) -> true
* 'hello'.startsWith('HELL') -> false
* 'hello'.startsWith('HELL', false) -> true
*
***/
'startsWith': function(reg, c) {
if(isUndefined(c)) c = true;
var source = isRegExp(reg) ? reg.source.replace('^', '') : escapeRegExp(reg);
return regexp('^' + source, c ? '' : 'i').test(this);
},
/***
* @method endsWith(<find>, [case] = true)
* @returns Boolean
* @short Returns true if the string ends with <find>.
* @extra <find> may be either a string or regex. Case sensitive if [case] is true.
* @example
*
* 'jumpy'.endsWith('py') -> true
* 'jumpy'.endsWith(/[q-z]/) -> true
* 'jumpy'.endsWith('MPY') -> false
* 'jumpy'.endsWith('MPY', false) -> true
*
***/
'endsWith': function(reg, c) {
if(isUndefined(c)) c = true;
var source = isRegExp(reg) ? reg.source.replace('$', '') : escapeRegExp(reg);
return regexp(source + '$', c ? '' : 'i').test(this);
},
/***
* @method isBlank()
* @returns Boolean
* @short Returns true if the string has a length of 0 or contains only whitespace.
* @example
*
* ''.isBlank() -> true
* ' '.isBlank() -> true
* 'noway'.isBlank() -> false
*
***/
'isBlank': function() {
return this.trim().length === 0;
},
/***
* @method has(<find>)
* @returns Boolean
* @short Returns true if the string matches <find>.
* @extra <find> may be a string or regex.
* @example
*
* 'jumpy'.has('py') -> true
* 'broken'.has(/[a-n]/) -> true
* 'broken'.has(/[s-z]/) -> false
*
***/
'has': function(find) {
return this.search(isRegExp(find) ? find : escapeRegExp(find)) !== -1;
},
/***
* @method add(<str>, [index] = length)
* @returns String
* @short Adds <str> at [index]. Negative values are also allowed.
* @extra %insert% is provided as an alias, and is generally more readable when using an index.
* @example
*
* 'schfifty'.add(' five') -> schfifty five
* 'dopamine'.insert('e', 3) -> dopeamine
* 'spelling eror'.insert('r', -3) -> spelling error
*
***/
'add': function(str, index) {
index = isUndefined(index) ? this.length : index;
return this.slice(0, index) + str + this.slice(index);
},
/***
* @method remove(<f>)
* @returns String
* @short Removes any part of the string that matches <f>.
* @extra <f> can be a string or a regex.
* @example
*
* 'schfifty five'.remove('f') -> 'schity ive'
* 'schfifty five'.remove(/[a-f]/g) -> 'shity iv'
*
***/
'remove': function(f) {
return this.replace(f, '');
},
/***
* @method reverse()
* @returns String
* @short Reverses the string.
* @example
*
* 'jumpy'.reverse() -> 'ypmuj'
* 'lucky charms'.reverse() -> 'smrahc ykcul'
*
***/
'reverse': function() {
return this.split('').reverse().join('');
},
/***
* @method compact()
* @returns String
* @short Compacts all white space in the string to a single space and trims the ends.
* @example
*
* 'too \n much \n space'.compact() -> 'too much space'
* 'enough \n '.compact() -> 'enought'
*
***/
'compact': function() {
return this.trim().replace(/([\r\n\s ])+/g, function(match, whitespace){
return whitespace === ' ' ? whitespace : ' ';
});
},
/***
* @method at(<index>, [loop] = true)
* @returns String or Array
* @short Gets the character(s) at a given index.
* @extra When [loop] is true, overshooting the end of the string (or the beginning) will begin counting from the other end. As an alternate syntax, passing multiple indexes will get the characters at those indexes.
* @example
*
* 'jumpy'.at(0) -> 'j'
* 'jumpy'.at(2) -> 'm'
* 'jumpy'.at(5) -> 'j'
* 'jumpy'.at(5, false) -> ''
* 'jumpy'.at(-1) -> 'y'
* 'lucky charms'.at(2,4,6,8) -> ['u','k','y',c']
*
***/
'at': function() {
return entryAtIndex(this, arguments, true);
},
/***
* @method from([index] = 0)
* @returns String
* @short Returns a section of the string starting from [index].
* @example
*
* 'lucky charms'.from() -> 'lucky charms'
* 'lucky charms'.from(7) -> 'harms'
*
***/
'from': function(num) {
return this.slice(num);
},
/***
* @method to([index] = end)
* @returns String
* @short Returns a section of the string ending at [index].
* @example
*
* 'lucky charms'.to() -> 'lucky charms'
* 'lucky charms'.to(7) -> 'lucky ch'
*
***/
'to': function(num) {
if(isUndefined(num)) num = this.length;
return this.slice(0, num);
},
/***
* @method dasherize()
* @returns String
* @short Converts underscores and camel casing to hypens.
* @example
*
* 'a_farewell_to_arms'.dasherize() -> 'a-farewell-to-arms'
* 'capsLock'.dasherize() -> 'caps-lock'
*
***/
'dasherize': function() {
return this.underscore().replace(/_/g, '-');
},
/***
* @method underscore()
* @returns String
* @short Converts hyphens and camel casing to underscores.
* @example
*
* 'a-farewell-to-arms'.underscore() -> 'a_farewell_to_arms'
* 'capsLock'.underscore() -> 'caps_lock'
*
***/
'underscore': function() {
return this
.replace(/[-\s]+/g, '_')
.replace(string.Inflector && string.Inflector.acronymRegExp, function(acronym, index) {
return (index > 0 ? '_' : '') + acronym.toLowerCase();
})
.replace(/([A-Z\d]+)([A-Z][a-z])/g,'$1_$2')
.replace(/([a-z\d])([A-Z])/g,'$1_$2')
.toLowerCase();
},
/***
* @method camelize([first] = true)
* @returns String
* @short Converts underscores and hyphens to camel case. If [first] is true the first letter will also be capitalized.
* @extra If the Inflections package is included acryonyms can also be defined that will be used when camelizing.
* @example
*
* 'caps_lock'.camelize() -> 'CapsLock'
* 'moz-border-radius'.camelize() -> 'MozBorderRadius'
* 'moz-border-radius'.camelize(false) -> 'mozBorderRadius'
*
***/
'camelize': function(first) {
return this.underscore().replace(/(^|_)([^_]+)/g, function(match, pre, word, index) {
var acronym = getAcronym(word), capitalize = first !== false || index > 0;
if(acronym) return capitalize ? acronym : acronym.toLowerCase();
return capitalize ? word.capitalize() : word;
});
},
/***
* @method spacify()
* @returns String
* @short Converts camel case, underscores, and hyphens to a properly spaced string.
* @example
*
* 'camelCase'.spacify() -> 'camel case'
* 'an-ugly-string'.spacify() -> 'an ugly string'
* 'oh-no_youDid-not'.spacify().capitalize(true) -> 'something else'
*
***/
'spacify': function() {
return this.underscore().replace(/_/g, ' ');
},
/***
* @method stripTags([tag1], [tag2], ...)
* @returns String
* @short Strips all HTML tags from the string.
* @extra Tags to strip may be enumerated in the parameters, otherwise will strip all.
* @example
*
* '<p>just <b>some</b> text</p>'.stripTags() -> 'just some text'
* '<p>just <b>some</b> text</p>'.stripTags('p') -> 'just <b>some</b> text'
*
***/
'stripTags': function() {
var str = this, args = arguments.length > 0 ? arguments : [''];
multiArgs(args, function(tag) {
str = str.replace(regexp('<\/?' + escapeRegExp(tag) + '[^<>]*>', 'gi'), '');
});
return str;
},
/***
* @method removeTags([tag1], [tag2], ...)
* @returns String
* @short Removes all HTML tags and their contents from the string.
* @extra Tags to remove may be enumerated in the parameters, otherwise will remove all.
* @example
*
* '<p>just <b>some</b> text</p>'.removeTags() -> ''
* '<p>just <b>some</b> text</p>'.removeTags('b') -> '<p>just text</p>'
*
***/
'removeTags': function() {
var str = this, args = arguments.length > 0 ? arguments : ['\\S+'];
multiArgs(args, function(t) {
var reg = regexp('<(' + t + ')[^<>]*(?:\\/>|>.*?<\\/\\1>)', 'gi');
str = str.replace(reg, '');
});
return str;
},
/***
* @method truncate(<length>, [split] = true, [from] = 'right', [ellipsis] = '...')
* @returns Object
* @short Truncates a string.
* @extra If [split] is %false%, will not split words up, and instead discard the word where the truncation occurred. [from] can also be %"middle"% or %"left"%.
* @example
*
* 'just sittin on the dock of the bay'.truncate(20) -> 'just sittin on the do...'
* 'just sittin on the dock of the bay'.truncate(20, false) -> 'just sittin on the...'
* 'just sittin on the dock of the bay'.truncate(20, true, 'middle') -> 'just sitt...of the bay'
* 'just sittin on the dock of the bay'.truncate(20, true, 'left') -> '...the dock of the bay'
*
***/
'truncate': function(length, split, from, ellipsis) {
var pos,
prepend = '',
append = '',
str = this.toString(),
chars = '[' + getTrimmableCharacters() + ']+',
space = '[^' + getTrimmableCharacters() + ']*',
reg = regexp(chars + space + '$');
ellipsis = isUndefined(ellipsis) ? '...' : string(ellipsis);
if(str.length <= length) {
return str;
}
switch(from) {
case 'left':
pos = str.length - length;
prepend = ellipsis;
str = str.slice(pos);
reg = regexp('^' + space + chars);
break;
case 'middle':
pos = floor(length / 2);
append = ellipsis + str.slice(str.length - pos).trimLeft();
str = str.slice(0, pos);
break;
default:
pos = length;
append = ellipsis;
str = str.slice(0, pos);
}
if(split === false && this.slice(pos, pos + 1).match(/\S/)) {
str = str.remove(reg);
}
return prepend + str + append;
},
/***
* @method pad[Side](<padding> = '', [num] = 1)
* @returns String
* @short Pads either/both sides of the string.
* @extra [num] is the number of characters on each side, and [padding] is the character to pad with.
*
* @set
* pad
* padLeft
* padRight
*
* @example
*
* 'wasabi'.pad('-') -> '-wasabi-'
* 'wasabi'.pad('-', 2) -> '--wasabi--'
* 'wasabi'.padLeft('-', 2) -> '--wasabi'
* 'wasabi'.padRight('-', 2) -> 'wasabi--'
*
***/
'pad': function(padding, num) {
return repeatString(num, padding) + this + repeatString(num, padding);
},
'padLeft': function(padding, num) {
return repeatString(num, padding) + this;
},
'padRight': function(padding, num) {
return this + repeatString(num, padding);
},
/***
* @method first([n] = 1)
* @returns String
* @short Returns the first [n] characters of the string.
* @example
*
* 'lucky charms'.first() -> 'l'
* 'lucky charms'.first(3) -> 'luc'
*
***/
'first': function(num) {
if(isUndefined(num)) num = 1;
return this.substr(0, num);
},
/***
* @method last([n] = 1)
* @returns String
* @short Returns the last [n] characters of the string.
* @example
*
* 'lucky charms'.last() -> 's'
* 'lucky charms'.last(3) -> 'rms'
*
***/
'last': function(num) {
if(isUndefined(num)) num = 1;
var start = this.length - num < 0 ? 0 : this.length - num;
return this.substr(start);
},
/***
* @method repeat([num] = 0)
* @returns String
* @short Returns the string repeated [num] times.
* @example
*
* 'jumpy'.repeat(2) -> 'jumpyjumpy'
* 'a'.repeat(5) -> 'aaaaa'
* 'a'.repeat(0) -> ''
*
***/
'repeat': function(num) {
var result = '', str = this;
if(!isNumber(num) || num < 1) return '';
while (num) {
if (num & 1) {
result += str;
}
if (num >>= 1) {
str += str;
}
}
return result;
},
/***
* @method toNumber([base] = 10)
* @returns Number
* @short Converts the string into a number.
* @extra Any value with a "." fill be converted to a floating point value, otherwise an integer.
* @example
*
* '153'.toNumber() -> 153
* '12,000'.toNumber() -> 12000
* '10px'.toNumber() -> 10
* 'ff'.toNumber(16) -> 255
*
***/
'toNumber': function(base) {
var str = this.replace(/,/g, '');
return str.match(/\./) ? parseFloat(str) : parseInt(str, base || 10);
},
/***
* @method capitalize([all] = false)
* @returns String
* @short Capitalizes the first character in the string.
* @extra If [all] is true, all words in the string will be capitalized.
* @example
*
* 'hello'.capitalize() -> 'Hello'
* 'hello kitty'.capitalize() -> 'Hello kitty'
* 'hello kitty'.capitalize(true) -> 'Hello Kitty'
*
*
***/
'capitalize': function(all) {
var lastResponded;
return this.toLowerCase().replace(all ? /[\s\S]/g : /^\S/, function(lower) {
var upper = lower.toUpperCase(), result;
result = lastResponded ? lower : upper;
lastResponded = upper !== lower;
return result;
});
},
/***
* @method assign(<obj1>, <obj2>, ...)
* @returns String
* @short Assigns variables to tokens in a string.
* @extra If an object is passed, it's properties can be assigned using the object's keys. If a non-object (string, number, etc.) is passed it can be accessed by the argument number beginning with 1 (as with regex tokens). Multiple objects can be passed and will be merged together (original objects are unaffected).
* @example
*
* 'Welcome, Mr. {name}.'.assign({ name: 'Franklin' }) -> 'Welcome, Mr. Franklin.'
* 'You are {1} years old today.'.assign(14) -> 'You are 14 years old today.'
* '{n} and {r}'.assign({ n: 'Cheech' }, { r: 'Chong' }) -> 'Cheech and Chong'
*
***/
'assign': function() {
var assign = {};
multiArgs(arguments, function(a, i) {
if(isObject(a)) {
simpleMerge(assign, a);
} else {
assign[i + 1] = a;
}
});
return this.replace(/\{([^{]+?)\}/g, function(m, key) {
return hasOwnProperty(assign, key) ? assign[key] : m;
});
},
/***
* @method namespace([init] = global)
* @returns Mixed
* @short Finds the namespace or property indicated by the string.
* @extra [init] can be passed to provide a starting context, otherwise the global context will be used. If any level returns a falsy value, that will be the final result.
* @example
*
* 'Path.To.Namespace'.namespace() -> Path.To.Namespace
* '$.fn'.namespace() -> $.fn
*
***/
'namespace': function(context) {
context = context || globalContext;
iterateOverObject(this.split('.'), function(i,s) {
return !!(context = context[s]);
});
return context;
}
});
// Aliases
extend(string, true, false, {
/***
* @method insert()
* @alias add
*
***/
'insert': string.prototype.add
});
buildBase64('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=');
/***
*
* @package Inflections
* @dependency string
* @description Pluralization similar to ActiveSupport including uncountable words and acronyms. Humanized and URL-friendly strings.
*
***/
/***
* String module
*
***/
var plurals = [],
singulars = [],
uncountables = [],
humans = [],
acronyms = {},
Downcased,
Inflector;
function removeFromArray(arr, find) {
var index = arr.indexOf(find);
if(index > -1) {
arr.splice(index, 1);
}
}
function removeFromUncountablesAndAddTo(arr, rule, replacement) {
if(isString(rule)) {
removeFromArray(uncountables, rule);
}
removeFromArray(uncountables, replacement);
arr.unshift({ rule: rule, replacement: replacement })
}
function paramMatchesType(param, type) {
return param == type || param == 'all' || !param;
}
function isUncountable(word) {
return uncountables.some(function(uncountable) {
return new regexp('\\b' + uncountable + '$', 'i').test(word);
});
}
function inflect(word, pluralize) {
word = isString(word) ? word.toString() : '';
if(word.isBlank() || isUncountable(word)) {
return word;
} else {
return runReplacements(word, pluralize ? plurals : singulars);
}
}
function runReplacements(word, table) {
iterateOverObject(table, function(i, inflection) {
if(word.match(inflection.rule)) {
word = word.replace(inflection.rule, inflection.replacement);
return false;
}
});
return word;
}
function capitalize(word) {
return word.replace(/^\W*[a-z]/, function(w){
return w.toUpperCase();
});
}
Inflector = {
/*
* Specifies a new acronym. An acronym must be specified as it will appear in a camelized string. An underscore
* string that contains the acronym will retain the acronym when passed to %camelize%, %humanize%, or %titleize%.
* A camelized string that contains the acronym will maintain the acronym when titleized or humanized, and will
* convert the acronym into a non-delimited single lowercase word when passed to String#underscore.
*
* Examples:
* String.Inflector.acronym('HTML')
* 'html'.titleize() -> 'HTML'
* 'html'.camelize() -> 'HTML'
* 'MyHTML'.underscore() -> 'my_html'
*
* The acronym, however, must occur as a delimited unit and not be part of another word for conversions to recognize it:
*
* String.Inflector.acronym('HTTP')
* 'my_http_delimited'.camelize() -> 'MyHTTPDelimited'
* 'https'.camelize() -> 'Https', not 'HTTPs'
* 'HTTPS'.underscore() -> 'http_s', not 'https'
*
* String.Inflector.acronym('HTTPS')
* 'https'.camelize() -> 'HTTPS'
* 'HTTPS'.underscore() -> 'https'
*
* Note: Acronyms that are passed to %pluralize% will no longer be recognized, since the acronym will not occur as
* a delimited unit in the pluralized result. To work around this, you must specify the pluralized form as an
* acronym as well:
*
* String.Inflector.acronym('API')
* 'api'.pluralize().camelize() -> 'Apis'
*
* String.Inflector.acronym('APIs')
* 'api'.pluralize().camelize() -> 'APIs'
*
* %acronym% may be used to specify any word that contains an acronym or otherwise needs to maintain a non-standard
* capitalization. The only restriction is that the word must begin with a capital letter.
*
* Examples:
* String.Inflector.acronym('RESTful')
* 'RESTful'.underscore() -> 'restful'
* 'RESTfulController'.underscore() -> 'restful_controller'
* 'RESTfulController'.titleize() -> 'RESTful Controller'
* 'restful'.camelize() -> 'RESTful'
* 'restful_controller'.camelize() -> 'RESTfulController'
*
* String.Inflector.acronym('McDonald')
* 'McDonald'.underscore() -> 'mcdonald'
* 'mcdonald'.camelize() -> 'McDonald'
*/
'acronym': function(word) {
acronyms[word.toLowerCase()] = word;
var all = object.keys(acronyms).map(function(key) {
return acronyms[key];
});
Inflector.acronymRegExp = regexp(all.join('|'), 'g');
},
/*
* Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression.
* The replacement should always be a string that may include references to the matched data from the rule.
*/
'plural': function(rule, replacement) {
removeFromUncountablesAndAddTo(plurals, rule, replacement);
},
/*
* Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression.
* The replacement should always be a string that may include references to the matched data from the rule.
*/
'singular': function(rule, replacement) {
removeFromUncountablesAndAddTo(singulars, rule, replacement);
},
/*
* Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used
* for strings, not regular expressions. You simply pass the irregular in singular and plural form.
*
* Examples:
* String.Inflector.irregular('octopus', 'octopi')
* String.Inflector.irregular('person', 'people')
*/
'irregular': function(singular, plural) {
var singularFirst = singular.first(),
singularRest = singular.from(1),
pluralFirst = plural.first(),
pluralRest = plural.from(1),
pluralFirstUpper = pluralFirst.toUpperCase(),
pluralFirstLower = pluralFirst.toLowerCase(),
singularFirstUpper = singularFirst.toUpperCase(),
singularFirstLower = singularFirst.toLowerCase();
removeFromArray(uncountables, singular);
removeFromArray(uncountables, plural);
if(singularFirstUpper == pluralFirstUpper) {
Inflector.plural(new regexp('({1}){2}$'.assign(singularFirst, singularRest), 'i'), '$1' + pluralRest);
Inflector.plural(new regexp('({1}){2}$'.assign(pluralFirst, pluralRest), 'i'), '$1' + pluralRest);
Inflector.singular(new regexp('({1}){2}$'.assign(pluralFirst, pluralRest), 'i'), '$1' + singularRest);
} else {
Inflector.plural(new regexp('{1}{2}$'.assign(singularFirstUpper, singularRest)), pluralFirstUpper + pluralRest);
Inflector.plural(new regexp('{1}{2}$'.assign(singularFirstLower, singularRest)), pluralFirstLower + pluralRest);
Inflector.plural(new regexp('{1}{2}$'.assign(pluralFirstUpper, pluralRest)), pluralFirstUpper + pluralRest);
Inflector.plural(new regexp('{1}{2}$'.assign(pluralFirstLower, pluralRest)), pluralFirstLower + pluralRest);
Inflector.singular(new regexp('{1}{2}$'.assign(pluralFirstUpper, pluralRest)), singularFirstUpper + singularRest);
Inflector.singular(new regexp('{1}{2}$'.assign(pluralFirstLower, pluralRest)), singularFirstLower + singularRest);
}
},
/*
* Add uncountable words that shouldn't be attempted inflected.
*
* Examples:
* String.Inflector.uncountable('money')
* String.Inflector.uncountable('money', 'information')
* String.Inflector.uncountable(['money', 'information', 'rice'])
*/
'uncountable': function(first) {
var add = array.isArray(first) ? first : multiArgs(arguments);
uncountables = uncountables.concat(add);
},
/*
* Specifies a humanized form of a string by a regular expression rule or by a string mapping.
* When using a regular expression based replacement, the normal humanize formatting is called after the replacement.
* When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name')
*
* Examples:
* String.Inflector.human(/_cnt$/i, '_count')
* String.Inflector.human('legacy_col_person_name', 'Name')
*/
'human': function(rule, replacement) {
humans.unshift({ rule: rule, replacement: replacement })
},
/*
* Clears the loaded inflections within a given scope (default is 'all').
* Options are: 'all', 'plurals', 'singulars', 'uncountables', 'humans'.
*
* Examples:
* String.Inflector.clear('all')
* String.Inflector.clear('plurals')
*/
'clear': function(type) {
if(paramMatchesType(type, 'singulars')) singulars = [];
if(paramMatchesType(type, 'plurals')) plurals = [];
if(paramMatchesType(type, 'uncountables')) uncountables = [];
if(paramMatchesType(type, 'humans')) humans = [];
if(paramMatchesType(type, 'acronyms')) acronyms = {};
}
};
Downcased = [
'and', 'or', 'nor', 'a', 'an', 'the', 'so', 'but', 'to', 'of', 'at',
'by', 'from', 'into', 'on', 'onto', 'off', 'out', 'in', 'over',
'with', 'for'
];
Inflector.plural(/$/, 's');
Inflector.plural(/s$/gi, 's');
Inflector.plural(/(ax|test)is$/gi, '$1es');
Inflector.plural(/(octop|vir|fung|foc|radi|alumn)(i|us)$/gi, '$1i');
Inflector.plural(/(census|alias|status)$/gi, '$1es');
Inflector.plural(/(bu)s$/gi, '$1ses');
Inflector.plural(/(buffal|tomat)o$/gi, '$1oes');
Inflector.plural(/([ti])um$/gi, '$1a');
Inflector.plural(/([ti])a$/gi, '$1a');
Inflector.plural(/sis$/gi, 'ses');
Inflector.plural(/f+e?$/gi, 'ves');
Inflector.plural(/(cuff|roof)$/gi, '$1s');
Inflector.plural(/([ht]ive)$/gi, '$1s');
Inflector.plural(/([^aeiouy]o)$/gi, '$1es');
Inflector.plural(/([^aeiouy]|qu)y$/gi, '$1ies');
Inflector.plural(/(x|ch|ss|sh)$/gi, '$1es');
Inflector.plural(/(matr|vert|ind)(?:ix|ex)$/gi, '$1ices');
Inflector.plural(/([ml])ouse$/gi, '$1ice');
Inflector.plural(/([ml])ice$/gi, '$1ice');
Inflector.plural(/^(ox)$/gi, '$1en');
Inflector.plural(/^(oxen)$/gi, '$1');
Inflector.plural(/(quiz)$/gi, '$1zes');
Inflector.plural(/(phot|cant|hom|zer|pian|portic|pr|quart|kimon)o$/gi, '$1os');
Inflector.plural(/(craft)$/gi, '$1');
Inflector.plural(/([ft])[eo]{2}(th?)$/gi, '$1ee$2');
Inflector.singular(/s$/gi, '');
Inflector.singular(/([pst][aiu]s)$/gi, '$1');
Inflector.singular(/([aeiouy])ss$/gi, '$1ss');
Inflector.singular(/(n)ews$/gi, '$1ews');
Inflector.singular(/([ti])a$/gi, '$1um');
Inflector.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/gi, '$1$2sis');
Inflector.singular(/(^analy)ses$/gi, '$1sis');
Inflector.singular(/(i)(f|ves)$/i, '$1fe');
Inflector.singular(/([aeolr]f?)(f|ves)$/i, '$1f');
Inflector.singular(/([ht]ive)s$/gi, '$1');
Inflector.singular(/([^aeiouy]|qu)ies$/gi, '$1y');
Inflector.singular(/(s)eries$/gi, '$1eries');
Inflector.singular(/(m)ovies$/gi, '$1ovie');
Inflector.singular(/(x|ch|ss|sh)es$/gi, '$1');
Inflector.singular(/([ml])(ous|ic)e$/gi, '$1ouse');
Inflector.singular(/(bus)(es)?$/gi, '$1');
Inflector.singular(/(o)es$/gi, '$1');
Inflector.singular(/(shoe)s?$/gi, '$1');
Inflector.singular(/(cris|ax|test)[ie]s$/gi, '$1is');
Inflector.singular(/(octop|vir|fung|foc|radi|alumn)(i|us)$/gi, '$1us');
Inflector.singular(/(census|alias|status)(es)?$/gi, '$1');
Inflector.singular(/^(ox)(en)?/gi, '$1');
Inflector.singular(/(vert|ind)(ex|ices)$/gi, '$1ex');
Inflector.singular(/(matr)(ix|ices)$/gi, '$1ix');
Inflector.singular(/(quiz)(zes)?$/gi, '$1');
Inflector.singular(/(database)s?$/gi, '$1');
Inflector.singular(/ee(th?)$/gi, 'oo$1');
Inflector.irregular('person', 'people');
Inflector.irregular('man', 'men');
Inflector.irregular('child', 'children');
Inflector.irregular('sex', 'sexes');
Inflector.irregular('move', 'moves');
Inflector.irregular('save', 'saves');
Inflector.irregular('save', 'saves');
Inflector.irregular('cow', 'kine');
Inflector.irregular('goose', 'geese');
Inflector.irregular('zombie', 'zombies');
Inflector.uncountable('equipment,information,rice,money,species,series,fish,sheep,jeans'.split(','));
extend(string, true, false, {
/***
* @method pluralize()
* @returns String
* @short Returns the plural form of the word in the string.
* @example
*
* 'post'.pluralize() -> 'posts'
* 'octopus'.pluralize() -> 'octopi'
* 'sheep'.pluralize() -> 'sheep'
* 'words'.pluralize() -> 'words'
* 'CamelOctopus'.pluralize() -> 'CamelOctopi'
*
***/
'pluralize': function() {
return inflect(this, true);
},
/***
* @method singularize()
* @returns String
* @short The reverse of String#pluralize. Returns the singular form of a word in a string.
* @example
*
* 'posts'.singularize() -> 'post'
* 'octopi'.singularize() -> 'octopus'
* 'sheep'.singularize() -> 'sheep'
* 'word'.singularize() -> 'word'
* 'CamelOctopi'.singularize() -> 'CamelOctopus'
*
***/
'singularize': function() {
return inflect(this, false);
},
/***
* @method humanize()
* @returns String
* @short Creates a human readable string.
* @extra Capitalizes the first word and turns underscores into spaces and strips a trailing '_id', if any. Like String#titleize, this is meant for creating pretty output.
* @example
*
* 'employee_salary'.humanize() -> 'Employee salary'
* 'author_id'.humanize() -> 'Author'
*
***/
'humanize': function() {
var str = runReplacements(this, humans);
str = str.replace(/_id$/g, '');
str = str.replace(/(_)?([a-z\d]*)/gi, function(match, _, word){
return (_ ? ' ' : '') + (acronyms[word] || word.toLowerCase());
});
return capitalize(str);
},
/***
* @method titleize()
* @returns String
* @short Creates a title version of the string.
* @extra Capitalizes all the words and replaces some characters in the string to create a nicer looking title. String#titleize is meant for creating pretty output.
* @example
*
* 'man from the boondocks'.titleize() -> 'Man from the Boondocks'
* 'x-men: the last stand'.titleize() -> 'X Men: The Last Stand'
* 'TheManWithoutAPast'.titleize() -> 'The Man Without a Past'
* 'raiders_of_the_lost_ark'.titleize() -> 'Raiders of the Lost Ark'
*
***/
'titleize': function() {
var fullStopPunctuation = /[.:;!]$/, hasPunctuation, lastHadPunctuation, isFirstOrLast;
return this.spacify().humanize().words(function(word, index, words) {
hasPunctuation = fullStopPunctuation.test(word);
isFirstOrLast = index == 0 || index == words.length - 1 || hasPunctuation || lastHadPunctuation;
lastHadPunctuation = hasPunctuation;
if(isFirstOrLast || Downcased.indexOf(word) === -1) {
return capitalize(word);
} else {
return word;
}
}).join(' ');
},
/***
* @method parameterize()
* @returns String
* @short Replaces special characters in a string so that it may be used as part of a pretty URL.
* @example
*
* 'hell, no!'.parameterize() -> 'hell-no'
*
***/
'parameterize': function(separator) {
var str = this;
if(separator === undefined) separator = '-';
if(str.normalize) {
str = str.normalize();
}
str = str.replace(/[^a-z0-9\-_]+/gi, separator)
if(separator) {
str = str.replace(new regexp('^{sep}+|{sep}+$|({sep}){sep}+'.assign({ 'sep': escapeRegExp(separator) }), 'g'), '$1');
}
return encodeURI(str.toLowerCase());
}
});
string.Inflector = Inflector;
string.Inflector.acronyms = acronyms;
/***
*
* @package Language
* @dependency string
* @description Normalizing accented characters, character width conversion, Hiragana and Katakana conversions.
*
***/
/***
* String module
*
***/
var NormalizeMap,
NormalizeReg = '',
NormalizeSource;
/***
* @method has[Script]()
* @returns Boolean
* @short Returns true if the string contains any characters in that script.
*
* @set
* hasArabic
* hasCyrillic
* hasGreek
* hasHangul
* hasHan
* hasKanji
* hasHebrew
* hasHiragana
* hasKana
* hasKatakana
* hasLatin
* hasThai
* hasDevanagari
*
* @example
*
* 'أتكلم'.hasArabic() -> true
* 'визит'.hasCyrillic() -> true
* '잘 먹겠습니다!'.hasHangul() -> true
* 'ミックスです'.hasKatakana() -> true
* "l'année".hasLatin() -> true
*
***
* @method is[Script]()
* @returns Boolean
* @short Returns true if the string contains only characters in that script. Whitespace is ignored.
*
* @set
* isArabic
* isCyrillic
* isGreek
* isHangul
* isHan
* isKanji
* isHebrew
* isHiragana
* isKana
* isKatakana
* isKatakana
* isThai
* isDevanagari
*
* @example
*
* 'أتكلم'.isArabic() -> true
* 'визит'.isCyrillic() -> true
* '잘 먹겠습니다!'.isHangul() -> true
* 'ミックスです'.isKatakana() -> false
* "l'année".isLatin() -> true
*
***/
var unicodeScripts = [
{ names: ['Arabic'], source: '\u0600-\u06FF' },
{ names: ['Cyrillic'], source: '\u0400-\u04FF' },
{ names: ['Devanagari'], source: '\u0900-\u097F' },
{ names: ['Greek'], source: '\u0370-\u03FF' },
{ names: ['Hangul'], source: '\uAC00-\uD7AF\u1100-\u11FF' },
{ names: ['Han','Kanji'], source: '\u4E00-\u9FFF\uF900-\uFAFF' },
{ names: ['Hebrew'], source: '\u0590-\u05FF' },
{ names: ['Hiragana'], source: '\u3040-\u309F\u30FB-\u30FC' },
{ names: ['Kana'], source: '\u3040-\u30FF\uFF61-\uFF9F' },
{ names: ['Katakana'], source: '\u30A0-\u30FF\uFF61-\uFF9F' },
{ names: ['Latin'], source: '\u0001-\u007F\u0080-\u00FF\u0100-\u017F\u0180-\u024F' },
{ names: ['Thai'], source: '\u0E00-\u0E7F' }
];
function buildUnicodeScripts() {
unicodeScripts.forEach(function(s) {
var is = regexp('^['+s.source+'\\s]+$');
var has = regexp('['+s.source+']');
s.names.forEach(function(name) {
defineProperty(string.prototype, 'is' + name, function() { return is.test(this.trim()); });
defineProperty(string.prototype, 'has' + name, function() { return has.test(this); });
});
});
}
// Support for converting character widths and katakana to hiragana.
var widthConversionRanges = [
{ type: 'a', shift: 65248, start: 65, end: 90 },
{ type: 'a', shift: 65248, start: 97, end: 122 },
{ type: 'n', shift: 65248, start: 48, end: 57 },
{ type: 'p', shift: 65248, start: 33, end: 47 },
{ type: 'p', shift: 65248, start: 58, end: 64 },
{ type: 'p', shift: 65248, start: 91, end: 96 },
{ type: 'p', shift: 65248, start: 123, end: 126 }
];
var WidthConversionTable;
var allHankaku = /[\u0020-\u00A5]|[\uFF61-\uFF9F][゙゚]?/g;
var allZenkaku = /[\u3000-\u301C]|[\u301A-\u30FC]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g;
var hankakuPunctuation = '。、「」¥¢£';
var zenkakuPunctuation = '。、「」¥¢£';
var voicedKatakana = /[カキクケコサシスセソタチツテトハヒフヘホ]/;
var semiVoicedKatakana = /[ハヒフヘホヲ]/;
var hankakuKatakana = 'アイウエオァィゥェォカキクケコサシスセソタチツッテトナニヌネノハヒフヘホマミムメモヤャユュヨョラリルレロワヲンー・';
var zenkakuKatakana = 'アイウエオァィゥェォカキクケコサシスセソタチツッテトナニヌネノハヒフヘホマミムメモヤャユュヨョラリルレロワヲンー・';
function convertCharacterWidth(str, args, reg, type) {
if(!WidthConversionTable) {
buildWidthConversionTables();
}
var mode = multiArgs(args).join(''), table = WidthConversionTable[type];
mode = mode.replace(/all/, '').replace(/(\w)lphabet|umbers?|atakana|paces?|unctuation/g, '$1');
return str.replace(reg, function(c) {
if(table[c] && (!mode || mode.has(table[c].type))) {
return table[c].to;
} else {
return c;
}
});
}
function buildWidthConversionTables() {
var hankaku;
WidthConversionTable = {
'zenkaku': {},
'hankaku': {}
};
widthConversionRanges.forEach(function(r) {
getRange(r.start, r.end, function(n) {
setWidthConversion(r.type, chr(n), chr(n + r.shift));
});
});
zenkakuKatakana.each(function(c, i) {
hankaku = hankakuKatakana.charAt(i);
setWidthConversion('k', hankaku, c);
if(c.match(voicedKatakana)) {
setWidthConversion('k', hankaku + '゙', c.shift(1));
}
if(c.match(semiVoicedKatakana)) {
setWidthConversion('k', hankaku + '゚', c.shift(2));
}
});
zenkakuPunctuation.each(function(c, i) {
setWidthConversion('p', hankakuPunctuation.charAt(i), c);
});
setWidthConversion('k', 'ヴ', 'ヴ');
setWidthConversion('k', 'ヺ', 'ヺ');
setWidthConversion('s', ' ', ' ');
}
function setWidthConversion(type, half, full) {
WidthConversionTable['zenkaku'][half] = { type: type, to: full };
WidthConversionTable['hankaku'][full] = { type: type, to: half };
}
function buildNormalizeMap() {
NormalizeMap = {};
iterateOverObject(NormalizeSource, function(normalized, str) {
str.split('').forEach(function(character) {
NormalizeMap[character] = normalized;
});
NormalizeReg += str;
});
NormalizeReg = regexp('[' + NormalizeReg + ']', 'g');
}
NormalizeSource = {
'A': 'AⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ',
'B': 'BⒷBḂḄḆɃƂƁ',
'C': 'CⒸCĆĈĊČÇḈƇȻꜾ',
'D': 'DⒹDḊĎḌḐḒḎĐƋƊƉꝹ',
'E': 'EⒺEÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎ',
'F': 'FⒻFḞƑꝻ',
'G': 'GⒼGǴĜḠĞĠǦĢǤƓꞠꝽꝾ',
'H': 'HⒽHĤḢḦȞḤḨḪĦⱧⱵꞍ',
'I': 'IⒾIÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ',
'J': 'JⒿJĴɈ',
'K': 'KⓀKḰǨḲĶḴƘⱩꝀꝂꝄꞢ',
'L': 'LⓁLĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ',
'M': 'MⓂMḾṀṂⱮƜ',
'N': 'NⓃNǸŃÑṄŇṆŅṊṈȠƝꞐꞤ',
'O': 'OⓄOÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ',
'P': 'PⓅPṔṖƤⱣꝐꝒꝔ',
'Q': 'QⓆQꝖꝘɊ',
'R': 'RⓇRŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ',
'S': 'SⓈSẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ',
'T': 'TⓉTṪŤṬȚŢṰṮŦƬƮȾꞆ',
'U': 'UⓊUÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ',
'V': 'VⓋVṼṾƲꝞɅ',
'W': 'WⓌWẀẂŴẆẄẈⱲ',
'X': 'XⓍXẊẌ',
'Y': 'YⓎYỲÝŶỸȲẎŸỶỴƳɎỾ',
'Z': 'ZⓏZŹẐŻŽẒẔƵȤⱿⱫꝢ',
'a': 'aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐ',
'b': 'bⓑbḃḅḇƀƃɓ',
'c': 'cⓒcćĉċčçḉƈȼꜿↄ',
'd': 'dⓓdḋďḍḑḓḏđƌɖɗꝺ',
'e': 'eⓔeèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇɛǝ',
'f': 'fⓕfḟƒꝼ',
'g': 'gⓖgǵĝḡğġǧģǥɠꞡᵹꝿ',
'h': 'hⓗhĥḣḧȟḥḩḫẖħⱨⱶɥ',
'i': 'iⓘiìíîĩīĭïḯỉǐȉȋịįḭɨı',
'j': 'jⓙjĵǰɉ',
'k': 'kⓚkḱǩḳķḵƙⱪꝁꝃꝅꞣ',
'l': 'lⓛlŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇ',
'm': 'mⓜmḿṁṃɱɯ',
'n': 'nⓝnǹńñṅňṇņṋṉƞɲʼnꞑꞥ',
'o': 'oⓞoòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿɔꝋꝍɵ',
'p': 'pⓟpṕṗƥᵽꝑꝓꝕ',
'q': 'qⓠqɋꝗꝙ',
'r': 'rⓡrŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ',
's': 'sⓢsśṥŝṡšṧṣṩșşȿꞩꞅẛ',
't': 'tⓣtṫẗťṭțţṱṯŧƭʈⱦꞇ',
'u': 'uⓤuùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ',
'v': 'vⓥvṽṿʋꝟʌ',
'w': 'wⓦwẁẃŵẇẅẘẉⱳ',
'x': 'xⓧxẋẍ',
'y': 'yⓨyỳýŷỹȳẏÿỷẙỵƴɏỿ',
'z': 'zⓩzźẑżžẓẕƶȥɀⱬꝣ',
'AA': 'Ꜳ',
'AE': 'ÆǼǢ',
'AO': 'Ꜵ',
'AU': 'Ꜷ',
'AV': 'ꜸꜺ',
'AY': 'Ꜽ',
'DZ': 'DZDŽ',
'Dz': 'DzDž',
'LJ': 'LJ',
'Lj': 'Lj',
'NJ': 'NJ',
'Nj': 'Nj',
'OI': 'Ƣ',
'OO': 'Ꝏ',
'OU': 'Ȣ',
'TZ': 'Ꜩ',
'VY': 'Ꝡ',
'aa': 'ꜳ',
'ae': 'æǽǣ',
'ao': 'ꜵ',
'au': 'ꜷ',
'av': 'ꜹꜻ',
'ay': 'ꜽ',
'dz': 'dzdž',
'hv': 'ƕ',
'lj': 'lj',
'nj': 'nj',
'oi': 'ƣ',
'ou': 'ȣ',
'oo': 'ꝏ',
'ss': 'ß',
'tz': 'ꜩ',
'vy': 'ꝡ'
};
extend(string, true, false, {
/***
* @method normalize()
* @returns String
* @short Returns the string with accented and non-standard Latin-based characters converted into ASCII approximate equivalents.
* @example
*
* 'á'.normalize() -> 'a'
* 'Ménage à trois'.normalize() -> 'Menage a trois'
* 'Volkswagen'.normalize() -> 'Volkswagen'
* 'FULLWIDTH'.normalize() -> 'FULLWIDTH'
*
***/
'normalize': function() {
if(!NormalizeMap) {
buildNormalizeMap();
}
return this.replace(NormalizeReg, function(character) {
return NormalizeMap[character];
});
},
/***
* @method hankaku([mode] = 'all')
* @returns String
* @short Converts full-width characters (zenkaku) to half-width (hankaku).
* @extra [mode] accepts any combination of "a" (alphabet), "n" (numbers), "k" (katakana), "s" (spaces), "p" (punctuation), or "all".
* @example
*
* 'タロウ YAMADAです!'.hankaku() -> 'タロウ YAMADAです!'
* 'タロウ YAMADAです!'.hankaku('a') -> 'タロウ YAMADAです!'
* 'タロウ YAMADAです!'.hankaku('alphabet') -> 'タロウ YAMADAです!'
* 'タロウです! 25歳です!'.hankaku('katakana', 'numbers') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.hankaku('k', 'n') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.hankaku('kn') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.hankaku('sp') -> 'タロウです! 25歳です!'
*
***/
'hankaku': function() {
return convertCharacterWidth(this, arguments, allZenkaku, 'hankaku');
},
/***
* @method zenkaku([mode] = 'all')
* @returns String
* @short Converts half-width characters (hankaku) to full-width (zenkaku).
* @extra [mode] accepts any combination of "a" (alphabet), "n" (numbers), "k" (katakana), "s" (spaces), "p" (punctuation), or "all".
* @example
*
* 'タロウ YAMADAです!'.zenkaku() -> 'タロウ YAMADAです!'
* 'タロウ YAMADAです!'.zenkaku('a') -> 'タロウ YAMADAです!'
* 'タロウ YAMADAです!'.zenkaku('alphabet') -> 'タロウ YAMADAです!'
* 'タロウです! 25歳です!'.zenkaku('katakana', 'numbers') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.zenkaku('k', 'n') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.zenkaku('kn') -> 'タロウです! 25歳です!'
* 'タロウです! 25歳です!'.zenkaku('sp') -> 'タロウです! 25歳です!'
*
***/
'zenkaku': function() {
return convertCharacterWidth(this, arguments, allHankaku, 'zenkaku');
},
/***
* @method hiragana([all] = true)
* @returns String
* @short Converts katakana into hiragana.
* @extra If [all] is false, only full-width katakana will be converted.
* @example
*
* 'カタカナ'.hiragana() -> 'かたかな'
* 'コンニチハ'.hiragana() -> 'こんにちは'
* 'カタカナ'.hiragana() -> 'かたかな'
* 'カタカナ'.hiragana(false) -> 'カタカナ'
*
***/
'hiragana': function(all) {
var str = this;
if(all !== false) {
str = str.zenkaku('k');
}
return str.replace(/[\u30A1-\u30F6]/g, function(c) {
return c.shift(-96);
});
},
/***
* @method katakana()
* @returns String
* @short Converts hiragana into katakana.
* @example
*
* 'かたかな'.katakana() -> 'カタカナ'
* 'こんにちは'.katakana() -> 'コンニチハ'
*
***/
'katakana': function() {
return this.replace(/[\u3041-\u3096]/g, function(c) {
return c.shift(96);
});
}
});
buildUnicodeScripts();
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('da');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('da', {
'plural': true,
'months': 'januar,februar,marts,april,maj,juni,juli,august,september,oktober,november,december',
'weekdays': 'søndag|sondag,mandag,tirsdag,onsdag,torsdag,fredag,lørdag|lordag',
'units': 'millisekund:|er,sekund:|er,minut:|ter,tim:e|er,dag:|e,ug:e|er|en,måned:|er|en+maaned:|er|en,år:||et+aar:||et',
'numbers': 'en|et,to,tre,fire,fem,seks,syv,otte,ni,ti',
'tokens': 'den,for',
'articles': 'den',
'short':'d. {d}. {month} {yyyy}',
'long': 'den {d}. {month} {yyyy} {H}:{mm}',
'full': '{Weekday} den {d}. {month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'forgårs|i forgårs|forgaars|i forgaars', 'value': -2 },
{ 'name': 'day', 'src': 'i går|igår|i gaar|igaar', 'value': -1 },
{ 'name': 'day', 'src': 'i dag|idag', 'value': 0 },
{ 'name': 'day', 'src': 'i morgen|imorgen', 'value': 1 },
{ 'name': 'day', 'src': 'over morgon|overmorgen|i over morgen|i overmorgen|iovermorgen', 'value': 2 },
{ 'name': 'sign', 'src': 'siden', 'value': -1 },
{ 'name': 'sign', 'src': 'om', 'value': 1 },
{ 'name': 'shift', 'src': 'i sidste|sidste', 'value': -1 },
{ 'name': 'shift', 'src': 'denne', 'value': 0 },
{ 'name': 'shift', 'src': 'næste|naeste', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{1?} {num} {unit} {sign}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{0?} {weekday?} {date?} {month} {year}',
'{date} {month}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('de');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('de', {
'plural': true,
'capitalizeUnit': true,
'months': 'Januar,Februar,März|Marz,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember',
'weekdays': 'Sonntag,Montag,Dienstag,Mittwoch,Donnerstag,Freitag,Samstag',
'units': 'Millisekunde:|n,Sekunde:|n,Minute:|n,Stunde:|n,Tag:|en,Woche:|n,Monat:|en,Jahr:|en',
'numbers': 'ein:|e|er|en|em,zwei,drei,vier,fuenf,sechs,sieben,acht,neun,zehn',
'tokens': 'der',
'short':'{d}. {Month} {yyyy}',
'long': '{d}. {Month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d}. {Month} {yyyy} {H}:{mm}:{ss}',
'past': '{sign} {num} {unit}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'timeMarker': 'um',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'vorgestern', 'value': -2 },
{ 'name': 'day', 'src': 'gestern', 'value': -1 },
{ 'name': 'day', 'src': 'heute', 'value': 0 },
{ 'name': 'day', 'src': 'morgen', 'value': 1 },
{ 'name': 'day', 'src': 'übermorgen|ubermorgen|uebermorgen', 'value': 2 },
{ 'name': 'sign', 'src': 'vor:|her', 'value': -1 },
{ 'name': 'sign', 'src': 'in', 'value': 1 },
{ 'name': 'shift', 'src': 'letzte:|r|n|s', 'value': -1 },
{ 'name': 'shift', 'src': 'nächste:|r|n|s+nachste:|r|n|s+naechste:|r|n|s+kommende:n|r', 'value': 1 }
],
'dateParse': [
'{sign} {num} {unit}',
'{num} {unit} {sign}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{weekday?} {date?} {month} {year?}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('es');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('es', {
'plural': true,
'months': 'enero,febrero,marzo,abril,mayo,junio,julio,agosto,septiembre,octubre,noviembre,diciembre',
'weekdays': 'domingo,lunes,martes,miércoles|miercoles,jueves,viernes,sábado|sabado',
'units': 'milisegundo:|s,segundo:|s,minuto:|s,hora:|s,día|días|dia|dias,semana:|s,mes:|es,año|años|ano|anos',
'numbers': 'uno,dos,tres,cuatro,cinco,seis,siete,ocho,nueve,diez',
'tokens': 'el,de',
'short':'{d} {month} {yyyy}',
'long': '{d} {month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d} {month} {yyyy} {H}:{mm}:{ss}',
'past': '{sign} {num} {unit}',
'future': '{num} {unit} {sign}',
'duration': '{num} {unit}',
'timeMarker': 'a las',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'anteayer', 'value': -2 },
{ 'name': 'day', 'src': 'ayer', 'value': -1 },
{ 'name': 'day', 'src': 'hoy', 'value': 0 },
{ 'name': 'day', 'src': 'mañana|manana', 'value': 1 },
{ 'name': 'sign', 'src': 'hace', 'value': -1 },
{ 'name': 'sign', 'src': 'de ahora', 'value': 1 },
{ 'name': 'shift', 'src': 'pasad:o|a', 'value': -1 },
{ 'name': 'shift', 'src': 'próximo|próxima|proximo|proxima', 'value': 1 }
],
'dateParse': [
'{sign} {num} {unit}',
'{num} {unit} {sign}',
'{0?} {unit=5-7} {shift}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{shift} {weekday}',
'{weekday} {shift}',
'{date?} {1?} {month} {1?} {year?}'
]
});
Date.addLocale('fi', {
'plural': true,
'timeMarker': 'kello',
'ampm': ',',
'months': 'tammikuu,helmikuu,maaliskuu,huhtikuu,toukokuu,kesäkuu,heinäkuu,elokuu,syyskuu,lokakuu,marraskuu,joulukuu',
'weekdays': 'sunnuntai,maanantai,tiistai,keskiviikko,torstai,perjantai,lauantai',
'units': 'millisekun:ti|tia|teja|tina|nin,sekun:ti|tia|teja|tina|nin,minuut:ti|tia|teja|tina|in,tun:ti|tia|teja|tina|nin,päiv:ä|ää|iä|änä|än,viik:ko|koa|koja|on|kona,kuukau:si|sia|tta|den|tena,vuo:si|sia|tta|den|tena',
'numbers': 'yksi|ensimmäinen,kaksi|toinen,kolm:e|as,neljä:s,vii:si|des,kuu:si|des,seitsemä:n|s,kahdeksa:n|s,yhdeksä:n|s,kymmene:n|s',
'articles': '',
'optionals': '',
'short': '{d}. {month}ta {yyyy}',
'long': '{d}. {month}ta {yyyy} kello {H}.{mm}',
'full': '{Weekday}na {d}. {month}ta {yyyy} kello {H}.{mm}',
'relative': function(num, unit, ms, format) {
var units = this['units'];
function numberWithUnit(mult) {
return (num === 1 ? '' : num + ' ') + units[(8 * mult) + unit];
}
switch(format) {
case 'duration': return numberWithUnit(0);
case 'past': return numberWithUnit(num > 1 ? 1 : 0) + ' sitten';
case 'future': return numberWithUnit(4) + ' päästä';
}
},
'modifiers': [
{ 'name': 'day', 'src': 'toissa päivänä|toissa päiväistä', 'value': -2 },
{ 'name': 'day', 'src': 'eilen|eilistä', 'value': -1 },
{ 'name': 'day', 'src': 'tänään', 'value': 0 },
{ 'name': 'day', 'src': 'huomenna|huomista', 'value': 1 },
{ 'name': 'day', 'src': 'ylihuomenna|ylihuomista', 'value': 2 },
{ 'name': 'sign', 'src': 'sitten|aiemmin', 'value': -1 },
{ 'name': 'sign', 'src': 'päästä|kuluttua|myöhemmin', 'value': 1 },
{ 'name': 'edge', 'src': 'viimeinen|viimeisenä', 'value': -2 },
{ 'name': 'edge', 'src': 'lopussa', 'value': -1 },
{ 'name': 'edge', 'src': 'ensimmäinen|ensimmäisenä', 'value': 1 },
{ 'name': 'shift', 'src': 'edellinen|edellisenä|edeltävä|edeltävänä|viime|toissa', 'value': -1 },
{ 'name': 'shift', 'src': 'tänä|tämän', 'value': 0 },
{ 'name': 'shift', 'src': 'seuraava|seuraavana|tuleva|tulevana|ensi', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{num} {unit=4-5} {sign} {day}',
'{month} {year}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{0} {num}{1} {day} of {month} {year?}',
'{weekday?} {month} {date}{1} {year?}',
'{date} {month} {year}',
'{shift} {weekday}',
'{shift} week {weekday}',
'{weekday} {2} {shift} week',
'{0} {date}{1} of {month}',
'{0}{month?} {date?}{1} of {shift} {unit=6-7}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('fr');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('fr', {
'plural': true,
'months': 'janvier,février|fevrier,mars,avril,mai,juin,juillet,août,septembre,octobre,novembre,décembre|decembre',
'weekdays': 'dimanche,lundi,mardi,mercredi,jeudi,vendredi,samedi',
'units': 'milliseconde:|s,seconde:|s,minute:|s,heure:|s,jour:|s,semaine:|s,mois,an:|s|née|nee',
'numbers': 'un:|e,deux,trois,quatre,cinq,six,sept,huit,neuf,dix',
'tokens': ["l'|la|le"],
'short':'{d} {month} {yyyy}',
'long': '{d} {month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d} {month} {yyyy} {H}:{mm}:{ss}',
'past': '{sign} {num} {unit}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'timeMarker': 'à',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'hier', 'value': -1 },
{ 'name': 'day', 'src': "aujourd'hui", 'value': 0 },
{ 'name': 'day', 'src': 'demain', 'value': 1 },
{ 'name': 'sign', 'src': 'il y a', 'value': -1 },
{ 'name': 'sign', 'src': "dans|d'ici", 'value': 1 },
{ 'name': 'shift', 'src': 'derni:èr|er|ère|ere', 'value': -1 },
{ 'name': 'shift', 'src': 'prochain:|e', 'value': 1 }
],
'dateParse': [
'{sign} {num} {unit}',
'{sign} {num} {unit}',
'{0?} {unit=5-7} {shift}'
],
'timeParse': [
'{0?} {date?} {month} {year?}',
'{0?} {weekday} {shift}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('it');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('it', {
'plural': true,
'months': 'Gennaio,Febbraio,Marzo,Aprile,Maggio,Giugno,Luglio,Agosto,Settembre,Ottobre,Novembre,Dicembre',
'weekdays': 'Domenica,Luned:ì|i,Marted:ì|i,Mercoled:ì|i,Gioved:ì|i,Venerd:ì|i,Sabato',
'units': 'millisecond:o|i,second:o|i,minut:o|i,or:a|e,giorn:o|i,settiman:a|e,mes:e|i,ann:o|i',
'numbers': "un:|a|o|',due,tre,quattro,cinque,sei,sette,otto,nove,dieci",
'tokens': "l'|la|il",
'short':'{d} {Month} {yyyy}',
'long': '{d} {Month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d} {Month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{num} {unit} {sign}',
'duration': '{num} {unit}',
'timeMarker': 'alle',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'ieri', 'value': -1 },
{ 'name': 'day', 'src': 'oggi', 'value': 0 },
{ 'name': 'day', 'src': 'domani', 'value': 1 },
{ 'name': 'day', 'src': 'dopodomani', 'value': 2 },
{ 'name': 'sign', 'src': 'fa', 'value': -1 },
{ 'name': 'sign', 'src': 'da adesso', 'value': 1 },
{ 'name': 'shift', 'src': 'scors:o|a', 'value': -1 },
{ 'name': 'shift', 'src': 'prossim:o|a', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{0?} {unit=5-7} {shift}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{weekday?} {date?} {month} {year?}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('ja');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('ja', {
'monthSuffix': '月',
'weekdays': '日曜日,月曜日,火曜日,水曜日,木曜日,金曜日,土曜日',
'units': 'ミリ秒,秒,分,時間,日,週間|週,ヶ月|ヵ月|月,年',
'short': '{yyyy}年{M}月{d}日',
'long': '{yyyy}年{M}月{d}日 {H}時{mm}分',
'full': '{yyyy}年{M}月{d}日 {Weekday} {H}時{mm}分{ss}秒',
'past': '{num}{unit}{sign}',
'future': '{num}{unit}{sign}',
'duration': '{num}{unit}',
'timeSuffixes': '時,分,秒',
'ampm': '午前,午後',
'modifiers': [
{ 'name': 'day', 'src': '一昨日', 'value': -2 },
{ 'name': 'day', 'src': '昨日', 'value': -1 },
{ 'name': 'day', 'src': '今日', 'value': 0 },
{ 'name': 'day', 'src': '明日', 'value': 1 },
{ 'name': 'day', 'src': '明後日', 'value': 2 },
{ 'name': 'sign', 'src': '前', 'value': -1 },
{ 'name': 'sign', 'src': '後', 'value': 1 },
{ 'name': 'shift', 'src': '去|先', 'value': -1 },
{ 'name': 'shift', 'src': '来', 'value': 1 }
],
'dateParse': [
'{num}{unit}{sign}'
],
'timeParse': [
'{shift}{unit=5-7}{weekday?}',
'{year}年{month?}月?{date?}日?',
'{month}月{date?}日?',
'{date}日'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('ko');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('ko', {
'digitDate': true,
'monthSuffix': '월',
'weekdays': '일요일,월요일,화요일,수요일,목요일,금요일,토요일',
'units': '밀리초,초,분,시간,일,주,개월|달,년',
'numbers': '일|한,이,삼,사,오,육,칠,팔,구,십',
'short': '{yyyy}년{M}월{d}일',
'long': '{yyyy}년{M}월{d}일 {H}시{mm}분',
'full': '{yyyy}년{M}월{d}일 {Weekday} {H}시{mm}분{ss}초',
'past': '{num}{unit} {sign}',
'future': '{num}{unit} {sign}',
'duration': '{num}{unit}',
'timeSuffixes': '시,분,초',
'ampm': '오전,오후',
'modifiers': [
{ 'name': 'day', 'src': '그저께', 'value': -2 },
{ 'name': 'day', 'src': '어제', 'value': -1 },
{ 'name': 'day', 'src': '오늘', 'value': 0 },
{ 'name': 'day', 'src': '내일', 'value': 1 },
{ 'name': 'day', 'src': '모레', 'value': 2 },
{ 'name': 'sign', 'src': '전', 'value': -1 },
{ 'name': 'sign', 'src': '후', 'value': 1 },
{ 'name': 'shift', 'src': '지난|작', 'value': -1 },
{ 'name': 'shift', 'src': '이번', 'value': 0 },
{ 'name': 'shift', 'src': '다음|내', 'value': 1 }
],
'dateParse': [
'{num}{unit} {sign}',
'{shift?} {unit=5-7}'
],
'timeParse': [
'{shift} {unit=5?} {weekday}',
'{year}년{month?}월?{date?}일?',
'{month}월{date?}일?',
'{date}일'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('nl');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('nl', {
'plural': true,
'months': 'januari,februari,maart,april,mei,juni,juli,augustus,september,oktober,november,december',
'weekdays': 'zondag|zo,maandag|ma,dinsdag|di,woensdag|woe|wo,donderdag|do,vrijdag|vrij|vr,zaterdag|za',
'units': 'milliseconde:|n,seconde:|n,minu:ut|ten,uur,dag:|en,we:ek|ken,maand:|en,jaar',
'numbers': 'een,twee,drie,vier,vijf,zes,zeven,acht,negen',
'tokens': '',
'short':'{d} {Month} {yyyy}',
'long': '{d} {Month} {yyyy} {H}:{mm}',
'full': '{Weekday} {d} {Month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{num} {unit} {sign}',
'duration': '{num} {unit}',
'timeMarker': "'s|om",
'modifiers': [
{ 'name': 'day', 'src': 'gisteren', 'value': -1 },
{ 'name': 'day', 'src': 'vandaag', 'value': 0 },
{ 'name': 'day', 'src': 'morgen', 'value': 1 },
{ 'name': 'day', 'src': 'overmorgen', 'value': 2 },
{ 'name': 'sign', 'src': 'geleden', 'value': -1 },
{ 'name': 'sign', 'src': 'vanaf nu', 'value': 1 },
{ 'name': 'shift', 'src': 'laatste|vorige|afgelopen', 'value': -1 },
{ 'name': 'shift', 'src': 'volgend:|e', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{0?} {unit=5-7} {shift}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{weekday?} {date?} {month} {year?}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('pl');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.optionals. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('pl', {
'plural': true,
'months': 'Styczeń|Stycznia,Luty|Lutego,Marzec|Marca,Kwiecień|Kwietnia,Maj|Maja,Czerwiec|Czerwca,Lipiec|Lipca,Sierpień|Sierpnia,Wrzesień|Września,Październik|Października,Listopad|Listopada,Grudzień|Grudnia',
'weekdays': 'Niedziela|Niedzielę,Poniedziałek,Wtorek,Środ:a|ę,Czwartek,Piątek,Sobota|Sobotę',
'units': 'milisekund:a|y|,sekund:a|y|,minut:a|y|,godzin:a|y|,dzień|dni,tydzień|tygodnie|tygodni,miesiące|miesiące|miesięcy,rok|lata|lat',
'numbers': 'jeden|jedną,dwa|dwie,trzy,cztery,pięć,sześć,siedem,osiem,dziewięć,dziesięć',
'optionals': 'w|we,roku',
'short': '{d} {Month} {yyyy}',
'long': '{d} {Month} {yyyy} {H}:{mm}',
'full' : '{Weekday}, {d} {Month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'timeMarker':'o',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'przedwczoraj', 'value': -2 },
{ 'name': 'day', 'src': 'wczoraj', 'value': -1 },
{ 'name': 'day', 'src': 'dzisiaj|dziś', 'value': 0 },
{ 'name': 'day', 'src': 'jutro', 'value': 1 },
{ 'name': 'day', 'src': 'pojutrze', 'value': 2 },
{ 'name': 'sign', 'src': 'temu|przed', 'value': -1 },
{ 'name': 'sign', 'src': 'za', 'value': 1 },
{ 'name': 'shift', 'src': 'zeszły|zeszła|ostatni|ostatnia', 'value': -1 },
{ 'name': 'shift', 'src': 'następny|następna|następnego|przyszły|przyszła|przyszłego', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{month} {year}',
'{shift} {unit=5-7}',
'{0} {shift?} {weekday}'
],
'timeParse': [
'{date} {month} {year?} {1}',
'{0} {shift?} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('pt');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('pt', {
'plural': true,
'months': 'janeiro,fevereiro,março,abril,maio,junho,julho,agosto,setembro,outubro,novembro,dezembro',
'weekdays': 'domingo,segunda-feira,terça-feira,quarta-feira,quinta-feira,sexta-feira,sábado|sabado',
'units': 'milisegundo:|s,segundo:|s,minuto:|s,hora:|s,dia:|s,semana:|s,mês|mêses|mes|meses,ano:|s',
'numbers': 'um,dois,três|tres,quatro,cinco,seis,sete,oito,nove,dez,uma,duas',
'tokens': 'a,de',
'short':'{d} de {month} de {yyyy}',
'long': '{d} de {month} de {yyyy} {H}:{mm}',
'full': '{Weekday}, {d} de {month} de {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'timeMarker': 'às',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'anteontem', 'value': -2 },
{ 'name': 'day', 'src': 'ontem', 'value': -1 },
{ 'name': 'day', 'src': 'hoje', 'value': 0 },
{ 'name': 'day', 'src': 'amanh:ã|a', 'value': 1 },
{ 'name': 'sign', 'src': 'atrás|atras|há|ha', 'value': -1 },
{ 'name': 'sign', 'src': 'daqui a', 'value': 1 },
{ 'name': 'shift', 'src': 'passad:o|a', 'value': -1 },
{ 'name': 'shift', 'src': 'próximo|próxima|proximo|proxima', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{0?} {unit=5-7} {shift}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{date?} {1?} {month} {1?} {year?}',
'{0?} {shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('ru');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('ru', {
'months': 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь',
'weekdays': 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота',
'units': 'миллисекунд:а|у|ы|,секунд:а|у|ы|,минут:а|у|ы|,час:||а|ов,день|день|дня|дней,недел:я|ю|и|ь|е,месяц:||а|ев|е,год|год|года|лет|году',
'numbers': 'од:ин|ну,дв:а|е,три,четыре,пять,шесть,семь,восемь,девять,десять',
'tokens': 'в|на,года',
'short':'{d} {month} {yyyy} года',
'long': '{d} {month} {yyyy} года {H}:{mm}',
'full': '{Weekday} {d} {month} {yyyy} года {H}:{mm}:{ss}',
'relative': function(num, unit, ms, format) {
var numberWithUnit, last = num.toString().slice(-1);
switch(true) {
case num >= 11 && num <= 15: mult = 3; break;
case last == 1: mult = 1; break;
case last >= 2 && last <= 4: mult = 2; break;
default: mult = 3;
}
numberWithUnit = num + ' ' + this['units'][(mult * 8) + unit];
switch(format) {
case 'duration': return numberWithUnit;
case 'past': return numberWithUnit + ' назад';
case 'future': return 'через ' + numberWithUnit;
}
},
'timeMarker': 'в',
'ampm': ' утра, вечера',
'modifiers': [
{ 'name': 'day', 'src': 'позавчера', 'value': -2 },
{ 'name': 'day', 'src': 'вчера', 'value': -1 },
{ 'name': 'day', 'src': 'сегодня', 'value': 0 },
{ 'name': 'day', 'src': 'завтра', 'value': 1 },
{ 'name': 'day', 'src': 'послезавтра', 'value': 2 },
{ 'name': 'sign', 'src': 'назад', 'value': -1 },
{ 'name': 'sign', 'src': 'через', 'value': 1 },
{ 'name': 'shift', 'src': 'прошл:ый|ой|ом', 'value': -1 },
{ 'name': 'shift', 'src': 'следующ:ий|ей|ем', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{month} {year}',
'{0?} {shift} {unit=5-7}'
],
'timeParse': [
'{date} {month} {year?} {1?}',
'{0?} {shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('sv');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('sv', {
'plural': true,
'months': 'januari,februari,mars,april,maj,juni,juli,augusti,september,oktober,november,december',
'weekdays': 'söndag|sondag,måndag:|en+mandag:|en,tisdag,onsdag,torsdag,fredag,lördag|lordag',
'units': 'millisekund:|er,sekund:|er,minut:|er,timm:e|ar,dag:|ar,veck:a|or|an,månad:|er|en+manad:|er|en,år:||et+ar:||et',
'numbers': 'en|ett,två|tva,tre,fyra,fem,sex,sju,åtta|atta,nio,tio',
'tokens': 'den,för|for',
'articles': 'den',
'short':'den {d} {month} {yyyy}',
'long': 'den {d} {month} {yyyy} {H}:{mm}',
'full': '{Weekday} den {d} {month} {yyyy} {H}:{mm}:{ss}',
'past': '{num} {unit} {sign}',
'future': '{sign} {num} {unit}',
'duration': '{num} {unit}',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'förrgår|i förrgår|iförrgår|forrgar|i forrgar|iforrgar', 'value': -2 },
{ 'name': 'day', 'src': 'går|i går|igår|gar|i gar|igar', 'value': -1 },
{ 'name': 'day', 'src': 'dag|i dag|idag', 'value': 0 },
{ 'name': 'day', 'src': 'morgon|i morgon|imorgon', 'value': 1 },
{ 'name': 'day', 'src': 'över morgon|övermorgon|i över morgon|i övermorgon|iövermorgon|over morgon|overmorgon|i over morgon|i overmorgon|iovermorgon', 'value': 2 },
{ 'name': 'sign', 'src': 'sedan|sen', 'value': -1 },
{ 'name': 'sign', 'src': 'om', 'value': 1 },
{ 'name': 'shift', 'src': 'i förra|förra|i forra|forra', 'value': -1 },
{ 'name': 'shift', 'src': 'denna', 'value': 0 },
{ 'name': 'shift', 'src': 'nästa|nasta', 'value': 1 }
],
'dateParse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{1?} {num} {unit} {sign}',
'{shift} {unit=5-7}'
],
'timeParse': [
'{0?} {weekday?} {date?} {month} {year}',
'{date} {month}',
'{shift} {weekday}'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('zh-CN');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
Date.addLocale('zh-CN', {
'variant': true,
'monthSuffix': '月',
'weekdays': '星期日|周日,星期一|周一,星期二|周二,星期三|周三,星期四|周四,星期五|周五,星期六|周六',
'units': '毫秒,秒钟,分钟,小时,天,个星期|周,个月,年',
'tokens': '日|号',
'short':'{yyyy}年{M}月{d}日',
'long': '{yyyy}年{M}月{d}日 {tt}{h}:{mm}',
'full': '{yyyy}年{M}月{d}日 {weekday} {tt}{h}:{mm}:{ss}',
'past': '{num}{unit}{sign}',
'future': '{num}{unit}{sign}',
'duration': '{num}{unit}',
'timeSuffixes': '点|时,分钟?,秒',
'ampm': '上午,下午',
'modifiers': [
{ 'name': 'day', 'src': '前天', 'value': -2 },
{ 'name': 'day', 'src': '昨天', 'value': -1 },
{ 'name': 'day', 'src': '今天', 'value': 0 },
{ 'name': 'day', 'src': '明天', 'value': 1 },
{ 'name': 'day', 'src': '后天', 'value': 2 },
{ 'name': 'sign', 'src': '前', 'value': -1 },
{ 'name': 'sign', 'src': '后', 'value': 1 },
{ 'name': 'shift', 'src': '上|去', 'value': -1 },
{ 'name': 'shift', 'src': '这', 'value': 0 },
{ 'name': 'shift', 'src': '下|明', 'value': 1 }
],
'dateParse': [
'{num}{unit}{sign}',
'{shift}{unit=5-7}'
],
'timeParse': [
'{shift}{weekday}',
'{year}年{month?}月?{date?}{0?}',
'{month}月{date?}{0?}',
'{date}[日号]'
]
});
/*
*
* Date.addLocale(<code>) adds this locale to Sugar.
* To set the locale globally, simply call:
*
* Date.setLocale('zh-TW');
*
* var locale = Date.getLocale(<code>) will return this object, which
* can be tweaked to change the behavior of parsing/formatting in the locales.
*
* locale.addFormat adds a date format (see this file for examples).
* Special tokens in the date format will be parsed out into regex tokens:
*
* {0} is a reference to an entry in locale.tokens. Output: (?:the)?
* {unit} is a reference to all units. Output: (day|week|month|...)
* {unit3} is a reference to a specific unit. Output: (hour)
* {unit3-5} is a reference to a subset of the units array. Output: (hour|day|week)
* {unit?} "?" makes that token optional. Output: (day|week|month)?
*
* {day} Any reference to tokens in the modifiers array will include all with the same name. Output: (yesterday|today|tomorrow)
*
* All spaces are optional and will be converted to "\s*"
*
* Locale arrays months, weekdays, units, numbers, as well as the "src" field for
* all entries in the modifiers array follow a special format indicated by a colon:
*
* minute:|s = minute|minutes
* thicke:n|r = thicken|thicker
*
* Additionally in the months, weekdays, units, and numbers array these will be added at indexes that are multiples
* of the relevant number for retrieval. For example having "sunday:|s" in the units array will result in:
*
* units: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sundays']
*
* When matched, the index will be found using:
*
* units.indexOf(match) % 7;
*
* Resulting in the correct index with any number of alternates for that entry.
*
*/
//'zh-TW': '1;月;年;;星期日|週日,星期一|週一,星期二|週二,星期三|週三,星期四|週四,星期五|週五,星期六|週六;毫秒,秒鐘,分鐘,小時,天,個星期|週,個月,年;;;日|號;;上午,下午;點|時,分鐘?,秒;{num}{unit}{sign},{shift}{unit=5-7};{shift}{weekday},{year}年{month?}月?{date?}{0},{month}月{date?}{0},{date}{0};{yyyy}年{M}月{d}日 {Weekday};{tt}{h}:{mm}:{ss};前天,昨天,今天,明天,後天;,前,,後;,上|去,這,下|明',
Date.addLocale('zh-TW', {
'monthSuffix': '月',
'weekdays': '星期日|週日,星期一|週一,星期二|週二,星期三|週三,星期四|週四,星期五|週五,星期六|週六',
'units': '毫秒,秒鐘,分鐘,小時,天,個星期|週,個月,年',
'tokens': '日|號',
'short':'{yyyy}年{M}月{d}日',
'long': '{yyyy}年{M}月{d}日 {tt}{h}:{mm}',
'full': '{yyyy}年{M}月{d}日 {Weekday} {tt}{h}:{mm}:{ss}',
'past': '{num}{unit}{sign}',
'future': '{num}{unit}{sign}',
'duration': '{num}{unit}',
'timeSuffixes': '點|時,分鐘?,秒',
'ampm': '上午,下午',
'modifiers': [
{ 'name': 'day', 'src': '前天', 'value': -2 },
{ 'name': 'day', 'src': '昨天', 'value': -1 },
{ 'name': 'day', 'src': '今天', 'value': 0 },
{ 'name': 'day', 'src': '明天', 'value': 1 },
{ 'name': 'day', 'src': '後天', 'value': 2 },
{ 'name': 'sign', 'src': '前', 'value': -1 },
{ 'name': 'sign', 'src': '後', 'value': 1 },
{ 'name': 'shift', 'src': '上|去', 'value': -1 },
{ 'name': 'shift', 'src': '這', 'value': 0 },
{ 'name': 'shift', 'src': '下|明', 'value': 1 }
],
'dateParse': [
'{num}{unit}{sign}',
'{shift}{unit=5-7}'
],
'timeParse': [
'{shift}{weekday}',
'{year}年{month?}月?{date?}{0?}',
'{month}月{date?}{0?}',
'{date}[日號]'
]
});
})(); |
/**
@module ember
@submodule ember-htmlbars
*/
import Ember from 'ember-metal/core';
import { get } from 'ember-metal/property_get';
import updateScope from 'ember-htmlbars/utils/update-scope';
export default function updateSelf(env, scope, _self) {
let self = _self;
if (self && self.hasBoundController) {
let { controller } = self;
self = self.self;
updateScope(scope.locals, 'controller', controller || self);
}
Ember.assert('BUG: scope.attrs and self.isView should not both be true', !(scope.attrs && self.isView));
if (self && self.isView) {
updateScope(scope.locals, 'view', self, null);
updateScope(scope, 'self', get(self, 'context'), null, true);
return;
}
updateScope(scope, 'self', self, null);
}
|
CKEDITOR.plugins.setLang("colorbutton","ru",{auto:"Автоматически",bgColorTitle:"Цвет фона",colors:{"000":"Чёрный",8E5:"Бордовый","8B4513":"Кожано-коричневый","2F4F4F":"Темный синевато-серый","008080":"Сине-зелёный","000080":"Тёмно-синий","4B0082":"Индиго",696969:"Тёмно-серый",B22222:"Кирпичный",A52A2A:"Коричневый",DAA520:"Золотисто-берёзовый","006400":"Темно-зелёный","40E0D0":"Бирюзовый","0000CD":"Умеренно синий",800080:"Пурпурный",808080:"Серый",F00:"Красный",FF8C00:"Темно-оранжевый",FFD700:"Золотистый",
"008000":"Зелёный","0FF":"Васильковый","00F":"Синий",EE82EE:"Фиолетовый",A9A9A9:"Тускло-серый",FFA07A:"Светло-лососевый",FFA500:"Оранжевый",FFFF00:"Жёлтый","00FF00":"Лайма",AFEEEE:"Бледно-синий",ADD8E6:"Свелто-голубой",DDA0DD:"Сливовый",D3D3D3:"Светло-серый",FFF0F5:"Розово-лавандовый",FAEBD7:"Античный белый",FFFFE0:"Светло-жёлтый",F0FFF0:"Медвяной росы",F0FFFF:"Лазурный",F0F8FF:"Бледно-голубой",E6E6FA:"Лавандовый",FFF:"Белый","1ABC9C":"Strong Cyan","2ECC71":"Emerald","3498DB":"Bright Blue","9B59B6":"Amethyst",
"4E5F70":"Grayish Blue",F1C40F:"Vivid Yellow","16A085":"Dark Cyan","27AE60":"Dark Emerald","2980B9":"Strong Blue","8E44AD":"Dark Violet","2C3E50":"Desaturated Blue",F39C12:"Orange",E67E22:"Carrot",E74C3C:"Pale Red",ECF0F1:"Bright Silver","95A5A6":"Light Grayish Cyan",DDD:"Light Gray",D35400:"Pumpkin",C0392B:"Strong Red",BDC3C7:"Silver","7F8C8D":"Grayish Cyan",999:"Dark Gray"},more:"Ещё цвета...",panelTitle:"Цвета",textColorTitle:"Цвет текста"}); |
var env = require('../environment.js'),
q = require('q');
// Make sure that borwser-related plugin hooks work with browser sync on
exports.config = {
seleniumAddress: env.seleniumAddress,
framework: 'jasmine2',
// Spec patterns are relative to this directory.
specs: [
'specs/browser_get_wait_spec.js'
],
capabilities: env.capabilities,
baseUrl: env.baseUrl,
jasmineNodeOpts: {
isVerbose: true,
realtimeFailure: true
},
// Plugin patterns are relative to this directory.
plugins: [{
inline: {
onPageLoad: function() {
return q.delay(5000).then(function() {
protractor.ON_PAGE_LOAD = true;
});
},
onPageStable: function() {
if (protractor.ON_PAGE_LOAD) {
this.addSuccess();
} else {
this.addFailure(
'onPageLoad did not finish before onPageStable began');
}
return q.delay(5000).then(function() {
protractor.ON_PAGE_SYNC = true;
});
},
teardown: function() {
if (protractor.ON_PAGE_SYNC) {
this.addSuccess();
} else {
this.addFailure('onPageStable did not finish before teardown');
}
}
}
}]
};
|
var AbstractFilter = require('./AbstractFilter'),
math = require('../../../math');
// @see https://github.com/substack/brfs/issues/25
var fs = require('fs');
/**
* The SpriteMaskFilter class
*
* @class
* @extends PIXI.AbstractFilter
* @memberof PIXI
* @param sprite {Sprite} the target sprite
*/
function SpriteMaskFilter(sprite)
{
var maskMatrix = new math.Matrix();
AbstractFilter.call(this,
fs.readFileSync(__dirname + '/spriteMaskFilter.vert', 'utf8'),
fs.readFileSync(__dirname + '/spriteMaskFilter.frag', 'utf8'),
{
mask: { type: 'sampler2D', value: sprite._texture },
alpha: { type: 'f', value: 1},
otherMatrix: { type: 'mat3', value: maskMatrix.toArray(true) }
}
);
this.maskSprite = sprite;
this.maskMatrix = maskMatrix;
}
SpriteMaskFilter.prototype = Object.create(AbstractFilter.prototype);
SpriteMaskFilter.prototype.constructor = SpriteMaskFilter;
module.exports = SpriteMaskFilter;
/**
* Applies the filter ? @alvin
*
* @param renderer {WebGLRenderer} A reference to the WebGL renderer
* @param input {RenderTarget}
* @param output {RenderTarget}
*/
SpriteMaskFilter.prototype.applyFilter = function (renderer, input, output)
{
var filterManager = renderer.filterManager;
this.uniforms.mask.value = this.maskSprite._texture;
filterManager.calculateMappedMatrix(input.frame, this.maskSprite, this.maskMatrix);
this.uniforms.otherMatrix.value = this.maskMatrix.toArray(true);
this.uniforms.alpha.value = this.maskSprite.worldAlpha;
var shader = this.getShader(renderer);
// draw the filter...
filterManager.applyFilter(shader, input, output);
};
Object.defineProperties(SpriteMaskFilter.prototype, {
/**
* The texture used for the displacement map. Must be power of 2 sized texture.
*
* @member {Texture}
* @memberof SpriteMaskFilter#
*/
map: {
get: function ()
{
return this.uniforms.mask.value;
},
set: function (value)
{
this.uniforms.mask.value = value;
}
},
/**
* The offset used to move the displacement map.
*
* @member {Point}
* @memberof SpriteMaskFilter#
*/
offset: {
get: function()
{
return this.uniforms.offset.value;
},
set: function(value)
{
this.uniforms.offset.value = value;
}
}
});
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v3.3.2
* @link http://www.ag-grid.com/
* @license MIT
*/
var utils_1 = require('../utils');
var column_1 = require("../entities/column");
var MoveColumnController = (function () {
function MoveColumnController(column, eDraggableElement, eRoot, eHeaderCell, headerRenderer, columnController, dragService, gridPanel, gridOptionsWrapper) {
this.lastDelta = 0;
this.needToMoveLeft = false;
this.needToMoveRight = false;
this.eHeaderCell = eHeaderCell;
this.headerRenderer = headerRenderer;
this.columnController = columnController;
this.column = column;
this.gridPanel = gridPanel;
this.addMovingCssToGrid = !gridOptionsWrapper.isSuppressMovingCss();
this.centreWidth = gridPanel.getCenterWidth();
dragService.addDragHandling({
eDraggableElement: eDraggableElement,
eBody: eRoot,
cursor: 'move',
// we only want to start dragging if the user moves at least 4px, otherwise we will loose
// the ability for the user to click on the cell (eg for sorting)
startAfterPixels: 4,
onDragStart: this.onDragStart.bind(this),
onDragging: this.onDragging.bind(this)
});
}
MoveColumnController.prototype.onDragStart = function (event) {
// the overlay spans all three (left, right, center), so we need to
// pad the floating clone so it appears over the right container
if (this.column.getPinned() === column_1.default.PINNED_LEFT) {
this.floatPadding = 0;
}
else if (this.column.getPinned() === column_1.default.PINNED_RIGHT) {
this.floatPadding = this.headerRenderer.getRightPinnedStartPixel();
}
else {
this.floatPadding = this.columnController.getPinnedLeftContainerWidth();
this.floatPadding -= this.gridPanel.getHorizontalScrollPosition();
}
// make clone of header cell for the 'floating ghost'
this.eFloatingCloneCell = this.eHeaderCell.cloneNode(true);
this.headerRenderer.addChildToOverlay(this.eFloatingCloneCell);
this.startLeftPosition = this.columnController.getPixelsBeforeConsideringPinned(this.column);
utils_1.default.addCssClass(this.eFloatingCloneCell, 'ag-header-cell-moving-clone');
this.eFloatingCloneCell.style.position = 'absolute';
this.eFloatingCloneCell.style.top = 0 + 'px';
this.eFloatingCloneCell.style.left = this.floatPadding + this.startLeftPosition + 'px';
// showing menu while hovering looks ugly, so hide header
var cloneMenu = this.eFloatingCloneCell.querySelector('#agMenu');
if (cloneMenu) {
cloneMenu.style.display = 'none';
}
// see how many pixels to the edge of the column we are
var headerCellLeft = this.eHeaderCell.getBoundingClientRect().left;
this.clickPositionOnHeader = event.clientX - headerCellLeft;
this.column.setMoving(true);
if (this.addMovingCssToGrid) {
this.gridPanel.setMovingCss(true);
}
this.scrollSinceStart = 0;
this.hoveringOverPixelLastTime = this.startLeftPosition + this.clickPositionOnHeader + this.scrollSinceStart;
};
MoveColumnController.prototype.onDragging = function (delta, finished) {
this.eFloatingCloneCell.style.left = this.floatPadding + (this.startLeftPosition + delta) + 'px';
// get current pixel position
var hoveringOverPixel = this.startLeftPosition + this.clickPositionOnHeader + delta + this.scrollSinceStart;
var dragMovingRight = hoveringOverPixel > this.hoveringOverPixelLastTime;
var dragMovingLeft = hoveringOverPixel < this.hoveringOverPixelLastTime;
this.hoveringOverPixelLastTime = hoveringOverPixel;
// the while loop keeps going until there are no more columns to move. this caters for the user
// moving the mouse very fast and we need to swap the column twice or more
var checkForAnotherColumn = true;
while (checkForAnotherColumn) {
var dragOverLeftColumn = this.column.getLeft() > hoveringOverPixel;
var dragOverRightColumn = (this.column.getLeft() + this.column.getActualWidth()) < hoveringOverPixel;
var wantToMoveLeft = dragOverLeftColumn && dragMovingLeft;
var wantToMoveRight = dragOverRightColumn && dragMovingRight;
checkForAnotherColumn = false;
var colToSwapWith = null;
if (wantToMoveLeft) {
colToSwapWith = this.columnController.getDisplayedColBeforeForMoving(this.column);
}
if (wantToMoveRight) {
colToSwapWith = this.columnController.getDisplayedColAfterForMoving(this.column);
}
// if we are a closed group, we need to move all the columns, not just this one
if (colToSwapWith) {
var newIndex = this.columnController.getColumnIndex(colToSwapWith);
// we move one column, UNLESS the column is the only visible column
// of a group, in which case we move the whole group.
var columnsToMove = this.getColumnsAndOrphans(this.column);
this.columnController.moveColumns(columnsToMove.reverse(), newIndex);
checkForAnotherColumn = true;
}
}
// we only look to scroll if the column is not pinned, as pinned columns are always visible
if (!this.column.isPinned()) {
// scroll if the mouse has gone outside the grid (or just outside the scrollable part if pinning)
//var hoveringOverPixelScrollAdjusted = this.startLeftPosition + this.clickPositionOnHeaderScrollAdjusted + delta;
// putting in 50 buffer, so even if user gets to edge of grid, a scroll will happen
var firstVisiblePixel = this.gridPanel.getHorizontalScrollPosition();
var lastVisiblePixel = firstVisiblePixel + this.gridPanel.getCenterWidth();
this.needToMoveLeft = hoveringOverPixel < (firstVisiblePixel + 50);
this.needToMoveRight = hoveringOverPixel > (lastVisiblePixel - 50);
if (this.needToMoveLeft || this.needToMoveRight) {
this.ensureIntervalStarted();
}
else {
this.ensureIntervalCleared();
}
}
if (finished) {
this.column.setMoving(false);
this.headerRenderer.removeChildFromOverlay(this.eFloatingCloneCell);
if (this.addMovingCssToGrid) {
this.gridPanel.setMovingCss(false);
}
this.ensureIntervalCleared();
}
this.lastDelta = delta;
};
MoveColumnController.prototype.ensureIntervalStarted = function () {
if (!this.movingIntervalId) {
this.intervalCount = 0;
this.movingIntervalId = setInterval(this.moveInterval.bind(this), 100);
}
};
MoveColumnController.prototype.ensureIntervalCleared = function () {
if (this.moveInterval) {
clearInterval(this.movingIntervalId);
this.movingIntervalId = null;
}
};
MoveColumnController.prototype.moveInterval = function () {
var pixelsToMove;
this.intervalCount++;
pixelsToMove = 10 + (this.intervalCount * 5);
if (pixelsToMove > 100) {
pixelsToMove = 100;
}
var pixelsMoved = 0;
if (this.needToMoveLeft) {
pixelsMoved = this.gridPanel.scrollHorizontally(-pixelsToMove);
}
else if (this.needToMoveRight) {
pixelsMoved = this.gridPanel.scrollHorizontally(pixelsToMove);
}
this.scrollSinceStart += pixelsMoved;
this.onDragging(this.lastDelta, false);
};
MoveColumnController.prototype.getColumnsAndOrphans = function (column) {
// if this column was to move, how many children would be left without a parent
var pathToChild = this.columnController.getPathForColumn(column);
for (var i = pathToChild.length - 1; i >= 0; i--) {
var columnGroup = pathToChild[i];
var onlyDisplayedChild = columnGroup.getDisplayedChildren().length === 1;
var moreThanOneChild = columnGroup.getChildren().length > 1;
if (onlyDisplayedChild && moreThanOneChild) {
// return total columns below here, not including the column under inspection
var leafColumns = columnGroup.getLeafColumns();
return leafColumns;
}
}
return [column];
};
return MoveColumnController;
})();
exports.MoveColumnController = MoveColumnController;
|
/**
* @author lxxxvi / https://github.com/lxxxvi
* Developed as part of a project at University of Applied Sciences and Arts Northwestern Switzerland (www.fhnw.ch)
*/
QUnit.module( "SetRotationCommand" );
QUnit.test( "Test SetRotationCommand (Undo and Redo)", function( assert ) {
// setup
var editor = new Editor();
var box = aBox();
editor.execute( new AddObjectCommand( box ) );
var rotations = [
{ x: 1.1, y: 0.4, z: - 2.0 },
{ x: 2.2, y: - 1.3, z: 1.3 },
{ x: 0.3, y: - 0.1, z: - 1.9 }
];
rotations.map( function( rotation ) {
var newRotation = new THREE.Euler( rotation.x, rotation.y, rotation.z );
var cmd = new SetRotationCommand( box, newRotation );
cmd.updatable = false;
editor.execute ( cmd );
} );
assert.ok( box.rotation.x == rotations[ rotations.length - 1 ].x, "OK, changing X rotation was successful" );
assert.ok( box.rotation.y == rotations[ rotations.length - 1 ].y, "OK, changing Y rotation was successful" );
assert.ok( box.rotation.z == rotations[ rotations.length - 1 ].z, "OK, changing Z rotation was successful" );
editor.undo();
assert.ok( box.rotation.x == rotations[ rotations.length - 2 ].x, "OK, changing X rotation was successful (after undo)" );
assert.ok( box.rotation.y == rotations[ rotations.length - 2 ].y, "OK, changing Y rotation was successful (after undo)" );
assert.ok( box.rotation.z == rotations[ rotations.length - 2 ].z, "OK, changing Z rotation was successful (after undo)" );
editor.redo();
assert.ok( box.rotation.x == rotations[ rotations.length - 1 ].x, "OK, changing X rotation was successful (after redo)" );
assert.ok( box.rotation.y == rotations[ rotations.length - 1 ].y, "OK, changing Y rotation was successful (after redo)" );
assert.ok( box.rotation.z == rotations[ rotations.length - 1 ].z, "OK, changing Z rotation was successful (after redo)" );
} );
|
import WebpackDevMiddleware from 'webpack-dev-middleware'
import applyExpressMiddleware from '../lib/apply-express-middleware'
import _debug from 'debug'
import config from '../../config'
const paths = config.utils_paths
const debug = _debug('app:server:webpack-dev')
export default function (compiler, publicPath) {
debug('Enable webpack dev middleware.')
const middleware = WebpackDevMiddleware(compiler, {
publicPath,
contentBase: paths.base(config.dir_client),
hot: true,
quiet: config.compiler_quiet,
noInfo: config.compiler_quiet,
lazy: false,
stats: config.compiler_stats
})
return async function koaWebpackDevMiddleware (ctx, next) {
let hasNext = await applyExpressMiddleware(middleware, ctx.req, {
end: (content) => (ctx.body = content),
setHeader: function () {
ctx.set.apply(ctx, arguments)
}
})
if (hasNext) {
await next()
}
}
}
|
'use strict';
var should = require('chai').should();
var fs = require('hexo-fs');
var pathFn = require('path');
var Promise = require('bluebird');
describe('Load plugins', function(){
var Hexo = require('../../../lib/hexo');
var hexo = new Hexo(pathFn.join(__dirname, 'plugin_test'), {silent: true});
var loadPlugins = require('../../../lib/hexo/load_plugins');
var script = [
'hexo._script_test = {',
' filename: __filename,',
' dirname: __dirname,',
' module: module,',
' require: require',
'}'
].join('\n');
function validate(path){
var result = hexo._script_test;
result.filename.should.eql(path);
result.dirname.should.eql(pathFn.dirname(path));
result.module.id.should.eql(path);
result.module.filename.should.eql(path);
delete hexo._script_test;
}
function createPackageFile(){
var pkg = {
name: 'hexo-site',
version: '0.0.0',
private: true,
dependencies: {}
};
for (var i = 0, len = arguments.length; i < len; i++){
pkg.dependencies[arguments[i]] = '*';
}
return fs.writeFile(pathFn.join(hexo.base_dir, 'package.json'), JSON.stringify(pkg, null, ' '));
}
hexo.env.init = true;
hexo.theme_script_dir = pathFn.join(hexo.base_dir, 'themes', 'test', 'scripts');
before(function(){
return fs.mkdir(hexo.base_dir);
});
after(function(){
return fs.rmdir(hexo.base_dir);
});
it('load plugins', function(){
var name = 'hexo-plugin-test';
var path = pathFn.join(hexo.plugin_dir, name, 'index.js');
return Promise.all([
createPackageFile(name),
fs.writeFile(path, script)
]).then(function(){
return loadPlugins(hexo);
}).then(function(){
validate(path);
return fs.unlink(path);
});
});
it('ignore plugins whose name is not started with "hexo-"', function(){
var script = 'hexo._script_test = true';
var name = 'another-plugin';
var path = pathFn.join(hexo.plugin_dir, name, 'index.js');
return Promise.all([
createPackageFile(name),
fs.writeFile(path, script)
]).then(function(){
return loadPlugins(hexo);
}).then(function(){
should.not.exist(hexo._script_test);
return fs.unlink(path);
});
});
it('ignore plugins which are in package.json but not exist actually', function(){
return createPackageFile('hexo-plugin-test').then(function(){
return loadPlugins(hexo);
});
});
it('load scripts', function(){
var path = pathFn.join(hexo.script_dir, 'test.js');
return fs.writeFile(path, script).then(function(){
return loadPlugins(hexo);
}).then(function(){
validate(path);
return fs.unlink(path);
});
});
it('load theme scripts', function(){
var path = pathFn.join(hexo.theme_script_dir, 'test.js');
return fs.writeFile(path, script).then(function(){
return loadPlugins(hexo);
}).then(function(){
validate(path);
return fs.unlink(path);
});
});
it('don\'t load plugins in safe mode', function(){
var script = 'hexo._script_test = true';
var path = pathFn.join(hexo.script_dir, 'test.js');
return fs.writeFile(path, script).then(function(){
hexo.env.safe = true;
return loadPlugins(hexo);
}).then(function(){
hexo.env.safe = false;
should.not.exist(hexo._script_test);
return fs.unlink(path);
});
});
}); |
module.exports={title:"KTM",slug:"ktm",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>KTM icon</title><path d="M0 15.735h3.354l.843-2.06 1.55 2.06h7.225l2.234-2.081-.372 2.081h2.83L20 13.675l-.32 2.06h3.052L24 9.99h-3.068l-2.486 2.191.48-2.19h-2.942l-3.209 3.216 1.342-3.938h4.907l.225-1.003H6.381l-.378 1.003h4.732l-1.994 5.054-1.572-2.066L9.886 9.99H7.612l-2.787 2.23.938-2.23H2.44L0 15.735Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://ktm.com",hex:"FF6600"}; |
/*
* /MathJax/localization/fi/fi.js
*
* Copyright (c) 2009-2015 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("fi",null,{menuTitle:"suomi",version:"2.5.0",isLoaded:true,domains:{_:{version:"2.5.0",isLoaded:true,strings:{CookieConfig:"MathJax on l\u00F6yt\u00E4nyt ev\u00E4steen, joka sis\u00E4lt\u00E4\u00E4 asetuksia ja ohjelmakoodia. Haluatko ajaa sen?\n\n(Peru, ellet ole luonut ev\u00E4stett\u00E4 itse.)",MathProcessingError:"Matematiikan k\u00E4sittely ep\u00E4onnistui",MathError:"Matematiikkavirhe",LoadFile:"Ladataan tiedostoa %1",Loading:"Ladataan",LoadFailed:"Tiedoston %1 lataaminen ep\u00E4onnistui",ProcessMath:"K\u00E4sitell\u00E4\u00E4n matematiikkaa: %1%%",Processing:"K\u00E4sitell\u00E4\u00E4n",TypesetMath:"Ladotaan matematiikkaa: %1%%",Typesetting:"Ladotaan",MathJaxNotSupported:"Selaimesi ei tue MathJaxia"}},FontWarnings:{},"HTML-CSS":{},HelpDialog:{},MathML:{},MathMenu:{},TeX:{}},plural:function(a){if(a===1){return 1}return 2},number:function(a){return a}});MathJax.Ajax.loadComplete("[MathJax]/localization/fi/fi.js");
|
/**
* Dimensions.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This module measures nodes and returns client rects. The client rects has an
* extra node property.
*
* @private
* @class tinymce.dom.Dimensions
*/
define("tinymce/dom/Dimensions", [
"tinymce/util/Arr",
"tinymce/dom/NodeType",
"tinymce/geom/ClientRect"
], function(Arr, NodeType, ClientRect) {
function getClientRects(node) {
function toArrayWithNode(clientRects) {
return Arr.map(clientRects, function(clientRect) {
clientRect = ClientRect.clone(clientRect);
clientRect.node = node;
return clientRect;
});
}
if (Arr.isArray(node)) {
return Arr.reduce(node, function(result, node) {
return result.concat(getClientRects(node));
}, []);
}
if (NodeType.isElement(node)) {
return toArrayWithNode(node.getClientRects());
}
if (NodeType.isText(node)) {
var rng = node.ownerDocument.createRange();
rng.setStart(node, 0);
rng.setEnd(node, node.data.length);
return toArrayWithNode(rng.getClientRects());
}
}
return {
/**
* Returns the client rects for a specific node.
*
* @method getClientRects
* @param {Array/DOMNode} node Node or array of nodes to get client rects on.
* @param {Array} Array of client rects with a extra node property.
*/
getClientRects: getClientRects
};
}); |
(function() {
var errorMessage = "You have modified configuration";
var needToConfirm = false;
function confirm() {
needToConfirm = true;
}
function clearConfirm() {
needToConfirm = false;
}
function confirmExit() {
if (needToConfirm) {
return errorMessage;
}
}
function isModifyingButton(btn) {
// TODO don't consider hetero list 'add' buttons
// needs to handle the yui menus instead
// if (btn.classList.contains("hetero-list-add")) {
// return false;
// }
if (btn.parentNode.parentNode.classList.contains("advanced-button")) {
// don't consider 'advanced' buttons
return false;
}
// default to true
return true;
}
function initConfirm() {
// Timeout is needed since some events get sent on page load for some reason.
// Shouldn't hurt anything for this to only start monitoring events after a few millis;.
setTimeout(function() {
var configForm = document.getElementsByName("config");
if (configForm.length > 0) {
configForm = configForm[0]
} else {
configForm = document.getElementsByName("viewConfig")[0];
}
YAHOO.util.Event.on($(configForm), "submit", clearConfirm, this);
var buttons = configForm.getElementsByTagName("button");
var name;
for ( var i = 0; i < buttons.length; i++) {
name = buttons[i].parentNode.parentNode.getAttribute('name');
if (name == "Submit" || name == "Apply" || name == "OK") {
$(buttons[i]).on('click', function() {
needToConfirm = false;
});
} else {
if (isModifyingButton(buttons[i])) {
$(buttons[i]).on('click', confirm);
}
}
}
var inputs = configForm.getElementsByTagName("input");
for ( var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox' || inputs[i].type == 'radio') {
$(inputs[i]).on('click', confirm);
} else {
$(inputs[i]).on('input', confirm);
}
}
inputs = configForm.getElementsByTagName("select");
for ( var i = 0; i < inputs.length; i++) {
$(inputs[i]).on('change', confirm);
}
inputs = configForm.getElementsByTagName("textarea");
for ( var i = 0; i < inputs.length; i++) {
$(inputs[i]).on('input', confirm);
}
}, 100);
}
window.onbeforeunload = confirmExit;
Event.on(window,'load', initConfirm);
})();
|
/*! jquery.atwho - v0.4.9 - 2014-04-12
* Copyright (c) 2014 chord.luo <chord.luo@gmail.com>;
* homepage: http://ichord.github.com/At.js
* Licensed MIT
*/
(function() {
(function(factory) {
if (typeof define === 'function' && define.amd) {
return define(['jquery'], factory);
} else {
return factory(window.jQuery);
}
})(function($) {
var $CONTAINER, Api, App, Atwho, Controller, DEFAULT_CALLBACKS, KEY_CODE, Model, View,
__slice = [].slice;
App = (function() {
function App(inputor) {
this.current_flag = null;
this.controllers = {};
this.alias_maps = {};
this.$inputor = $(inputor);
this.iframe = null;
this.setIframe();
this.listen();
}
App.prototype.setIframe = function(iframe) {
var error;
if (iframe) {
this.window = iframe.contentWindow;
this.document = iframe.contentDocument || this.window.document;
this.iframe = iframe;
return this;
} else {
this.document = this.$inputor[0].ownerDocument;
this.window = this.document.defaultView || this.document.parentWindow;
try {
return this.iframe = this.window.frameElement;
} catch (_error) {
error = _error;
}
}
};
App.prototype.controller = function(at) {
return this.controllers[this.alias_maps[at] || at || this.current_flag];
};
App.prototype.set_context_for = function(at) {
this.current_flag = at;
return this;
};
App.prototype.reg = function(flag, setting) {
var controller, _base;
controller = (_base = this.controllers)[flag] || (_base[flag] = new Controller(this, flag));
if (setting.alias) {
this.alias_maps[setting.alias] = flag;
}
controller.init(setting);
return this;
};
App.prototype.listen = function() {
return this.$inputor.on('keyup.atwhoInner', (function(_this) {
return function(e) {
return _this.on_keyup(e);
};
})(this)).on('keydown.atwhoInner', (function(_this) {
return function(e) {
return _this.on_keydown(e);
};
})(this)).on('scroll.atwhoInner', (function(_this) {
return function(e) {
var _ref;
return (_ref = _this.controller()) != null ? _ref.view.hide() : void 0;
};
})(this)).on('blur.atwhoInner', (function(_this) {
return function(e) {
var c;
if (c = _this.controller()) {
return c.view.hide(c.get_opt("display_timeout"));
}
};
})(this));
};
App.prototype.shutdown = function() {
var c, _, _ref;
_ref = this.controllers;
for (_ in _ref) {
c = _ref[_];
c.destroy();
delete this.controllers[_];
}
return this.$inputor.off('.atwhoInner');
};
App.prototype.dispatch = function() {
return $.map(this.controllers, (function(_this) {
return function(c) {
if (c.look_up()) {
return _this.set_context_for(c.at);
}
};
})(this));
};
App.prototype.on_keyup = function(e) {
var _ref;
switch (e.keyCode) {
case KEY_CODE.ESC:
e.preventDefault();
if ((_ref = this.controller()) != null) {
_ref.view.hide();
}
break;
case KEY_CODE.DOWN:
case KEY_CODE.UP:
case KEY_CODE.CTRL:
$.noop();
break;
case KEY_CODE.P:
case KEY_CODE.N:
if (!e.ctrlKey) {
this.dispatch();
}
break;
default:
this.dispatch();
}
};
App.prototype.on_keydown = function(e) {
var view, _ref;
view = (_ref = this.controller()) != null ? _ref.view : void 0;
if (!(view && view.visible())) {
return;
}
switch (e.keyCode) {
case KEY_CODE.ESC:
e.preventDefault();
view.hide();
break;
case KEY_CODE.UP:
e.preventDefault();
view.prev();
break;
case KEY_CODE.DOWN:
e.preventDefault();
view.next();
break;
case KEY_CODE.P:
if (!e.ctrlKey) {
return;
}
e.preventDefault();
view.prev();
break;
case KEY_CODE.N:
if (!e.ctrlKey) {
return;
}
e.preventDefault();
view.next();
break;
case KEY_CODE.TAB:
case KEY_CODE.ENTER:
if (!view.visible()) {
return;
}
e.preventDefault();
view.choose();
break;
default:
$.noop();
}
};
return App;
})();
Controller = (function() {
Controller.prototype.uid = function() {
return (Math.random().toString(16) + "000000000").substr(2, 8) + (new Date().getTime());
};
function Controller(app, at) {
this.app = app;
this.at = at;
this.$inputor = this.app.$inputor;
this.id = this.$inputor[0].id || this.uid();
this.setting = null;
this.query = null;
this.pos = 0;
this.cur_rect = null;
this.range = null;
$CONTAINER.append(this.$el = $("<div id='atwho-ground-" + this.id + "'></div>"));
this.model = new Model(this);
this.view = new View(this);
}
Controller.prototype.init = function(setting) {
this.setting = $.extend({}, this.setting || $.fn.atwho["default"], setting);
this.view.init();
return this.model.reload(this.setting.data);
};
Controller.prototype.destroy = function() {
this.trigger('beforeDestroy');
this.model.destroy();
this.view.destroy();
return this.$el.remove();
};
Controller.prototype.call_default = function() {
var args, error, func_name;
func_name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
try {
return DEFAULT_CALLBACKS[func_name].apply(this, args);
} catch (_error) {
error = _error;
return $.error("" + error + " Or maybe At.js doesn't have function " + func_name);
}
};
Controller.prototype.trigger = function(name, data) {
var alias, event_name;
if (data == null) {
data = [];
}
data.push(this);
alias = this.get_opt('alias');
event_name = alias ? "" + name + "-" + alias + ".atwho" : "" + name + ".atwho";
return this.$inputor.trigger(event_name, data);
};
Controller.prototype.callbacks = function(func_name) {
return this.get_opt("callbacks")[func_name] || DEFAULT_CALLBACKS[func_name];
};
Controller.prototype.get_opt = function(at, default_value) {
var e;
try {
return this.setting[at];
} catch (_error) {
e = _error;
return null;
}
};
Controller.prototype.content = function() {
if (this.$inputor.is('textarea, input')) {
return this.$inputor.val();
} else {
return this.$inputor.text();
}
};
Controller.prototype.catch_query = function() {
var caret_pos, content, end, query, start, subtext;
content = this.content();
caret_pos = this.$inputor.caret('pos');
subtext = content.slice(0, caret_pos);
query = this.callbacks("matcher").call(this, this.at, subtext, this.get_opt('start_with_space'));
if (typeof query === "string" && query.length <= this.get_opt('max_len', 20)) {
start = caret_pos - query.length;
end = start + query.length;
this.pos = start;
query = {
'text': query,
'head_pos': start,
'end_pos': end
};
this.trigger("matched", [this.at, query.text]);
} else {
this.view.hide();
}
return this.query = query;
};
Controller.prototype.rect = function() {
var c, scale_bottom;
if (!(c = this.$inputor.caret({
iframe: this.app.iframe
}).caret('offset', this.pos - 1))) {
return;
}
if (this.$inputor.attr('contentEditable') === 'true') {
c = (this.cur_rect || (this.cur_rect = c)) || c;
}
scale_bottom = this.app.document.selection ? 0 : 2;
return {
left: c.left,
top: c.top,
bottom: c.top + c.height + scale_bottom
};
};
Controller.prototype.reset_rect = function() {
if (this.$inputor.attr('contentEditable') === 'true') {
return this.cur_rect = null;
}
};
Controller.prototype.mark_range = function() {
if (this.$inputor.attr('contentEditable') === 'true') {
if (this.app.window.getSelection) {
this.range = this.app.window.getSelection().getRangeAt(0);
}
if (this.app.document.selection) {
return this.ie8_range = this.app.document.selection.createRange();
}
}
};
Controller.prototype.insert_content_for = function($li) {
var data, data_value, tpl;
data_value = $li.data('value');
tpl = this.get_opt('insert_tpl');
if (this.$inputor.is('textarea, input') || !tpl) {
return data_value;
}
data = $.extend({}, $li.data('item-data'), {
'atwho-data-value': data_value,
'atwho-at': this.at
});
return this.callbacks("tpl_eval").call(this, tpl, data);
};
Controller.prototype.insert = function(content, $li) {
var $inputor, $insert_node, class_name, content_node, insert_node, pos, range, sel, source, start_str, text;
$inputor = this.$inputor;
if ($inputor.attr('contentEditable') === 'true') {
class_name = "atwho-view-flag atwho-view-flag-" + (this.get_opt('alias') || this.at);
content_node = "" + content + "<span contenteditable='false'> <span>";
insert_node = "<span contenteditable='false' class='" + class_name + "'>" + content_node + "</span>";
$insert_node = $(insert_node, this.app.document).data('atwho-data-item', $li.data('item-data'));
if (this.app.document.selection) {
$insert_node = $("<span contenteditable='true'></span>", this.app.document).html($insert_node);
}
}
if ($inputor.is('textarea, input')) {
content = '' + content;
source = $inputor.val();
start_str = source.slice(0, Math.max(this.query.head_pos - this.at.length, 0));
text = "" + start_str + content + " " + (source.slice(this.query['end_pos'] || 0));
$inputor.val(text);
$inputor.caret('pos', start_str.length + content.length + 1);
} else if (range = this.range) {
pos = range.startOffset - (this.query.end_pos - this.query.head_pos) - this.at.length;
range.setStart(range.endContainer, Math.max(pos, 0));
range.setEnd(range.endContainer, range.endOffset);
range.deleteContents();
range.insertNode($insert_node[0]);
range.collapse(false);
sel = this.app.window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (range = this.ie8_range) {
range.moveStart('character', this.query.end_pos - this.query.head_pos - this.at.length);
range.pasteHTML(content_node);
range.collapse(false);
range.select();
}
if (!$inputor.is(':focus')) {
$inputor.focus();
}
return $inputor.change();
};
Controller.prototype.render_view = function(data) {
var search_key;
search_key = this.get_opt("search_key");
data = this.callbacks("sorter").call(this, this.query.text, data.slice(0, 1001), search_key);
return this.view.render(data.slice(0, this.get_opt('limit')));
};
Controller.prototype.look_up = function() {
var query, _callback;
if (!(query = this.catch_query())) {
return;
}
_callback = function(data) {
if (data && data.length > 0) {
return this.render_view(data);
} else {
return this.view.hide();
}
};
this.model.query(query.text, $.proxy(_callback, this));
return query;
};
return Controller;
})();
Model = (function() {
function Model(context) {
this.context = context;
this.at = this.context.at;
this.storage = this.context.$inputor;
}
Model.prototype.destroy = function() {
return this.storage.data(this.at, null);
};
Model.prototype.saved = function() {
return this.fetch() > 0;
};
Model.prototype.query = function(query, callback) {
var data, search_key, _remote_filter;
data = this.fetch();
search_key = this.context.get_opt("search_key");
data = this.context.callbacks('filter').call(this.context, query, data, search_key) || [];
_remote_filter = this.context.callbacks('remote_filter');
if (data.length > 0 || (!_remote_filter && data.length === 0)) {
return callback(data);
} else {
return _remote_filter.call(this.context, query, callback);
}
};
Model.prototype.fetch = function() {
return this.storage.data(this.at) || [];
};
Model.prototype.save = function(data) {
return this.storage.data(this.at, this.context.callbacks("before_save").call(this.context, data || []));
};
Model.prototype.load = function(data) {
if (!(this.saved() || !data)) {
return this._load(data);
}
};
Model.prototype.reload = function(data) {
return this._load(data);
};
Model.prototype._load = function(data) {
if (typeof data === "string") {
return $.ajax(data, {
dataType: "json"
}).done((function(_this) {
return function(data) {
return _this.save(data);
};
})(this));
} else {
return this.save(data);
}
};
return Model;
})();
View = (function() {
function View(context) {
this.context = context;
this.$el = $("<div class='atwho-view'><ul class='atwho-view-ul'></ul></div>");
this.timeout_id = null;
this.context.$el.append(this.$el);
this.bind_event();
}
View.prototype.init = function() {
var id;
id = this.context.get_opt("alias") || this.context.at.charCodeAt(0);
return this.$el.attr({
'id': "at-view-" + id
});
};
View.prototype.destroy = function() {
return this.$el.remove();
};
View.prototype.bind_event = function() {
var $menu;
$menu = this.$el.find('ul');
return $menu.on('mouseenter.atwho-view', 'li', function(e) {
$menu.find('.cur').removeClass('cur');
return $(e.currentTarget).addClass('cur');
}).on('click', (function(_this) {
return function(e) {
_this.choose();
return e.preventDefault();
};
})(this));
};
View.prototype.visible = function() {
return this.$el.is(":visible");
};
View.prototype.choose = function() {
var $li, content;
if (($li = this.$el.find(".cur")).length) {
content = this.context.insert_content_for($li);
this.context.insert(this.context.callbacks("before_insert").call(this.context, content, $li), $li);
this.context.trigger("inserted", [$li]);
return this.hide();
}
};
View.prototype.reposition = function(rect) {
var offset, _ref;
if (rect.bottom + this.$el.height() - $(window).scrollTop() > $(window).height()) {
rect.bottom = rect.top - this.$el.height();
}
offset = {
left: rect.left,
top: rect.bottom
};
if ((_ref = this.context.callbacks("before_reposition")) != null) {
_ref.call(this.context, offset);
}
this.$el.offset(offset);
return this.context.trigger("reposition", [offset]);
};
View.prototype.next = function() {
var cur, next;
cur = this.$el.find('.cur').removeClass('cur');
next = cur.next();
if (!next.length) {
next = this.$el.find('li:first');
}
return next.addClass('cur');
};
View.prototype.prev = function() {
var cur, prev;
cur = this.$el.find('.cur').removeClass('cur');
prev = cur.prev();
if (!prev.length) {
prev = this.$el.find('li:last');
}
return prev.addClass('cur');
};
View.prototype.show = function() {
var rect;
this.context.mark_range();
if (!this.visible()) {
this.$el.show();
this.context.trigger('shown');
}
if (rect = this.context.rect()) {
return this.reposition(rect);
}
};
View.prototype.hide = function(time) {
var callback;
if (isNaN(time && this.visible())) {
this.context.reset_rect();
this.$el.hide();
return this.context.trigger('hidden');
} else {
callback = (function(_this) {
return function() {
return _this.hide();
};
})(this);
clearTimeout(this.timeout_id);
return this.timeout_id = setTimeout(callback, time);
}
};
View.prototype.render = function(list) {
var $li, $ul, item, li, tpl, _i, _len;
if (!($.isArray(list) && list.length > 0)) {
this.hide();
return;
}
this.$el.find('ul').empty();
$ul = this.$el.find('ul');
tpl = this.context.get_opt('tpl');
for (_i = 0, _len = list.length; _i < _len; _i++) {
item = list[_i];
item = $.extend({}, item, {
'atwho-at': this.context.at
});
li = this.context.callbacks("tpl_eval").call(this.context, tpl, item);
$li = $(this.context.callbacks("highlighter").call(this.context, li, this.context.query.text));
$li.data("item-data", item);
$ul.append($li);
}
this.show();
if (this.context.get_opt('highlight_first')) {
return $ul.find("li:first").addClass("cur");
}
};
return View;
})();
KEY_CODE = {
DOWN: 40,
UP: 38,
ESC: 27,
TAB: 9,
ENTER: 13,
CTRL: 17,
P: 80,
N: 78
};
DEFAULT_CALLBACKS = {
before_save: function(data) {
var item, _i, _len, _results;
if (!$.isArray(data)) {
return data;
}
_results = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
item = data[_i];
if ($.isPlainObject(item)) {
_results.push(item);
} else {
_results.push({
name: item
});
}
}
return _results;
},
matcher: function(flag, subtext, should_start_with_space) {
var match, regexp;
flag = flag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
if (should_start_with_space) {
flag = '(?:^|\\s)' + flag;
}
regexp = new RegExp(flag + '([A-Za-z0-9_\+\-]*)$|' + flag + '([^\\x00-\\xff]*)$', 'gi');
match = regexp.exec(subtext);
if (match) {
return match[2] || match[1];
} else {
return null;
}
},
filter: function(query, data, search_key) {
var item, _i, _len, _results;
_results = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
item = data[_i];
if (~item[search_key].toLowerCase().indexOf(query.toLowerCase())) {
_results.push(item);
}
}
return _results;
},
remote_filter: null,
sorter: function(query, items, search_key) {
var item, _i, _len, _results;
if (!query) {
return items;
}
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
item.atwho_order = item[search_key].toLowerCase().indexOf(query.toLowerCase());
if (item.atwho_order > -1) {
_results.push(item);
}
}
return _results.sort(function(a, b) {
return a.atwho_order - b.atwho_order;
});
},
tpl_eval: function(tpl, map) {
var error;
try {
return tpl.replace(/\$\{([^\}]*)\}/g, function(tag, key, pos) {
return map[key];
});
} catch (_error) {
error = _error;
return "";
}
},
highlighter: function(li, query) {
var regexp;
if (!query) {
return li;
}
regexp = new RegExp(">\\s*(\\w*)(" + query.replace("+", "\\+") + ")(\\w*)\\s*<", 'ig');
return li.replace(regexp, function(str, $1, $2, $3) {
return '> ' + $1 + '<strong>' + $2 + '</strong>' + $3 + ' <';
});
},
before_insert: function(value, $li) {
return value;
}
};
Api = {
load: function(at, data) {
var c;
if (c = this.controller(at)) {
return c.model.load(data);
}
},
getInsertedItemsWithIDs: function(at) {
var c, ids, items;
if (!(c = this.controller(at))) {
return [null, null];
}
if (at) {
at = "-" + (c.get_opt('alias') || c.at);
}
ids = [];
items = $.map(this.$inputor.find("span.atwho-view-flag" + (at || "")), function(item) {
var data;
data = $(item).data('atwho-data-item');
if (ids.indexOf(data.id) > -1) {
return;
}
if (data.id) {
ids.push = data.id;
}
return data;
});
return [ids, items];
},
getInsertedItems: function(at) {
return Api.getInsertedItemsWithIDs.apply(this, [at])[1];
},
getInsertedIDs: function(at) {
return Api.getInsertedItemsWithIDs.apply(this, [at])[0];
},
setIframe: function(iframe) {
return this.setIframe(iframe);
},
run: function() {
return this.dispatch();
},
destroy: function() {
this.shutdown();
return this.$inputor.data('atwho', null);
}
};
Atwho = {
init: function(options) {
var $this, app;
app = ($this = $(this)).data("atwho");
if (!app) {
$this.data('atwho', (app = new App(this)));
}
app.reg(options.at, options);
return this;
}
};
$CONTAINER = $("<div id='atwho-container'></div>");
$.fn.atwho = function(method) {
var result, _args;
_args = arguments;
$('body').append($CONTAINER);
result = null;
this.filter('textarea, input, [contenteditable=true]').each(function() {
var app;
if (typeof method === 'object' || !method) {
return Atwho.init.apply(this, _args);
} else if (Api[method]) {
if (app = $(this).data('atwho')) {
return result = Api[method].apply(app, Array.prototype.slice.call(_args, 1));
}
} else {
return $.error("Method " + method + " does not exist on jQuery.caret");
}
});
return result || this;
};
$.fn.atwho["default"] = {
at: void 0,
alias: void 0,
data: null,
tpl: "<li data-value='${atwho-at}${name}'>${name}</li>",
insert_tpl: "<span>${atwho-data-value}</span>",
callbacks: DEFAULT_CALLBACKS,
search_key: "name",
start_with_space: true,
highlight_first: true,
limit: 5,
max_len: 20,
display_timeout: 300
};
});
}).call(this);
|
/*jshint node:true*/
module.exports = function(grunt) {
"use strict";
var banner,
umdStart,
umdMiddle,
umdEnd,
umdStandardDefine,
umdAdditionalDefine,
umdLocalizationDefine;
banner = "/*!\n" +
" * jQuery Validation Plugin v<%= pkg.version %>\n" +
" *\n" +
" * <%= pkg.homepage %>\n" +
" *\n" +
" * Copyright (c) <%= grunt.template.today('yyyy') %> <%= pkg.author.name %>\n" +
" * Released under the <%= _.pluck(pkg.licenses, 'type').join(', ') %> license\n" +
" */\n";
// define UMD wrapper variables
umdStart = "(function( factory ) {\n" +
"\tif ( typeof define === \"function\" && define.amd ) {\n";
umdMiddle = "\t} else {\n" +
"\t\tfactory( jQuery );\n" +
"\t}\n" +
"}(function( $ ) {\n\n";
umdEnd = "\n}));";
umdStandardDefine = "\t\tdefine( [\"jquery\"], factory );\n";
umdAdditionalDefine = "\t\tdefine( [\"jquery\", \"./jquery.validate\"], factory );\n";
umdLocalizationDefine = "\t\tdefine( [\"jquery\", \"../jquery.validate\"], factory );\n";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
concat: {
// used to copy to dist folder
dist: {
options: {
banner: banner +
umdStart +
umdStandardDefine +
umdMiddle,
footer: umdEnd
},
files: {
"dist/jquery.validate.js": [ "src/core.js", "src/*.js" ]
}
},
extra: {
options: {
banner: banner +
umdStart +
umdAdditionalDefine +
umdMiddle,
footer: umdEnd
},
files: {
"dist/additional-methods.js": [ "src/additional/additional.js", "src/additional/*.js" ]
}
}
},
uglify: {
options: {
preserveComments: false,
banner: "/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - " +
"<%= grunt.template.today('m/d/yyyy') %>\n" +
" * <%= pkg.homepage %>\n" +
" * Copyright (c) <%= grunt.template.today('yyyy') %> <%= pkg.author.name %>;" +
" Licensed <%= _.pluck(pkg.licenses, 'type').join(', ') %> */\n"
},
dist: {
files: {
"dist/additional-methods.min.js": "dist/additional-methods.js",
"dist/jquery.validate.min.js": "dist/jquery.validate.js"
}
},
all: {
expand: true,
cwd: "dist/localization",
src: "**/*.js",
dest: "dist/localization",
ext: ".min.js"
}
},
compress: {
dist: {
options: {
mode: "zip",
level: 1,
archive: "dist/<%= pkg.name %>-<%= pkg.version %>.zip",
pretty: true
},
src: [
"changelog.txt",
"demo/**/*.*",
"dist/**/*.js",
"Gruntfile.js",
"lib/**/*.*",
"package.json",
"README.md",
"src/**/*.*",
"test/**/*.*"
]
}
},
qunit: {
files: "test/index.html"
},
jshint: {
options: {
jshintrc: true
},
core: {
src: "src/**/*.js"
},
test: {
src: "test/*.js"
},
grunt: {
src: "Gruntfile.js"
}
},
watch: {
options: {
atBegin: true
},
src: {
files: "<%= jshint.core.src %>",
tasks: [
"concat"
]
}
},
jscs: {
all: [ "<%= jshint.core.src %>", "<%= jshint.test.src %>", "<%= jshint.grunt.src %>" ]
},
copy: {
dist: {
options: {
// append UMD wrapper
process: function( content ) {
return umdStart + umdLocalizationDefine + umdMiddle + content + umdEnd;
}
},
src: "src/localization/*",
dest: "dist/localization",
expand: true,
flatten: true,
filter: "isFile"
}
},
replace: {
dist: {
src: "dist/**/*.min.js",
overwrite: true,
replacements: [
{
from: "./jquery.validate",
to: "./jquery.validate.min"
}
]
}
}
});
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-qunit");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-compress");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-jscs");
grunt.loadNpmTasks("grunt-contrib-copy");
grunt.loadNpmTasks("grunt-text-replace");
grunt.registerTask("default", [ "concat", "copy", "jscs", "jshint", "qunit" ]);
grunt.registerTask("release", [ "default", "uglify", "replace", "compress" ]);
grunt.registerTask("start", [ "concat", "watch" ]);
};
|
var moment = require('../../moment');
/**************************************************
English
*************************************************/
exports['locale:en'] = {
setUp : function (cb) {
moment.locale('en');
moment.createFromInputFallback = function () {
throw new Error('input not handled by moment');
};
cb();
},
tearDown : function (cb) {
moment.locale('en');
cb();
},
'parse' : function (test) {
var i,
tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_');
function equalTest(input, mmm, i) {
test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
}
for (i = 0; i < 12; i++) {
tests[i] = tests[i].split(' ');
equalTest(tests[i][0], 'MMM', i);
equalTest(tests[i][1], 'MMM', i);
equalTest(tests[i][0], 'MMMM', i);
equalTest(tests[i][1], 'MMMM', i);
equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
}
test.done();
},
'format' : function (test) {
var a = [
['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'],
['ddd, hA', 'Sun, 3PM'],
['M Mo MM MMMM MMM', '2 2nd 02 February Feb'],
['YYYY YY', '2010 10'],
['D Do DD', '14 14th 14'],
['d do dddd ddd dd', '0 0th Sunday Sun Su'],
['DDD DDDo DDDD', '45 45th 045'],
['w wo ww', '8 8th 08'],
['h hh', '3 03'],
['H HH', '15 15'],
['m mm', '25 25'],
['s ss', '50 50'],
['a A', 'pm PM'],
['[the] DDDo [day of the year]', 'the 45th day of the year'],
['L', '02/14/2010'],
['LL', 'February 14, 2010'],
['LLL', 'February 14, 2010 3:25 PM'],
['LLLL', 'Sunday, February 14, 2010 3:25 PM'],
['l', '2/14/2010'],
['ll', 'Feb 14, 2010'],
['lll', 'Feb 14, 2010 3:25 PM'],
['llll', 'Sun, Feb 14, 2010 3:25 PM']
],
b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
i;
for (i = 0; i < a.length; i++) {
test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
}
test.done();
},
'format ordinal' : function (test) {
test.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st');
test.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd');
test.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd');
test.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th');
test.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th');
test.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th');
test.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th');
test.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th');
test.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th');
test.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th');
test.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th');
test.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th');
test.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th');
test.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th');
test.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th');
test.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th');
test.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th');
test.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th');
test.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th');
test.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th');
test.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st');
test.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd');
test.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd');
test.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th');
test.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th');
test.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th');
test.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th');
test.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th');
test.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th');
test.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th');
test.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st');
test.done();
},
'format month' : function (test) {
var i,
expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_');
for (i = 0; i < expected.length; i++) {
test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
}
test.done();
},
'format week' : function (test) {
var i,
expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split('_');
for (i = 0; i < expected.length; i++) {
test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
}
test.done();
},
'from' : function (test) {
var start = moment([2007, 1, 28]);
test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'a few seconds', '44 seconds = a few seconds');
test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'a minute', '45 seconds = a minute');
test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'a minute', '89 seconds = a minute');
test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes');
test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes');
test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'an hour', '45 minutes = an hour');
test.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'an hour', '89 minutes = an hour');
test.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hours', '90 minutes = 2 hours');
test.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hours', '5 hours = 5 hours');
test.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hours', '21 hours = 21 hours');
test.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'a day', '22 hours = a day');
test.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'a day', '35 hours = a day');
test.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 days', '36 hours = 2 days');
test.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'a day', '1 day = a day');
test.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 days', '5 days = 5 days');
test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 days', '25 days = 25 days');
test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'a month', '26 days = a month');
test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'a month', '30 days = a month');
test.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'a month', '43 days = a month');
test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 months', '46 days = 2 months');
test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 months', '75 days = 2 months');
test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 months', '76 days = 3 months');
test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'a month', '1 month = a month');
test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 months', '5 months = 5 months');
test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'a year', '345 days = a year');
test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 years', '548 days = 2 years');
test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'a year', '1 year = a year');
test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 years', '5 years = 5 years');
test.done();
},
'suffix' : function (test) {
test.equal(moment(30000).from(0), 'in a few seconds', 'prefix');
test.equal(moment(0).from(30000), 'a few seconds ago', 'suffix');
test.done();
},
'now from now' : function (test) {
test.equal(moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past');
test.done();
},
'fromNow' : function (test) {
test.equal(moment().add({s: 30}).fromNow(), 'in a few seconds', 'in a few seconds');
test.equal(moment().add({d: 5}).fromNow(), 'in 5 days', 'in 5 days');
test.done();
},
'calendar day' : function (test) {
var a = moment().hours(2).minutes(0).seconds(0);
test.equal(moment(a).calendar(), 'Today at 2:00 AM', 'today at the same time');
test.equal(moment(a).add({m: 25}).calendar(), 'Today at 2:25 AM', 'Now plus 25 min');
test.equal(moment(a).add({h: 1}).calendar(), 'Today at 3:00 AM', 'Now plus 1 hour');
test.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at 2:00 AM', 'tomorrow at the same time');
test.equal(moment(a).subtract({h: 1}).calendar(), 'Today at 1:00 AM', 'Now minus 1 hour');
test.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at 2:00 AM', 'yesterday at the same time');
test.done();
},
'calendar next week' : function (test) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().add({d: i});
test.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
test.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
test.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day');
}
test.done();
},
'calendar last week' : function (test) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().subtract({d: i});
test.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
test.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
test.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day');
}
test.done();
},
'calendar all else' : function (test) {
var weeksAgo = moment().subtract({w: 1}),
weeksFromNow = moment().add({w: 1});
test.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
weeksAgo = moment().subtract({w: 2});
weeksFromNow = moment().add({w: 2});
test.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
test.done();
},
// Sunday is the first day of the week.
// The week that contains Jan 1st is the first week of the year.
'weeks year starting sunday' : function (test) {
test.equal(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1');
test.equal(moment([2012, 0, 7]).week(), 1, 'Jan 7 2012 should be week 1');
test.equal(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2');
test.equal(moment([2012, 0, 14]).week(), 2, 'Jan 14 2012 should be week 2');
test.equal(moment([2012, 0, 15]).week(), 3, 'Jan 15 2012 should be week 3');
test.done();
},
'weeks year starting monday' : function (test) {
test.equal(moment([2006, 11, 31]).week(), 1, 'Dec 31 2006 should be week 1');
test.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1');
test.equal(moment([2007, 0, 6]).week(), 1, 'Jan 6 2007 should be week 1');
test.equal(moment([2007, 0, 7]).week(), 2, 'Jan 7 2007 should be week 2');
test.equal(moment([2007, 0, 13]).week(), 2, 'Jan 13 2007 should be week 2');
test.equal(moment([2007, 0, 14]).week(), 3, 'Jan 14 2007 should be week 3');
test.done();
},
'weeks year starting tuesday' : function (test) {
test.equal(moment([2007, 11, 29]).week(), 52, 'Dec 29 2007 should be week 52');
test.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1');
test.equal(moment([2008, 0, 5]).week(), 1, 'Jan 5 2008 should be week 1');
test.equal(moment([2008, 0, 6]).week(), 2, 'Jan 6 2008 should be week 2');
test.equal(moment([2008, 0, 12]).week(), 2, 'Jan 12 2008 should be week 2');
test.equal(moment([2008, 0, 13]).week(), 3, 'Jan 13 2008 should be week 3');
test.done();
},
'weeks year starting wednesday' : function (test) {
test.equal(moment([2002, 11, 29]).week(), 1, 'Dec 29 2002 should be week 1');
test.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1');
test.equal(moment([2003, 0, 4]).week(), 1, 'Jan 4 2003 should be week 1');
test.equal(moment([2003, 0, 5]).week(), 2, 'Jan 5 2003 should be week 2');
test.equal(moment([2003, 0, 11]).week(), 2, 'Jan 11 2003 should be week 2');
test.equal(moment([2003, 0, 12]).week(), 3, 'Jan 12 2003 should be week 3');
test.done();
},
'weeks year starting thursday' : function (test) {
test.equal(moment([2008, 11, 28]).week(), 1, 'Dec 28 2008 should be week 1');
test.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1');
test.equal(moment([2009, 0, 3]).week(), 1, 'Jan 3 2009 should be week 1');
test.equal(moment([2009, 0, 4]).week(), 2, 'Jan 4 2009 should be week 2');
test.equal(moment([2009, 0, 10]).week(), 2, 'Jan 10 2009 should be week 2');
test.equal(moment([2009, 0, 11]).week(), 3, 'Jan 11 2009 should be week 3');
test.done();
},
'weeks year starting friday' : function (test) {
test.equal(moment([2009, 11, 27]).week(), 1, 'Dec 27 2009 should be week 1');
test.equal(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1');
test.equal(moment([2010, 0, 2]).week(), 1, 'Jan 2 2010 should be week 1');
test.equal(moment([2010, 0, 3]).week(), 2, 'Jan 3 2010 should be week 2');
test.equal(moment([2010, 0, 9]).week(), 2, 'Jan 9 2010 should be week 2');
test.equal(moment([2010, 0, 10]).week(), 3, 'Jan 10 2010 should be week 3');
test.done();
},
'weeks year starting saturday' : function (test) {
test.equal(moment([2010, 11, 26]).week(), 1, 'Dec 26 2010 should be week 1');
test.equal(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1');
test.equal(moment([2011, 0, 2]).week(), 2, 'Jan 2 2011 should be week 2');
test.equal(moment([2011, 0, 8]).week(), 2, 'Jan 8 2011 should be week 2');
test.equal(moment([2011, 0, 9]).week(), 3, 'Jan 9 2011 should be week 3');
test.done();
},
'weeks year starting sunday format' : function (test) {
test.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1st', 'Jan 1 2012 should be week 1');
test.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1st', 'Jan 7 2012 should be week 1');
test.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2nd', 'Jan 8 2012 should be week 2');
test.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2nd', 'Jan 14 2012 should be week 2');
test.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3rd', 'Jan 15 2012 should be week 3');
test.done();
}
};
|
/*
* bootstrap-table - v1.10.0 - 2016-01-18
* https://github.com/wenzhixin/bootstrap-table
* Copyright (c) 2016 zhixin wen
* Licensed MIT License
*/
!function(a){"use strict";a.fn.bootstrapTable.locales["ur-PK"]={formatLoadingMessage:function(){return"براۓ مہربانی انتظار کیجئے"},formatRecordsPerPage:function(a){return a+" ریکارڈز فی صفہ "},formatShowingRows:function(a,b,c){return"دیکھیں "+a+" سے "+b+" کے "+c+"ریکارڈز"},formatSearch:function(){return"تلاش"},formatNoMatches:function(){return"کوئی ریکارڈ نہیں ملا"},formatRefresh:function(){return"تازہ کریں"},formatToggle:function(){return"تبدیل کریں"},formatColumns:function(){return"کالم"}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales["ur-PK"])}(jQuery); |
CKEDITOR.plugins.setLang("docprops","eu",{bgColor:"Atzeko planoko kolorea",bgFixed:"Korritze gabeko atzeko planoa (finkoa)",bgImage:"Atzeko planoko irudiaren URLa",charset:"Karaktere-jokoaren kodeketa",charsetASCII:"ASCII",charsetCE:"Erdialdeko Europakoa",charsetCR:"Zirilikoa",charsetCT:"Txinatar tradizionala (Big5)",charsetGR:"Grekoa",charsetJP:"Japoniarra",charsetKR:"Korearra",charsetOther:"Beste karaktere-joko kodeketa bat",charsetTR:"Turkiarra",charsetUN:"Unicode (UTF-8)",charsetWE:"Mendebaldeko Europakoa",
chooseColor:"Aukeratu",design:"Diseinua",docTitle:"Orriaren izenburua",docType:"Document Type goiburua",docTypeOther:"Beste Document Type goiburu bat",label:"Dokumentuaren propietateak",margin:"Orrialdearen marjinak",marginBottom:"Behean",marginLeft:"Ezkerrean",marginRight:"Eskuinean",marginTop:"Goian",meta:"Meta etiketak",metaAuthor:"Egilea",metaCopyright:"Copyright-a",metaDescription:"Dokumentuaren deskribapena",metaKeywords:"Dokumentua indexatzeko gako-hitzak (komaz banatuta)",other:"Bestelakoa...",
previewHtml:'\x3cp\x3eHau \x3cstrong\x3eadibideko testua\x3c/strong\x3e da. \x3ca href\x3d"javascript:void(0)"\x3eCKEditor\x3c/a\x3e erabiltzen ari zara.\x3c/p\x3e',title:"Dokumentuaren propietateak",txtColor:"Testu-kolorea",xhtmlDec:"Sartu XHTML deklarazioak"}); |
/*!
* Bootstrap v4.0.0-alpha.6 (https://getbootstrap.com)
* Copyright 2011-2017 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.')
}
+function ($) {
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] >= 4)) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0')
}
}(jQuery);
+function () {
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): util.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Util = function ($) {
/**
* ------------------------------------------------------------------------
* Private TransitionEnd Helpers
* ------------------------------------------------------------------------
*/
var transition = false;
var MAX_UID = 1000000;
var TransitionEndEvent = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
// shoutout AngusCroll (https://goo.gl/pxwQGp)
function toType(obj) {
return {}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
function isElement(obj) {
return (obj[0] || obj).nodeType;
}
function getSpecialTransitionEndEvent() {
return {
bindType: transition.end,
delegateType: transition.end,
handle: function handle(event) {
if ($(event.target).is(this)) {
return event.handleObj.handler.apply(this, arguments); // eslint-disable-line prefer-rest-params
}
return undefined;
}
};
}
function transitionEndTest() {
if (window.QUnit) {
return false;
}
var el = document.createElement('bootstrap');
for (var name in TransitionEndEvent) {
if (el.style[name] !== undefined) {
return {
end: TransitionEndEvent[name]
};
}
}
return false;
}
function transitionEndEmulator(duration) {
var _this = this;
var called = false;
$(this).one(Util.TRANSITION_END, function () {
called = true;
});
setTimeout(function () {
if (!called) {
Util.triggerTransitionEnd(_this);
}
}, duration);
return this;
}
function setTransitionEndSupport() {
transition = transitionEndTest();
$.fn.emulateTransitionEnd = transitionEndEmulator;
if (Util.supportsTransitionEnd()) {
$.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent();
}
}
/**
* --------------------------------------------------------------------------
* Public Util Api
* --------------------------------------------------------------------------
*/
var Util = {
TRANSITION_END: 'bsTransitionEnd',
getUID: function getUID(prefix) {
do {
// eslint-disable-next-line no-bitwise
prefix += ~~(Math.random() * MAX_UID); // "~~" acts like a faster Math.floor() here
} while (document.getElementById(prefix));
return prefix;
},
getSelectorFromElement: function getSelectorFromElement(element) {
var selector = element.getAttribute('data-target');
if (!selector) {
selector = element.getAttribute('href') || '';
selector = /^#[a-z]/i.test(selector) ? selector : null;
}
return selector;
},
reflow: function reflow(element) {
return element.offsetHeight;
},
triggerTransitionEnd: function triggerTransitionEnd(element) {
$(element).trigger(transition.end);
},
supportsTransitionEnd: function supportsTransitionEnd() {
return Boolean(transition);
},
typeCheckConfig: function typeCheckConfig(componentName, config, configTypes) {
for (var property in configTypes) {
if (configTypes.hasOwnProperty(property)) {
var expectedTypes = configTypes[property];
var value = config[property];
var valueType = value && isElement(value) ? 'element' : toType(value);
if (!new RegExp(expectedTypes).test(valueType)) {
throw new Error(componentName.toUpperCase() + ': ' + ('Option "' + property + '" provided type "' + valueType + '" ') + ('but expected type "' + expectedTypes + '".'));
}
}
}
}
};
setTransitionEndSupport();
return Util;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): alert.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Alert = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'alert';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.alert';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var Selector = {
DISMISS: '[data-dismiss="alert"]'
};
var Event = {
CLOSE: 'close' + EVENT_KEY,
CLOSED: 'closed' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
ALERT: 'alert',
FADE: 'fade',
SHOW: 'show'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Alert = function () {
function Alert(element) {
_classCallCheck(this, Alert);
this._element = element;
}
// getters
// public
Alert.prototype.close = function close(element) {
element = element || this._element;
var rootElement = this._getRootElement(element);
var customEvent = this._triggerCloseEvent(rootElement);
if (customEvent.isDefaultPrevented()) {
return;
}
this._removeElement(rootElement);
};
Alert.prototype.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
this._element = null;
};
// private
Alert.prototype._getRootElement = function _getRootElement(element) {
var selector = Util.getSelectorFromElement(element);
var parent = false;
if (selector) {
parent = $(selector)[0];
}
if (!parent) {
parent = $(element).closest('.' + ClassName.ALERT)[0];
}
return parent;
};
Alert.prototype._triggerCloseEvent = function _triggerCloseEvent(element) {
var closeEvent = $.Event(Event.CLOSE);
$(element).trigger(closeEvent);
return closeEvent;
};
Alert.prototype._removeElement = function _removeElement(element) {
var _this2 = this;
$(element).removeClass(ClassName.SHOW);
if (!Util.supportsTransitionEnd() || !$(element).hasClass(ClassName.FADE)) {
this._destroyElement(element);
return;
}
$(element).one(Util.TRANSITION_END, function (event) {
return _this2._destroyElement(element, event);
}).emulateTransitionEnd(TRANSITION_DURATION);
};
Alert.prototype._destroyElement = function _destroyElement(element) {
$(element).detach().trigger(Event.CLOSED).remove();
};
// static
Alert._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $(this);
var data = $element.data(DATA_KEY);
if (!data) {
data = new Alert(this);
$element.data(DATA_KEY, data);
}
if (config === 'close') {
data[config](this);
}
});
};
Alert._handleDismiss = function _handleDismiss(alertInstance) {
return function (event) {
if (event) {
event.preventDefault();
}
alertInstance.close(this);
};
};
_createClass(Alert, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Alert;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DISMISS, Alert._handleDismiss(new Alert()));
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Alert._jQueryInterface;
$.fn[NAME].Constructor = Alert;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Alert._jQueryInterface;
};
return Alert;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): button.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Button = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'button';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.button';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var ClassName = {
ACTIVE: 'active',
BUTTON: 'btn',
FOCUS: 'focus'
};
var Selector = {
DATA_TOGGLE_CARROT: '[data-toggle^="button"]',
DATA_TOGGLE: '[data-toggle="buttons"]',
INPUT: 'input',
ACTIVE: '.active',
BUTTON: '.btn'
};
var Event = {
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY,
FOCUS_BLUR_DATA_API: 'focus' + EVENT_KEY + DATA_API_KEY + ' ' + ('blur' + EVENT_KEY + DATA_API_KEY)
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Button = function () {
function Button(element) {
_classCallCheck(this, Button);
this._element = element;
}
// getters
// public
Button.prototype.toggle = function toggle() {
var triggerChangeEvent = true;
var rootElement = $(this._element).closest(Selector.DATA_TOGGLE)[0];
if (rootElement) {
var input = $(this._element).find(Selector.INPUT)[0];
if (input) {
if (input.type === 'radio') {
if (input.checked && $(this._element).hasClass(ClassName.ACTIVE)) {
triggerChangeEvent = false;
} else {
var activeElement = $(rootElement).find(Selector.ACTIVE)[0];
if (activeElement) {
$(activeElement).removeClass(ClassName.ACTIVE);
}
}
}
if (triggerChangeEvent) {
input.checked = !$(this._element).hasClass(ClassName.ACTIVE);
$(input).trigger('change');
}
input.focus();
}
}
this._element.setAttribute('aria-pressed', !$(this._element).hasClass(ClassName.ACTIVE));
if (triggerChangeEvent) {
$(this._element).toggleClass(ClassName.ACTIVE);
}
};
Button.prototype.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
this._element = null;
};
// static
Button._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
if (!data) {
data = new Button(this);
$(this).data(DATA_KEY, data);
}
if (config === 'toggle') {
data[config]();
}
});
};
_createClass(Button, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Button;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
event.preventDefault();
var button = event.target;
if (!$(button).hasClass(ClassName.BUTTON)) {
button = $(button).closest(Selector.BUTTON);
}
Button._jQueryInterface.call($(button), 'toggle');
}).on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
var button = $(event.target).closest(Selector.BUTTON)[0];
$(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type));
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Button._jQueryInterface;
$.fn[NAME].Constructor = Button;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Button._jQueryInterface;
};
return Button;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): carousel.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Carousel = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'carousel';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.carousel';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 600;
var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key
var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key
var Default = {
interval: 5000,
keyboard: true,
slide: false,
pause: 'hover',
wrap: true
};
var DefaultType = {
interval: '(number|boolean)',
keyboard: 'boolean',
slide: '(boolean|string)',
pause: '(string|boolean)',
wrap: 'boolean'
};
var Direction = {
NEXT: 'next',
PREV: 'prev',
LEFT: 'left',
RIGHT: 'right'
};
var Event = {
SLIDE: 'slide' + EVENT_KEY,
SLID: 'slid' + EVENT_KEY,
KEYDOWN: 'keydown' + EVENT_KEY,
MOUSEENTER: 'mouseenter' + EVENT_KEY,
MOUSELEAVE: 'mouseleave' + EVENT_KEY,
LOAD_DATA_API: 'load' + EVENT_KEY + DATA_API_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
CAROUSEL: 'carousel',
ACTIVE: 'active',
SLIDE: 'slide',
RIGHT: 'carousel-item-right',
LEFT: 'carousel-item-left',
NEXT: 'carousel-item-next',
PREV: 'carousel-item-prev',
ITEM: 'carousel-item'
};
var Selector = {
ACTIVE: '.active',
ACTIVE_ITEM: '.active.carousel-item',
ITEM: '.carousel-item',
NEXT_PREV: '.carousel-item-next, .carousel-item-prev',
INDICATORS: '.carousel-indicators',
DATA_SLIDE: '[data-slide], [data-slide-to]',
DATA_RIDE: '[data-ride="carousel"]'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Carousel = function () {
function Carousel(element, config) {
_classCallCheck(this, Carousel);
this._items = null;
this._interval = null;
this._activeElement = null;
this._isPaused = false;
this._isSliding = false;
this._config = this._getConfig(config);
this._element = $(element)[0];
this._indicatorsElement = $(this._element).find(Selector.INDICATORS)[0];
this._addEventListeners();
}
// getters
// public
Carousel.prototype.next = function next() {
if (this._isSliding) {
throw new Error('Carousel is sliding');
}
this._slide(Direction.NEXT);
};
Carousel.prototype.nextWhenVisible = function nextWhenVisible() {
// Don't call next when the page isn't visible
if (!document.hidden) {
this.next();
}
};
Carousel.prototype.prev = function prev() {
if (this._isSliding) {
throw new Error('Carousel is sliding');
}
this._slide(Direction.PREVIOUS);
};
Carousel.prototype.pause = function pause(event) {
if (!event) {
this._isPaused = true;
}
if ($(this._element).find(Selector.NEXT_PREV)[0] && Util.supportsTransitionEnd()) {
Util.triggerTransitionEnd(this._element);
this.cycle(true);
}
clearInterval(this._interval);
this._interval = null;
};
Carousel.prototype.cycle = function cycle(event) {
if (!event) {
this._isPaused = false;
}
if (this._interval) {
clearInterval(this._interval);
this._interval = null;
}
if (this._config.interval && !this._isPaused) {
this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
}
};
Carousel.prototype.to = function to(index) {
var _this3 = this;
this._activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0];
var activeIndex = this._getItemIndex(this._activeElement);
if (index > this._items.length - 1 || index < 0) {
return;
}
if (this._isSliding) {
$(this._element).one(Event.SLID, function () {
return _this3.to(index);
});
return;
}
if (activeIndex === index) {
this.pause();
this.cycle();
return;
}
var direction = index > activeIndex ? Direction.NEXT : Direction.PREVIOUS;
this._slide(direction, this._items[index]);
};
Carousel.prototype.dispose = function dispose() {
$(this._element).off(EVENT_KEY);
$.removeData(this._element, DATA_KEY);
this._items = null;
this._config = null;
this._element = null;
this._interval = null;
this._isPaused = null;
this._isSliding = null;
this._activeElement = null;
this._indicatorsElement = null;
};
// private
Carousel.prototype._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
Carousel.prototype._addEventListeners = function _addEventListeners() {
var _this4 = this;
if (this._config.keyboard) {
$(this._element).on(Event.KEYDOWN, function (event) {
return _this4._keydown(event);
});
}
if (this._config.pause === 'hover' && !('ontouchstart' in document.documentElement)) {
$(this._element).on(Event.MOUSEENTER, function (event) {
return _this4.pause(event);
}).on(Event.MOUSELEAVE, function (event) {
return _this4.cycle(event);
});
}
};
Carousel.prototype._keydown = function _keydown(event) {
if (/input|textarea/i.test(event.target.tagName)) {
return;
}
switch (event.which) {
case ARROW_LEFT_KEYCODE:
event.preventDefault();
this.prev();
break;
case ARROW_RIGHT_KEYCODE:
event.preventDefault();
this.next();
break;
default:
return;
}
};
Carousel.prototype._getItemIndex = function _getItemIndex(element) {
this._items = $.makeArray($(element).parent().find(Selector.ITEM));
return this._items.indexOf(element);
};
Carousel.prototype._getItemByDirection = function _getItemByDirection(direction, activeElement) {
var isNextDirection = direction === Direction.NEXT;
var isPrevDirection = direction === Direction.PREVIOUS;
var activeIndex = this._getItemIndex(activeElement);
var lastItemIndex = this._items.length - 1;
var isGoingToWrap = isPrevDirection && activeIndex === 0 || isNextDirection && activeIndex === lastItemIndex;
if (isGoingToWrap && !this._config.wrap) {
return activeElement;
}
var delta = direction === Direction.PREVIOUS ? -1 : 1;
var itemIndex = (activeIndex + delta) % this._items.length;
return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex];
};
Carousel.prototype._triggerSlideEvent = function _triggerSlideEvent(relatedTarget, eventDirectionName) {
var slideEvent = $.Event(Event.SLIDE, {
relatedTarget: relatedTarget,
direction: eventDirectionName
});
$(this._element).trigger(slideEvent);
return slideEvent;
};
Carousel.prototype._setActiveIndicatorElement = function _setActiveIndicatorElement(element) {
if (this._indicatorsElement) {
$(this._indicatorsElement).find(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)];
if (nextIndicator) {
$(nextIndicator).addClass(ClassName.ACTIVE);
}
}
};
Carousel.prototype._slide = function _slide(direction, element) {
var _this5 = this;
var activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0];
var nextElement = element || activeElement && this._getItemByDirection(direction, activeElement);
var isCycling = Boolean(this._interval);
var directionalClassName = void 0;
var orderClassName = void 0;
var eventDirectionName = void 0;
if (direction === Direction.NEXT) {
directionalClassName = ClassName.LEFT;
orderClassName = ClassName.NEXT;
eventDirectionName = Direction.LEFT;
} else {
directionalClassName = ClassName.RIGHT;
orderClassName = ClassName.PREV;
eventDirectionName = Direction.RIGHT;
}
if (nextElement && $(nextElement).hasClass(ClassName.ACTIVE)) {
this._isSliding = false;
return;
}
var slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);
if (slideEvent.isDefaultPrevented()) {
return;
}
if (!activeElement || !nextElement) {
// some weirdness is happening, so we bail
return;
}
this._isSliding = true;
if (isCycling) {
this.pause();
}
this._setActiveIndicatorElement(nextElement);
var slidEvent = $.Event(Event.SLID, {
relatedTarget: nextElement,
direction: eventDirectionName
});
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.SLIDE)) {
$(nextElement).addClass(orderClassName);
Util.reflow(nextElement);
$(activeElement).addClass(directionalClassName);
$(nextElement).addClass(directionalClassName);
$(activeElement).one(Util.TRANSITION_END, function () {
$(nextElement).removeClass(directionalClassName + ' ' + orderClassName).addClass(ClassName.ACTIVE);
$(activeElement).removeClass(ClassName.ACTIVE + ' ' + orderClassName + ' ' + directionalClassName);
_this5._isSliding = false;
setTimeout(function () {
return $(_this5._element).trigger(slidEvent);
}, 0);
}).emulateTransitionEnd(TRANSITION_DURATION);
} else {
$(activeElement).removeClass(ClassName.ACTIVE);
$(nextElement).addClass(ClassName.ACTIVE);
this._isSliding = false;
$(this._element).trigger(slidEvent);
}
if (isCycling) {
this.cycle();
}
};
// static
Carousel._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = $.extend({}, Default, $(this).data());
if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') {
$.extend(_config, config);
}
var action = typeof config === 'string' ? config : _config.slide;
if (!data) {
data = new Carousel(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'number') {
data.to(config);
} else if (typeof action === 'string') {
if (data[action] === undefined) {
throw new Error('No method named "' + action + '"');
}
data[action]();
} else if (_config.interval) {
data.pause();
data.cycle();
}
});
};
Carousel._dataApiClickHandler = function _dataApiClickHandler(event) {
var selector = Util.getSelectorFromElement(this);
if (!selector) {
return;
}
var target = $(selector)[0];
if (!target || !$(target).hasClass(ClassName.CAROUSEL)) {
return;
}
var config = $.extend({}, $(target).data(), $(this).data());
var slideIndex = this.getAttribute('data-slide-to');
if (slideIndex) {
config.interval = false;
}
Carousel._jQueryInterface.call($(target), config);
if (slideIndex) {
$(target).data(DATA_KEY).to(slideIndex);
}
event.preventDefault();
};
_createClass(Carousel, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return Carousel;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_SLIDE, Carousel._dataApiClickHandler);
$(window).on(Event.LOAD_DATA_API, function () {
$(Selector.DATA_RIDE).each(function () {
var $carousel = $(this);
Carousel._jQueryInterface.call($carousel, $carousel.data());
});
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Carousel._jQueryInterface;
$.fn[NAME].Constructor = Carousel;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Carousel._jQueryInterface;
};
return Carousel;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): collapse.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Collapse = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'collapse';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.collapse';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 600;
var Default = {
toggle: true,
parent: ''
};
var DefaultType = {
toggle: 'boolean',
parent: 'string'
};
var Event = {
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SHOW: 'show',
COLLAPSE: 'collapse',
COLLAPSING: 'collapsing',
COLLAPSED: 'collapsed'
};
var Dimension = {
WIDTH: 'width',
HEIGHT: 'height'
};
var Selector = {
ACTIVES: '.card > .show, .card > .collapsing',
DATA_TOGGLE: '[data-toggle="collapse"]'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Collapse = function () {
function Collapse(element, config) {
_classCallCheck(this, Collapse);
this._isTransitioning = false;
this._element = element;
this._config = this._getConfig(config);
this._triggerArray = $.makeArray($('[data-toggle="collapse"][href="#' + element.id + '"],' + ('[data-toggle="collapse"][data-target="#' + element.id + '"]')));
this._parent = this._config.parent ? this._getParent() : null;
if (!this._config.parent) {
this._addAriaAndCollapsedClass(this._element, this._triggerArray);
}
if (this._config.toggle) {
this.toggle();
}
}
// getters
// public
Collapse.prototype.toggle = function toggle() {
if ($(this._element).hasClass(ClassName.SHOW)) {
this.hide();
} else {
this.show();
}
};
Collapse.prototype.show = function show() {
var _this6 = this;
if (this._isTransitioning) {
throw new Error('Collapse is transitioning');
}
if ($(this._element).hasClass(ClassName.SHOW)) {
return;
}
var actives = void 0;
var activesData = void 0;
if (this._parent) {
actives = $.makeArray($(this._parent).find(Selector.ACTIVES));
if (!actives.length) {
actives = null;
}
}
if (actives) {
activesData = $(actives).data(DATA_KEY);
if (activesData && activesData._isTransitioning) {
return;
}
}
var startEvent = $.Event(Event.SHOW);
$(this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
if (actives) {
Collapse._jQueryInterface.call($(actives), 'hide');
if (!activesData) {
$(actives).data(DATA_KEY, null);
}
}
var dimension = this._getDimension();
$(this._element).removeClass(ClassName.COLLAPSE).addClass(ClassName.COLLAPSING);
this._element.style[dimension] = 0;
this._element.setAttribute('aria-expanded', true);
if (this._triggerArray.length) {
$(this._triggerArray).removeClass(ClassName.COLLAPSED).attr('aria-expanded', true);
}
this.setTransitioning(true);
var complete = function complete() {
$(_this6._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).addClass(ClassName.SHOW);
_this6._element.style[dimension] = '';
_this6.setTransitioning(false);
$(_this6._element).trigger(Event.SHOWN);
};
if (!Util.supportsTransitionEnd()) {
complete();
return;
}
var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
var scrollSize = 'scroll' + capitalizedDimension;
$(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
this._element.style[dimension] = this._element[scrollSize] + 'px';
};
Collapse.prototype.hide = function hide() {
var _this7 = this;
if (this._isTransitioning) {
throw new Error('Collapse is transitioning');
}
if (!$(this._element).hasClass(ClassName.SHOW)) {
return;
}
var startEvent = $.Event(Event.HIDE);
$(this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
var dimension = this._getDimension();
var offsetDimension = dimension === Dimension.WIDTH ? 'offsetWidth' : 'offsetHeight';
this._element.style[dimension] = this._element[offsetDimension] + 'px';
Util.reflow(this._element);
$(this._element).addClass(ClassName.COLLAPSING).removeClass(ClassName.COLLAPSE).removeClass(ClassName.SHOW);
this._element.setAttribute('aria-expanded', false);
if (this._triggerArray.length) {
$(this._triggerArray).addClass(ClassName.COLLAPSED).attr('aria-expanded', false);
}
this.setTransitioning(true);
var complete = function complete() {
_this7.setTransitioning(false);
$(_this7._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).trigger(Event.HIDDEN);
};
this._element.style[dimension] = '';
if (!Util.supportsTransitionEnd()) {
complete();
return;
}
$(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
};
Collapse.prototype.setTransitioning = function setTransitioning(isTransitioning) {
this._isTransitioning = isTransitioning;
};
Collapse.prototype.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
this._config = null;
this._parent = null;
this._element = null;
this._triggerArray = null;
this._isTransitioning = null;
};
// private
Collapse.prototype._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
config.toggle = Boolean(config.toggle); // coerce string values
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
Collapse.prototype._getDimension = function _getDimension() {
var hasWidth = $(this._element).hasClass(Dimension.WIDTH);
return hasWidth ? Dimension.WIDTH : Dimension.HEIGHT;
};
Collapse.prototype._getParent = function _getParent() {
var _this8 = this;
var parent = $(this._config.parent)[0];
var selector = '[data-toggle="collapse"][data-parent="' + this._config.parent + '"]';
$(parent).find(selector).each(function (i, element) {
_this8._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]);
});
return parent;
};
Collapse.prototype._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) {
if (element) {
var isOpen = $(element).hasClass(ClassName.SHOW);
element.setAttribute('aria-expanded', isOpen);
if (triggerArray.length) {
$(triggerArray).toggleClass(ClassName.COLLAPSED, !isOpen).attr('aria-expanded', isOpen);
}
}
};
// static
Collapse._getTargetFromElement = function _getTargetFromElement(element) {
var selector = Util.getSelectorFromElement(element);
return selector ? $(selector)[0] : null;
};
Collapse._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $(this);
var data = $this.data(DATA_KEY);
var _config = $.extend({}, Default, $this.data(), (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config);
if (!data && _config.toggle && /show|hide/.test(config)) {
_config.toggle = false;
}
if (!data) {
data = new Collapse(this, _config);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
};
_createClass(Collapse, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return Collapse;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
var target = Collapse._getTargetFromElement(this);
var data = $(target).data(DATA_KEY);
var config = data ? 'toggle' : $(this).data();
Collapse._jQueryInterface.call($(target), config);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Collapse._jQueryInterface;
$.fn[NAME].Constructor = Collapse;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Collapse._jQueryInterface;
};
return Collapse;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): dropdown.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Dropdown = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'dropdown';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.dropdown';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key
var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key
var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key
var RIGHT_MOUSE_BUTTON_WHICH = 3; // MouseEvent.which value for the right button (assuming a right-handed mouse)
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
CLICK: 'click' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY,
FOCUSIN_DATA_API: 'focusin' + EVENT_KEY + DATA_API_KEY,
KEYDOWN_DATA_API: 'keydown' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
BACKDROP: 'dropdown-backdrop',
DISABLED: 'disabled',
SHOW: 'show'
};
var Selector = {
BACKDROP: '.dropdown-backdrop',
DATA_TOGGLE: '[data-toggle="dropdown"]',
FORM_CHILD: '.dropdown form',
ROLE_MENU: '[role="menu"]',
ROLE_LISTBOX: '[role="listbox"]',
NAVBAR_NAV: '.navbar-nav',
VISIBLE_ITEMS: '[role="menu"] li:not(.disabled) a, ' + '[role="listbox"] li:not(.disabled) a'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Dropdown = function () {
function Dropdown(element) {
_classCallCheck(this, Dropdown);
this._element = element;
this._addEventListeners();
}
// getters
// public
Dropdown.prototype.toggle = function toggle() {
if (this.disabled || $(this).hasClass(ClassName.DISABLED)) {
return false;
}
var parent = Dropdown._getParentFromElement(this);
var isActive = $(parent).hasClass(ClassName.SHOW);
Dropdown._clearMenus();
if (isActive) {
return false;
}
if ('ontouchstart' in document.documentElement && !$(parent).closest(Selector.NAVBAR_NAV).length) {
// if mobile we use a backdrop because click events don't delegate
var dropdown = document.createElement('div');
dropdown.className = ClassName.BACKDROP;
$(dropdown).insertBefore(this);
$(dropdown).on('click', Dropdown._clearMenus);
}
var relatedTarget = {
relatedTarget: this
};
var showEvent = $.Event(Event.SHOW, relatedTarget);
$(parent).trigger(showEvent);
if (showEvent.isDefaultPrevented()) {
return false;
}
this.focus();
this.setAttribute('aria-expanded', true);
$(parent).toggleClass(ClassName.SHOW);
$(parent).trigger($.Event(Event.SHOWN, relatedTarget));
return false;
};
Dropdown.prototype.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
$(this._element).off(EVENT_KEY);
this._element = null;
};
// private
Dropdown.prototype._addEventListeners = function _addEventListeners() {
$(this._element).on(Event.CLICK, this.toggle);
};
// static
Dropdown._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
if (!data) {
data = new Dropdown(this);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config].call(this);
}
});
};
Dropdown._clearMenus = function _clearMenus(event) {
if (event && event.which === RIGHT_MOUSE_BUTTON_WHICH) {
return;
}
var backdrop = $(Selector.BACKDROP)[0];
if (backdrop) {
backdrop.parentNode.removeChild(backdrop);
}
var toggles = $.makeArray($(Selector.DATA_TOGGLE));
for (var i = 0; i < toggles.length; i++) {
var parent = Dropdown._getParentFromElement(toggles[i]);
var relatedTarget = {
relatedTarget: toggles[i]
};
if (!$(parent).hasClass(ClassName.SHOW)) {
continue;
}
if (event && (event.type === 'click' && /input|textarea/i.test(event.target.tagName) || event.type === 'focusin') && $.contains(parent, event.target)) {
continue;
}
var hideEvent = $.Event(Event.HIDE, relatedTarget);
$(parent).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
continue;
}
toggles[i].setAttribute('aria-expanded', 'false');
$(parent).removeClass(ClassName.SHOW).trigger($.Event(Event.HIDDEN, relatedTarget));
}
};
Dropdown._getParentFromElement = function _getParentFromElement(element) {
var parent = void 0;
var selector = Util.getSelectorFromElement(element);
if (selector) {
parent = $(selector)[0];
}
return parent || element.parentNode;
};
Dropdown._dataApiKeydownHandler = function _dataApiKeydownHandler(event) {
if (!/(38|40|27|32)/.test(event.which) || /input|textarea/i.test(event.target.tagName)) {
return;
}
event.preventDefault();
event.stopPropagation();
if (this.disabled || $(this).hasClass(ClassName.DISABLED)) {
return;
}
var parent = Dropdown._getParentFromElement(this);
var isActive = $(parent).hasClass(ClassName.SHOW);
if (!isActive && event.which !== ESCAPE_KEYCODE || isActive && event.which === ESCAPE_KEYCODE) {
if (event.which === ESCAPE_KEYCODE) {
var toggle = $(parent).find(Selector.DATA_TOGGLE)[0];
$(toggle).trigger('focus');
}
$(this).trigger('click');
return;
}
var items = $(parent).find(Selector.VISIBLE_ITEMS).get();
if (!items.length) {
return;
}
var index = items.indexOf(event.target);
if (event.which === ARROW_UP_KEYCODE && index > 0) {
// up
index--;
}
if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) {
// down
index++;
}
if (index < 0) {
index = 0;
}
items[index].focus();
};
_createClass(Dropdown, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Dropdown;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE, Dropdown._dataApiKeydownHandler).on(Event.KEYDOWN_DATA_API, Selector.ROLE_MENU, Dropdown._dataApiKeydownHandler).on(Event.KEYDOWN_DATA_API, Selector.ROLE_LISTBOX, Dropdown._dataApiKeydownHandler).on(Event.CLICK_DATA_API + ' ' + Event.FOCUSIN_DATA_API, Dropdown._clearMenus).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, Dropdown.prototype.toggle).on(Event.CLICK_DATA_API, Selector.FORM_CHILD, function (e) {
e.stopPropagation();
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Dropdown._jQueryInterface;
$.fn[NAME].Constructor = Dropdown;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Dropdown._jQueryInterface;
};
return Dropdown;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): modal.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Modal = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'modal';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.modal';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 300;
var BACKDROP_TRANSITION_DURATION = 150;
var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key
var Default = {
backdrop: true,
keyboard: true,
focus: true,
show: true
};
var DefaultType = {
backdrop: '(boolean|string)',
keyboard: 'boolean',
focus: 'boolean',
show: 'boolean'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
RESIZE: 'resize' + EVENT_KEY,
CLICK_DISMISS: 'click.dismiss' + EVENT_KEY,
KEYDOWN_DISMISS: 'keydown.dismiss' + EVENT_KEY,
MOUSEUP_DISMISS: 'mouseup.dismiss' + EVENT_KEY,
MOUSEDOWN_DISMISS: 'mousedown.dismiss' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SCROLLBAR_MEASURER: 'modal-scrollbar-measure',
BACKDROP: 'modal-backdrop',
OPEN: 'modal-open',
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
DIALOG: '.modal-dialog',
DATA_TOGGLE: '[data-toggle="modal"]',
DATA_DISMISS: '[data-dismiss="modal"]',
FIXED_CONTENT: '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Modal = function () {
function Modal(element, config) {
_classCallCheck(this, Modal);
this._config = this._getConfig(config);
this._element = element;
this._dialog = $(element).find(Selector.DIALOG)[0];
this._backdrop = null;
this._isShown = false;
this._isBodyOverflowing = false;
this._ignoreBackdropClick = false;
this._isTransitioning = false;
this._originalBodyPadding = 0;
this._scrollbarWidth = 0;
}
// getters
// public
Modal.prototype.toggle = function toggle(relatedTarget) {
return this._isShown ? this.hide() : this.show(relatedTarget);
};
Modal.prototype.show = function show(relatedTarget) {
var _this9 = this;
if (this._isTransitioning) {
throw new Error('Modal is transitioning');
}
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
this._isTransitioning = true;
}
var showEvent = $.Event(Event.SHOW, {
relatedTarget: relatedTarget
});
$(this._element).trigger(showEvent);
if (this._isShown || showEvent.isDefaultPrevented()) {
return;
}
this._isShown = true;
this._checkScrollbar();
this._setScrollbar();
$(document.body).addClass(ClassName.OPEN);
this._setEscapeEvent();
this._setResizeEvent();
$(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, function (event) {
return _this9.hide(event);
});
$(this._dialog).on(Event.MOUSEDOWN_DISMISS, function () {
$(_this9._element).one(Event.MOUSEUP_DISMISS, function (event) {
if ($(event.target).is(_this9._element)) {
_this9._ignoreBackdropClick = true;
}
});
});
this._showBackdrop(function () {
return _this9._showElement(relatedTarget);
});
};
Modal.prototype.hide = function hide(event) {
var _this10 = this;
if (event) {
event.preventDefault();
}
if (this._isTransitioning) {
throw new Error('Modal is transitioning');
}
var transition = Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE);
if (transition) {
this._isTransitioning = true;
}
var hideEvent = $.Event(Event.HIDE);
$(this._element).trigger(hideEvent);
if (!this._isShown || hideEvent.isDefaultPrevented()) {
return;
}
this._isShown = false;
this._setEscapeEvent();
this._setResizeEvent();
$(document).off(Event.FOCUSIN);
$(this._element).removeClass(ClassName.SHOW);
$(this._element).off(Event.CLICK_DISMISS);
$(this._dialog).off(Event.MOUSEDOWN_DISMISS);
if (transition) {
$(this._element).one(Util.TRANSITION_END, function (event) {
return _this10._hideModal(event);
}).emulateTransitionEnd(TRANSITION_DURATION);
} else {
this._hideModal();
}
};
Modal.prototype.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
$(window, document, this._element, this._backdrop).off(EVENT_KEY);
this._config = null;
this._element = null;
this._dialog = null;
this._backdrop = null;
this._isShown = null;
this._isBodyOverflowing = null;
this._ignoreBackdropClick = null;
this._originalBodyPadding = null;
this._scrollbarWidth = null;
};
// private
Modal.prototype._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
Modal.prototype._showElement = function _showElement(relatedTarget) {
var _this11 = this;
var transition = Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE);
if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
// don't move modals dom position
document.body.appendChild(this._element);
}
this._element.style.display = 'block';
this._element.removeAttribute('aria-hidden');
this._element.scrollTop = 0;
if (transition) {
Util.reflow(this._element);
}
$(this._element).addClass(ClassName.SHOW);
if (this._config.focus) {
this._enforceFocus();
}
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: relatedTarget
});
var transitionComplete = function transitionComplete() {
if (_this11._config.focus) {
_this11._element.focus();
}
_this11._isTransitioning = false;
$(_this11._element).trigger(shownEvent);
};
if (transition) {
$(this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
transitionComplete();
}
};
Modal.prototype._enforceFocus = function _enforceFocus() {
var _this12 = this;
$(document).off(Event.FOCUSIN) // guard against infinite focus loop
.on(Event.FOCUSIN, function (event) {
if (document !== event.target && _this12._element !== event.target && !$(_this12._element).has(event.target).length) {
_this12._element.focus();
}
});
};
Modal.prototype._setEscapeEvent = function _setEscapeEvent() {
var _this13 = this;
if (this._isShown && this._config.keyboard) {
$(this._element).on(Event.KEYDOWN_DISMISS, function (event) {
if (event.which === ESCAPE_KEYCODE) {
_this13.hide();
}
});
} else if (!this._isShown) {
$(this._element).off(Event.KEYDOWN_DISMISS);
}
};
Modal.prototype._setResizeEvent = function _setResizeEvent() {
var _this14 = this;
if (this._isShown) {
$(window).on(Event.RESIZE, function (event) {
return _this14._handleUpdate(event);
});
} else {
$(window).off(Event.RESIZE);
}
};
Modal.prototype._hideModal = function _hideModal() {
var _this15 = this;
this._element.style.display = 'none';
this._element.setAttribute('aria-hidden', 'true');
this._isTransitioning = false;
this._showBackdrop(function () {
$(document.body).removeClass(ClassName.OPEN);
_this15._resetAdjustments();
_this15._resetScrollbar();
$(_this15._element).trigger(Event.HIDDEN);
});
};
Modal.prototype._removeBackdrop = function _removeBackdrop() {
if (this._backdrop) {
$(this._backdrop).remove();
this._backdrop = null;
}
};
Modal.prototype._showBackdrop = function _showBackdrop(callback) {
var _this16 = this;
var animate = $(this._element).hasClass(ClassName.FADE) ? ClassName.FADE : '';
if (this._isShown && this._config.backdrop) {
var doAnimate = Util.supportsTransitionEnd() && animate;
this._backdrop = document.createElement('div');
this._backdrop.className = ClassName.BACKDROP;
if (animate) {
$(this._backdrop).addClass(animate);
}
$(this._backdrop).appendTo(document.body);
$(this._element).on(Event.CLICK_DISMISS, function (event) {
if (_this16._ignoreBackdropClick) {
_this16._ignoreBackdropClick = false;
return;
}
if (event.target !== event.currentTarget) {
return;
}
if (_this16._config.backdrop === 'static') {
_this16._element.focus();
} else {
_this16.hide();
}
});
if (doAnimate) {
Util.reflow(this._backdrop);
}
$(this._backdrop).addClass(ClassName.SHOW);
if (!callback) {
return;
}
if (!doAnimate) {
callback();
return;
}
$(this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else if (!this._isShown && this._backdrop) {
$(this._backdrop).removeClass(ClassName.SHOW);
var callbackRemove = function callbackRemove() {
_this16._removeBackdrop();
if (callback) {
callback();
}
};
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
$(this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else {
callbackRemove();
}
} else if (callback) {
callback();
}
};
// ----------------------------------------------------------------------
// the following methods are used to handle overflowing modals
// todo (fat): these should probably be refactored out of modal.js
// ----------------------------------------------------------------------
Modal.prototype._handleUpdate = function _handleUpdate() {
this._adjustDialog();
};
Modal.prototype._adjustDialog = function _adjustDialog() {
var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
if (!this._isBodyOverflowing && isModalOverflowing) {
this._element.style.paddingLeft = this._scrollbarWidth + 'px';
}
if (this._isBodyOverflowing && !isModalOverflowing) {
this._element.style.paddingRight = this._scrollbarWidth + 'px';
}
};
Modal.prototype._resetAdjustments = function _resetAdjustments() {
this._element.style.paddingLeft = '';
this._element.style.paddingRight = '';
};
Modal.prototype._checkScrollbar = function _checkScrollbar() {
this._isBodyOverflowing = document.body.clientWidth < window.innerWidth;
this._scrollbarWidth = this._getScrollbarWidth();
};
Modal.prototype._setScrollbar = function _setScrollbar() {
var bodyPadding = parseInt($(Selector.FIXED_CONTENT).css('padding-right') || 0, 10);
this._originalBodyPadding = document.body.style.paddingRight || '';
if (this._isBodyOverflowing) {
document.body.style.paddingRight = bodyPadding + this._scrollbarWidth + 'px';
}
};
Modal.prototype._resetScrollbar = function _resetScrollbar() {
document.body.style.paddingRight = this._originalBodyPadding;
};
Modal.prototype._getScrollbarWidth = function _getScrollbarWidth() {
// thx d.walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = ClassName.SCROLLBAR_MEASURER;
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
};
// static
Modal._jQueryInterface = function _jQueryInterface(config, relatedTarget) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = $.extend({}, Modal.Default, $(this).data(), (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config);
if (!data) {
data = new Modal(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config](relatedTarget);
} else if (_config.show) {
data.show(relatedTarget);
}
});
};
_createClass(Modal, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return Modal;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
var _this17 = this;
var target = void 0;
var selector = Util.getSelectorFromElement(this);
if (selector) {
target = $(selector)[0];
}
var config = $(target).data(DATA_KEY) ? 'toggle' : $.extend({}, $(target).data(), $(this).data());
if (this.tagName === 'A' || this.tagName === 'AREA') {
event.preventDefault();
}
var $target = $(target).one(Event.SHOW, function (showEvent) {
if (showEvent.isDefaultPrevented()) {
// only register focus restorer if modal will actually get shown
return;
}
$target.one(Event.HIDDEN, function () {
if ($(_this17).is(':visible')) {
_this17.focus();
}
});
});
Modal._jQueryInterface.call($(target), config, this);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Modal._jQueryInterface;
$.fn[NAME].Constructor = Modal;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Modal._jQueryInterface;
};
return Modal;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): scrollspy.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var ScrollSpy = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'scrollspy';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.scrollspy';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var Default = {
offset: 10,
method: 'auto',
target: ''
};
var DefaultType = {
offset: 'number',
method: 'string',
target: '(string|element)'
};
var Event = {
ACTIVATE: 'activate' + EVENT_KEY,
SCROLL: 'scroll' + EVENT_KEY,
LOAD_DATA_API: 'load' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DROPDOWN_ITEM: 'dropdown-item',
DROPDOWN_MENU: 'dropdown-menu',
NAV_LINK: 'nav-link',
NAV: 'nav',
ACTIVE: 'active'
};
var Selector = {
DATA_SPY: '[data-spy="scroll"]',
ACTIVE: '.active',
LIST_ITEM: '.list-item',
LI: 'li',
LI_DROPDOWN: 'li.dropdown',
NAV_LINKS: '.nav-link',
DROPDOWN: '.dropdown',
DROPDOWN_ITEMS: '.dropdown-item',
DROPDOWN_TOGGLE: '.dropdown-toggle'
};
var OffsetMethod = {
OFFSET: 'offset',
POSITION: 'position'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var ScrollSpy = function () {
function ScrollSpy(element, config) {
var _this18 = this;
_classCallCheck(this, ScrollSpy);
this._element = element;
this._scrollElement = element.tagName === 'BODY' ? window : element;
this._config = this._getConfig(config);
this._selector = this._config.target + ' ' + Selector.NAV_LINKS + ',' + (this._config.target + ' ' + Selector.DROPDOWN_ITEMS);
this._offsets = [];
this._targets = [];
this._activeTarget = null;
this._scrollHeight = 0;
$(this._scrollElement).on(Event.SCROLL, function (event) {
return _this18._process(event);
});
this.refresh();
this._process();
}
// getters
// public
ScrollSpy.prototype.refresh = function refresh() {
var _this19 = this;
var autoMethod = this._scrollElement !== this._scrollElement.window ? OffsetMethod.POSITION : OffsetMethod.OFFSET;
var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method;
var offsetBase = offsetMethod === OffsetMethod.POSITION ? this._getScrollTop() : 0;
this._offsets = [];
this._targets = [];
this._scrollHeight = this._getScrollHeight();
var targets = $.makeArray($(this._selector));
targets.map(function (element) {
var target = void 0;
var targetSelector = Util.getSelectorFromElement(element);
if (targetSelector) {
target = $(targetSelector)[0];
}
if (target && (target.offsetWidth || target.offsetHeight)) {
// todo (fat): remove sketch reliance on jQuery position/offset
return [$(target)[offsetMethod]().top + offsetBase, targetSelector];
}
return null;
}).filter(function (item) {
return item;
}).sort(function (a, b) {
return a[0] - b[0];
}).forEach(function (item) {
_this19._offsets.push(item[0]);
_this19._targets.push(item[1]);
});
};
ScrollSpy.prototype.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
$(this._scrollElement).off(EVENT_KEY);
this._element = null;
this._scrollElement = null;
this._config = null;
this._selector = null;
this._offsets = null;
this._targets = null;
this._activeTarget = null;
this._scrollHeight = null;
};
// private
ScrollSpy.prototype._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
if (typeof config.target !== 'string') {
var id = $(config.target).attr('id');
if (!id) {
id = Util.getUID(NAME);
$(config.target).attr('id', id);
}
config.target = '#' + id;
}
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
ScrollSpy.prototype._getScrollTop = function _getScrollTop() {
return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop;
};
ScrollSpy.prototype._getScrollHeight = function _getScrollHeight() {
return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
};
ScrollSpy.prototype._getOffsetHeight = function _getOffsetHeight() {
return this._scrollElement === window ? window.innerHeight : this._scrollElement.offsetHeight;
};
ScrollSpy.prototype._process = function _process() {
var scrollTop = this._getScrollTop() + this._config.offset;
var scrollHeight = this._getScrollHeight();
var maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight();
if (this._scrollHeight !== scrollHeight) {
this.refresh();
}
if (scrollTop >= maxScroll) {
var target = this._targets[this._targets.length - 1];
if (this._activeTarget !== target) {
this._activate(target);
}
return;
}
if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) {
this._activeTarget = null;
this._clear();
return;
}
for (var i = this._offsets.length; i--;) {
var isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (this._offsets[i + 1] === undefined || scrollTop < this._offsets[i + 1]);
if (isActiveTarget) {
this._activate(this._targets[i]);
}
}
};
ScrollSpy.prototype._activate = function _activate(target) {
this._activeTarget = target;
this._clear();
var queries = this._selector.split(',');
queries = queries.map(function (selector) {
return selector + '[data-target="' + target + '"],' + (selector + '[href="' + target + '"]');
});
var $link = $(queries.join(','));
if ($link.hasClass(ClassName.DROPDOWN_ITEM)) {
$link.closest(Selector.DROPDOWN).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
$link.addClass(ClassName.ACTIVE);
} else {
// todo (fat) this is kinda sus...
// recursively add actives to tested nav-links
$link.parents(Selector.LI).find('> ' + Selector.NAV_LINKS).addClass(ClassName.ACTIVE);
}
$(this._scrollElement).trigger(Event.ACTIVATE, {
relatedTarget: target
});
};
ScrollSpy.prototype._clear = function _clear() {
$(this._selector).filter(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
};
// static
ScrollSpy._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config;
if (!data) {
data = new ScrollSpy(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
};
_createClass(ScrollSpy, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return ScrollSpy;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(window).on(Event.LOAD_DATA_API, function () {
var scrollSpys = $.makeArray($(Selector.DATA_SPY));
for (var i = scrollSpys.length; i--;) {
var $spy = $(scrollSpys[i]);
ScrollSpy._jQueryInterface.call($spy, $spy.data());
}
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = ScrollSpy._jQueryInterface;
$.fn[NAME].Constructor = ScrollSpy;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return ScrollSpy._jQueryInterface;
};
return ScrollSpy;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): tab.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tab = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tab';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.tab';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DROPDOWN_MENU: 'dropdown-menu',
ACTIVE: 'active',
DISABLED: 'disabled',
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
A: 'a',
LI: 'li',
DROPDOWN: '.dropdown',
LIST: 'ul:not(.dropdown-menu), ol:not(.dropdown-menu), nav:not(.dropdown-menu)',
FADE_CHILD: '> .nav-item .fade, > .fade',
ACTIVE: '.active',
ACTIVE_CHILD: '> .nav-item > .active, > .active',
DATA_TOGGLE: '[data-toggle="tab"], [data-toggle="pill"]',
DROPDOWN_TOGGLE: '.dropdown-toggle',
DROPDOWN_ACTIVE_CHILD: '> .dropdown-menu .active'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Tab = function () {
function Tab(element) {
_classCallCheck(this, Tab);
this._element = element;
}
// getters
// public
Tab.prototype.show = function show() {
var _this20 = this;
if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $(this._element).hasClass(ClassName.ACTIVE) || $(this._element).hasClass(ClassName.DISABLED)) {
return;
}
var target = void 0;
var previous = void 0;
var listElement = $(this._element).closest(Selector.LIST)[0];
var selector = Util.getSelectorFromElement(this._element);
if (listElement) {
previous = $.makeArray($(listElement).find(Selector.ACTIVE));
previous = previous[previous.length - 1];
}
var hideEvent = $.Event(Event.HIDE, {
relatedTarget: this._element
});
var showEvent = $.Event(Event.SHOW, {
relatedTarget: previous
});
if (previous) {
$(previous).trigger(hideEvent);
}
$(this._element).trigger(showEvent);
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) {
return;
}
if (selector) {
target = $(selector)[0];
}
this._activate(this._element, listElement);
var complete = function complete() {
var hiddenEvent = $.Event(Event.HIDDEN, {
relatedTarget: _this20._element
});
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: previous
});
$(previous).trigger(hiddenEvent);
$(_this20._element).trigger(shownEvent);
};
if (target) {
this._activate(target, target.parentNode, complete);
} else {
complete();
}
};
Tab.prototype.dispose = function dispose() {
$.removeClass(this._element, DATA_KEY);
this._element = null;
};
// private
Tab.prototype._activate = function _activate(element, container, callback) {
var _this21 = this;
var active = $(container).find(Selector.ACTIVE_CHILD)[0];
var isTransitioning = callback && Util.supportsTransitionEnd() && (active && $(active).hasClass(ClassName.FADE) || Boolean($(container).find(Selector.FADE_CHILD)[0]));
var complete = function complete() {
return _this21._transitionComplete(element, active, isTransitioning, callback);
};
if (active && isTransitioning) {
$(active).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
complete();
}
if (active) {
$(active).removeClass(ClassName.SHOW);
}
};
Tab.prototype._transitionComplete = function _transitionComplete(element, active, isTransitioning, callback) {
if (active) {
$(active).removeClass(ClassName.ACTIVE);
var dropdownChild = $(active.parentNode).find(Selector.DROPDOWN_ACTIVE_CHILD)[0];
if (dropdownChild) {
$(dropdownChild).removeClass(ClassName.ACTIVE);
}
active.setAttribute('aria-expanded', false);
}
$(element).addClass(ClassName.ACTIVE);
element.setAttribute('aria-expanded', true);
if (isTransitioning) {
Util.reflow(element);
$(element).addClass(ClassName.SHOW);
} else {
$(element).removeClass(ClassName.FADE);
}
if (element.parentNode && $(element.parentNode).hasClass(ClassName.DROPDOWN_MENU)) {
var dropdownElement = $(element).closest(Selector.DROPDOWN)[0];
if (dropdownElement) {
$(dropdownElement).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
}
element.setAttribute('aria-expanded', true);
}
if (callback) {
callback();
}
};
// static
Tab._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $(this);
var data = $this.data(DATA_KEY);
if (!data) {
data = new Tab(this);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
};
_createClass(Tab, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Tab;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
Tab._jQueryInterface.call($(this), 'show');
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Tab._jQueryInterface;
$.fn[NAME].Constructor = Tab;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Tab._jQueryInterface;
};
return Tab;
}(jQuery);
/* global Tether */
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): tooltip.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tooltip = function ($) {
/**
* Check for Tether dependency
* Tether - http://tether.io/
*/
if (typeof Tether === 'undefined') {
throw new Error('Bootstrap tooltips require Tether (http://tether.io/)');
}
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tooltip';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.tooltip';
var EVENT_KEY = '.' + DATA_KEY;
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var CLASS_PREFIX = 'bs-tether';
var Default = {
animation: true,
template: '<div class="tooltip" role="tooltip">' + '<div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
selector: false,
placement: 'top',
offset: '0 0',
constraints: [],
container: false
};
var DefaultType = {
animation: 'boolean',
template: 'string',
title: '(string|element|function)',
trigger: 'string',
delay: '(number|object)',
html: 'boolean',
selector: '(string|boolean)',
placement: '(string|function)',
offset: 'string',
constraints: 'array',
container: '(string|element|boolean)'
};
var AttachmentMap = {
TOP: 'bottom center',
RIGHT: 'middle left',
BOTTOM: 'top center',
LEFT: 'middle right'
};
var HoverState = {
SHOW: 'show',
OUT: 'out'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
INSERTED: 'inserted' + EVENT_KEY,
CLICK: 'click' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
FOCUSOUT: 'focusout' + EVENT_KEY,
MOUSEENTER: 'mouseenter' + EVENT_KEY,
MOUSELEAVE: 'mouseleave' + EVENT_KEY
};
var ClassName = {
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
TOOLTIP: '.tooltip',
TOOLTIP_INNER: '.tooltip-inner'
};
var TetherClass = {
element: false,
enabled: false
};
var Trigger = {
HOVER: 'hover',
FOCUS: 'focus',
CLICK: 'click',
MANUAL: 'manual'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Tooltip = function () {
function Tooltip(element, config) {
_classCallCheck(this, Tooltip);
// private
this._isEnabled = true;
this._timeout = 0;
this._hoverState = '';
this._activeTrigger = {};
this._isTransitioning = false;
this._tether = null;
// protected
this.element = element;
this.config = this._getConfig(config);
this.tip = null;
this._setListeners();
}
// getters
// public
Tooltip.prototype.enable = function enable() {
this._isEnabled = true;
};
Tooltip.prototype.disable = function disable() {
this._isEnabled = false;
};
Tooltip.prototype.toggleEnabled = function toggleEnabled() {
this._isEnabled = !this._isEnabled;
};
Tooltip.prototype.toggle = function toggle(event) {
if (event) {
var dataKey = this.constructor.DATA_KEY;
var context = $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
context._activeTrigger.click = !context._activeTrigger.click;
if (context._isWithActiveTrigger()) {
context._enter(null, context);
} else {
context._leave(null, context);
}
} else {
if ($(this.getTipElement()).hasClass(ClassName.SHOW)) {
this._leave(null, this);
return;
}
this._enter(null, this);
}
};
Tooltip.prototype.dispose = function dispose() {
clearTimeout(this._timeout);
this.cleanupTether();
$.removeData(this.element, this.constructor.DATA_KEY);
$(this.element).off(this.constructor.EVENT_KEY);
$(this.element).closest('.modal').off('hide.bs.modal');
if (this.tip) {
$(this.tip).remove();
}
this._isEnabled = null;
this._timeout = null;
this._hoverState = null;
this._activeTrigger = null;
this._tether = null;
this.element = null;
this.config = null;
this.tip = null;
};
Tooltip.prototype.show = function show() {
var _this22 = this;
if ($(this.element).css('display') === 'none') {
throw new Error('Please use show on visible elements');
}
var showEvent = $.Event(this.constructor.Event.SHOW);
if (this.isWithContent() && this._isEnabled) {
if (this._isTransitioning) {
throw new Error('Tooltip is transitioning');
}
$(this.element).trigger(showEvent);
var isInTheDom = $.contains(this.element.ownerDocument.documentElement, this.element);
if (showEvent.isDefaultPrevented() || !isInTheDom) {
return;
}
var tip = this.getTipElement();
var tipId = Util.getUID(this.constructor.NAME);
tip.setAttribute('id', tipId);
this.element.setAttribute('aria-describedby', tipId);
this.setContent();
if (this.config.animation) {
$(tip).addClass(ClassName.FADE);
}
var placement = typeof this.config.placement === 'function' ? this.config.placement.call(this, tip, this.element) : this.config.placement;
var attachment = this._getAttachment(placement);
var container = this.config.container === false ? document.body : $(this.config.container);
$(tip).data(this.constructor.DATA_KEY, this).appendTo(container);
$(this.element).trigger(this.constructor.Event.INSERTED);
this._tether = new Tether({
attachment: attachment,
element: tip,
target: this.element,
classes: TetherClass,
classPrefix: CLASS_PREFIX,
offset: this.config.offset,
constraints: this.config.constraints,
addTargetClasses: false
});
Util.reflow(tip);
this._tether.position();
$(tip).addClass(ClassName.SHOW);
var complete = function complete() {
var prevHoverState = _this22._hoverState;
_this22._hoverState = null;
_this22._isTransitioning = false;
$(_this22.element).trigger(_this22.constructor.Event.SHOWN);
if (prevHoverState === HoverState.OUT) {
_this22._leave(null, _this22);
}
};
if (Util.supportsTransitionEnd() && $(this.tip).hasClass(ClassName.FADE)) {
this._isTransitioning = true;
$(this.tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(Tooltip._TRANSITION_DURATION);
return;
}
complete();
}
};
Tooltip.prototype.hide = function hide(callback) {
var _this23 = this;
var tip = this.getTipElement();
var hideEvent = $.Event(this.constructor.Event.HIDE);
if (this._isTransitioning) {
throw new Error('Tooltip is transitioning');
}
var complete = function complete() {
if (_this23._hoverState !== HoverState.SHOW && tip.parentNode) {
tip.parentNode.removeChild(tip);
}
_this23.element.removeAttribute('aria-describedby');
$(_this23.element).trigger(_this23.constructor.Event.HIDDEN);
_this23._isTransitioning = false;
_this23.cleanupTether();
if (callback) {
callback();
}
};
$(this.element).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
return;
}
$(tip).removeClass(ClassName.SHOW);
this._activeTrigger[Trigger.CLICK] = false;
this._activeTrigger[Trigger.FOCUS] = false;
this._activeTrigger[Trigger.HOVER] = false;
if (Util.supportsTransitionEnd() && $(this.tip).hasClass(ClassName.FADE)) {
this._isTransitioning = true;
$(tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
complete();
}
this._hoverState = '';
};
// protected
Tooltip.prototype.isWithContent = function isWithContent() {
return Boolean(this.getTitle());
};
Tooltip.prototype.getTipElement = function getTipElement() {
return this.tip = this.tip || $(this.config.template)[0];
};
Tooltip.prototype.setContent = function setContent() {
var $tip = $(this.getTipElement());
this.setElementContent($tip.find(Selector.TOOLTIP_INNER), this.getTitle());
$tip.removeClass(ClassName.FADE + ' ' + ClassName.SHOW);
this.cleanupTether();
};
Tooltip.prototype.setElementContent = function setElementContent($element, content) {
var html = this.config.html;
if ((typeof content === 'undefined' ? 'undefined' : _typeof(content)) === 'object' && (content.nodeType || content.jquery)) {
// content is a DOM node or a jQuery
if (html) {
if (!$(content).parent().is($element)) {
$element.empty().append(content);
}
} else {
$element.text($(content).text());
}
} else {
$element[html ? 'html' : 'text'](content);
}
};
Tooltip.prototype.getTitle = function getTitle() {
var title = this.element.getAttribute('data-original-title');
if (!title) {
title = typeof this.config.title === 'function' ? this.config.title.call(this.element) : this.config.title;
}
return title;
};
Tooltip.prototype.cleanupTether = function cleanupTether() {
if (this._tether) {
this._tether.destroy();
}
};
// private
Tooltip.prototype._getAttachment = function _getAttachment(placement) {
return AttachmentMap[placement.toUpperCase()];
};
Tooltip.prototype._setListeners = function _setListeners() {
var _this24 = this;
var triggers = this.config.trigger.split(' ');
triggers.forEach(function (trigger) {
if (trigger === 'click') {
$(_this24.element).on(_this24.constructor.Event.CLICK, _this24.config.selector, function (event) {
return _this24.toggle(event);
});
} else if (trigger !== Trigger.MANUAL) {
var eventIn = trigger === Trigger.HOVER ? _this24.constructor.Event.MOUSEENTER : _this24.constructor.Event.FOCUSIN;
var eventOut = trigger === Trigger.HOVER ? _this24.constructor.Event.MOUSELEAVE : _this24.constructor.Event.FOCUSOUT;
$(_this24.element).on(eventIn, _this24.config.selector, function (event) {
return _this24._enter(event);
}).on(eventOut, _this24.config.selector, function (event) {
return _this24._leave(event);
});
}
$(_this24.element).closest('.modal').on('hide.bs.modal', function () {
return _this24.hide();
});
});
if (this.config.selector) {
this.config = $.extend({}, this.config, {
trigger: 'manual',
selector: ''
});
} else {
this._fixTitle();
}
};
Tooltip.prototype._fixTitle = function _fixTitle() {
var titleType = _typeof(this.element.getAttribute('data-original-title'));
if (this.element.getAttribute('title') || titleType !== 'string') {
this.element.setAttribute('data-original-title', this.element.getAttribute('title') || '');
this.element.setAttribute('title', '');
}
};
Tooltip.prototype._enter = function _enter(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusin' ? Trigger.FOCUS : Trigger.HOVER] = true;
}
if ($(context.getTipElement()).hasClass(ClassName.SHOW) || context._hoverState === HoverState.SHOW) {
context._hoverState = HoverState.SHOW;
return;
}
clearTimeout(context._timeout);
context._hoverState = HoverState.SHOW;
if (!context.config.delay || !context.config.delay.show) {
context.show();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HoverState.SHOW) {
context.show();
}
}, context.config.delay.show);
};
Tooltip.prototype._leave = function _leave(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusout' ? Trigger.FOCUS : Trigger.HOVER] = false;
}
if (context._isWithActiveTrigger()) {
return;
}
clearTimeout(context._timeout);
context._hoverState = HoverState.OUT;
if (!context.config.delay || !context.config.delay.hide) {
context.hide();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HoverState.OUT) {
context.hide();
}
}, context.config.delay.hide);
};
Tooltip.prototype._isWithActiveTrigger = function _isWithActiveTrigger() {
for (var trigger in this._activeTrigger) {
if (this._activeTrigger[trigger]) {
return true;
}
}
return false;
};
Tooltip.prototype._getConfig = function _getConfig(config) {
config = $.extend({}, this.constructor.Default, $(this.element).data(), config);
if (config.delay && typeof config.delay === 'number') {
config.delay = {
show: config.delay,
hide: config.delay
};
}
Util.typeCheckConfig(NAME, config, this.constructor.DefaultType);
return config;
};
Tooltip.prototype._getDelegateConfig = function _getDelegateConfig() {
var config = {};
if (this.config) {
for (var key in this.config) {
if (this.constructor.Default[key] !== this.config[key]) {
config[key] = this.config[key];
}
}
}
return config;
};
// static
Tooltip._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config;
if (!data && /dispose|hide/.test(config)) {
return;
}
if (!data) {
data = new Tooltip(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
};
_createClass(Tooltip, null, [{
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}, {
key: 'NAME',
get: function get() {
return NAME;
}
}, {
key: 'DATA_KEY',
get: function get() {
return DATA_KEY;
}
}, {
key: 'Event',
get: function get() {
return Event;
}
}, {
key: 'EVENT_KEY',
get: function get() {
return EVENT_KEY;
}
}, {
key: 'DefaultType',
get: function get() {
return DefaultType;
}
}]);
return Tooltip;
}();
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Tooltip._jQueryInterface;
$.fn[NAME].Constructor = Tooltip;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Tooltip._jQueryInterface;
};
return Tooltip;
}(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.6): popover.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Popover = function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'popover';
var VERSION = '4.0.0-alpha.6';
var DATA_KEY = 'bs.popover';
var EVENT_KEY = '.' + DATA_KEY;
var JQUERY_NO_CONFLICT = $.fn[NAME];
var Default = $.extend({}, Tooltip.Default, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip">' + '<h3 class="popover-title"></h3>' + '<div class="popover-content"></div></div>'
});
var DefaultType = $.extend({}, Tooltip.DefaultType, {
content: '(string|element|function)'
});
var ClassName = {
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
TITLE: '.popover-title',
CONTENT: '.popover-content'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
INSERTED: 'inserted' + EVENT_KEY,
CLICK: 'click' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
FOCUSOUT: 'focusout' + EVENT_KEY,
MOUSEENTER: 'mouseenter' + EVENT_KEY,
MOUSELEAVE: 'mouseleave' + EVENT_KEY
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Popover = function (_Tooltip) {
_inherits(Popover, _Tooltip);
function Popover() {
_classCallCheck(this, Popover);
return _possibleConstructorReturn(this, _Tooltip.apply(this, arguments));
}
// overrides
Popover.prototype.isWithContent = function isWithContent() {
return this.getTitle() || this._getContent();
};
Popover.prototype.getTipElement = function getTipElement() {
return this.tip = this.tip || $(this.config.template)[0];
};
Popover.prototype.setContent = function setContent() {
var $tip = $(this.getTipElement());
// we use append for html objects to maintain js events
this.setElementContent($tip.find(Selector.TITLE), this.getTitle());
this.setElementContent($tip.find(Selector.CONTENT), this._getContent());
$tip.removeClass(ClassName.FADE + ' ' + ClassName.SHOW);
this.cleanupTether();
};
// private
Popover.prototype._getContent = function _getContent() {
return this.element.getAttribute('data-content') || (typeof this.config.content === 'function' ? this.config.content.call(this.element) : this.config.content);
};
// static
Popover._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' ? config : null;
if (!data && /destroy|hide/.test(config)) {
return;
}
if (!data) {
data = new Popover(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
};
_createClass(Popover, null, [{
key: 'VERSION',
// getters
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}, {
key: 'NAME',
get: function get() {
return NAME;
}
}, {
key: 'DATA_KEY',
get: function get() {
return DATA_KEY;
}
}, {
key: 'Event',
get: function get() {
return Event;
}
}, {
key: 'EVENT_KEY',
get: function get() {
return EVENT_KEY;
}
}, {
key: 'DefaultType',
get: function get() {
return DefaultType;
}
}]);
return Popover;
}(Tooltip);
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Popover._jQueryInterface;
$.fn[NAME].Constructor = Popover;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Popover._jQueryInterface;
};
return Popover;
}(jQuery);
}();
|
// (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the terms of the MIT license.
// Portions of Underscore are inspired by or borrowed from Prototype.js,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets thrown to break out of a loop iteration.
var breaker = typeof StopIteration !== 'undefined' ? StopIteration : '__break__';
// Quick regexp-escaping function, because JS doesn't have a `RegExp.escape()`.
var escapeRegExp = function(s) { return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); };
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty,
propertyIsEnumerable = ObjProto.propertyIsEnumerable;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
// Export the Underscore object for **CommonJS**.
if (typeof exports !== 'undefined') exports._ = _;
// Export Underscore to the global scope.
root._ = _;
// Current version.
_.VERSION = '1.1.1';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation.
// Handles objects implementing `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.forEach = function(obj, iterator, context) {
try {
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (_.isNumber(obj.length)) {
for (var i = 0, l = obj.length; i < l; i++) iterator.call(context, obj[i], i, obj);
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) iterator.call(context, obj[key], key, obj);
}
}
} catch(e) {
if (e != breaker) throw e;
}
return obj;
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = function(obj, iterator, context) {
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
var results = [];
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = function(obj, iterator, memo, context) {
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return obj.reduce(iterator, memo);
}
each(obj, function(value, index, list) {
memo = iterator.call(context, memo, value, index, list);
});
return memo;
};
// The right-associative version of reduce, also known as `foldr`. Uses
// Delegates to **ECMAScript 5**'s native reduceRight if available.
_.reduceRight = function(obj, iterator, memo, context) {
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return obj.reduceRight(iterator, memo);
}
var reversed = _.clone(_.toArray(obj)).reverse();
return _.reduce(reversed, iterator, memo, context);
};
// Return the first value which passes a truth test.
_.detect = function(obj, iterator, context) {
var result;
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
_.breakLoop();
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
_.filter = function(obj, iterator, context) {
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
var results = [];
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) {
var results = [];
each(obj, function(value, index, list) {
if (!iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
_.every = function(obj, iterator, context) {
iterator = iterator || _.identity;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
var result = true;
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) _.breakLoop();
});
return result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
_.some = function(obj, iterator, context) {
iterator = iterator || _.identity;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
var result = false;
each(obj, function(value, index, list) {
if (result = iterator.call(context, value, index, list)) _.breakLoop();
});
return result;
};
// Determine if a given value is included in the array or object using `===`.
_.include = function(obj, target) {
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
var found = false;
each(obj, function(value) {
if (found = value === target) _.breakLoop();
});
return found;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (method ? value[method] : value).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]; });
};
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
var result = {computed : -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)) return Math.min.apply(Math, obj);
var result = {computed : 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;
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator = iterator || _.identity;
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
if (_.isArray(iterable)) return iterable;
if (_.isArguments(iterable)) return slice.call(iterable);
return _.values(iterable);
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.toArray(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`. The **guard** check allows it to work
// with `_.map`.
_.first = function(array, n, guard) {
return n && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
// check allows it to work with `_.map`.
_.rest = function(array, index, guard) {
return slice.call(array, _.isUndefined(index) || guard ? 1 : index);
};
// Get the last element of an array.
_.last = function(array) {
return array[array.length - 1];
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(_.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
var values = slice.call(arguments, 1);
return _.filter(array, function(value){ return !_.include(values, value); });
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
_.uniq = function(array, isSorted) {
return _.reduce(array, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
return memo;
}, []);
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// 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;
};
// 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 occurence 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.
_.indexOf = function(array, item) {
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (var i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
var i = 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) {
var a = slice.call(arguments);
var solo = a.length <= 1;
var start = solo ? 0 : a[0], stop = solo ? a[0] : a[1], step = a[2] || 1;
var len = Math.ceil((stop - start) / step);
if (len <= 0) return [];
var range = new Array(len);
for (var i = start, idx = 0; true; i += step) {
if ((step > 0 ? i - stop : stop - i) >= 0) return range;
range[idx++] = i;
}
};
// Function Functions
// ------------------
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
_.bind = function(func, obj) {
var args = slice.call(arguments, 2);
return function() {
return func.apply(obj || {}, 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 key in memo ? 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(func, 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 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].concat(slice.call(arguments));
return wrapper.apply(wrapper, 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 = slice.call(arguments);
return function() {
var args = slice.call(arguments);
for (var i=funcs.length-1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (_.isArray(obj)) return _.range(0, obj.length);
var keys = [];
for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.map(obj, _.identity);
};
// Return a sorted list of the function names available on the object.
_.functions = function(obj) {
return _.filter(_.keys(obj), function(key){ return _.isFunction(obj[key]); }).sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) obj[prop] = source[prop];
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (_.isArray(obj)) return obj.slice(0);
return _.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;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
// Check object identity.
if (a === b) return true;
// Different types?
var atype = typeof(a), btype = typeof(b);
if (atype != btype) return false;
// Basic equality test (watch out for coercions).
if (a == b) return true;
// One is falsy and the other truthy.
if ((!a && b) || (a && !b)) return false;
// One of them implements an isEqual()?
if (a.isEqual) return a.isEqual(b);
// Check dates' integer values.
if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
// Both are NaN?
if (_.isNaN(a) && _.isNaN(b)) return false;
// Compare regular expressions.
if (_.isRegExp(a) && _.isRegExp(b))
return a.source === b.source &&
a.global === b.global &&
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
// If a is not an object by this point, we can't handle it.
if (atype !== 'object') return false;
// Check for different array lengths before comparing contents.
if (a.length && (a.length !== b.length)) return false;
// Nothing else worked, deep compare the contents.
var aKeys = _.keys(a), bKeys = _.keys(b);
// Different object sizes?
if (aKeys.length != bKeys.length) return false;
// Recursive comparison of contents.
for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
return true;
};
// Is a given array or object empty?
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (hasOwnProperty.call(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 !!(obj && obj.concat && obj.unshift && !obj.callee);
};
// Is a given variable an arguments object?
_.isArguments = function(obj) {
return !!(obj && obj.callee);
};
// Is a given value a function?
_.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
// Is a given value a string?
_.isString = function(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
};
// Is a given value a number?
_.isNumber = function(obj) {
return (obj === +obj) || (toString.call(obj) === '[object Number]');
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false;
};
// Is a given value a date?
_.isDate = function(obj) {
return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
// Is the given value NaN -- this one is interesting. NaN != NaN, and
// isNaN(undefined) == true, so we make sure it's a number first.
_.isNaN = function(obj) {
return _.isNumber(obj) && isNaN(obj);
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return typeof obj == 'undefined';
};
// 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) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Break out of the middle of an iteration.
_.breakLoop = function() {
throw breaker;
};
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
addToWrapper(name, _[name] = obj[name]);
});
};
// 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
};
// 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(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/'/g, "\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', tmpl);
return data ? func(data) : func;
};
// Aliases:
// --------
_.each = _.forEach;
_.foldl = _.inject = _.reduce;
_.foldr = _.reduceRight;
_.select = _.filter;
_.all = _.every;
_.any = _.some;
_.contains = _.include;
_.head = _.first;
_.tail = _.rest;
_.methods = _.functions;
// The OOP Wrapper
// ---------------
// 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.
var wrapper = function(obj) { this._wrapped = obj; };
// Helper function to continue chaining intermediate results.
var result = function(obj, chain) {
return chain ? _(obj).chain() : obj;
};
// A method to easily add functions to the OOP wrapper.
var addToWrapper = function(name, func) {
wrapper.prototype[name] = function() {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(_, args), this._chain);
};
};
// 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];
wrapper.prototype[name] = function() {
method.apply(this._wrapped, arguments);
return result(this._wrapped, this._chain);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
return result(method.apply(this._wrapped, arguments), this._chain);
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.value = function() {
return this._wrapped;
};
})();
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v3.3.0
* @link http://www.ag-grid.com/
* @license MIT
*/
// class returns unique instance id's for columns.
// eg, the following calls (in this order) will result in:
//
// getInstanceIdForKey('country') => 0
// getInstanceIdForKey('country') => 1
// getInstanceIdForKey('country') => 2
// getInstanceIdForKey('country') => 3
// getInstanceIdForKey('age') => 0
// getInstanceIdForKey('age') => 1
// getInstanceIdForKey('country') => 4
var GroupInstanceIdCreator = (function () {
function GroupInstanceIdCreator() {
// this map contains keys to numbers, so we remember what the last call was
this.existingIds = {};
}
GroupInstanceIdCreator.prototype.getInstanceIdForKey = function (key) {
var lastResult = this.existingIds[key];
var result;
if (typeof lastResult !== 'number') {
// first time this key
result = 0;
}
else {
result = lastResult + 1;
}
this.existingIds[key] = result;
return result;
};
return GroupInstanceIdCreator;
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = GroupInstanceIdCreator;
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'liststyle', 'pt', {
armenian: 'Numeração armênia',
bulletedTitle: 'Bulleted List Properties',
circle: 'Círculo',
decimal: 'Decimal (1, 2, 3, etc.)',
decimalLeadingZero: 'Decimal leading zero (01, 02, 03, etc.)',
disc: 'Disco',
georgian: 'Georgian numbering (an, ban, gan, etc.)',
lowerAlpha: 'Lower Alpha (a, b, c, d, e, etc.)',
lowerGreek: 'Lower Greek (alpha, beta, gamma, etc.)',
lowerRoman: 'Lower Roman (i, ii, iii, iv, v, etc.)',
none: 'Nenhum',
notset: '<not set>',
numberedTitle: 'Numbered List Properties',
square: 'Quadrado',
start: 'Iniciar',
type: 'Tipo',
upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)',
upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)',
validateStartNumber: 'List start number must be a whole number.'
});
|
function strcspn (str, mask, start, length) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brett-zamir.me)
// * example 1: strcspn('abcdefg123', '1234567890');
// * returns 1: 7
// * example 2: strcspn('123abc', '1234567890');
// * returns 2: 3
start = start ? start : 0;
var count = (length && ((start + length) < str.length)) ? start + length : str.length;
strct: for (var i = start, lgth = 0; i < count; i++) {
for (var j = 0; j < mask.length; j++) {
if (str.charAt(i).indexOf(mask[j]) !== -1) {
continue strct;
}
}++lgth;
}
return lgth;
}
|
'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
var url = 'https://raw.githubusercontent.com/imagemin/jpegtran-bin/v' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'macos/jpegtran', 'darwin')
.src(url + 'linux/x86/jpegtran', 'linux', 'x86')
.src(url + 'linux/x64/jpegtran', 'linux', 'x64')
.src(url + 'freebsd/x86/jpegtran', 'freebsd', 'x86')
.src(url + 'freebsd/x64/jpegtran', 'freebsd', 'x64')
.src(url + 'sunos/x86/jpegtran', 'sunos', 'x86')
.src(url + 'sunos/x64/jpegtran', 'sunos', 'x64')
.src(url + 'win/x86/jpegtran.exe', 'win32', 'x86')
.src(url + 'win/x64/jpegtran.exe', 'win32', 'x64')
.src(url + 'win/x86/libjpeg-62.dll', 'win32', 'x86')
.src(url + 'win/x64/libjpeg-62.dll', 'win32', 'x64')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'jpegtran.exe' : 'jpegtran');
|
/*!
* FullCalendar v2.7.3 Google Calendar Plugin
* Docs & License: http://fullcalendar.io/
* (c) 2016 Adam Shaw
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
define([ 'jquery' ], factory);
}
else if (typeof exports === 'object') { // Node/CommonJS
module.exports = factory(require('jquery'));
}
else {
factory(jQuery);
}
})(function($) {
var API_BASE = 'https://www.googleapis.com/calendar/v3/calendars';
var FC = $.fullCalendar;
var applyAll = FC.applyAll;
FC.sourceNormalizers.push(function(sourceOptions) {
var googleCalendarId = sourceOptions.googleCalendarId;
var url = sourceOptions.url;
var match;
// if the Google Calendar ID hasn't been explicitly defined
if (!googleCalendarId && url) {
// detect if the ID was specified as a single string.
// will match calendars like "asdf1234@calendar.google.com" in addition to person email calendars.
if (/^[^\/]+@([^\/\.]+\.)*(google|googlemail|gmail)\.com$/.test(url)) {
googleCalendarId = url;
}
// try to scrape it out of a V1 or V3 API feed URL
else if (
(match = /^https:\/\/www.googleapis.com\/calendar\/v3\/calendars\/([^\/]*)/.exec(url)) ||
(match = /^https?:\/\/www.google.com\/calendar\/feeds\/([^\/]*)/.exec(url))
) {
googleCalendarId = decodeURIComponent(match[1]);
}
if (googleCalendarId) {
sourceOptions.googleCalendarId = googleCalendarId;
}
}
if (googleCalendarId) { // is this a Google Calendar?
// make each Google Calendar source uneditable by default
if (sourceOptions.editable == null) {
sourceOptions.editable = false;
}
// We want removeEventSource to work, but it won't know about the googleCalendarId primitive.
// Shoehorn it into the url, which will function as the unique primitive. Won't cause side effects.
// This hack is obsolete since 2.2.3, but keep it so this plugin file is compatible with old versions.
sourceOptions.url = googleCalendarId;
}
});
FC.sourceFetchers.push(function(sourceOptions, start, end, timezone) {
if (sourceOptions.googleCalendarId) {
return transformOptions(sourceOptions, start, end, timezone, this); // `this` is the calendar
}
});
function transformOptions(sourceOptions, start, end, timezone, calendar) {
var url = API_BASE + '/' + encodeURIComponent(sourceOptions.googleCalendarId) + '/events?callback=?'; // jsonp
var apiKey = sourceOptions.googleCalendarApiKey || calendar.options.googleCalendarApiKey;
var success = sourceOptions.success;
var data;
var timezoneArg; // populated when a specific timezone. escaped to Google's liking
function reportError(message, apiErrorObjs) {
var errorObjs = apiErrorObjs || [ { message: message } ]; // to be passed into error handlers
// call error handlers
(sourceOptions.googleCalendarError || $.noop).apply(calendar, errorObjs);
(calendar.options.googleCalendarError || $.noop).apply(calendar, errorObjs);
// print error to debug console
FC.warn.apply(null, [ message ].concat(apiErrorObjs || []));
}
if (!apiKey) {
reportError("Specify a googleCalendarApiKey. See http://fullcalendar.io/docs/google_calendar/");
return {}; // an empty source to use instead. won't fetch anything.
}
// The API expects an ISO8601 datetime with a time and timezone part.
// Since the calendar's timezone offset isn't always known, request the date in UTC and pad it by a day on each
// side, guaranteeing we will receive all events in the desired range, albeit a superset.
// .utc() will set a zone and give it a 00:00:00 time.
if (!start.hasZone()) {
start = start.clone().utc().add(-1, 'day');
}
if (!end.hasZone()) {
end = end.clone().utc().add(1, 'day');
}
// when sending timezone names to Google, only accepts underscores, not spaces
if (timezone && timezone != 'local') {
timezoneArg = timezone.replace(' ', '_');
}
data = $.extend({}, sourceOptions.data || {}, {
key: apiKey,
timeMin: start.format(),
timeMax: end.format(),
timeZone: timezoneArg,
singleEvents: true,
maxResults: 9999
});
return $.extend({}, sourceOptions, {
googleCalendarId: null, // prevents source-normalizing from happening again
url: url,
data: data,
startParam: false, // `false` omits this parameter. we already included it above
endParam: false, // same
timezoneParam: false, // same
success: function(data) {
var events = [];
var successArgs;
var successRes;
if (data.error) {
reportError('Google Calendar API: ' + data.error.message, data.error.errors);
}
else if (data.items) {
$.each(data.items, function(i, entry) {
var url = entry.htmlLink || null;
// make the URLs for each event show times in the correct timezone
if (timezoneArg && url !== null) {
url = injectQsComponent(url, 'ctz=' + timezoneArg);
}
events.push({
id: entry.id,
title: entry.summary,
start: entry.start.dateTime || entry.start.date, // try timed. will fall back to all-day
end: entry.end.dateTime || entry.end.date, // same
url: url,
location: entry.location,
description: entry.description
});
});
// call the success handler(s) and allow it to return a new events array
successArgs = [ events ].concat(Array.prototype.slice.call(arguments, 1)); // forward other jq args
successRes = applyAll(success, this, successArgs);
if ($.isArray(successRes)) {
return successRes;
}
}
return events;
}
});
}
// Injects a string like "arg=value" into the querystring of a URL
function injectQsComponent(url, component) {
// inject it after the querystring but before the fragment
return url.replace(/(\?.*?)?(#|$)/, function(whole, qs, hash) {
return (qs ? qs + '&' : '?') + component + hash;
});
}
});
|
/*
* input.js
*
* All javascript needed for ACF to work
*
* @type awesome
* @date 1/08/13
*
* @param N/A
* @return N/A
*/
var acf = {
// vars
ajaxurl : '',
admin_url : '',
wp_version : '',
post_id : 0,
nonce : '',
l10n : null,
o : null,
// helper functions
helpers : {
get_atts : null,
version_compare : null,
uniqid : null,
sortable : null,
add_message : null,
is_clone_field : null,
url_to_object : null
},
// modules
validation : null,
conditional_logic : null,
media : null,
// fields
fields : {
date_picker : null,
color_picker : null,
Image : null,
file : null,
wysiwyg : null,
gallery : null,
relationship : null
}
};
(function($){
/*
* acf.helpers.isset
*
* description
*
* @type function
* @date 20/07/13
*
* @param {mixed} arguments
* @return {boolean}
*/
acf.helpers.isset = function(){
var a = arguments,
l = a.length,
c = null,
undef;
if (l === 0) {
throw new Error('Empty isset');
}
c = a[0];
for (i = 1; i < l; i++) {
if (a[i] === undef || c[ a[i] ] === undef) {
return false;
}
c = c[ a[i] ];
}
return true;
};
/*
* acf.helpers.get_atts
*
* description
*
* @type function
* @date 1/06/13
*
* @param {el} $el
* @return {object} atts
*/
acf.helpers.get_atts = function( $el ){
var atts = {};
$.each( $el[0].attributes, function( index, attr ) {
if( attr.name.substr(0, 5) == 'data-' )
{
atts[ attr.name.replace('data-', '') ] = attr.value;
}
});
return atts;
};
/**
* Simply compares two string version values.
*
* Example:
* versionCompare('1.1', '1.2') => -1
* versionCompare('1.1', '1.1') => 0
* versionCompare('1.2', '1.1') => 1
* versionCompare('2.23.3', '2.22.3') => 1
*
* Returns:
* -1 = left is LOWER than right
* 0 = they are equal
* 1 = left is GREATER = right is LOWER
* And FALSE if one of input versions are not valid
*
* @function
* @param {String} left Version #1
* @param {String} right Version #2
* @return {Integer|Boolean}
* @author Alexey Bass (albass)
* @since 2011-07-14
*/
acf.helpers.version_compare = function(left, right)
{
if (typeof left + typeof right != 'stringstring')
return false;
var a = left.split('.')
, b = right.split('.')
, i = 0, len = Math.max(a.length, b.length);
for (; i < len; i++) {
if ((a[i] && !b[i] && parseInt(a[i]) > 0) || (parseInt(a[i]) > parseInt(b[i]))) {
return 1;
} else if ((b[i] && !a[i] && parseInt(b[i]) > 0) || (parseInt(a[i]) < parseInt(b[i]))) {
return -1;
}
}
return 0;
};
/*
* Helper: uniqid
*
* @description:
* @since: 3.5.8
* @created: 17/01/13
*/
acf.helpers.uniqid = function()
{
var newDate = new Date;
return newDate.getTime();
};
/*
* Helper: url_to_object
*
* @description:
* @since: 4.0.0
* @created: 17/01/13
*/
acf.helpers.url_to_object = function( url ){
// vars
var obj = {},
pairs = url.split('&');
for( i in pairs )
{
var split = pairs[i].split('=');
obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
}
return obj;
};
/*
* Sortable Helper
*
* @description: keeps widths of td's inside a tr
* @since 3.5.1
* @created: 10/11/12
*/
acf.helpers.sortable = function(e, ui)
{
ui.children().each(function(){
$(this).width($(this).width());
});
return ui;
};
/*
* is_clone_field
*
* @description:
* @since: 3.5.8
* @created: 17/01/13
*/
acf.helpers.is_clone_field = function( input )
{
if( input.attr('name') && input.attr('name').indexOf('[acfcloneindex]') != -1 )
{
return true;
}
return false;
};
/*
* acf.helpers.add_message
*
* @description:
* @since: 3.2.7
* @created: 10/07/2012
*/
acf.helpers.add_message = function( message, div ){
var message = $('<div class="acf-message-wrapper"><div class="message updated"><p>' + message + '</p></div></div>');
div.prepend( message );
setTimeout(function(){
message.animate({
opacity : 0
}, 250, function(){
message.remove();
});
}, 1500);
};
/*
* Exists
*
* @description: returns true / false
* @created: 1/03/2011
*/
$.fn.exists = function()
{
return $(this).length>0;
};
/*
* 3.5 Media
*
* @description:
* @since: 3.5.7
* @created: 16/01/13
*/
acf.media = {
div : null,
frame : null,
render_timout : null,
clear_frame : function(){
// validate
if( !this.frame )
{
return;
}
// detach
this.frame.detach();
this.frame.dispose();
// reset var
this.frame = null;
},
type : function(){
// default
var type = 'thickbox';
// if wp exists
if( typeof wp !== 'undefined' )
{
type = 'backbone';
}
// return
return type;
},
init : function(){
// validate
if( this.type() !== 'backbone' )
{
return false;
}
// validate prototype
if( ! acf.helpers.isset(wp, 'media', 'view', 'AttachmentCompat', 'prototype') )
{
return false;
}
// vars
var _prototype = wp.media.view.AttachmentCompat.prototype;
// orig
_prototype.orig_render = _prototype.render;
_prototype.orig_dispose = _prototype.dispose;
// update class
_prototype.className = 'compat-item acf_postbox no_box';
// modify render
_prototype.render = function() {
// reference
var _this = this;
// validate
if( _this.ignore_render )
{
return this;
}
// run the old render function
this.orig_render();
// add button
setTimeout(function(){
// vars
var $media_model = _this.$el.closest('.media-modal');
// is this an edit only modal?
if( $media_model.hasClass('acf-media-modal') )
{
return;
}
// does button already exist?
if( $media_model.find('.media-frame-router .acf-expand-details').exists() )
{
return;
}
// create button
var button = $([
'<a href="#" class="acf-expand-details">',
'<span class="icon"></span>',
'<span class="is-closed">' + acf.l10n.core.expand_details + '</span>',
'<span class="is-open">' + acf.l10n.core.collapse_details + '</span>',
'</a>'
].join(''));
// add events
button.on('click', function( e ){
e.preventDefault();
if( $media_model.hasClass('acf-expanded') )
{
$media_model.removeClass('acf-expanded');
}
else
{
$media_model.addClass('acf-expanded');
}
});
// append
$media_model.find('.media-frame-router').append( button );
}, 0);
// setup fields
// The clearTimout is needed to prevent many setup functions from running at the same time
clearTimeout( acf.media.render_timout );
acf.media.render_timout = setTimeout(function(){
$(document).trigger( 'acf/setup_fields', [ _this.$el ] );
}, 50);
// return based on the origional render function
return this;
};
// modify dispose
_prototype.dispose = function() {
// remove
$(document).trigger('acf/remove_fields', [ this.$el ]);
// run the old render function
this.orig_dispose();
};
// override save
_prototype.save = function( event ) {
var data = {},
names = {};
if ( event )
event.preventDefault();
_.each( this.$el.serializeArray(), function( pair ) {
// initiate name
if( pair.name.slice(-2) === '[]' )
{
// remove []
pair.name = pair.name.replace('[]', '');
// initiate counter
if( typeof names[ pair.name ] === 'undefined'){
names[ pair.name ] = -1;
//console.log( names[ pair.name ] );
}
names[ pair.name ]++
pair.name += '[' + names[ pair.name ] +']';
}
data[ pair.name ] = pair.value;
});
this.ignore_render = true;
this.model.saveCompat( data );
};
}
};
/*
* Conditional Logic Calculate
*
* @description:
* @since 3.5.1
* @created: 15/10/12
*/
acf.conditional_logic = {
items : [],
init : function(){
// reference
var _this = this;
// events
$(document).on('change', '.field input, .field textarea, .field select', function(){
// preview hack
if( $('#acf-has-changed').exists() )
{
$('#acf-has-changed').val(1);
}
_this.change( $(this) );
});
$(document).on('acf/setup_fields', function(e, el){
//console.log('acf/setup_fields calling acf.conditional_logic.refresh()');
_this.refresh( $(el) );
});
//console.log('acf.conditional_logic.init() calling acf.conditional_logic.refresh()');
_this.refresh();
},
change : function( $el ){
//console.log('change %o', $el);
// reference
var _this = this;
// vars
var $field = $el.closest('.field'),
key = $field.attr('data-field_key');
// loop through items and find rules where this field key is a trigger
$.each(this.items, function( k, item ){
$.each(item.rules, function( k2, rule ){
// compare rule against the changed $field
if( rule.field == key )
{
_this.refresh_field( item );
}
});
});
},
refresh_field : function( item ){
//console.log( 'refresh_field: %o ', item );
// reference
var _this = this;
// vars
var $targets = $('.field_key-' + item.field);
// may be multiple targets (sub fields)
$targets.each(function(){
//console.log('target %o', $(this));
// vars
var show = true;
// if 'any' was selected, start of as false and any match will result in show = true
if( item.allorany == 'any' )
{
show = false;
}
// vars
var $target = $(this),
hide_all = true;
// loop through rules
$.each(item.rules, function( k2, rule ){
// vars
var $toggle = $('.field_key-' + rule.field);
// are any of $toggle a sub field?
if( $toggle.hasClass('sub_field') )
{
// toggle may be a sibling sub field.
// if so ,show an empty td but keep the column
$toggle = $target.siblings('.field_key-' + rule.field);
hide_all = false;
// if no toggle was found, we need to look at parent sub fields.
// if so, hide the entire column
if( ! $toggle.exists() )
{
// loop through all the parents that could contain sub fields
$target.parents('tr').each(function(){
// attempt to update $toggle to this parent sub field
$toggle = $(this).find('.field_key-' + rule.field)
// if the parent sub field actuallly exists, great! Stop the loop
if( $toggle.exists() )
{
return false;
}
});
hide_all = true;
}
}
// if this sub field is within a flexible content layout, hide the entire column because
// there will never be another row added to this table
var parent = $target.parent('tr').parent().parent('table').parent('.layout');
if( parent.exists() )
{
hide_all = true;
if( $target.is('th') && $toggle.is('th') )
{
$toggle = $target.closest('.layout').find('td.field_key-' + rule.field);
}
}
// if this sub field is within a repeater field which has a max row of 1, hide the entire column because
// there will never be another row added to this table
var parent = $target.parent('tr').parent().parent('table').parent('.repeater');
if( parent.exists() && parent.attr('data-max_rows') == '1' )
{
hide_all = true;
if( $target.is('th') && $toggle.is('th') )
{
$toggle = $target.closest('table').find('td.field_key-' + rule.field);
}
}
var calculate = _this.calculate( rule, $toggle, $target );
if( item.allorany == 'all' )
{
if( calculate == false )
{
show = false;
// end loop
return false;
}
}
else
{
if( calculate == true )
{
show = true;
// end loop
return false;
}
}
});
// $.each(item.rules, function( k2, rule ){
// clear classes
$target.removeClass('acf-conditional_logic-hide acf-conditional_logic-show acf-show-blank');
// hide / show field
if( show )
{
// remove "disabled"
$target.find('input, textarea, select').removeAttr('disabled');
$target.addClass('acf-conditional_logic-show');
// hook
$(document).trigger('acf/conditional_logic/show', [ $target, item ]);
}
else
{
// add "disabled"
$target.find('input, textarea, select').attr('disabled', 'disabled');
$target.addClass('acf-conditional_logic-hide');
if( !hide_all )
{
$target.addClass('acf-show-blank');
}
// hook
$(document).trigger('acf/conditional_logic/hide', [ $target, item ]);
}
});
},
refresh : function( $el ){
// defaults
$el = $el || $('body');
// reference
var _this = this;
// loop through items and find rules where this field key is a trigger
$.each(this.items, function( k, item ){
$.each(item.rules, function( k2, rule ){
// is this field within the $el
// this will increase performance by ignoring conditional logic outside of this newly appended element ($el)
if( ! $el.find('.field[data-field_key="' + item.field + '"]').exists() )
{
return;
}
_this.refresh_field( item );
});
});
},
calculate : function( rule, $toggle, $target ){
// vars
var r = false;
// compare values
if( $toggle.hasClass('field_type-true_false') || $toggle.hasClass('field_type-checkbox') || $toggle.hasClass('field_type-radio') )
{
var exists = $toggle.find('input[value="' + rule.value + '"]:checked').exists();
if( rule.operator == "==" )
{
if( exists )
{
r = true;
}
}
else
{
if( ! exists )
{
r = true;
}
}
}
else
{
// get val and make sure it is an array
var val = $toggle.find('input, textarea, select').last().val();
if( ! $.isArray(val) )
{
val = [ val ];
}
if( rule.operator == "==" )
{
if( $.inArray(rule.value, val) > -1 )
{
r = true;
}
}
else
{
if( $.inArray(rule.value, val) < 0 )
{
r = true;
}
}
}
// return
return r;
}
};
/*
* Document Ready
*
* @description:
* @since: 3.5.8
* @created: 17/01/13
*/
$(document).ready(function(){
// conditional logic
acf.conditional_logic.init();
// fix for older options page add-on
$('.acf_postbox > .inside > .options').each(function(){
$(this).closest('.acf_postbox').addClass( $(this).attr('data-layout') );
});
// Remove 'field_123' from native custom field metabox
$('#metakeyselect option[value^="field_"]').remove();
});
/*
* window load
*
* @description:
* @since: 3.5.5
* @created: 22/12/12
*/
$(window).on('load', function(){
// init
acf.media.init();
setTimeout(function(){
// Hack for CPT without a content editor
try
{
// post_id may be string (user_1) and therefore, the uploaded image cannot be attached to the post
if( $.isNumeric(acf.o.post_id) )
{
wp.media.view.settings.post.id = acf.o.post_id;
}
}
catch(e)
{
// one of the objects was 'undefined'...
}
// setup fields
$(document).trigger('acf/setup_fields', [ $('#poststuff') ]);
}, 10);
});
/*
* Gallery field Add-on Fix
*
* Gallery field v1.0.0 required some data in the acf object.
* Now not required, but older versions of gallery field need this.
*
* @type object
* @date 1/08/13
*
* @param N/A
* @return N/A
*/
acf.fields.gallery = {
add : function(){},
edit : function(){},
update_count : function(){},
hide_selected_items : function(){},
text : {
title_add : "Select Images"
}
};
})(jQuery);
(function($){
/*
* acf.screen
*
* Data used by AJAX to hide / show field groups
*
* @type object
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
acf.screen = {
action : 'acf/location/match_field_groups_ajax',
post_id : 0,
page_template : 0,
page_parent : 0,
page_type : 0,
post_category : 0,
post_format : 0,
taxonomy : 0,
lang : 0,
nonce : 0
};
/*
* Document Ready
*
* Updates acf.screen with more data
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).ready(function(){
// update post_id
acf.screen.post_id = acf.o.post_id;
acf.screen.nonce = acf.o.nonce;
// MPML
if( $('#icl-als-first').length > 0 )
{
var href = $('#icl-als-first').children('a').attr('href'),
regex = new RegExp( "lang=([^&#]*)" ),
results = regex.exec( href );
// lang
acf.screen.lang = results[1];
}
});
/*
* acf/update_field_groups
*
* finds the new id's for metaboxes and show's hides metaboxes
*
* @type event
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('acf/update_field_groups', function(){
// Only for a post.
// This is an attempt to stop the action running on the options page add-on.
if( ! acf.screen.post_id || ! $.isNumeric(acf.screen.post_id) )
{
return false;
}
$.ajax({
url: ajaxurl,
data: acf.screen,
type: 'post',
dataType: 'json',
success: function(result){
// validate
if( !result )
{
return false;
}
// hide all metaboxes
$('.acf_postbox').addClass('acf-hidden');
$('.acf_postbox-toggle').addClass('acf-hidden');
// dont bother loading style or html for inputs
if( result.length == 0 )
{
return false;
}
// show the new postboxes
$.each(result, function(k, v) {
// vars
var $el = $('#acf_' + v),
$toggle = $('#adv-settings .acf_postbox-toggle[for="acf_' + v + '-hide"]');
// classes
$el.removeClass('acf-hidden hide-if-js');
$toggle.removeClass('acf-hidden');
$toggle.find('input[type="checkbox"]').attr('checked', 'checked');
// load fields if needed
$el.find('.acf-replace-with-fields').each(function(){
var $replace = $(this);
$.ajax({
url : ajaxurl,
data : {
action : 'acf/post/render_fields',
acf_id : v,
post_id : acf.o.post_id,
nonce : acf.o.nonce
},
type : 'post',
dataType : 'html',
success : function( html ){
$replace.replaceWith( html );
$(document).trigger('acf/setup_fields', $el);
}
});
});
});
// load style
$.ajax({
url : ajaxurl,
data : {
action : 'acf/post/get_style',
acf_id : result[0],
nonce : acf.o.nonce
},
type : 'post',
dataType : 'html',
success : function( result ){
$('#acf_style').html( result );
}
});
}
});
});
/*
* Events
*
* Updates acf.screen with more data and triggers the update event
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('change', '#page_template', function(){
acf.screen.page_template = $(this).val();
$(document).trigger('acf/update_field_groups');
});
$(document).on('change', '#parent_id', function(){
var val = $(this).val();
// set page_type / page_parent
if( val != "" )
{
acf.screen.page_type = 'child';
acf.screen.page_parent = val;
}
else
{
acf.screen.page_type = 'parent';
acf.screen.page_parent = 0;
}
$(document).trigger('acf/update_field_groups');
});
$(document).on('change', '#post-formats-select input[type="radio"]', function(){
var val = $(this).val();
if( val == '0' )
{
val = 'standard';
}
acf.screen.post_format = val;
$(document).trigger('acf/update_field_groups');
});
function _sync_taxonomy_terms() {
// vars
var values = [];
$('.categorychecklist input:checked, .acf-taxonomy-field input:checked, .acf-taxonomy-field option:selected').each(function(){
// validate
if( $(this).is(':hidden') || $(this).is(':disabled') )
{
return;
}
// validate media popup
if( $(this).closest('.media-frame').exists() )
{
return;
}
// validate acf
if( $(this).closest('.acf-taxonomy-field').exists() )
{
if( $(this).closest('.acf-taxonomy-field').attr('data-load_save') == '0' )
{
return;
}
}
// append
if( values.indexOf( $(this).val() ) === -1 )
{
values.push( $(this).val() );
}
});
// update screen
acf.screen.post_category = values;
acf.screen.taxonomy = values;
// trigger change
$(document).trigger('acf/update_field_groups');
}
$(document).on('change', '.categorychecklist input, .acf-taxonomy-field input, .acf-taxonomy-field select', function(){
// a taxonomy field may trigger this change event, however, the value selected is not
// actually a term relatinoship, it is meta data
if( $(this).closest('.acf-taxonomy-field').exists() )
{
if( $(this).closest('.acf-taxonomy-field').attr('data-save') == '0' )
{
return;
}
}
// this may be triggered from editing an imgae in a popup. Popup does not support correct metaboxes so ignore this
if( $(this).closest('.media-frame').exists() )
{
return;
}
// set timeout to fix issue with chrome which does not register the change has yet happened
setTimeout(function(){
_sync_taxonomy_terms();
}, 1);
});
})(jQuery);
(function($){
/*
* Color Picker
*
* jQuery functionality for this field type
*
* @type object
* @date 20/07/13
*
* @param N/A
* @return N/A
*/
var _cp = acf.fields.color_picker = {
$el : null,
$input : null,
set : function( o ){
// merge in new option
$.extend( this, o );
// find input
this.$input = this.$el.find('input[type="text"]');
// return this for chaining
return this;
},
init : function(){
// vars (reference)
var $input = this.$input;
// is clone field?
if( acf.helpers.is_clone_field($input) )
{
return;
}
this.$input.wpColorPicker();
}
};
/*
* acf/setup_fields
*
* run init function on all elements for this field
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/setup_fields', function(e, el){
$(el).find('.acf-color_picker').each(function(){
_cp.set({ $el : $(this) }).init();
});
});
})(jQuery);
(function($){
/*
* Date Picker
*
* static model for this field
*
* @type event
* @date 1/06/13
*
*/
acf.fields.date_picker = {
$el : null,
$input : null,
$hidden : null,
o : {},
set : function( o ){
// merge in new option
$.extend( this, o );
// find input
this.$input = this.$el.find('input[type="text"]');
this.$hidden = this.$el.find('input[type="hidden"]');
// get options
this.o = acf.helpers.get_atts( this.$el );
// return this for chaining
return this;
},
init : function(){
// is clone field?
if( acf.helpers.is_clone_field(this.$hidden) )
{
return;
}
// get and set value from alt field
this.$input.val( this.$hidden.val() );
// create options
var options = $.extend( {}, acf.l10n.date_picker, {
dateFormat : this.o.save_format,
altField : this.$hidden,
altFormat : this.o.save_format,
changeYear : true,
yearRange : "-100:+100",
changeMonth : true,
showButtonPanel : true,
firstDay : this.o.first_day
});
// add date picker
this.$input.addClass('active').datepicker( options );
// now change the format back to how it should be.
this.$input.datepicker( "option", "dateFormat", this.o.display_format );
// wrap the datepicker (only if it hasn't already been wrapped)
if( $('body > #ui-datepicker-div').length > 0 )
{
$('#ui-datepicker-div').wrap('<div class="ui-acf" />');
}
},
blur : function(){
if( !this.$input.val() )
{
this.$hidden.val('');
}
}
};
/*
* acf/setup_fields
*
* run init function on all elements for this field
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/setup_fields', function(e, el){
$(el).find('.acf-date_picker').each(function(){
acf.fields.date_picker.set({ $el : $(this) }).init();
});
});
/*
* Events
*
* jQuery events for this field
*
* @type event
* @date 1/06/13
*
*/
$(document).on('blur', '.acf-date_picker input[type="text"]', function( e ){
acf.fields.date_picker.set({ $el : $(this).parent() }).blur();
});
})(jQuery);
(function($){
/*
* File
*
* static model for this field
*
* @type event
* @date 1/06/13
*
*/
// reference
var _media = acf.media;
acf.fields.file = {
$el : null,
$input : null,
o : {},
set : function( o ){
// merge in new option
$.extend( this, o );
// find input
this.$input = this.$el.find('input[type="hidden"]');
// get options
this.o = acf.helpers.get_atts( this.$el );
// multiple?
this.o.multiple = this.$el.closest('.repeater').exists() ? true : false;
// wp library query
this.o.query = {};
// library
if( this.o.library == 'uploadedTo' )
{
this.o.query.uploadedTo = acf.o.post_id;
}
// return this for chaining
return this;
},
init : function(){
// is clone field?
if( acf.helpers.is_clone_field(this.$input) )
{
return;
}
},
add : function( file ){
// this function must reference a global div variable due to the pre WP 3.5 uploader
// vars
var div = _media.div;
// set atts
div.find('.acf-file-icon').attr( 'src', file.icon );
div.find('.acf-file-title').text( file.title );
div.find('.acf-file-name').text( file.name ).attr( 'href', file.url );
div.find('.acf-file-size').text( file.size );
div.find('.acf-file-value').val( file.id ).trigger('change');
// set div class
div.addClass('active');
// validation
div.closest('.field').removeClass('error');
},
new_frame: function( attributes ){
// set global var
_media.div = this.$el;
// clear the frame
_media.clear_frame();
// vars
attributes.states = [];
// append states
attributes.states.push(
new wp.media.controller.Library({
library : wp.media.query( this.o.query ),
multiple : attributes.multiple,
title : attributes.title,
priority : 20,
filterable : 'all'
})
);
// edit image functionality (added in WP 3.9)
if( acf.helpers.isset(wp, 'media', 'controller', 'EditImage') ) {
attributes.states.push( new wp.media.controller.EditImage() );
}
// Create the media frame
_media.frame = wp.media( attributes );
// edit image view
// source: media-views.js:2410 editImageContent()
_media.frame.on('content:render:edit-image', function(){
var image = this.state().get('image'),
view = new wp.media.view.EditImage( { model: image, controller: this } ).render();
this.content.set( view );
// after creating the wrapper view, load the actual editor via an ajax call
view.loadEditor();
}, _media.frame);
// update toolbar button
_media.frame.on( 'toolbar:create:select', function( toolbar ) {
toolbar.view = new wp.media.view.Toolbar.Select({
text: attributes.button.text,
controller: this
});
}, _media.frame );
// return
return _media.frame;
},
edit : function(){
// vars
var id = this.$input.val();
// create frame
this.new_frame({
title : acf.l10n.file.edit,
multiple : false,
button : { text : acf.l10n.file.update }
});
// open
_media.frame.on('open',function() {
// set to browse
if( _media.frame.content._mode != 'browse' )
{
_media.frame.content.mode('browse');
}
// add class
_media.frame.$el.closest('.media-modal').addClass('acf-media-modal acf-expanded');
// set selection
var selection = _media.frame.state().get('selection'),
attachment = wp.media.attachment( id );
// to fetch or not to fetch
if( $.isEmptyObject(attachment.changed) )
{
attachment.fetch();
}
selection.add( attachment );
});
// close
_media.frame.on('close',function(){
// remove class
_media.frame.$el.closest('.media-modal').removeClass('acf-media-modal');
});
// Finally, open the modal
acf.media.frame.open();
},
remove : function()
{
// set atts
this.$el.find('.acf-file-icon').attr( 'src', '' );
this.$el.find('.acf-file-title').text( '' );
this.$el.find('.acf-file-name').text( '' ).attr( 'href', '' );
this.$el.find('.acf-file-size').text( '' );
this.$el.find('.acf-file-value').val( '' ).trigger('change');
// remove class
this.$el.removeClass('active');
},
popup : function()
{
// reference
var t = this;
// create frame
this.new_frame({
title : acf.l10n.file.select,
multiple : t.o.multiple,
button : { text : acf.l10n.file.select }
});
// customize model / view
acf.media.frame.on('content:activate', function(){
// vars
var toolbar = null,
filters = null;
// populate above vars making sure to allow for failure
try
{
toolbar = acf.media.frame.content.get().toolbar;
filters = toolbar.get('filters');
}
catch(e)
{
// one of the objects was 'undefined'... perhaps the frame open is Upload Files
//console.log( e );
}
// validate
if( !filters )
{
return false;
}
// no need for 'uploaded' filter
if( t.o.library == 'uploadedTo' )
{
filters.$el.find('option[value="uploaded"]').remove();
filters.$el.after('<span>' + acf.l10n.file.uploadedTo + '</span>')
$.each( filters.filters, function( k, v ){
v.props.uploadedTo = acf.o.post_id;
});
}
});
// When an image is selected, run a callback.
acf.media.frame.on( 'select', function() {
// get selected images
selection = _media.frame.state().get('selection');
if( selection )
{
var i = 0;
selection.each(function(attachment){
// counter
i++;
// select / add another file field?
if( i > 1 )
{
// vars
var $td = _media.div.closest('td'),
$tr = $td.closest('.row'),
$repeater = $tr.closest('.repeater'),
key = $td.attr('data-field_key'),
selector = 'td .acf-file-uploader:first';
// key only exists for repeater v1.0.1 +
if( key )
{
selector = 'td[data-field_key="' + key + '"] .acf-file-uploader';
}
// add row?
if( ! $tr.next('.row').exists() )
{
$repeater.find('.add-row-end').trigger('click');
}
// update current div
_media.div = $tr.next('.row').find( selector );
}
// vars
var file = {
id : attachment.id,
title : attachment.attributes.title,
name : attachment.attributes.filename,
url : attachment.attributes.url,
icon : attachment.attributes.icon,
size : attachment.attributes.filesize
};
// add file to field
acf.fields.file.add( file );
});
// selection.each(function(attachment){
}
// if( selection )
});
// acf.media.frame.on( 'select', function() {
// Finally, open the modal
acf.media.frame.open();
return false;
}
};
/*
* Events
*
* jQuery events for this field
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('click', '.acf-file-uploader .acf-button-edit', function( e ){
e.preventDefault();
acf.fields.file.set({ $el : $(this).closest('.acf-file-uploader') }).edit();
});
$(document).on('click', '.acf-file-uploader .acf-button-delete', function( e ){
e.preventDefault();
acf.fields.file.set({ $el : $(this).closest('.acf-file-uploader') }).remove();
});
$(document).on('click', '.acf-file-uploader .add-file', function( e ){
e.preventDefault();
acf.fields.file.set({ $el : $(this).closest('.acf-file-uploader') }).popup();
});
})(jQuery);
(function($){
/*
* Location
*
* static model for this field
*
* @type event
* @date 1/06/13
*
*/
acf.fields.google_map = {
$el : null,
$input : null,
o : {},
api: {
sensor: false,
libraries: 'places'
},
ready : false,
geocoder : false,
map : false,
maps : {},
set : function( o ){
// merge in new option
$.extend( this, o );
// find input
this.$input = this.$el.find('.input-address');
// get options
this.o = acf.helpers.get_atts( this.$el );
// get map
if( this.maps[ this.o.id ] )
{
this.map = this.maps[ this.o.id ];
}
// return this for chaining
return this;
},
init : function(){
// geocode
if( !this.geocoder )
{
this.geocoder = new google.maps.Geocoder();
}
// google maps is loaded and ready
this.ready = true;
// is clone field?
if( acf.helpers.is_clone_field(this.$input) )
{
return;
}
this.render();
},
render : function(){
// reference
var _this = this,
_$el = this.$el;
// vars
var args = {
zoom : parseInt(this.o.zoom),
center : new google.maps.LatLng(this.o.lat, this.o.lng),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map
this.map = new google.maps.Map( this.$el.find('.canvas')[0], args);
// add search
var autocomplete = new google.maps.places.Autocomplete( this.$el.find('.search')[0] );
autocomplete.map = this.map;
autocomplete.bindTo('bounds', this.map);
// add dummy marker
this.map.marker = new google.maps.Marker({
draggable : true,
raiseOnDrag : true,
map : this.map,
});
// add references
this.map.$el = this.$el;
// value exists?
var lat = this.$el.find('.input-lat').val(),
lng = this.$el.find('.input-lng').val();
if( lat && lng )
{
this.update( lat, lng ).center();
}
// events
google.maps.event.addListener(autocomplete, 'place_changed', function( e ) {
// reference
var $el = this.map.$el;
// manually update address
var address = $el.find('.search').val();
$el.find('.input-address').val( address );
$el.find('.title h4').text( address );
// vars
var place = this.getPlace();
// validate
if( place.geometry )
{
var lat = place.geometry.location.lat(),
lng = place.geometry.location.lng();
_this.set({ $el : $el }).update( lat, lng ).center();
}
else
{
// client hit enter, manulaly get the place
_this.geocoder.geocode({ 'address' : address }, function( results, status ){
// validate
if( status != google.maps.GeocoderStatus.OK )
{
console.log('Geocoder failed due to: ' + status);
return;
}
if( !results[0] )
{
console.log('No results found');
return;
}
// get place
place = results[0];
var lat = place.geometry.location.lat(),
lng = place.geometry.location.lng();
_this.set({ $el : $el }).update( lat, lng ).center();
});
}
});
google.maps.event.addListener( this.map.marker, 'dragend', function(){
// reference
var $el = this.map.$el;
// vars
var position = this.map.marker.getPosition(),
lat = position.lat(),
lng = position.lng();
_this.set({ $el : $el }).update( lat, lng ).sync();
});
google.maps.event.addListener( this.map, 'click', function( e ) {
// reference
var $el = this.$el;
// vars
var lat = e.latLng.lat(),
lng = e.latLng.lng();
_this.set({ $el : $el }).update( lat, lng ).sync();
});
// add to maps
this.maps[ this.o.id ] = this.map;
},
update : function( lat, lng ){
// vars
var latlng = new google.maps.LatLng( lat, lng );
// update inputs
this.$el.find('.input-lat').val( lat );
this.$el.find('.input-lng').val( lng ).trigger('change');
// update marker
this.map.marker.setPosition( latlng );
// show marker
this.map.marker.setVisible( true );
// update class
this.$el.addClass('active');
// validation
this.$el.closest('.field').removeClass('error');
// return for chaining
return this;
},
center : function(){
// vars
var position = this.map.marker.getPosition(),
lat = this.o.lat,
lng = this.o.lng;
// if marker exists, center on the marker
if( position )
{
lat = position.lat();
lng = position.lng();
}
var latlng = new google.maps.LatLng( lat, lng );
// set center of map
this.map.setCenter( latlng );
},
sync : function(){
// reference
var $el = this.$el;
// vars
var position = this.map.marker.getPosition(),
latlng = new google.maps.LatLng( position.lat(), position.lng() );
this.geocoder.geocode({ 'latLng' : latlng }, function( results, status ){
// validate
if( status != google.maps.GeocoderStatus.OK )
{
console.log('Geocoder failed due to: ' + status);
return;
}
if( !results[0] )
{
console.log('No results found');
return;
}
// get location
var location = results[0];
// update h4
$el.find('.title h4').text( location.formatted_address );
// update input
$el.find('.input-address').val( location.formatted_address ).trigger('change');
});
// return for chaining
return this;
},
locate : function(){
// reference
var _this = this,
_$el = this.$el;
// Try HTML5 geolocation
if( ! navigator.geolocation )
{
alert( acf.l10n.google_map.browser_support );
return this;
}
// show loading text
_$el.find('.title h4').text(acf.l10n.google_map.locating + '...');
_$el.addClass('active');
navigator.geolocation.getCurrentPosition(function(position){
// vars
var lat = position.coords.latitude,
lng = position.coords.longitude;
_this.set({ $el : _$el }).update( lat, lng ).sync().center();
});
},
clear : function(){
// update class
this.$el.removeClass('active');
// clear search
this.$el.find('.search').val('');
// clear inputs
this.$el.find('.input-address').val('');
this.$el.find('.input-lat').val('');
this.$el.find('.input-lng').val('');
// hide marker
this.map.marker.setVisible( false );
},
edit : function(){
// update class
this.$el.removeClass('active');
// clear search
var val = this.$el.find('.title h4').text();
this.$el.find('.search').val( val ).focus();
},
refresh : function(){
// trigger resize on div
google.maps.event.trigger(this.map, 'resize');
// center map
this.center();
}
};
/*
* acf/setup_fields
*
* run init function on all elements for this field
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/setup_fields', function(e, el){
// reference
var self = acf.fields.google_map;
// vars
var $fields = $(el).find('.acf-google-map');
// validate
if( ! $fields.exists() ) return false;
// no google
if( !acf.helpers.isset(window, 'google', 'load') ) {
// load API
$.getScript('https://www.google.com/jsapi', function(){
// load maps
google.load('maps', '3', { other_params: $.param(self.api), callback: function(){
$fields.each(function(){
acf.fields.google_map.set({ $el : $(this) }).init();
});
}});
});
return false;
}
// no maps or places
if( !acf.helpers.isset(window, 'google', 'maps', 'places') ) {
google.load('maps', '3', { other_params: $.param(self.api), callback: function(){
$fields.each(function(){
acf.fields.google_map.set({ $el : $(this) }).init();
});
}});
return false;
}
// google exists
$fields.each(function(){
acf.fields.google_map.set({ $el : $(this) }).init();
});
// return
return true;
});
/*
* Events
*
* jQuery events for this field
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('click', '.acf-google-map .acf-sprite-remove', function( e ){
e.preventDefault();
acf.fields.google_map.set({ $el : $(this).closest('.acf-google-map') }).clear();
$(this).blur();
});
$(document).on('click', '.acf-google-map .acf-sprite-locate', function( e ){
e.preventDefault();
acf.fields.google_map.set({ $el : $(this).closest('.acf-google-map') }).locate();
$(this).blur();
});
$(document).on('click', '.acf-google-map .title h4', function( e ){
e.preventDefault();
acf.fields.google_map.set({ $el : $(this).closest('.acf-google-map') }).edit();
});
$(document).on('keydown', '.acf-google-map .search', function( e ){
// prevent form from submitting
if( e.which == 13 )
{
return false;
}
});
$(document).on('blur', '.acf-google-map .search', function( e ){
// vars
var $el = $(this).closest('.acf-google-map');
// has a value?
if( $el.find('.input-lat').val() )
{
$el.addClass('active');
}
});
$(document).on('acf/fields/tab/show acf/conditional_logic/show', function( e, $field ){
// validate
if( ! acf.fields.google_map.ready )
{
return;
}
// validate
if( $field.attr('data-field_type') == 'google_map' )
{
acf.fields.google_map.set({ $el : $field.find('.acf-google-map') }).refresh();
}
});
})(jQuery);
(function($){
/*
* Image
*
* static model for this field
*
* @type event
* @date 1/06/13
*
*/
// reference
var _media = acf.media;
acf.fields.image = {
$el : null,
$input : null,
o : {},
set : function( o ){
// merge in new option
$.extend( this, o );
// find input
this.$input = this.$el.find('input[type="hidden"]');
// get options
this.o = acf.helpers.get_atts( this.$el );
// multiple?
this.o.multiple = this.$el.closest('.repeater').exists() ? true : false;
// wp library query
this.o.query = {
type : 'image'
};
// library
if( this.o.library == 'uploadedTo' )
{
this.o.query.uploadedTo = acf.o.post_id;
}
// return this for chaining
return this;
},
init : function(){
// is clone field?
if( acf.helpers.is_clone_field(this.$input) )
{
return;
}
},
add : function( image ){
// this function must reference a global div variable due to the pre WP 3.5 uploader
// vars
var div = _media.div;
// set atts
div.find('.acf-image-image').attr( 'src', image.url );
div.find('.acf-image-value').val( image.id ).trigger('change');
// set div class
div.addClass('active');
// validation
div.closest('.field').removeClass('error');
},
new_frame: function( attributes ){
// set global var
_media.div = this.$el;
// clear the frame
_media.clear_frame();
// vars
attributes.states = [];
// append states
attributes.states.push(
new wp.media.controller.Library({
library : wp.media.query( this.o.query ),
multiple : attributes.multiple,
title : attributes.title,
priority : 20,
filterable : 'all'
})
);
// edit image functionality (added in WP 3.9)
if( acf.helpers.isset(wp, 'media', 'controller', 'EditImage') ) {
attributes.states.push( new wp.media.controller.EditImage() );
}
// Create the media frame
_media.frame = wp.media( attributes );
// edit image view
// source: media-views.js:2410 editImageContent()
_media.frame.on('content:render:edit-image', function(){
var image = this.state().get('image'),
view = new wp.media.view.EditImage( { model: image, controller: this } ).render();
this.content.set( view );
// after creating the wrapper view, load the actual editor via an ajax call
view.loadEditor();
}, _media.frame);
// update toolbar button
_media.frame.on( 'toolbar:create:select', function( toolbar ) {
toolbar.view = new wp.media.view.Toolbar.Select({
text: attributes.button.text,
controller: this
});
}, _media.frame );
// return
return _media.frame;
},
edit : function(){
// vars
var id = this.$input.val();
// create frame
this.new_frame({
title : acf.l10n.image.edit,
multiple : false,
button : { text : acf.l10n.image.update }
});
// open
_media.frame.on('open',function() {
// set to browse
if( _media.frame.content._mode != 'browse' )
{
_media.frame.content.mode('browse');
}
// add class
_media.frame.$el.closest('.media-modal').addClass('acf-media-modal acf-expanded');
// set selection
var selection = _media.frame.state().get('selection'),
attachment = wp.media.attachment( id );
// to fetch or not to fetch
if( $.isEmptyObject(attachment.changed) )
{
attachment.fetch();
}
selection.add( attachment );
});
// close
_media.frame.on('close',function(){
// remove class
_media.frame.$el.closest('.media-modal').removeClass('acf-media-modal');
});
// Finally, open the modal
_media.frame.open();
},
remove : function()
{
// set atts
this.$el.find('.acf-image-image').attr( 'src', '' );
this.$el.find('.acf-image-value').val( '' ).trigger('change');
// remove class
this.$el.removeClass('active');
},
popup : function()
{
// reference
var t = this;
// create frame
this.new_frame({
title : acf.l10n.image.select,
multiple : t.o.multiple,
button : { text : acf.l10n.image.select }
});
// customize model / view
_media.frame.on('content:activate', function(){
// vars
var toolbar = null,
filters = null;
// populate above vars making sure to allow for failure
try
{
toolbar = acf.media.frame.content.get().toolbar;
filters = toolbar.get('filters');
}
catch(e)
{
// one of the objects was 'undefined'... perhaps the frame open is Upload Files
//console.log( e );
}
// validate
if( !filters )
{
return false;
}
// filter only images
$.each( filters.filters, function( k, v ){
v.props.type = 'image';
});
// no need for 'uploaded' filter
if( t.o.library == 'uploadedTo' )
{
filters.$el.find('option[value="uploaded"]').remove();
filters.$el.after('<span>' + acf.l10n.image.uploadedTo + '</span>')
$.each( filters.filters, function( k, v ){
v.props.uploadedTo = acf.o.post_id;
});
}
// remove non image options from filter list
filters.$el.find('option').each(function(){
// vars
var v = $(this).attr('value');
// don't remove the 'uploadedTo' if the library option is 'all'
if( v == 'uploaded' && t.o.library == 'all' )
{
return;
}
if( v.indexOf('image') === -1 )
{
$(this).remove();
}
});
// set default filter
filters.$el.val('image').trigger('change');
});
// When an image is selected, run a callback.
acf.media.frame.on( 'select', function() {
// get selected images
selection = _media.frame.state().get('selection');
if( selection )
{
var i = 0;
selection.each(function(attachment){
// counter
i++;
// select / add another image field?
if( i > 1 )
{
// vars
var $td = _media.div.closest('td'),
$tr = $td.closest('.row'),
$repeater = $tr.closest('.repeater'),
key = $td.attr('data-field_key'),
selector = 'td .acf-image-uploader:first';
// key only exists for repeater v1.0.1 +
if( key )
{
selector = 'td[data-field_key="' + key + '"] .acf-image-uploader';
}
// add row?
if( ! $tr.next('.row').exists() )
{
$repeater.find('.add-row-end').trigger('click');
}
// update current div
_media.div = $tr.next('.row').find( selector );
}
// vars
var image = {
id : attachment.id,
url : attachment.attributes.url
};
// is preview size available?
if( attachment.attributes.sizes && attachment.attributes.sizes[ t.o.preview_size ] )
{
image.url = attachment.attributes.sizes[ t.o.preview_size ].url;
}
// add image to field
acf.fields.image.add( image );
});
// selection.each(function(attachment){
}
// if( selection )
});
// acf.media.frame.on( 'select', function() {
// Finally, open the modal
acf.media.frame.open();
return false;
},
// temporary gallery fix
text : {
title_add : "Select Image",
title_edit : "Edit Image"
}
};
/*
* Events
*
* jQuery events for this field
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('click', '.acf-image-uploader .acf-button-edit', function( e ){
e.preventDefault();
acf.fields.image.set({ $el : $(this).closest('.acf-image-uploader') }).edit();
});
$(document).on('click', '.acf-image-uploader .acf-button-delete', function( e ){
e.preventDefault();
acf.fields.image.set({ $el : $(this).closest('.acf-image-uploader') }).remove();
});
$(document).on('click', '.acf-image-uploader .add-image', function( e ){
e.preventDefault();
acf.fields.image.set({ $el : $(this).closest('.acf-image-uploader') }).popup();
});
})(jQuery);
(function($){
/*
* Radio
*
* static model and events for this field
*
* @type event
* @date 1/06/13
*
*/
acf.fields.radio = {
$el : null,
$input : null,
$other : null,
farbtastic : null,
set : function( o ){
// merge in new option
$.extend( this, o );
// find input
this.$input = this.$el.find('input[type="radio"]:checked');
this.$other = this.$el.find('input[type="text"]');
// return this for chaining
return this;
},
change : function(){
if( this.$input.val() == 'other' )
{
this.$other.attr('name', this.$input.attr('name'));
this.$other.show();
}
else
{
this.$other.attr('name', '');
this.$other.hide();
}
}
};
/*
* Events
*
* jQuery events for this field
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('change', '.acf-radio-list input[type="radio"]', function( e ){
acf.fields.radio.set({ $el : $(this).closest('.acf-radio-list') }).change();
});
})(jQuery);
(function($){
/*
* Relationship
*
* static model for this field
*
* @type event
* @date 1/06/13
*
*/
acf.fields.relationship = {
$el : null,
$input : null,
$left : null,
$right : null,
o : {},
timeout : null,
set : function( o ){
// merge in new option
$.extend( this, o );
// find elements
this.$input = this.$el.children('input[type="hidden"]');
this.$left = this.$el.find('.relationship_left'),
this.$right = this.$el.find('.relationship_right');
// get options
this.o = acf.helpers.get_atts( this.$el );
// return this for chaining
return this;
},
init : function(){
// reference
var _this = this;
// is clone field?
if( acf.helpers.is_clone_field(this.$input) )
{
return;
}
// set height of right column
this.$right.find('.relationship_list').height( this.$left.height() -2 );
// right sortable
this.$right.find('.relationship_list').sortable({
axis : 'y',
items : '> li',
forceHelperSize : true,
forcePlaceholderSize : true,
scroll : true,
update : function(){
_this.$input.trigger('change');
}
});
// load more
var $el = this.$el;
this.$left.find('.relationship_list').scrollTop( 0 ).on('scroll', function(e){
// validate
if( $el.hasClass('loading') || $el.hasClass('no-results') )
{
return;
}
// Scrolled to bottom
if( $(this).scrollTop() + $(this).innerHeight() >= $(this).get(0).scrollHeight )
{
var paged = parseInt( $el.attr('data-paged') );
// update paged
$el.attr('data-paged', (paged + 1) );
// fetch
_this.set({ $el : $el }).fetch();
}
});
// ajax fetch values for left side
this.fetch();
},
fetch : function(){
// reference
var _this = this,
$el = this.$el;
// add loading class, stops scroll loading
$el.addClass('loading');
// get results
$.ajax({
url : acf.o.ajaxurl,
type : 'post',
dataType : 'json',
data : $.extend({
action : 'acf/fields/relationship/query_posts',
post_id : acf.o.post_id,
nonce : acf.o.nonce
}, this.o ),
success : function( json ){
// render
_this.set({ $el : $el }).render( json );
}
});
},
render : function( json ){
// reference
var _this = this;
// update classes
this.$el.removeClass('no-results').removeClass('loading');
// new search?
if( this.o.paged == 1 )
{
this.$el.find('.relationship_left li:not(.load-more)').remove();
}
// no results?
if( ! json || ! json.html )
{
this.$el.addClass('no-results');
return;
}
// append new results
this.$el.find('.relationship_left .load-more').before( json.html );
// next page?
if( ! json.next_page_exists )
{
this.$el.addClass('no-results');
}
// apply .hide to left li's
this.$left.find('a').each(function(){
var id = $(this).attr('data-post_id');
if( _this.$right.find('a[data-post_id="' + id + '"]').exists() )
{
$(this).parent().addClass('hide');
}
});
},
add : function( $a ){
// vars
var id = $a.attr('data-post_id'),
title = $a.html();
// max posts
if( this.$right.find('a').length >= this.o.max )
{
alert( acf.l10n.relationship.max.replace('{max}', this.o.max) );
return false;
}
// can be added?
if( $a.parent().hasClass('hide') )
{
return false;
}
// hide
$a.parent().addClass('hide');
// template
var html = [
'<li>',
'<a href="#" data-post_id="' + $a.attr('data-post_id') + '">',
$a.html() + '<span class="acf-button-remove"></span>',
'</a>',
'<input type="hidden" name="' + this.$input.attr('name') + '[]" value="' + $a.attr('data-post_id') + '" />',
'</li>'].join('');
// add new li
this.$right.find('.relationship_list').append( html )
// trigger change on new_li
this.$input.trigger('change');
// validation
this.$el.closest('.field').removeClass('error');
},
remove : function( $a ){
// remove
$a.parent().remove();
// show
this.$left.find('a[data-post_id="' + $a.attr('data-post_id') + '"]').parent('li').removeClass('hide');
// trigger change on new_li
this.$input.trigger('change');
}
};
/*
* acf/setup_fields
*
* run init function on all elements for this field
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/setup_fields', function(e, el){
$(el).find('.acf_relationship').each(function(){
acf.fields.relationship.set({ $el : $(this) }).init();
});
});
/*
* Events
*
* jQuery events for this field
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('change', '.acf_relationship .select-post_type', function(e){
// vars
var val = $(this).val(),
$el = $(this).closest('.acf_relationship');
// update attr
$el.attr('data-post_type', val);
$el.attr('data-paged', 1);
// fetch
acf.fields.relationship.set({ $el : $el }).fetch();
});
$(document).on('click', '.acf_relationship .relationship_left .relationship_list a', function( e ){
e.preventDefault();
acf.fields.relationship.set({ $el : $(this).closest('.acf_relationship') }).add( $(this) );
$(this).blur();
});
$(document).on('click', '.acf_relationship .relationship_right .relationship_list a', function( e ){
e.preventDefault();
acf.fields.relationship.set({ $el : $(this).closest('.acf_relationship') }).remove( $(this) );
$(this).blur();
});
$(document).on('keyup', '.acf_relationship input.relationship_search', function( e ){
// vars
var val = $(this).val(),
$el = $(this).closest('.acf_relationship');
// update attr
$el.attr('data-s', val);
$el.attr('data-paged', 1);
// fetch
clearTimeout( acf.fields.relationship.timeout );
acf.fields.relationship.timeout = setTimeout(function(){
acf.fields.relationship.set({ $el : $el }).fetch();
}, 500);
});
$(document).on('keypress', '.acf_relationship input.relationship_search', function( e ){
// don't submit form
if( e.which == 13 )
{
e.preventDefault();
}
});
})(jQuery);
(function($){
acf.fields.tab = {
add_group : function( $wrap ){
// vars
var html = '';
// generate html
if( $wrap.is('tbody') )
{
html = '<tr class="acf-tab-wrap"><td colspan="2"><ul class="hl clearfix acf-tab-group"></ul></td></tr>';
}
else
{
html = '<div class="acf-tab-wrap"><ul class="hl clearfix acf-tab-group"></ul></div>';
}
// append html
$wrap.children('.field_type-tab:first').before( html );
},
add_tab : function( $tab ){
// vars
var $field = $tab.closest('.field'),
$wrap = $field.parent(),
key = $field.attr('data-field_key'),
label = $tab.text();
// create tab group if it doesnt exist
if( ! $wrap.children('.acf-tab-wrap').exists() )
{
this.add_group( $wrap );
}
// add tab
$wrap.children('.acf-tab-wrap').find('.acf-tab-group').append('<li><a class="acf-tab-button" href="#" data-key="' + key + '">' + label + '</a></li>');
},
toggle : function( $a ){
// reference
var _this = this;
//console.log( 'toggle %o ', $a);
// vars
var $wrap = $a.closest('.acf-tab-wrap').parent(),
key = $a.attr('data-key');
// classes
$a.parent('li').addClass('active').siblings('li').removeClass('active');
// hide / show
$wrap.children('.field_type-tab').each(function(){
// vars
var $tab = $(this);
if( $tab.attr('data-field_key') == key )
{
_this.show_tab_fields( $(this) );
}
else
{
_this.hide_tab_fields( $(this) );
}
});
},
show_tab_fields : function( $field ) {
//console.log('show tab fields %o', $field);
$field.nextUntil('.field_type-tab').each(function(){
$(this).removeClass('acf-tab_group-hide').addClass('acf-tab_group-show');
$(document).trigger('acf/fields/tab/show', [ $(this) ]);
});
},
hide_tab_fields : function( $field ) {
$field.nextUntil('.field_type-tab').each(function(){
$(this).removeClass('acf-tab_group-show').addClass('acf-tab_group-hide');
$(document).trigger('acf/fields/tab/hide', [ $(this) ]);
});
},
refresh : function( $el ){
// reference
var _this = this;
// trigger
$el.find('.acf-tab-group').each(function(){
$(this).find('.acf-tab-button:first').each(function(){
_this.toggle( $(this) );
});
});
}
};
/*
* acf/setup_fields
*
* run init function on all elements for this field
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/setup_fields', function(e, el){
// add tabs
$(el).find('.acf-tab').each(function(){
acf.fields.tab.add_tab( $(this) );
});
// activate first tab
acf.fields.tab.refresh( $(el) );
// NOTE: this code is defined BEFORE the acf.conditional_logic action. This is becuase the 'acf/setup_fields' listener is defined INSIDE the conditional_logic.init() function which is run on doc.ready
// trigger conditional logic
// this code ( acf/setup_fields ) is run after the main acf.conditional_logic.init();
//console.log('acf/setup_fields (after tab refresh) calling acf.conditional_logic.refresh()');
//acf.conditional_logic.refresh();
});
/*
* Events
*
* jQuery events for this field
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('click', '.acf-tab-button', function( e ){
e.preventDefault();
acf.fields.tab.toggle( $(this) );
$(this).trigger('blur');
});
$(document).on('acf/conditional_logic/hide', function( e, $target, item ){
// validate
if( $target.attr('data-field_type') != 'tab' )
{
return;
}
//console.log('conditional_logic/hide tab %o', $target);
// vars
var $tab = $target.siblings('.acf-tab-wrap').find('a[data-key="' + $target.attr('data-field_key') + '"]');
// if tab is already hidden, then ignore the following functiolnality
if( $tab.is(':hidden') )
{
return;
}
// visibility
$tab.parent().hide();
// if
if( $tab.parent().siblings(':visible').exists() )
{
// if the $target to be hidden is a tab button, lets toggle a sibling tab button
$tab.parent().siblings(':visible').first().children('a').trigger('click');
}
else
{
// no onther tabs
acf.fields.tab.hide_tab_fields( $target );
}
});
$(document).on('acf/conditional_logic/show', function( e, $target, item ){
// validate
if( $target.attr('data-field_type') != 'tab' )
{
return;
}
//console.log('conditional_logic/show tab %o', $target);
// vars
var $tab = $target.siblings('.acf-tab-wrap').find('a[data-key="' + $target.attr('data-field_key') + '"]');
// if tab is already visible, then ignore the following functiolnality
if( $tab.is(':visible') )
{
return;
}
// visibility
$tab.parent().show();
// if this is the active tab
if( $tab.parent().hasClass('active') )
{
$tab.trigger('click');
return;
}
// if the sibling active tab is actually hidden by conditional logic, take ownership of tabs
if( $tab.parent().siblings('.active').is(':hidden') )
{
// show this tab group
$tab.trigger('click');
return;
}
});
})(jQuery);
(function($){
/*
* Validation
*
* JS model
*
* @type object
* @date 1/06/13
*
*/
acf.validation = {
status : true,
disabled : false,
run : function(){
// reference
var _this = this;
// reset
_this.status = true;
// loop through all fields
$('.field.required, .form-field.required').each(function(){
// run validation
_this.validate( $(this) );
});
// end loop through all fields
},
/*
* show_spinner
*
* This function will show a spinner element. Logic changed in WP 4.2
*
* @type function
* @date 3/05/2015
* @since 5.2.3
*
* @param $spinner (jQuery)
* @return n/a
*/
show_spinner: function( $spinner ){
// bail early if no spinner
if( !$spinner.exists() ) {
return;
}
// vars
var wp_version = acf.o.wp_version;
// show
if( parseFloat(wp_version) >= 4.2 ) {
$spinner.addClass('is-active');
} else {
$spinner.css('display', 'inline-block');
}
},
/*
* hide_spinner
*
* This function will hide a spinner element. Logic changed in WP 4.2
*
* @type function
* @date 3/05/2015
* @since 5.2.3
*
* @param $spinner (jQuery)
* @return n/a
*/
hide_spinner: function( $spinner ){
// bail early if no spinner
if( !$spinner.exists() ) {
return;
}
// vars
var wp_version = acf.o.wp_version;
// hide
if( parseFloat(wp_version) >= 4.2 ) {
$spinner.removeClass('is-active');
} else {
$spinner.css('display', 'none');
}
},
validate : function( div ){
// var
var ignore = false,
$tab = null;
// set validation data
div.data('validation', true);
// not visible
if( div.is(':hidden') )
{
// ignore validation
ignore = true;
// if this field is hidden by a tab group, allow validation
if( div.hasClass('acf-tab_group-hide') )
{
ignore = false;
// vars
var $tab_field = div.prevAll('.field_type-tab:first'),
$tab_group = div.prevAll('.acf-tab-wrap:first');
// if the tab itself is hidden, bypass validation
if( $tab_field.hasClass('acf-conditional_logic-hide') )
{
ignore = true;
}
else
{
// activate this tab as it holds hidden required field!
$tab = $tab_group.find('.acf-tab-button[data-key="' + $tab_field.attr('data-field_key') + '"]');
}
}
}
// if is hidden by conditional logic, ignore
if( div.hasClass('acf-conditional_logic-hide') )
{
ignore = true;
}
// if field group is hidden, igrnoe
if( div.closest('.postbox.acf-hidden').exists() ) {
ignore = true;
}
if( ignore )
{
return;
}
// text / textarea
if( div.find('input[type="text"], input[type="email"], input[type="number"], input[type="hidden"], textarea').val() == "" )
{
div.data('validation', false);
}
// wysiwyg
if( div.find('.acf_wysiwyg').exists() && typeof(tinyMCE) == "object")
{
div.data('validation', true);
var id = div.find('.wp-editor-area').attr('id'),
editor = tinyMCE.get( id );
if( editor && !editor.getContent() )
{
div.data('validation', false);
}
}
// select
if( div.find('select').exists() )
{
div.data('validation', true);
if( div.find('select').val() == "null" || ! div.find('select').val() )
{
div.data('validation', false);
}
}
// radio
if( div.find('input[type="radio"]').exists() )
{
div.data('validation', false);
if( div.find('input[type="radio"]:checked').exists() )
{
div.data('validation', true);
}
}
// checkbox
if( div.find('input[type="checkbox"]').exists() )
{
div.data('validation', false);
if( div.find('input[type="checkbox"]:checked').exists() )
{
div.data('validation', true);
}
}
// relationship
if( div.find('.acf_relationship').exists() )
{
div.data('validation', false);
if( div.find('.acf_relationship .relationship_right input').exists() )
{
div.data('validation', true);
}
}
// repeater
if( div.find('.repeater').exists() )
{
div.data('validation', false);
if( div.find('.repeater tr.row').exists() )
{
div.data('validation', true);
}
}
// gallery
if( div.find('.acf-gallery').exists() )
{
div.data('validation', false);
if( div.find('.acf-gallery .thumbnail').exists())
{
div.data('validation', true);
}
}
// hook for custom validation
$(document).trigger('acf/validate_field', [ div ] );
// set validation
if( ! div.data('validation') )
{
// show error
this.status = false;
div.closest('.field').addClass('error');
// custom validation message
if( div.data('validation_message') )
{
var $label = div.find('p.label:first'),
$message = null;
// remove old message
$label.children('.acf-error-message').remove();
$label.append( '<span class="acf-error-message"><i class="bit"></i>' + div.data('validation_message') + '</span>' );
}
// display field (curently hidden due to another tab being active)
if( $tab )
{
$tab.trigger('click');
}
}
}
};
/*
* Events
*
* Remove error class on focus
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('focus click', '.field.required input, .field.required textarea, .field.required select', function( e ){
$(this).closest('.field').removeClass('error');
});
/*
$(document).on('blur change', '.field.required input, .field.required textarea, .field.required select', function( e ){
acf.validation.validate( $(this).closest('.field') );
});
*/
/*
* Save Post
*
* If user is saving a draft, allow them to bypass the validation
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('click', '#save-post', function(){
acf.validation.disabled = true;
});
/*
* Submit Post
*
* Run validation and return true|false accordingly
*
* @type function
* @date 1/03/2011
*
* @param N/A
* @return N/A
*/
$(document).on('submit', '#post', function(){
// If disabled, bail early on the validation check
if( acf.validation.disabled )
{
return true;
}
// do validation
acf.validation.run();
if( ! acf.validation.status ) {
// vars
var $form = $(this);
// show message
$form.siblings('#message').remove();
$form.before('<div id="message" class="error"><p>' + acf.l10n.validation.error + '</p></div>');
// hide ajax stuff on submit button
if( $('#submitdiv').exists() ) {
// remove disabled classes
$('#submitdiv').find('.disabled').removeClass('disabled');
$('#submitdiv').find('.button-disabled').removeClass('button-disabled');
$('#submitdiv').find('.button-primary-disabled').removeClass('button-primary-disabled');
// remove spinner
acf.validation.hide_spinner( $('#submitdiv .spinner') );
}
return false;
}
// remove hidden postboxes
// + this will stop them from being posted to save
$('.acf_postbox.acf-hidden').remove();
// submit the form
return true;
});
})(jQuery);
(function($){
/*
* WYSIWYG
*
* jQuery functionality for this field type
*
* @type object
* @date 20/07/13
*
* @param N/A
* @return N/A
*/
var _wysiwyg = acf.fields.wysiwyg = {
$el: null,
$textarea: null,
o: {},
set: function( o ){
// merge in new option
$.extend( this, o );
// find textarea
this.$textarea = this.$el.find('textarea');
// get options
this.o = acf.helpers.get_atts( this.$el );
this.o.id = this.$textarea.attr('id');
// return this for chaining
return this;
},
has_tinymce : function(){
var r = false;
if( typeof(tinyMCE) == "object" )
{
r = true;
}
return r;
},
get_toolbar : function(){
// safely get toolbar
if( acf.helpers.isset( this, 'toolbars', this.o.toolbar ) ) {
return this.toolbars[ this.o.toolbar ];
}
// return
return false;
},
init : function(){
// is clone field?
if( acf.helpers.is_clone_field( this.$textarea ) )
{
return;
}
// vars
var id = this.o.id,
toolbar = this.get_toolbar(),
command = 'mceAddControl',
setting = 'theme_advanced_buttons{i}';
// backup
var _settings = $.extend( {}, tinyMCE.settings );
// v4 settings
if( tinymce.majorVersion == 4 ) {
command = 'mceAddEditor';
setting = 'toolbar{i}';
}
// add toolbars
if( toolbar ) {
for( var i = 1; i < 5; i++ ) {
// vars
var v = '';
// load toolbar
if( acf.helpers.isset( toolbar, 'theme_advanced_buttons' + i ) ) {
v = toolbar['theme_advanced_buttons' + i];
}
// update setting
tinyMCE.settings[ setting.replace('{i}', i) ] = v;
}
}
// add editor
tinyMCE.execCommand( command, false, id);
// events - load
$(document).trigger('acf/wysiwyg/load', id);
// add events (click, focus, blur) for inserting image into correct editor
setTimeout(function(){
_wysiwyg.add_events( id );
}, 100);
// restore tinyMCE.settings
tinyMCE.settings = _settings;
// set active editor to null
wpActiveEditor = null;
},
add_events: function( id ){
// vars
var editor = tinyMCE.get( id );
// validate
if( !editor ) return;
// vars
var $container = $('#wp-' + id + '-wrap'),
$body = $( editor.getBody() );
// events
$container.on('click', function(){
$(document).trigger('acf/wysiwyg/click', id);
});
$body.on('focus', function(){
$(document).trigger('acf/wysiwyg/focus', id);
});
$body.on('blur', function(){
$(document).trigger('acf/wysiwyg/blur', id);
});
},
destroy : function(){
// vars
var id = this.o.id,
command = 'mceRemoveControl';
// Remove tinymcy functionality.
// Due to the media popup destroying and creating the field within such a short amount of time,
// a JS error will be thrown when launching the edit window twice in a row.
try {
// vars
var editor = tinyMCE.get( id );
// validate
if( !editor ) {
return;
}
// v4 settings
if( tinymce.majorVersion == 4 ) {
command = 'mceRemoveEditor';
}
// store value
var val = editor.getContent();
// remove editor
tinyMCE.execCommand(command, false, id);
// set value
this.$textarea.val( val );
} catch(e) {
//console.log( e );
}
// set active editor to null
wpActiveEditor = null;
}
};
/*
* acf/setup_fields
*
* run init function on all elements for this field
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/setup_fields', function(e, el){
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
// Destory all WYSIWYG fields
// This hack will fix a problem when the WP popup is created and hidden, then the ACF popup (image/file field) is opened
$(el).find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).destroy();
});
// Add WYSIWYG fields
setTimeout(function(){
$(el).find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).init();
});
}, 0);
});
/*
* acf/remove_fields
*
* This action is called when the $el is being removed from the DOM
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} $el jQuery element being removed
* @return N/A
*/
$(document).on('acf/remove_fields', function(e, $el){
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
$el.find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).destroy();
});
});
/*
* acf/wysiwyg/click
*
* this event is run when a user clicks on a WYSIWYG field
*
* @type event
* @date 17/01/13
*
* @param {object} e event object
* @param {int} id WYSIWYG ID
* @return N/A
*/
$(document).on('acf/wysiwyg/click', function(e, id){
wpActiveEditor = id;
container = $('#wp-' + id + '-wrap').closest('.field').removeClass('error');
});
/*
* acf/wysiwyg/focus
*
* this event is run when a user focuses on a WYSIWYG field body
*
* @type event
* @date 17/01/13
*
* @param {object} e event object
* @param {int} id WYSIWYG ID
* @return N/A
*/
$(document).on('acf/wysiwyg/focus', function(e, id){
wpActiveEditor = id;
container = $('#wp-' + id + '-wrap').closest('.field').removeClass('error');
});
/*
* acf/wysiwyg/blur
*
* this event is run when a user loses focus on a WYSIWYG field body
*
* @type event
* @date 17/01/13
*
* @param {object} e event object
* @param {int} id WYSIWYG ID
* @return N/A
*/
$(document).on('acf/wysiwyg/blur', function(e, id){
wpActiveEditor = null;
// update the hidden textarea
// - This fixes a but when adding a taxonomy term as the form is not posted and the hidden tetarea is never populated!
var editor = tinyMCE.get( id );
// validate
if( !editor )
{
return;
}
var el = editor.getElement();
// save to textarea
editor.save();
// trigger change on textarea
$( el ).trigger('change');
});
/*
* acf/sortable_start
*
* this event is run when a element is being drag / dropped
*
* @type event
* @date 10/11/12
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/sortable_start', function(e, el) {
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
$(el).find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).destroy();
});
});
/*
* acf/sortable_stop
*
* this event is run when a element has finnished being drag / dropped
*
* @type event
* @date 10/11/12
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/sortable_stop', function(e, el) {
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
$(el).find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).init();
});
});
/*
* window load
*
* @description:
* @since: 3.5.5
* @created: 22/12/12
*/
$(window).on('load', function(){
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
// vars
var wp_content = $('#wp-content-wrap').exists(),
wp_acf_settings = $('#wp-acf_settings-wrap').exists()
mode = 'tmce';
// has_editor
if( wp_acf_settings )
{
// html_mode
if( $('#wp-acf_settings-wrap').hasClass('html-active') )
{
mode = 'html';
}
}
setTimeout(function(){
// trigger click on hidden wysiwyg (to get in HTML mode)
if( wp_acf_settings && mode == 'html' )
{
$('#acf_settings-tmce').trigger('click');
}
}, 1);
setTimeout(function(){
// trigger html mode for people who want to stay in HTML mode
if( wp_acf_settings && mode == 'html' )
{
$('#acf_settings-html').trigger('click');
}
// Add events to content editor
if( wp_content )
{
_wysiwyg.add_events('content');
}
}, 11);
});
/*
* Full screen
*
* @description: this hack will hide the 'image upload' button in the wysiwyg full screen mode if the field has disabled image uploads!
* @since: 3.6
* @created: 26/02/13
*/
$(document).on('click', '.acf_wysiwyg a.mce_fullscreen', function(){
// vars
var wysiwyg = $(this).closest('.acf_wysiwyg'),
upload = wysiwyg.attr('data-upload');
if( upload == 'no' )
{
$('#mce_fullscreen_container td.mceToolbar .mce_add_media').remove();
}
});
})(jQuery);
|
'use strict';
/* globals getInputCompileHelper: false */
describe('ngModel', function() {
describe('NgModelController', function() {
/* global NgModelController: false */
var ctrl, scope, ngModelAccessor, element, parentFormCtrl;
beforeEach(inject(function($rootScope, $controller) {
var attrs = {name: 'testAlias', ngModel: 'value'};
parentFormCtrl = {
$$setPending: jasmine.createSpy('$$setPending'),
$setValidity: jasmine.createSpy('$setValidity'),
$setDirty: jasmine.createSpy('$setDirty'),
$$clearControlValidity: noop
};
element = jqLite('<form><input></form>');
scope = $rootScope;
ngModelAccessor = jasmine.createSpy('ngModel accessor');
ctrl = $controller(NgModelController, {
$scope: scope,
$element: element.find('input'),
$attrs: attrs
});
//Assign the mocked parentFormCtrl to the model controller
ctrl.$$parentForm = parentFormCtrl;
}));
afterEach(function() {
dealoc(element);
});
it('should init the properties', function() {
expect(ctrl.$untouched).toBe(true);
expect(ctrl.$touched).toBe(false);
expect(ctrl.$dirty).toBe(false);
expect(ctrl.$pristine).toBe(true);
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(ctrl.$viewValue).toBeDefined();
expect(ctrl.$modelValue).toBeDefined();
expect(ctrl.$formatters).toEqual([]);
expect(ctrl.$parsers).toEqual([]);
expect(ctrl.$name).toBe('testAlias');
});
describe('setValidity', function() {
function expectOneError() {
expect(ctrl.$error).toEqual({someError: true});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toBeUndefined();
}
function expectOneSuccess() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({someError: true});
expect(ctrl.$pending).toBeUndefined();
}
function expectOnePending() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toEqual({someError: true});
}
function expectCleared() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toBeUndefined();
}
it('should propagate validity to the parent form', function() {
expect(parentFormCtrl.$setValidity).not.toHaveBeenCalled();
ctrl.$setValidity('ERROR', false);
expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', false, ctrl);
});
it('should transition from states correctly', function() {
expectCleared();
ctrl.$setValidity('someError', false);
expectOneError();
ctrl.$setValidity('someError', undefined);
expectOnePending();
ctrl.$setValidity('someError', true);
expectOneSuccess();
ctrl.$setValidity('someError', null);
expectCleared();
});
it('should set valid/invalid with multiple errors', function() {
ctrl.$setValidity('first', false);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('second', false);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('third', undefined);
expect(ctrl.$valid).toBe(undefined);
expect(ctrl.$invalid).toBe(undefined);
ctrl.$setValidity('third', null);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('second', true);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('first', true);
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
});
});
describe('setPristine', function() {
it('should set control to its pristine state', function() {
ctrl.$setViewValue('edit');
expect(ctrl.$dirty).toBe(true);
expect(ctrl.$pristine).toBe(false);
ctrl.$setPristine();
expect(ctrl.$dirty).toBe(false);
expect(ctrl.$pristine).toBe(true);
});
});
describe('setDirty', function() {
it('should set control to its dirty state', function() {
expect(ctrl.$pristine).toBe(true);
expect(ctrl.$dirty).toBe(false);
ctrl.$setDirty();
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
});
it('should set parent form to its dirty state', function() {
ctrl.$setDirty();
expect(parentFormCtrl.$setDirty).toHaveBeenCalled();
});
});
describe('setUntouched', function() {
it('should set control to its untouched state', function() {
ctrl.$setTouched();
ctrl.$setUntouched();
expect(ctrl.$touched).toBe(false);
expect(ctrl.$untouched).toBe(true);
});
});
describe('setTouched', function() {
it('should set control to its touched state', function() {
ctrl.$setUntouched();
ctrl.$setTouched();
expect(ctrl.$touched).toBe(true);
expect(ctrl.$untouched).toBe(false);
});
});
describe('view -> model', function() {
it('should set the value to $viewValue', function() {
ctrl.$setViewValue('some-val');
expect(ctrl.$viewValue).toBe('some-val');
});
it('should pipeline all registered parsers and set result to $modelValue', function() {
var log = [];
ctrl.$parsers.push(function(value) {
log.push(value);
return value + '-a';
});
ctrl.$parsers.push(function(value) {
log.push(value);
return value + '-b';
});
ctrl.$setViewValue('init');
expect(log).toEqual(['init', 'init-a']);
expect(ctrl.$modelValue).toBe('init-a-b');
});
it('should fire viewChangeListeners when the value changes in the view (even if invalid)',
function() {
var spy = jasmine.createSpy('viewChangeListener');
ctrl.$viewChangeListeners.push(spy);
ctrl.$setViewValue('val');
expect(spy).toHaveBeenCalledOnce();
spy.reset();
// invalid
ctrl.$parsers.push(function() {return undefined;});
ctrl.$setViewValue('val2');
expect(spy).toHaveBeenCalledOnce();
});
it('should reset the model when the view is invalid', function() {
ctrl.$setViewValue('aaaa');
expect(ctrl.$modelValue).toBe('aaaa');
// add a validator that will make any input invalid
ctrl.$parsers.push(function() {return undefined;});
expect(ctrl.$modelValue).toBe('aaaa');
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBeUndefined();
});
it('should not reset the model when the view is invalid due to an external validator', function() {
ctrl.$setViewValue('aaaa');
expect(ctrl.$modelValue).toBe('aaaa');
ctrl.$setValidity('someExternalError', false);
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBe('bbbb');
});
it('should not reset the view when the view is invalid', function() {
// this test fails when the view changes the model and
// then the model listener in ngModel picks up the change and
// tries to update the view again.
// add a validator that will make any input invalid
ctrl.$parsers.push(function() {return undefined;});
spyOn(ctrl, '$render');
// first digest
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBeUndefined();
expect(ctrl.$viewValue).toBe('bbbb');
expect(ctrl.$render).not.toHaveBeenCalled();
expect(scope.value).toBeUndefined();
// further digests
scope.$apply('value = "aaa"');
expect(ctrl.$viewValue).toBe('aaa');
ctrl.$render.reset();
ctrl.$setViewValue('cccc');
expect(ctrl.$modelValue).toBeUndefined();
expect(ctrl.$viewValue).toBe('cccc');
expect(ctrl.$render).not.toHaveBeenCalled();
expect(scope.value).toBeUndefined();
});
it('should call parentForm.$setDirty only when pristine', function() {
ctrl.$setViewValue('');
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
expect(parentFormCtrl.$setDirty).toHaveBeenCalledOnce();
parentFormCtrl.$setDirty.reset();
ctrl.$setViewValue('');
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
expect(parentFormCtrl.$setDirty).not.toHaveBeenCalled();
});
it('should remove all other errors when any parser returns undefined', function() {
var a, b, val = function(val, x) {
return x ? val : x;
};
ctrl.$parsers.push(function(v) { return val(v, a); });
ctrl.$parsers.push(function(v) { return val(v, b); });
ctrl.$validators.high = function(value) {
return !isDefined(value) || value > 5;
};
ctrl.$validators.even = function(value) {
return !isDefined(value) || value % 2 === 0;
};
a = b = true;
ctrl.$setViewValue('3');
expect(ctrl.$error).toEqual({ high: true, even: true });
ctrl.$setViewValue('10');
expect(ctrl.$error).toEqual({});
a = undefined;
ctrl.$setViewValue('12');
expect(ctrl.$error).toEqual({ parse: true });
a = true;
b = undefined;
ctrl.$setViewValue('14');
expect(ctrl.$error).toEqual({ parse: true });
a = undefined;
b = undefined;
ctrl.$setViewValue('16');
expect(ctrl.$error).toEqual({ parse: true });
a = b = false; //not undefined
ctrl.$setViewValue('2');
expect(ctrl.$error).toEqual({ high: true });
});
it('should not remove external validators when a parser failed', function() {
ctrl.$parsers.push(function(v) { return undefined; });
ctrl.$setValidity('externalError', false);
ctrl.$setViewValue('someValue');
expect(ctrl.$error).toEqual({ externalError: true, parse: true });
});
it('should remove all non-parse-related CSS classes from the form when a parser fails',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var ctrl = $rootScope.myForm.myControl;
var parserIsFailing = false;
ctrl.$parsers.push(function(value) {
return parserIsFailing ? undefined : value;
});
ctrl.$validators.alwaysFail = function() {
return false;
};
ctrl.$setViewValue('123');
scope.$digest();
expect(element).toHaveClass('ng-valid-parse');
expect(element).not.toHaveClass('ng-invalid-parse');
expect(element).toHaveClass('ng-invalid-always-fail');
parserIsFailing = true;
ctrl.$setViewValue('12345');
scope.$digest();
expect(element).not.toHaveClass('ng-valid-parse');
expect(element).toHaveClass('ng-invalid-parse');
expect(element).not.toHaveClass('ng-invalid-always-fail');
dealoc(element);
}));
it('should set the ng-invalid-parse and ng-valid-parse CSS class when parsers fail and pass', function() {
var pass = true;
ctrl.$parsers.push(function(v) {
return pass ? v : undefined;
});
var input = element.find('input');
ctrl.$setViewValue('1');
expect(input).toHaveClass('ng-valid-parse');
expect(input).not.toHaveClass('ng-invalid-parse');
pass = undefined;
ctrl.$setViewValue('2');
expect(input).not.toHaveClass('ng-valid-parse');
expect(input).toHaveClass('ng-invalid-parse');
});
it('should update the model after all async validators resolve', inject(function($q) {
var defer;
ctrl.$asyncValidators.promiseValidator = function(value) {
defer = $q.defer();
return defer.promise;
};
// set view value on first digest
ctrl.$setViewValue('b');
expect(ctrl.$modelValue).toBeUndefined();
expect(scope.value).toBeUndefined();
defer.resolve();
scope.$digest();
expect(ctrl.$modelValue).toBe('b');
expect(scope.value).toBe('b');
// set view value on further digests
ctrl.$setViewValue('c');
expect(ctrl.$modelValue).toBe('b');
expect(scope.value).toBe('b');
defer.resolve();
scope.$digest();
expect(ctrl.$modelValue).toBe('c');
expect(scope.value).toBe('c');
}));
});
describe('model -> view', function() {
it('should set the value to $modelValue', function() {
scope.$apply('value = 10');
expect(ctrl.$modelValue).toBe(10);
});
it('should pipeline all registered formatters in reversed order and set result to $viewValue',
function() {
var log = [];
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + 2;
});
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + '';
});
scope.$apply('value = 3');
expect(log).toEqual([3, 5]);
expect(ctrl.$viewValue).toBe('5');
});
it('should $render only if value changed', function() {
spyOn(ctrl, '$render');
scope.$apply('value = 3');
expect(ctrl.$render).toHaveBeenCalledOnce();
ctrl.$render.reset();
ctrl.$formatters.push(function() {return 3;});
scope.$apply('value = 5');
expect(ctrl.$render).not.toHaveBeenCalled();
});
it('should clear the view even if invalid', function() {
spyOn(ctrl, '$render');
ctrl.$formatters.push(function() {return undefined;});
scope.$apply('value = 5');
expect(ctrl.$render).toHaveBeenCalledOnce();
});
it('should render immediately even if there are async validators', inject(function($q) {
spyOn(ctrl, '$render');
ctrl.$asyncValidators.someValidator = function() {
return $q.defer().promise;
};
scope.$apply('value = 5');
expect(ctrl.$viewValue).toBe(5);
expect(ctrl.$render).toHaveBeenCalledOnce();
}));
it('should not rerender nor validate in case view value is not changed', function() {
ctrl.$formatters.push(function(value) {
return 'nochange';
});
spyOn(ctrl, '$render');
ctrl.$validators.spyValidator = jasmine.createSpy('spyValidator');
scope.$apply('value = "first"');
scope.$apply('value = "second"');
expect(ctrl.$validators.spyValidator).toHaveBeenCalledOnce();
expect(ctrl.$render).toHaveBeenCalledOnce();
});
it('should always format the viewValue as a string for a blank input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for a `text` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="text" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for an `email` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="email" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for a `url` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="url" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should set NaN as the $modelValue when an asyncValidator is present',
inject(function($q) {
ctrl.$asyncValidators.test = function() {
return $q(function(resolve, reject) {
resolve();
});
};
scope.$apply('value = 10');
expect(ctrl.$modelValue).toBe(10);
expect(function() {
scope.$apply(function() {
scope.value = NaN;
});
}).not.toThrow();
expect(ctrl.$modelValue).toBeNaN();
}));
});
describe('validation', function() {
describe('$validate', function() {
it('should perform validations when $validate() is called', function() {
scope.$apply('value = ""');
var validatorResult = false;
ctrl.$validators.someValidator = function(value) {
return validatorResult;
};
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
validatorResult = true;
ctrl.$validate();
expect(ctrl.$valid).toBe(true);
});
it('should pass the last parsed modelValue to the validators', function() {
ctrl.$parsers.push(function(modelValue) {
return modelValue + 'def';
});
ctrl.$setViewValue('abc');
ctrl.$validators.test = function(modelValue, viewValue) {
return true;
};
spyOn(ctrl.$validators, 'test');
ctrl.$validate();
expect(ctrl.$validators.test).toHaveBeenCalledWith('abcdef', 'abc');
});
it('should set the model to undefined when it becomes invalid', function() {
var valid = true;
ctrl.$validators.test = function(modelValue, viewValue) {
return valid;
};
scope.$apply('value = "abc"');
expect(scope.value).toBe('abc');
valid = false;
ctrl.$validate();
expect(scope.value).toBeUndefined();
});
it('should update the model when it becomes valid', function() {
var valid = true;
ctrl.$validators.test = function(modelValue, viewValue) {
return valid;
};
scope.$apply('value = "abc"');
expect(scope.value).toBe('abc');
valid = false;
ctrl.$validate();
expect(scope.value).toBeUndefined();
valid = true;
ctrl.$validate();
expect(scope.value).toBe('abc');
});
it('should not update the model when it is valid, but there is a parse error', function() {
ctrl.$parsers.push(function(modelValue) {
return undefined;
});
ctrl.$setViewValue('abc');
expect(ctrl.$error.parse).toBe(true);
expect(scope.value).toBeUndefined();
ctrl.$validators.test = function(modelValue, viewValue) {
return true;
};
ctrl.$validate();
expect(ctrl.$error).toEqual({parse: true});
expect(scope.value).toBeUndefined();
});
it('should not set an invalid model to undefined when validity is the same', function() {
ctrl.$validators.test = function() {
return false;
};
scope.$apply('value = "invalid"');
expect(ctrl.$valid).toBe(false);
expect(scope.value).toBe('invalid');
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
expect(scope.value).toBe('invalid');
});
it('should not change a model that has a formatter', function() {
ctrl.$validators.test = function() {
return true;
};
ctrl.$formatters.push(function(modelValue) {
return 'xyz';
});
scope.$apply('value = "abc"');
expect(ctrl.$viewValue).toBe('xyz');
ctrl.$validate();
expect(scope.value).toBe('abc');
});
it('should not change a model that has a parser', function() {
ctrl.$validators.test = function() {
return true;
};
ctrl.$parsers.push(function(modelValue) {
return 'xyz';
});
scope.$apply('value = "abc"');
ctrl.$validate();
expect(scope.value).toBe('abc');
});
});
describe('view -> model update', function() {
it('should always perform validations using the parsed model value', function() {
var captures;
ctrl.$validators.raw = function() {
captures = arguments;
return captures[0];
};
ctrl.$parsers.push(function(value) {
return value.toUpperCase();
});
ctrl.$setViewValue('my-value');
expect(captures).toEqual(['MY-VALUE', 'my-value']);
});
it('should always perform validations using the formatted view value', function() {
var captures;
ctrl.$validators.raw = function() {
captures = arguments;
return captures[0];
};
ctrl.$formatters.push(function(value) {
return value + '...';
});
scope.$apply('value = "matias"');
expect(captures).toEqual(['matias', 'matias...']);
});
it('should only perform validations if the view value is different', function() {
var count = 0;
ctrl.$validators.countMe = function() {
count++;
};
ctrl.$setViewValue('my-value');
expect(count).toBe(1);
ctrl.$setViewValue('my-value');
expect(count).toBe(1);
ctrl.$setViewValue('your-value');
expect(count).toBe(2);
});
});
it('should perform validations twice each time the model value changes within a digest', function() {
var count = 0;
ctrl.$validators.number = function(value) {
count++;
return (/^\d+$/).test(value);
};
scope.$apply('value = ""');
expect(count).toBe(1);
scope.$apply('value = 1');
expect(count).toBe(2);
scope.$apply('value = 1');
expect(count).toBe(2);
scope.$apply('value = ""');
expect(count).toBe(3);
});
it('should only validate to true if all validations are true', function() {
var curry = function(v) {
return function() {
return v;
};
};
ctrl.$modelValue = undefined;
ctrl.$validators.a = curry(true);
ctrl.$validators.b = curry(true);
ctrl.$validators.c = curry(false);
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
ctrl.$validators.c = curry(true);
ctrl.$validate();
expect(ctrl.$valid).toBe(true);
});
it('should register invalid validations on the $error object', function() {
var curry = function(v) {
return function() {
return v;
};
};
ctrl.$modelValue = undefined;
ctrl.$validators.unique = curry(false);
ctrl.$validators.tooLong = curry(false);
ctrl.$validators.notNumeric = curry(true);
ctrl.$validate();
expect(ctrl.$error.unique).toBe(true);
expect(ctrl.$error.tooLong).toBe(true);
expect(ctrl.$error.notNumeric).not.toBe(true);
});
it('should render a validator asynchronously when a promise is returned', inject(function($q) {
var defer;
ctrl.$asyncValidators.promiseValidator = function(value) {
defer = $q.defer();
return defer.promise;
};
scope.$apply('value = ""');
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
expect(ctrl.$pending.promiseValidator).toBe(true);
defer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(ctrl.$pending).toBeUndefined();
scope.$apply('value = "123"');
defer.reject();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(ctrl.$pending).toBeUndefined();
}));
it('should throw an error when a promise is not returned for an asynchronous validator', inject(function($q) {
ctrl.$asyncValidators.async = function(value) {
return true;
};
expect(function() {
scope.$apply('value = "123"');
}).toThrowMinErr("ngModel", "$asyncValidators",
"Expected asynchronous validator to return a promise but got 'true' instead.");
}));
it('should only run the async validators once all the sync validators have passed',
inject(function($q) {
var stages = {};
stages.sync = { status1: false, status2: false, count: 0 };
ctrl.$validators.syncValidator1 = function(modelValue, viewValue) {
stages.sync.count++;
return stages.sync.status1;
};
ctrl.$validators.syncValidator2 = function(modelValue, viewValue) {
stages.sync.count++;
return stages.sync.status2;
};
stages.async = { defer: null, count: 0 };
ctrl.$asyncValidators.asyncValidator = function(modelValue, viewValue) {
stages.async.defer = $q.defer();
stages.async.count++;
return stages.async.defer.promise;
};
scope.$apply('value = "123"');
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(stages.sync.count).toBe(2);
expect(stages.async.count).toBe(0);
stages.sync.status1 = true;
scope.$apply('value = "456"');
expect(stages.sync.count).toBe(4);
expect(stages.async.count).toBe(0);
stages.sync.status2 = true;
scope.$apply('value = "789"');
expect(stages.sync.count).toBe(6);
expect(stages.async.count).toBe(1);
stages.async.defer.resolve();
scope.$apply();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
}));
it('should ignore expired async validation promises once delivered', inject(function($q) {
var defer, oldDefer, newDefer;
ctrl.$asyncValidators.async = function(value) {
defer = $q.defer();
return defer.promise;
};
scope.$apply('value = ""');
oldDefer = defer;
scope.$apply('value = "123"');
newDefer = defer;
newDefer.reject();
scope.$digest();
oldDefer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(ctrl.$pending).toBeUndefined();
}));
it('should clear and ignore all pending promises when the model value changes', inject(function($q) {
ctrl.$validators.sync = function(value) {
return true;
};
var defers = [];
ctrl.$asyncValidators.async = function(value) {
var defer = $q.defer();
defers.push(defer);
return defer.promise;
};
scope.$apply('value = "123"');
expect(ctrl.$pending).toEqual({async: true});
expect(ctrl.$valid).toBe(undefined);
expect(ctrl.$invalid).toBe(undefined);
expect(defers.length).toBe(1);
expect(isObject(ctrl.$pending)).toBe(true);
scope.$apply('value = "456"');
expect(ctrl.$pending).toEqual({async: true});
expect(ctrl.$valid).toBe(undefined);
expect(ctrl.$invalid).toBe(undefined);
expect(defers.length).toBe(2);
expect(isObject(ctrl.$pending)).toBe(true);
defers[1].resolve();
scope.$digest();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(isObject(ctrl.$pending)).toBe(false);
}));
it('should clear and ignore all pending promises when a parser fails', inject(function($q) {
var failParser = false;
ctrl.$parsers.push(function(value) {
return failParser ? undefined : value;
});
var defer;
ctrl.$asyncValidators.async = function(value) {
defer = $q.defer();
return defer.promise;
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$valid).toBe(undefined);
expect(ctrl.$invalid).toBe(undefined);
failParser = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(isObject(ctrl.$pending)).toBe(false);
defer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(isObject(ctrl.$pending)).toBe(false);
}));
it('should clear all errors from async validators if a parser fails', inject(function($q) {
var failParser = false;
ctrl.$parsers.push(function(value) {
return failParser ? undefined : value;
});
ctrl.$asyncValidators.async = function(value) {
return $q.reject();
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$error).toEqual({async: true});
failParser = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$error).toEqual({parse: true});
}));
it('should clear all errors from async validators if a sync validator fails', inject(function($q) {
var failValidator = false;
ctrl.$validators.sync = function(value) {
return !failValidator;
};
ctrl.$asyncValidators.async = function(value) {
return $q.reject();
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$error).toEqual({async: true});
failValidator = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$error).toEqual({sync: true});
}));
it('should be possible to extend Object prototype and still be able to do form validation',
inject(function($compile, $rootScope) {
Object.prototype.someThing = function() {};
var element = $compile('<form name="myForm">' +
'<input type="text" name="username" ng-model="username" minlength="10" required />' +
'</form>')($rootScope);
var inputElm = element.find('input');
var formCtrl = $rootScope.myForm;
var usernameCtrl = formCtrl.username;
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('valid-username');
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
delete Object.prototype.someThing;
dealoc(element);
}));
it('should re-evaluate the form validity state once the asynchronous promise has been delivered',
inject(function($compile, $rootScope, $q) {
var element = $compile('<form name="myForm">' +
'<input type="text" name="username" ng-model="username" minlength="10" required />' +
'<input type="number" name="age" ng-model="age" min="10" required />' +
'</form>')($rootScope);
var inputElm = element.find('input');
var formCtrl = $rootScope.myForm;
var usernameCtrl = formCtrl.username;
var ageCtrl = formCtrl.age;
var usernameDefer;
usernameCtrl.$asyncValidators.usernameAvailability = function() {
usernameDefer = $q.defer();
return usernameDefer.promise;
};
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('valid-username');
$rootScope.$digest();
expect(formCtrl.$pending.usernameAvailability).toBeTruthy();
expect(usernameCtrl.$invalid).toBe(undefined);
expect(formCtrl.$invalid).toBe(undefined);
usernameDefer.resolve();
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(true);
ageCtrl.$setViewValue(22);
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(ageCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
usernameCtrl.$setViewValue('valid');
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(ageCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('another-valid-username');
$rootScope.$digest();
usernameDefer.resolve();
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
expect(formCtrl.$pending).toBeFalsy();
expect(ageCtrl.$invalid).toBe(false);
dealoc(element);
}));
it('should minimize janky setting of classes during $validate() and ngModelWatch', inject(function($animate, $compile, $rootScope) {
var addClass = $animate.addClass;
var removeClass = $animate.removeClass;
var addClassCallCount = 0;
var removeClassCallCount = 0;
var input;
$animate.addClass = function(element, className) {
if (input && element[0] === input[0]) ++addClassCallCount;
return addClass.call($animate, element, className);
};
$animate.removeClass = function(element, className) {
if (input && element[0] === input[0]) ++removeClassCallCount;
return removeClass.call($animate, element, className);
};
dealoc(element);
$rootScope.value = "123456789";
element = $compile(
'<form name="form">' +
'<input type="text" ng-model="value" name="alias" ng-maxlength="10">' +
'</form>'
)($rootScope);
var form = $rootScope.form;
input = element.children().eq(0);
$rootScope.$digest();
expect(input).toBeValid();
expect(input).not.toHaveClass('ng-invalid-maxlength');
expect(input).toHaveClass('ng-valid-maxlength');
expect(addClassCallCount).toBe(1);
expect(removeClassCallCount).toBe(0);
dealoc(element);
}));
it('should always use the most recent $viewValue for validation', function() {
ctrl.$parsers.push(function(value) {
if (value && value.substr(-1) === 'b') {
value = 'a';
ctrl.$setViewValue(value);
ctrl.$render();
}
return value;
});
ctrl.$validators.mock = function(modelValue) {
return true;
};
spyOn(ctrl.$validators, 'mock').andCallThrough();
ctrl.$setViewValue('ab');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'a');
expect(ctrl.$validators.mock.calls.length).toEqual(2);
});
it('should validate even if the modelValue did not change', function() {
ctrl.$parsers.push(function(value) {
if (value && value.substr(-1) === 'b') {
value = 'a';
}
return value;
});
ctrl.$validators.mock = function(modelValue) {
return true;
};
spyOn(ctrl.$validators, 'mock').andCallThrough();
ctrl.$setViewValue('a');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'a');
expect(ctrl.$validators.mock.calls.length).toEqual(1);
ctrl.$setViewValue('ab');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'ab');
expect(ctrl.$validators.mock.calls.length).toEqual(2);
});
it('should validate correctly when $parser name equals $validator key', function() {
ctrl.$validators.parserOrValidator = function(value) {
switch (value) {
case 'allInvalid':
case 'parseValid-validatorsInvalid':
case 'stillParseValid-validatorsInvalid':
return false;
default:
return true;
}
};
ctrl.$validators.validator = function(value) {
switch (value) {
case 'allInvalid':
case 'parseValid-validatorsInvalid':
case 'stillParseValid-validatorsInvalid':
return false;
default:
return true;
}
};
ctrl.$$parserName = 'parserOrValidator';
ctrl.$parsers.push(function(value) {
switch (value) {
case 'allInvalid':
case 'stillAllInvalid':
case 'parseInvalid-validatorsValid':
case 'stillParseInvalid-validatorsValid':
return undefined;
default:
return value;
}
});
//Parser and validators are invalid
scope.$apply('value = "allInvalid"');
expect(scope.value).toBe('allInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toEqual('allInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$setViewValue('stillAllInvalid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
//Parser is valid, validators are invalid
scope.$apply('value = "parseValid-validatorsInvalid"');
expect(scope.value).toBe('parseValid-validatorsInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toBe('parseValid-validatorsInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$setViewValue('stillParseValid-validatorsInvalid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
//Parser is invalid, validators are valid
scope.$apply('value = "parseInvalid-validatorsValid"');
expect(scope.value).toBe('parseInvalid-validatorsValid');
expect(ctrl.$error).toEqual({});
ctrl.$validate();
expect(scope.value).toBe('parseInvalid-validatorsValid');
expect(ctrl.$error).toEqual({});
ctrl.$setViewValue('stillParseInvalid-validatorsValid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
});
});
});
describe('CSS classes', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
it('should set css classes (ng-valid, ng-invalid, ng-pristine, ng-dirty, ng-untouched, ng-touched)',
inject(function($compile, $rootScope, $sniffer) {
var element = $compile('<input type="email" ng-model="value" />')($rootScope);
$rootScope.$digest();
expect(element).toBeValid();
expect(element).toBePristine();
expect(element).toBeUntouched();
expect(element.hasClass('ng-valid-email')).toBe(true);
expect(element.hasClass('ng-invalid-email')).toBe(false);
$rootScope.$apply("value = 'invalid-email'");
expect(element).toBeInvalid();
expect(element).toBePristine();
expect(element.hasClass('ng-valid-email')).toBe(false);
expect(element.hasClass('ng-invalid-email')).toBe(true);
element.val('invalid-again');
browserTrigger(element, ($sniffer.hasEvent('input')) ? 'input' : 'change');
expect(element).toBeInvalid();
expect(element).toBeDirty();
expect(element.hasClass('ng-valid-email')).toBe(false);
expect(element.hasClass('ng-invalid-email')).toBe(true);
element.val('vojta@google.com');
browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change');
expect(element).toBeValid();
expect(element).toBeDirty();
expect(element.hasClass('ng-valid-email')).toBe(true);
expect(element.hasClass('ng-invalid-email')).toBe(false);
browserTrigger(element, 'blur');
expect(element).toBeTouched();
dealoc(element);
}));
it('should set invalid classes on init', inject(function($compile, $rootScope) {
var element = $compile('<input type="email" ng-model="value" required />')($rootScope);
$rootScope.$digest();
expect(element).toBeInvalid();
expect(element).toHaveClass('ng-invalid-required');
dealoc(element);
}));
});
describe('custom formatter and parser that are added by a directive in post linking', function() {
var inputElm, scope;
beforeEach(module(function($compileProvider) {
$compileProvider.directive('customFormat', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function(value) {
return value.part;
});
ngModelCtrl.$parsers.push(function(value) {
return {part: value};
});
}
};
});
}));
afterEach(function() {
dealoc(inputElm);
});
function createInput(type) {
inject(function($compile, $rootScope) {
scope = $rootScope;
inputElm = $compile('<input type="' + type + '" ng-model="val" custom-format/>')($rootScope);
});
}
it('should use them after the builtin ones for text inputs', function() {
createInput('text');
scope.$apply('val = {part: "a"}');
expect(inputElm.val()).toBe('a');
inputElm.val('b');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: 'b'});
});
it('should use them after the builtin ones for number inputs', function() {
createInput('number');
scope.$apply('val = {part: 1}');
expect(inputElm.val()).toBe('1');
inputElm.val('2');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: 2});
});
it('should use them after the builtin ones for date inputs', function() {
createInput('date');
scope.$apply(function() {
scope.val = {part: new Date(2000, 10, 8)};
});
expect(inputElm.val()).toBe('2000-11-08');
inputElm.val('2001-12-09');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: new Date(2001, 11, 9)});
});
});
describe('$touched', function() {
it('should set the control touched state on "blur" event', inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
browserTrigger(inputElm, 'blur');
expect(control.$touched).toBe(true);
expect(control.$untouched).toBe(false);
dealoc(element);
}));
it('should not cause a digest on "blur" event if control is already touched',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
control.$setTouched();
spyOn($rootScope, '$apply');
browserTrigger(inputElm, 'blur');
expect($rootScope.$apply).not.toHaveBeenCalled();
dealoc(element);
}));
it('should digest asynchronously on "blur" event if a apply is already in progress',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
$rootScope.$apply(function() {
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
browserTrigger(inputElm, 'blur');
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
});
expect(control.$touched).toBe(true);
expect(control.$untouched).toBe(false);
dealoc(element);
}));
});
describe('nested in a form', function() {
it('should register/deregister a nested ngModel with parent form when entering or leaving DOM',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input ng-if="inputPresent" name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
var isFormValid;
$rootScope.inputPresent = false;
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
$rootScope.inputPresent = true;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(false);
expect(isFormValid).toBe(false);
expect($rootScope.myForm.myControl).toBeDefined();
$rootScope.inputPresent = false;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
dealoc(element);
}));
it('should register/deregister a nested ngModel with parent form when entering or leaving DOM with animations',
function() {
// ngAnimate performs the dom manipulation after digest, and since the form validity can be affected by a form
// control going away we must ensure that the deregistration happens during the digest while we are still doing
// dirty checking.
module('ngAnimate');
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input ng-if="inputPresent" name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
var isFormValid;
$rootScope.inputPresent = false;
// this watch ensure that the form validity gets updated during digest (so that we can observe it)
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
$rootScope.inputPresent = true;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(false);
expect(isFormValid).toBe(false);
expect($rootScope.myForm.myControl).toBeDefined();
$rootScope.inputPresent = false;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
dealoc(element);
});
});
it('should keep previously defined watches consistent when changes in validity are made',
inject(function($compile, $rootScope) {
var isFormValid;
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
$rootScope.$apply();
expect(isFormValid).toBe(false);
expect($rootScope.myForm.$valid).toBe(false);
$rootScope.value='value';
$rootScope.$apply();
expect(isFormValid).toBe(true);
expect($rootScope.myForm.$valid).toBe(true);
dealoc(element);
}));
});
describe('animations', function() {
function findElementAnimations(element, queue) {
var node = element[0];
var animations = [];
for (var i = 0; i < queue.length; i++) {
var animation = queue[i];
if (animation.element[0] == node) {
animations.push(animation);
}
}
return animations;
}
function assertValidAnimation(animation, event, classNameA, classNameB) {
expect(animation.event).toBe(event);
expect(animation.args[1]).toBe(classNameA);
if (classNameB) expect(animation.args[2]).toBe(classNameB);
}
var doc, input, scope, model;
beforeEach(module('ngAnimateMock'));
beforeEach(inject(function($rootScope, $compile, $rootElement, $animate) {
scope = $rootScope.$new();
doc = jqLite('<form name="myForm">' +
' <input type="text" ng-model="input" name="myInput" />' +
'</form>');
$rootElement.append(doc);
$compile(doc)(scope);
$animate.queue = [];
input = doc.find('input');
model = scope.myForm.myInput;
}));
afterEach(function() {
dealoc(input);
});
it('should trigger an animation when invalid', inject(function($animate) {
model.$setValidity('required', false);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-valid');
assertValidAnimation(animations[1], 'addClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-invalid-required');
}));
it('should trigger an animation when valid', inject(function($animate) {
model.$setValidity('required', false);
$animate.queue = [];
model.$setValidity('required', true);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'addClass', 'ng-valid');
assertValidAnimation(animations[1], 'removeClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-valid-required');
assertValidAnimation(animations[3], 'removeClass', 'ng-invalid-required');
}));
it('should trigger an animation when dirty', inject(function($animate) {
model.$setViewValue('some dirty value');
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-pristine');
assertValidAnimation(animations[1], 'addClass', 'ng-dirty');
}));
it('should trigger an animation when pristine', inject(function($animate) {
model.$setPristine();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-dirty');
assertValidAnimation(animations[1], 'addClass', 'ng-pristine');
}));
it('should trigger an animation when untouched', inject(function($animate) {
model.$setUntouched();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'setClass', 'ng-untouched');
expect(animations[0].args[2]).toBe('ng-touched');
}));
it('should trigger an animation when touched', inject(function($animate) {
model.$setTouched();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'setClass', 'ng-touched', 'ng-untouched');
expect(animations[0].args[2]).toBe('ng-untouched');
}));
it('should trigger custom errors as addClass/removeClass when invalid/valid', inject(function($animate) {
model.$setValidity('custom-error', false);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-valid');
assertValidAnimation(animations[1], 'addClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-invalid-custom-error');
$animate.queue = [];
model.$setValidity('custom-error', true);
animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'addClass', 'ng-valid');
assertValidAnimation(animations[1], 'removeClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-valid-custom-error');
assertValidAnimation(animations[3], 'removeClass', 'ng-invalid-custom-error');
}));
});
});
describe('ngModelOptions attributes', function() {
var helper, $rootScope, $compile, $timeout, $q;
beforeEach(function() {
helper = getInputCompileHelper(this);
});
afterEach(function() {
helper.dealoc();
});
beforeEach(inject(function(_$compile_, _$rootScope_, _$timeout_, _$q_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
$q = _$q_;
}));
it('should allow overriding the model update trigger event on text inputs', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ updateOn: \'blur\' }"' +
'/>');
helper.changeInputValueTo('a');
expect($rootScope.name).toBeUndefined();
browserTrigger(inputElm, 'blur');
expect($rootScope.name).toEqual('a');
});
it('should not dirty the input if nothing was changed before updateOn trigger', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ updateOn: \'blur\' }"' +
'/>');
browserTrigger(inputElm, 'blur');
expect($rootScope.form.alias.$pristine).toBeTruthy();
});
it('should allow overriding the model update trigger event on text areas', function() {
var inputElm = helper.compileInput(
'<textarea ng-model="name" name="alias" ' +
'ng-model-options="{ updateOn: \'blur\' }"' +
'/>');
helper.changeInputValueTo('a');
expect($rootScope.name).toBeUndefined();
browserTrigger(inputElm, 'blur');
expect($rootScope.name).toEqual('a');
});
it('should bind the element to a list of events', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ updateOn: \'blur mousemove\' }"' +
'/>');
helper.changeInputValueTo('a');
expect($rootScope.name).toBeUndefined();
browserTrigger(inputElm, 'blur');
expect($rootScope.name).toEqual('a');
helper.changeInputValueTo('b');
expect($rootScope.name).toEqual('a');
browserTrigger(inputElm, 'mousemove');
expect($rootScope.name).toEqual('b');
});
it('should allow keeping the default update behavior on text inputs', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ updateOn: \'default\' }"' +
'/>');
helper.changeInputValueTo('a');
expect($rootScope.name).toEqual('a');
});
it('should allow sharing options between multiple inputs', function() {
$rootScope.options = {updateOn: 'default'};
var inputElm = helper.compileInput(
'<input type="text" ng-model="name1" name="alias1" ' +
'ng-model-options="options"' +
'/>' +
'<input type="text" ng-model="name2" name="alias2" ' +
'ng-model-options="options"' +
'/>');
helper.changeGivenInputTo(inputElm.eq(0), 'a');
helper.changeGivenInputTo(inputElm.eq(1), 'b');
expect($rootScope.name1).toEqual('a');
expect($rootScope.name2).toEqual('b');
});
it('should hold a copy of the options object', function() {
$rootScope.options = {updateOn: 'default'};
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="options"' +
'/>');
expect($rootScope.options).toEqual({updateOn: 'default'});
expect($rootScope.form.alias.$options).not.toBe($rootScope.options);
});
it('should allow overriding the model update trigger event on checkboxes', function() {
var inputElm = helper.compileInput(
'<input type="checkbox" ng-model="checkbox" ' +
'ng-model-options="{ updateOn: \'blur\' }"' +
'/>');
browserTrigger(inputElm, 'click');
expect($rootScope.checkbox).toBe(undefined);
browserTrigger(inputElm, 'blur');
expect($rootScope.checkbox).toBe(true);
browserTrigger(inputElm, 'click');
expect($rootScope.checkbox).toBe(true);
});
it('should allow keeping the default update behavior on checkboxes', function() {
var inputElm = helper.compileInput(
'<input type="checkbox" ng-model="checkbox" ' +
'ng-model-options="{ updateOn: \'blur default\' }"' +
'/>');
browserTrigger(inputElm, 'click');
expect($rootScope.checkbox).toBe(true);
browserTrigger(inputElm, 'click');
expect($rootScope.checkbox).toBe(false);
});
it('should allow overriding the model update trigger event on radio buttons', function() {
var inputElm = helper.compileInput(
'<input type="radio" ng-model="color" value="white" ' +
'ng-model-options="{ updateOn: \'blur\'}"' +
'/>' +
'<input type="radio" ng-model="color" value="red" ' +
'ng-model-options="{ updateOn: \'blur\'}"' +
'/>' +
'<input type="radio" ng-model="color" value="blue" ' +
'ng-model-options="{ updateOn: \'blur\'}"' +
'/>');
$rootScope.$apply("color = 'white'");
browserTrigger(inputElm[2], 'click');
expect($rootScope.color).toBe('white');
browserTrigger(inputElm[2], 'blur');
expect($rootScope.color).toBe('blue');
});
it('should allow keeping the default update behavior on radio buttons', function() {
var inputElm = helper.compileInput(
'<input type="radio" ng-model="color" value="white" ' +
'ng-model-options="{ updateOn: \'blur default\' }"' +
'/>' +
'<input type="radio" ng-model="color" value="red" ' +
'ng-model-options="{ updateOn: \'blur default\' }"' +
'/>' +
'<input type="radio" ng-model="color" value="blue" ' +
'ng-model-options="{ updateOn: \'blur default\' }"' +
'/>');
$rootScope.$apply("color = 'white'");
browserTrigger(inputElm[2], 'click');
expect($rootScope.color).toBe('blue');
});
it('should trigger only after timeout in text inputs', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ debounce: 10000 }"' +
'/>');
helper.changeInputValueTo('a');
helper.changeInputValueTo('b');
helper.changeInputValueTo('c');
expect($rootScope.name).toEqual(undefined);
$timeout.flush(2000);
expect($rootScope.name).toEqual(undefined);
$timeout.flush(9000);
expect($rootScope.name).toEqual('c');
});
it('should trigger only after timeout in checkboxes', function() {
var inputElm = helper.compileInput(
'<input type="checkbox" ng-model="checkbox" ' +
'ng-model-options="{ debounce: 10000 }"' +
'/>');
browserTrigger(inputElm, 'click');
expect($rootScope.checkbox).toBe(undefined);
$timeout.flush(2000);
expect($rootScope.checkbox).toBe(undefined);
$timeout.flush(9000);
expect($rootScope.checkbox).toBe(true);
});
it('should trigger only after timeout in radio buttons', function() {
var inputElm = helper.compileInput(
'<input type="radio" ng-model="color" value="white" />' +
'<input type="radio" ng-model="color" value="red" ' +
'ng-model-options="{ debounce: 20000 }"' +
'/>' +
'<input type="radio" ng-model="color" value="blue" ' +
'ng-model-options="{ debounce: 30000 }"' +
'/>');
browserTrigger(inputElm[0], 'click');
expect($rootScope.color).toBe('white');
browserTrigger(inputElm[1], 'click');
expect($rootScope.color).toBe('white');
$timeout.flush(12000);
expect($rootScope.color).toBe('white');
$timeout.flush(10000);
expect($rootScope.color).toBe('red');
});
it('should not trigger digest while debouncing', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ debounce: 10000 }"' +
'/>');
var watchSpy = jasmine.createSpy('watchSpy');
$rootScope.$watch(watchSpy);
helper.changeInputValueTo('a');
expect(watchSpy).not.toHaveBeenCalled();
$timeout.flush(10000);
expect(watchSpy).toHaveBeenCalled();
});
it('should allow selecting different debounce timeouts for each event',
function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{' +
'updateOn: \'default blur\', ' +
'debounce: { default: 10000, blur: 5000 }' +
'}"' +
'/>');
helper.changeInputValueTo('a');
expect($rootScope.checkbox).toBe(undefined);
$timeout.flush(6000);
expect($rootScope.checkbox).toBe(undefined);
$timeout.flush(4000);
expect($rootScope.name).toEqual('a');
helper.changeInputValueTo('b');
browserTrigger(inputElm, 'blur');
$timeout.flush(4000);
expect($rootScope.name).toEqual('a');
$timeout.flush(2000);
expect($rootScope.name).toEqual('b');
});
it('should allow selecting different debounce timeouts for each event on checkboxes', function() {
var inputElm = helper.compileInput('<input type="checkbox" ng-model="checkbox" ' +
'ng-model-options="{ ' +
'updateOn: \'default blur\', debounce: { default: 10000, blur: 5000 } }"' +
'/>');
inputElm[0].checked = false;
browserTrigger(inputElm, 'click');
expect($rootScope.checkbox).toBe(undefined);
$timeout.flush(8000);
expect($rootScope.checkbox).toBe(undefined);
$timeout.flush(3000);
expect($rootScope.checkbox).toBe(true);
inputElm[0].checked = true;
browserTrigger(inputElm, 'click');
browserTrigger(inputElm, 'blur');
$timeout.flush(3000);
expect($rootScope.checkbox).toBe(true);
$timeout.flush(3000);
expect($rootScope.checkbox).toBe(false);
});
it('should allow selecting 0 for non-default debounce timeouts for each event on checkboxes', function() {
var inputElm = helper.compileInput('<input type="checkbox" ng-model="checkbox" ' +
'ng-model-options="{ ' +
'updateOn: \'default blur\', debounce: { default: 10000, blur: 0 } }"' +
'/>');
inputElm[0].checked = false;
browserTrigger(inputElm, 'click');
expect($rootScope.checkbox).toBe(undefined);
$timeout.flush(8000);
expect($rootScope.checkbox).toBe(undefined);
$timeout.flush(3000);
expect($rootScope.checkbox).toBe(true);
inputElm[0].checked = true;
browserTrigger(inputElm, 'click');
browserTrigger(inputElm, 'blur');
$timeout.flush(0);
expect($rootScope.checkbox).toBe(false);
});
it('should inherit model update settings from ancestor elements', function() {
var doc = $compile(
'<form name="test" ' +
'ng-model-options="{ debounce: 10000, updateOn: \'blur\' }" >' +
'<input type="text" ng-model="name" name="alias" />' +
'</form>')($rootScope);
$rootScope.$digest();
var inputElm = doc.find('input').eq(0);
helper.changeGivenInputTo(inputElm, 'a');
expect($rootScope.name).toEqual(undefined);
browserTrigger(inputElm, 'blur');
expect($rootScope.name).toBe(undefined);
$timeout.flush(2000);
expect($rootScope.name).toBe(undefined);
$timeout.flush(9000);
expect($rootScope.name).toEqual('a');
dealoc(doc);
});
it('should flush debounced events when calling $commitViewValue directly', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ debounce: 1000 }" />');
helper.changeInputValueTo('a');
expect($rootScope.name).toEqual(undefined);
$rootScope.form.alias.$commitViewValue();
expect($rootScope.name).toEqual('a');
});
it('should cancel debounced events when calling $commitViewValue', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ debounce: 1000 }"/>');
helper.changeInputValueTo('a');
$rootScope.form.alias.$commitViewValue();
expect($rootScope.name).toEqual('a');
$rootScope.form.alias.$setPristine();
$timeout.flush(1000);
expect($rootScope.form.alias.$pristine).toBeTruthy();
});
it('should reset input val if rollbackViewValue called during pending update', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ updateOn: \'blur\' }" />');
helper.changeInputValueTo('a');
expect(inputElm.val()).toBe('a');
$rootScope.form.alias.$rollbackViewValue();
expect(inputElm.val()).toBe('');
browserTrigger(inputElm, 'blur');
expect(inputElm.val()).toBe('');
});
it('should allow canceling pending updates', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ updateOn: \'blur\' }" />');
helper.changeInputValueTo('a');
expect($rootScope.name).toEqual(undefined);
$rootScope.form.alias.$rollbackViewValue();
expect($rootScope.name).toEqual(undefined);
browserTrigger(inputElm, 'blur');
expect($rootScope.name).toEqual(undefined);
});
it('should allow canceling debounced updates', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ debounce: 10000 }" />');
helper.changeInputValueTo('a');
expect($rootScope.name).toEqual(undefined);
$timeout.flush(2000);
$rootScope.form.alias.$rollbackViewValue();
expect($rootScope.name).toEqual(undefined);
$timeout.flush(10000);
expect($rootScope.name).toEqual(undefined);
});
it('should handle model updates correctly even if rollbackViewValue is not invoked', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ updateOn: \'blur\' }" />');
helper.changeInputValueTo('a');
$rootScope.$apply("name = 'b'");
browserTrigger(inputElm, 'blur');
expect($rootScope.name).toBe('b');
});
it('should reset input val if rollbackViewValue called during debounce', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" name="alias" ' +
'ng-model-options="{ debounce: 2000 }" />');
helper.changeInputValueTo('a');
expect(inputElm.val()).toBe('a');
$rootScope.form.alias.$rollbackViewValue();
expect(inputElm.val()).toBe('');
$timeout.flush(3000);
expect(inputElm.val()).toBe('');
});
it('should not try to invoke a model if getterSetter is false', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" ' +
'ng-model-options="{ getterSetter: false }" />');
var spy = $rootScope.name = jasmine.createSpy('setterSpy');
helper.changeInputValueTo('a');
expect(spy).not.toHaveBeenCalled();
expect(inputElm.val()).toBe('a');
});
it('should not try to invoke a model if getterSetter is not set', function() {
var inputElm = helper.compileInput('<input type="text" ng-model="name" />');
var spy = $rootScope.name = jasmine.createSpy('setterSpy');
helper.changeInputValueTo('a');
expect(spy).not.toHaveBeenCalled();
expect(inputElm.val()).toBe('a');
});
it('should try to invoke a function model if getterSetter is true', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" ' +
'ng-model-options="{ getterSetter: true }" />');
var spy = $rootScope.name = jasmine.createSpy('setterSpy').andCallFake(function() {
return 'b';
});
$rootScope.$apply();
expect(inputElm.val()).toBe('b');
helper.changeInputValueTo('a');
expect(inputElm.val()).toBe('b');
expect(spy).toHaveBeenCalledWith('a');
expect($rootScope.name).toBe(spy);
});
it('should assign to non-function models if getterSetter is true', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="name" ' +
'ng-model-options="{ getterSetter: true }" />');
$rootScope.name = 'c';
helper.changeInputValueTo('d');
expect(inputElm.val()).toBe('d');
expect($rootScope.name).toBe('d');
});
it('should fail on non-assignable model binding if getterSetter is false', function() {
expect(function() {
var inputElm = helper.compileInput('<input type="text" ng-model="accessor(user, \'name\')" />');
}).toThrowMinErr('ngModel', 'nonassign', 'Expression \'accessor(user, \'name\')\' is non-assignable.');
});
it('should not fail on non-assignable model binding if getterSetter is true', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="accessor(user, \'name\')" ' +
'ng-model-options="{ getterSetter: true }" />');
});
it('should invoke a model in the correct context if getterSetter is true', function() {
var inputElm = helper.compileInput(
'<input type="text" ng-model="someService.getterSetter" ' +
'ng-model-options="{ getterSetter: true }" />');
$rootScope.someService = {
value: 'a',
getterSetter: function(newValue) {
this.value = newValue || this.value;
return this.value;
}
};
spyOn($rootScope.someService, 'getterSetter').andCallThrough();
$rootScope.$apply();
expect(inputElm.val()).toBe('a');
expect($rootScope.someService.getterSetter).toHaveBeenCalledWith();
expect($rootScope.someService.value).toBe('a');
helper.changeInputValueTo('b');
expect($rootScope.someService.getterSetter).toHaveBeenCalledWith('b');
expect($rootScope.someService.value).toBe('b');
$rootScope.someService.value = 'c';
$rootScope.$apply();
expect(inputElm.val()).toBe('c');
expect($rootScope.someService.getterSetter).toHaveBeenCalledWith();
});
it('should assign invalid values to the scope if allowInvalid is true', function() {
var inputElm = helper.compileInput('<input type="text" name="input" ng-model="value" maxlength="1" ' +
'ng-model-options="{allowInvalid: true}" />');
helper.changeInputValueTo('12345');
expect($rootScope.value).toBe('12345');
expect(inputElm).toBeInvalid();
});
it('should not assign not parsable values to the scope if allowInvalid is true', function() {
var inputElm = helper.compileInput('<input type="number" name="input" ng-model="value" ' +
'ng-model-options="{allowInvalid: true}" />', {
valid: false,
badInput: true
});
helper.changeInputValueTo('abcd');
expect($rootScope.value).toBeUndefined();
expect(inputElm).toBeInvalid();
});
it('should update the scope before async validators execute if allowInvalid is true', function() {
var inputElm = helper.compileInput('<input type="text" name="input" ng-model="value" ' +
'ng-model-options="{allowInvalid: true}" />');
var defer;
$rootScope.form.input.$asyncValidators.promiseValidator = function(value) {
defer = $q.defer();
return defer.promise;
};
helper.changeInputValueTo('12345');
expect($rootScope.value).toBe('12345');
expect($rootScope.form.input.$pending.promiseValidator).toBe(true);
defer.reject();
$rootScope.$digest();
expect($rootScope.value).toBe('12345');
expect(inputElm).toBeInvalid();
});
it('should update the view before async validators execute if allowInvalid is true', function() {
var inputElm = helper.compileInput('<input type="text" name="input" ng-model="value" ' +
'ng-model-options="{allowInvalid: true}" />');
var defer;
$rootScope.form.input.$asyncValidators.promiseValidator = function(value) {
defer = $q.defer();
return defer.promise;
};
$rootScope.$apply('value = \'12345\'');
expect(inputElm.val()).toBe('12345');
expect($rootScope.form.input.$pending.promiseValidator).toBe(true);
defer.reject();
$rootScope.$digest();
expect(inputElm.val()).toBe('12345');
expect(inputElm).toBeInvalid();
});
it('should not call ng-change listeners twice if the model did not change with allowInvalid', function() {
var inputElm = helper.compileInput('<input type="text" name="input" ng-model="value" ' +
'ng-model-options="{allowInvalid: true}" ng-change="changed()" />');
$rootScope.changed = jasmine.createSpy('changed');
$rootScope.form.input.$parsers.push(function(value) {
return 'modelValue';
});
helper.changeInputValueTo('input1');
expect($rootScope.value).toBe('modelValue');
expect($rootScope.changed).toHaveBeenCalledOnce();
helper.changeInputValueTo('input2');
expect($rootScope.value).toBe('modelValue');
expect($rootScope.changed).toHaveBeenCalledOnce();
});
});
|
YUI.add('swfdetect', function(Y) {
/**
* Utility for Flash version detection
* @module swfdetect
*/
// Shortcuts and helper methods
var version = 0,
uA = Y.UA,
lG = Y.Lang,
sF = "ShockwaveFlash",
mF, eP, vS, ax6, ax;
function makeInt(n) {
return parseInt(n, 10);
}
function parseFlashVersion (flashVer) {
if (lG.isNumber(makeInt(flashVer[0]))) {
uA.flashMajor = flashVer[0];
}
if (lG.isNumber(makeInt(flashVer[1]))) {
uA.flashMinor = flashVer[1];
}
if (lG.isNumber(makeInt(flashVer[2]))) {
uA.flashRev = flashVer[2];
}
}
if (uA.gecko || uA.webkit || uA.opera) {
if ((mF = navigator.mimeTypes['application/x-shockwave-flash'])) {
if ((eP = mF.enabledPlugin)) {
vS = eP.description.replace(/\s[rd]/g, '.').replace(/[A-Za-z\s]+/g, '').split('.');
parseFlashVersion(vS);
}
}
}
else if(uA.ie) {
try
{
ax6 = new ActiveXObject(sF + "." + sF + ".6");
ax6.AllowScriptAccess = "always";
}
catch (e)
{
if(ax6 !== null)
{
version = 6.0;
}
}
if (version === 0) {
try
{
ax = new ActiveXObject(sF + "." + sF);
vS = ax.GetVariable("$version").replace(/[A-Za-z\s]+/g, '').split(',');
parseFlashVersion(vS);
} catch (e2) {}
}
}
/** Create a calendar view to represent a single or multiple
* month range of dates, rendered as a grid with date and
* weekday labels.
*
* @class SWFDetect
* @constructor
*/
Y.SWFDetect = {
/**
* Returns the version of either the Flash Player plugin (in Mozilla/WebKit/Opera browsers),
* or the Flash Player ActiveX control (in IE), as a String of the form "MM.mm.rr", where
* MM is the major version, mm is the minor version, and rr is the revision.
* @method getFlashVersion
*/
getFlashVersion : function () {
return (String(uA.flashMajor) + "." + String(uA.flashMinor) + "." + String(uA.flashRev));
},
/**
* Checks whether the version of the Flash player installed on the user's machine is greater
* than or equal to the one specified. If it is, this method returns true; it is false otherwise.
* @method isFlashVersionAtLeast
* @return {Boolean} Whether the Flash player version is greater than or equal to the one specified.
* @param flashMajor {int} The Major version of the Flash player to compare against.
* @param flashMinor {int} The Minor version of the Flash player to compare against.
* @param flashRev {int} The Revision version of the Flash player to compare against.
*/
isFlashVersionAtLeast : function (flashMajor, flashMinor, flashRev) {
var uaMajor = makeInt(uA.flashMajor),
uaMinor = makeInt(uA.flashMinor),
uaRev = makeInt(uA.flashRev);
flashMajor = makeInt(flashMajor || 0);
flashMinor = makeInt(flashMinor || 0);
flashRev = makeInt(flashRev || 0);
if (flashMajor === uaMajor) {
if (flashMinor === uaMinor) {
return flashRev <= uaRev;
}
return flashMinor < uaMinor;
}
return flashMajor < uaMajor;
}
};
}, '@VERSION@' ,{requires:['yui-base']});
|
'use strict';
describe('HTML', function() {
var expectHTML;
beforeEach(module('ngSanitize'));
beforeEach(function() {
expectHTML = function(html) {
var sanitize;
inject(function($sanitize) {
sanitize = $sanitize;
});
return expect(sanitize(html));
};
});
describe('htmlParser', function() {
/* global htmlParser */
if (angular.isUndefined(window.htmlParser)) return;
var handler, start, text, comment;
beforeEach(function() {
text = "";
start = null;
handler = {
start: function(tag, attrs) {
start = {
tag: tag,
attrs: attrs
};
// Since different browsers handle newlines differently we trim
// so that it is easier to write tests.
for (var i = 0, ii = attrs.length; i < ii; i++) {
var keyValue = attrs[i];
var key = keyValue.key;
var value = keyValue.value;
attrs[key] = value.replace(/^\s*/, '').replace(/\s*$/, '');
}
},
chars: function(text_) {
text += text_;
},
end:function(tag) {
expect(tag).toEqual(start.tag);
},
comment:function(comment_) {
comment = comment_;
}
};
});
it('should not parse comments', function() {
htmlParser('<!--FOOBAR-->', handler);
expect(comment).not.toBeDefined();
});
it('should parse basic format', function() {
htmlParser('<tag attr="value">text</tag>', handler);
expect(start).toEqual({tag:'tag', attrs:{attr:'value'}});
expect(text).toEqual('text');
});
it('should not treat "<" followed by a non-/ or non-letter as a tag', function() {
expectHTML('<- text1 text2 <1 text1 text2 <{', handler).
toBe('<- text1 text2 <1 text1 text2 <{');
});
it('should accept tag delimiters such as "<" inside real tags', function() {
// Assert that the < is part of the text node content, and not part of a tag name.
htmlParser('<p> 10 < 100 </p>', handler);
expect(text).toEqual(' 10 < 100 ');
});
it('should parse newlines in tags', function() {
htmlParser('<tag\n attr="value"\n>text</\ntag\n>', handler);
expect(start).toEqual({tag:'tag', attrs:{attr:'value'}});
expect(text).toEqual('text');
});
it('should parse newlines in attributes', function() {
htmlParser('<tag attr="\nvalue\n">text</tag>', handler);
expect(start).toEqual({tag:'tag', attrs:{attr:'\nvalue\n'}});
expect(text).toEqual('text');
});
it('should parse namespace', function() {
htmlParser('<ns:t-a-g ns:a-t-t-r="\nvalue\n">text</ns:t-a-g>', handler);
expect(start).toEqual({tag:'ns:t-a-g', attrs:{'ns:a-t-t-r':'\nvalue\n'}});
expect(text).toEqual('text');
});
it('should parse empty value attribute of node', function() {
htmlParser('<test-foo selected value="">abc</test-foo>', handler);
expect(start).toEqual({tag:'test-foo', attrs:{selected:'', value:''}});
expect(text).toEqual('abc');
});
});
// THESE TESTS ARE EXECUTED WITH COMPILED ANGULAR
it('should echo html', function() {
expectHTML('hello<b class="1\'23" align=\'""\'>world</b>.').
toBeOneOf('hello<b class="1\'23" align="""">world</b>.',
'hello<b align="""" class="1\'23">world</b>.');
});
it('should remove script', function() {
expectHTML('a<SCRIPT>evil< / scrIpt >c.').toEqual('a');
expectHTML('a<SCRIPT>evil</scrIpt>c.').toEqual('ac.');
});
it('should remove script that has newline characters', function() {
expectHTML('a<SCRIPT\n>\n\revil\n\r</scrIpt\n >c.').toEqual('ac.');
});
it('should remove DOCTYPE header', function() {
expectHTML('<!DOCTYPE html>').toEqual('');
expectHTML('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">').toEqual('');
expectHTML('a<!DOCTYPE html>c.').toEqual('ac.');
expectHTML('a<!DocTyPe html>c.').toEqual('ac.');
});
it('should escape non-start tags', function() {
expectHTML('a< SCRIPT >A< SCRIPT >evil< / scrIpt >B< / scrIpt >c.').
toBe('a< SCRIPT >A< SCRIPT >evil< / scrIpt >B< / scrIpt >c.');
});
it('should remove attrs', function() {
expectHTML('a<div style="abc">b</div>c').toEqual('a<div>b</div>c');
});
it('should remove style', function() {
expectHTML('a<STyle>evil</stYle>c.').toEqual('ac.');
});
it('should remove style that has newline characters', function() {
expectHTML('a<STyle \n>\n\revil\n\r</stYle\n>c.').toEqual('ac.');
});
it('should remove script and style', function() {
expectHTML('a<STyle>evil<script></script></stYle>c.').toEqual('ac.');
});
it('should remove double nested script', function() {
expectHTML('a<SCRIPT>ev<script>evil</sCript>il</scrIpt>c.').toEqual('ailc.');
});
it('should remove unknown names', function() {
expectHTML('a<xxx><B>b</B></xxx>c').toEqual('a<b>b</b>c');
});
it('should remove unsafe value', function() {
expectHTML('<a href="javascript:alert()">').toEqual('<a></a>');
});
it('should handle self closed elements', function() {
expectHTML('a<hr/>c').toEqual('a<hr>c');
});
it('should handle namespace', function() {
expectHTML('a<my:hr/><my:div>b</my:div>c').toEqual('abc');
});
it('should handle entities', function() {
var everything = '<div rel="!@#$%^&*()_+-={}[]:";\'<>?,./`~ ħ">' +
'!@#$%^&*()_+-={}[]:";\'<>?,./`~ ħ</div>';
expectHTML(everything).toEqual(everything);
});
it('should mangle improper html', function() {
// This text is encoded more than a real HTML parser would, but it should render the same.
expectHTML('< div rel="</div>" alt=abc dir=\'"\' >text< /div>').
toBe('< div rel="" alt=abc dir=\'"\' >text< /div>');
});
it('should mangle improper html2', function() {
// A proper HTML parser would clobber this more in most cases, but it looks reasonable.
expectHTML('< div rel="</div>" / >').
toBe('< div rel="" / >');
});
it('should ignore back slash as escape', function() {
expectHTML('<img alt="xxx\\" title="><script>....">').
toBeOneOf('<img alt="xxx\\" title="><script>....">',
'<img title="><script>...." alt="xxx\\">');
});
it('should ignore object attributes', function() {
expectHTML('<a constructor="hola">:)</a>').
toEqual('<a>:)</a>');
expectHTML('<constructor constructor="hola">:)</constructor>').
toEqual('');
});
it('should keep spaces as prefix/postfix', function() {
expectHTML(' a ').toEqual(' a ');
});
it('should allow multiline strings', function() {
expectHTML('\na\n').toEqual(' a ');
});
it('should accept tag delimiters such as "<" inside real tags (with nesting)', function() {
//this is an integrated version of the 'should accept tag delimiters such as "<" inside real tags' test
expectHTML('<p> 10 < <span>100</span> </p>')
.toEqual('<p> 10 < <span>100</span> </p>');
});
it('should accept non-string arguments', function() {
expectHTML(null).toBe('');
expectHTML(undefined).toBe('');
expectHTML(42).toBe('42');
expectHTML({}).toBe('[object Object]');
expectHTML([1, 2, 3]).toBe('1,2,3');
expectHTML(true).toBe('true');
expectHTML(false).toBe('false');
});
it('should strip svg elements if not enabled via provider', function() {
expectHTML('<svg width="400px" height="150px" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"></svg>')
.toEqual('');
});
if (/Chrome/.test(window.navigator.userAgent)) {
it('should prevent mXSS attacks', function() {
expectHTML('<a href=" javascript:alert(1)">CLICKME</a>').toBe('<a>CLICKME</a>');
});
}
it('should strip html comments', function() {
expectHTML('<!-- comment 1 --><p>text1<!-- comment 2 -->text2</p><!-- comment 3 -->')
.toEqual('<p>text1text2</p>');
});
describe('SVG support', function() {
beforeEach(module(function($sanitizeProvider) {
$sanitizeProvider.enableSvg(true);
}));
it('should accept SVG tags', function() {
expectHTML('<svg width="400px" height="150px" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"></svg>')
.toBeOneOf('<svg width="400px" height="150px" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"></circle></svg>',
'<svg xmlns="http://www.w3.org/2000/svg" height="150px" width="400px"><circle fill="red" stroke-width="3" stroke="black" r="40" cy="50" cx="50"></circle></svg>',
'<svg width="400px" height="150px" xmlns="http://www.w3.org/2000/svg"><circle fill="red" stroke="black" stroke-width="3" cx="50" cy="50" r="40"></circle></svg>');
});
it('should not ignore white-listed svg camelCased attributes', function() {
expectHTML('<svg preserveAspectRatio="true"></svg>')
.toBeOneOf('<svg preserveAspectRatio="true"></svg>',
'<svg preserveAspectRatio="true" xmlns="http://www.w3.org/2000/svg"></svg>');
});
it('should sanitize SVG xlink:href attribute values', function() {
expectHTML('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a xlink:href="javascript:alert()"></a></svg>')
.toBeOneOf('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a></a></svg>',
'<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><a></a></svg>',
'<svg xmlns="http://www.w3.org/2000/svg"><a xmlns:xlink="http://www.w3.org/1999/xlink"></a></svg>');
expectHTML('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a xlink:href="https://example.com"></a></svg>')
.toBeOneOf('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a xlink:href="https://example.com"></a></svg>',
'<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><a xlink:href="https://example.com"></a></svg>',
'<svg xmlns="http://www.w3.org/2000/svg"><a xlink:href="https://example.com" xmlns:xlink="http://www.w3.org/1999/xlink"></a></svg>',
'<svg xmlns="http://www.w3.org/2000/svg"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://example.com"></a></svg>');
});
it('should sanitize unknown namespaced SVG attributes', function() {
expectHTML('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a xlink:foo="javascript:alert()"></a></svg>')
.toBeOneOf('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a></a></svg>',
'<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><a></a></svg>',
'<svg xmlns="http://www.w3.org/2000/svg"><a></a></svg>');
expectHTML('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a xlink:bar="https://example.com"></a></svg>')
.toBeOneOf('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a></a></svg>',
'<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><a></a></svg>',
'<svg xmlns="http://www.w3.org/2000/svg"><a></a></svg>');
});
it('should not accept SVG animation tags', function() {
expectHTML('<svg xmlns:xlink="http://www.w3.org/1999/xlink"><a><text y="1em">Click me</text><animate attributeName="xlink:href" values="javascript:alert(1)"/></a></svg>')
.toBeOneOf('<svg xmlns:xlink="http://www.w3.org/1999/xlink"><a><text y="1em">Click me</text></a></svg>',
'<svg xmlns="http://www.w3.org/2000/svg"><a><text y="1em">Click me</text></a></svg>');
expectHTML('<svg><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="?"><circle r="400"></circle>' +
'<animate attributeName="xlink:href" begin="0" from="javascript:alert(1)" to="&" /></a></svg>')
.toBeOneOf('<svg><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="?"><circle r="400"></circle></a></svg>',
'<svg><a xlink:href="?" xmlns:xlink="http://www.w3.org/1999/xlink"><circle r="400"></circle></a></svg>',
'<svg xmlns="http://www.w3.org/2000/svg"><a xlink:href="?" xmlns:xlink="http://www.w3.org/1999/xlink"><circle r="400"></circle></a></svg>',
'<svg xmlns="http://www.w3.org/2000/svg"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="?"><circle r="400"></circle></a></svg>');
});
});
describe('htmlSanitizerWriter', function() {
/* global htmlSanitizeWriter: false */
if (angular.isUndefined(window.htmlSanitizeWriter)) return;
var writer, html, uriValidator;
beforeEach(function() {
html = '';
uriValidator = jasmine.createSpy('uriValidator');
writer = htmlSanitizeWriter({push:function(text) {html+=text;}}, uriValidator);
});
it('should write basic HTML', function() {
writer.chars('before');
writer.start('div', {rel:'123'}, false);
writer.chars('in');
writer.end('div');
writer.chars('after');
expect(html).toEqual('before<div rel="123">in</div>after');
});
it('should escape text nodes', function() {
writer.chars('a<div>&</div>c');
expect(html).toEqual('a<div>&</div>c');
});
it('should escape IE script', function() {
writer.chars('&<>{}');
expect(html).toEqual('&<>{}');
});
it('should escape attributes', function() {
writer.start('div', {rel:'!@#$%^&*()_+-={}[]:";\'<>?,./`~ \n\0\r\u0127'});
expect(html).toEqual('<div rel="!@#$%^&*()_+-={}[]:";\'<>?,./`~ � ħ">');
});
it('should ignore missformed elements', function() {
writer.start('d>i&v', {});
expect(html).toEqual('');
});
it('should ignore unknown attributes', function() {
writer.start('div', {unknown:""});
expect(html).toEqual('<div>');
});
it('should handle surrogate pair', function() {
writer.chars(String.fromCharCode(55357, 56374));
expect(html).toEqual('🐶');
});
describe('explicitly disallow', function() {
it('should not allow attributes', function() {
writer.start('div', {id:'a', name:'a', style:'a'});
expect(html).toEqual('<div>');
});
it('should not allow tags', function() {
function tag(name) {
writer.start(name, {});
writer.end(name);
}
tag('frameset');
tag('frame');
tag('form');
tag('param');
tag('object');
tag('embed');
tag('textarea');
tag('input');
tag('button');
tag('option');
tag('select');
tag('script');
tag('style');
tag('link');
tag('base');
tag('basefont');
expect(html).toEqual('');
});
});
describe('uri validation', function() {
it('should call the uri validator', function() {
writer.start('a', {href:'someUrl'}, false);
expect(uriValidator).toHaveBeenCalledWith('someUrl', false);
uriValidator.reset();
writer.start('img', {src:'someImgUrl'}, false);
expect(uriValidator).toHaveBeenCalledWith('someImgUrl', true);
uriValidator.reset();
writer.start('someTag', {src:'someNonUrl'}, false);
expect(uriValidator).not.toHaveBeenCalled();
});
it('should drop non valid uri attributes', function() {
uriValidator.andReturn(false);
writer.start('a', {href:'someUrl'}, false);
expect(html).toEqual('<a>');
html = '';
uriValidator.andReturn(true);
writer.start('a', {href:'someUrl'}, false);
expect(html).toEqual('<a href="someUrl">');
});
});
});
describe('uri checking', function() {
beforeEach(function() {
this.addMatchers({
toBeValidUrl: function() {
var sanitize;
inject(function($sanitize) {
sanitize = $sanitize;
});
var input = '<a href="' + this.actual + '"></a>';
return sanitize(input) === input;
},
toBeValidImageSrc: function() {
var sanitize;
inject(function($sanitize) {
sanitize = $sanitize;
});
var input = '<img src="' + this.actual + '"/>';
return sanitize(input) === input;
}
});
});
it('should use $$sanitizeUri for links', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function() {
$$sanitizeUri.andReturn('someUri');
expectHTML('<a href="someUri"></a>').toEqual('<a href="someUri"></a>');
expect($$sanitizeUri).toHaveBeenCalledWith('someUri', false);
$$sanitizeUri.andReturn('unsafe:someUri');
expectHTML('<a href="someUri"></a>').toEqual('<a></a>');
});
});
it('should use $$sanitizeUri for links', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function() {
$$sanitizeUri.andReturn('someUri');
expectHTML('<img src="someUri"/>').toEqual('<img src="someUri">');
expect($$sanitizeUri).toHaveBeenCalledWith('someUri', true);
$$sanitizeUri.andReturn('unsafe:someUri');
expectHTML('<img src="someUri"/>').toEqual('<img>');
});
});
it('should be URI', function() {
expect('').toBeValidUrl();
expect('http://abc').toBeValidUrl();
expect('HTTP://abc').toBeValidUrl();
expect('https://abc').toBeValidUrl();
expect('HTTPS://abc').toBeValidUrl();
expect('ftp://abc').toBeValidUrl();
expect('FTP://abc').toBeValidUrl();
expect('mailto:me@example.com').toBeValidUrl();
expect('MAILTO:me@example.com').toBeValidUrl();
expect('tel:123-123-1234').toBeValidUrl();
expect('TEL:123-123-1234').toBeValidUrl();
expect('#anchor').toBeValidUrl();
expect('/page1.md').toBeValidUrl();
});
it('should not be URI', function() {
/* jshint scripturl: true */
expect('javascript:alert').not.toBeValidUrl();
});
describe('javascript URLs', function() {
it('should ignore javascript:', function() {
/* jshint scripturl: true */
expect('JavaScript:abc').not.toBeValidUrl();
expect(' \n Java\n Script:abc').not.toBeValidUrl();
expect('http://JavaScript/my.js').toBeValidUrl();
});
it('should ignore dec encoded javascript:', function() {
expect('javascript:').not.toBeValidUrl();
expect('javascript:').not.toBeValidUrl();
expect('j avascript:').not.toBeValidUrl();
});
it('should ignore decimal with leading 0 encodede javascript:', function() {
expect('javascript:').not.toBeValidUrl();
expect('j avascript:').not.toBeValidUrl();
expect('j avascript:').not.toBeValidUrl();
});
it('should ignore hex encoded javascript:', function() {
expect('javascript:').not.toBeValidUrl();
expect('javascript:').not.toBeValidUrl();
expect('j avascript:').not.toBeValidUrl();
});
it('should ignore hex encoded whitespace javascript:', function() {
expect('jav	ascript:alert();').not.toBeValidUrl();
expect('jav
ascript:alert();').not.toBeValidUrl();
expect('jav
 ascript:alert();').not.toBeValidUrl();
expect('jav\u0000ascript:alert();').not.toBeValidUrl();
expect('java\u0000\u0000script:alert();').not.toBeValidUrl();
expect('  java\u0000\u0000script:alert();').not.toBeValidUrl();
});
});
});
describe('sanitizeText', function() {
/* global sanitizeText: false */
it('should escape text', function() {
expect(sanitizeText('a<div>&</div>c')).toEqual('a<div>&</div>c');
});
});
});
describe('decodeEntities', function() {
var handler, text;
beforeEach(function() {
text = '';
handler = {
start: function() {},
chars: function(text_) {
text = text_;
},
end: function() {},
comment: function() {}
};
module('ngSanitize');
});
it('should unescape text', function() {
htmlParser('a<div>&</div>c', handler);
expect(text).toEqual('a<div>&</div>c');
});
it('should preserve whitespace', function() {
htmlParser(' a&b ', handler);
expect(text).toEqual(' a&b ');
});
});
|
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="node" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
/**
* 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];
};
}
module.exports = property;
|
tinyMCE.addI18n('ja.paste_dlg',{"word_title":"Ctrl V(\u30ad\u30fc\u30dc\u30fc\u30c9)\u3092\u4f7f\u7528\u3057\u3066\u3001\u30c6\u30ad\u30b9\u30c8\u3092\u30a6\u30a3\u30f3\u30c9\u30a6\u306b\u8cbc\u308a\u4ed8\u3051\u3066\u304f\u3060\u3055\u3044\u3002","text_linebreaks":"\u6539\u884c\u3092\u4fdd\u6301","text_title":"Ctrl V(\u30ad\u30fc\u30dc\u30fc\u30c9)\u3092\u4f7f\u7528\u3057\u3066\u3001\u30c6\u30ad\u30b9\u30c8\u3092\u30a6\u30a3\u30f3\u30c9\u30a6\u306b\u8cbc\u308a\u4ed8\u3051\u3066\u304f\u3060\u3055\u3044\u3002"}); |
var SPARTAN_HOST = "localhost";
var SPARTAN_PORT = "80";
/*
* Semi-short callback script for SPARTAN.
*
* There may well be bugs. You have been warned. (Especially if you set
* useRawForm to false, as iframes are buggy, and form submission in iframes is
* really buggy.)
*
* Example:
* var spartan = new spartanHandler("My amazing test suite");
* spartan.addTest("This test passes!", true);
* spartan.addTest("This test fails!", false, "Test message about fail, timeout, etc.");
* spartan.send();
*
* Usage:
* - The spartanHandler constructor creates a new test suite, and takes one
* string as an argument, the name of the test suite.
* - addTest adds a test to the test suite, whose first argument is the test
* case name (this must be unique within the test suite), a string, and
* whose second argument is a boolean where true is a pass and false is a
* failure.
* - send sends the results to SPARTAN.
*
* NB: The combined length of the test suite name and any test case name plus
* two (as they are concatenated with ": ") must not be greater than 255.
*
* NB: Neither the test suite name nor any test case name can contain a tab
* character.
*/
var spartanHandler = function(name) {
if (name) {
var testSuiteName = String(name);
if (testSuiteName.indexOf("\t") !== -1) {
throw new Error("spartanHandler's name parameter must not contain any tabs");
}
} else {
var testSuiteName = "";
}
var tests = [],
sendOnLoad = false,
sent = false,
useRawForm = false,
useXHR = true;
this.addTest = function (name, passed, message) {
name = String(name);
message = message ? String(message) : '';
if (name.indexOf("\t") !== -1) {
throw new Error("spartanHandler.addTest's name parameter must not contain any tabs");
}
if (typeof passed !== "boolean") {
throw new TypeError("spartanHandler.addTest's passed parameter must be a boolean");
}
if (message.indexOf("\t") !== -1) {
throw new Error("spartanHandler.addTest's message parameter must not contain any tabs");
}
tests.push([name, passed, message]);
};
this.send = function() {
if (sent) {
throw new Error("spartanHandler has already sent results");
}
if (document.body || document.createElement("iframe").contentDocument !== null || useRawForm ||
useXHR) {
realSend();
}
else {
sendOnLoad = true;
}
};
var formatTestName = function(test_name) {
var name = (testSuiteName ? testSuiteName + ": " : "") + test_name;
if (name.length > 255) {
throw new Error("Test case identifier is longer than 255 characters: " + name);
}
return name;
};
var formatValue = function(test_name, pass, test_message) {
var name = formatTestName(test_name);
if (test_message != '') {
test_message = "\t# " + test_message;
}
return name + "\t" + (pass ? "PASSED" : "FAILED") + test_message;
};
var createFormRaw = function() {
var form = document.createElement("form");
if (typeof g_resultHome !== "undefined")
{
form.action = g_resultHome;
}
else
{
var host = "localhost";
var port = "80";
if (typeof SPARTAN_HOST != "undefined")
host = SPARTAN_HOST;
if (typeof SPARTAN_PORT != "undefined")
port = SPARTAN_PORT;
form.action = "http://" + host + ":" + port + "/";
}
form.method = "POST";
return form;
};
var createFormIframe = function() {
var iframe = document.createElement("iframe");
//iframe.style.display = "none";
document.body.appendChild(iframe);
var iframeDoc = iframe.contentDocument;
var form = iframeDoc.forms[0];
if (typeof g_resultHome !== "undefined")
{
form.action = g_resultHome;
}
else
{
var host = "localhost";
var port = "80";
if (typeof SPARTAN_HOST != "undefined")
host = SPARTAN_HOST;
if (typeof SPARTAN_PORT != "undefined")
port = SPARTAN_PORT;
form.action = "http://" + host + ":" + port + "/";
}
return form;
};
var populateForm = function(form) {
tests.forEach(function(test) {
form.appendChild(form.ownerDocument.createElement("input"));
form.lastChild.name = "jstests[]";
form.lastChild.value = formatValue(test[0], test[1], test[2]);
});
return form;
};
var sendForm = function(create_func) {
populateForm(create_func()).submit();
};
var formEncode = function(data) {
var encoded = data.reduce(function(prev, cur) {
return prev + (prev === "" ? "" : "&") + encodeURIComponent(cur[0]) + "=" + encodeURIComponent(cur[1]);
}, "");
var space_replaced = encoded.replace("%20", "+");
return encoded;
};
var sendXHR = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === 4 && document.body) {
var pre = document.createElement("pre");
pre.textContent = "Response from localhost:\n" + this.responseText;
document.body.appendChild(pre);
}
};
var form_name_values = tests.map(function(x) {
return ["jstests[]", formatValue(x[0], x[1])];
});
var data = formEncode(form_name_values);
if (typeof g_resultHome !== "undefined")
{
xhr.open("POST", g_resultHome);
}
else
{
var host = "localhost";
var port = "80";
if (typeof SPARTAN_HOST != "undefined")
host = SPARTAN_HOST;
if (typeof SPARTAN_PORT != "undefined")
port = SPARTAN_PORT;
xhr.open("POST", "http://" + host + ":" + port + "/");
}
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xhr.send(data);
};
var realSend = function() {
if (useXHR) {
sendXHR();
} else if (useRawForm) {
sendForm(createFormRaw);
} else {
sendForm(createFormIframe);
}
};
document.addEventListener("DOMContentLoaded", function() {
if (sendOnLoad) {
realSend();
sendOnLoad = false;
}
}, false);
};
function register_spartan_handler(name) {
//XXX should really escape tab characters here
var spartan_handler = new spartanHandler("");
var register_result = function(test) {
var name = test.name;
var passed = test.status === test.PASS;
var message = test.message;
spartan_handler.addTest(name, passed, message);
};
var send_results = function(tests) {
spartan_handler.send();
};
add_result_callback(register_result);
add_completion_callback(send_results);
}
if (window.opera) {
register_spartan_handler();
}
|
// Update the `ghost-*` clients so that they definitely have a proper secret
var models = require('../../../../models'),
_ = require('lodash'),
Promise = require('bluebird'),
crypto = require('crypto'),
message = 'Updating client secret';
module.exports = function updateGhostClientsSecrets(options, logger) {
return models.Clients.forge().query('where', 'secret', '=', 'not_available').fetch(options).then(function (results) {
if (results.models.length === 0) {
logger.warn(message);
return;
}
return Promise.map(results.models, function mapper(client) {
logger.info(message + ' (' + client.slug + ')');
client.secret = crypto.randomBytes(6).toString('hex');
return models.Client.edit(
_.extend({}, client, {secret: crypto.randomBytes(6).toString('hex')}),
_.extend({}, options, {id: client.id})
);
});
});
};
|
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Barn=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var _ = require('underscore');
var Barn = require('./lib/barn');
function API(namespace, storage){
if(!storage){
storage = namespace;
namespace = 'BARN';
}
this.barn = new Barn(namespace, storage);
}
_.extend(API.prototype, {
get: function(key){
return this.barn.execCmd('GET', key);
},
set: function(key, val){
return this.barn.execCmd('SET', key, val);
},
del: function(key){
return this.barn.execCmd('DEL', key);
},
lpop: function(key){
return this.barn.execCmd('LPOP', key);
},
lpush: function(key, val){
return this.barn.execCmd('LPUSH', key, val);
},
rpop: function(key){
return this.barn.execCmd('RPOP', key);
},
rpush: function(key, val){
return this.barn.execCmd('RPUSH', key, val);
},
sadd: function(key, val){
return this.barn.execCmd('SADD', key, val);
},
smembers: function(key){
return this.barn.execCmd('SMEMBERS', key);
},
sismember: function(key, val){
return this.barn.execCmd('SISMEMBER', key, val);
},
srem: function(key, val){
return this.barn.execCmd('SREM', key, val);
},
condense: function(){
return this.barn.condense();
},
});
module.exports = API;
},{"./lib/barn":2,"underscore":4}],2:[function(require,module,exports){
"use strict";
var NSStorage = require('nsstorage');
var _ = require('underscore');
function Barn(namespace, storage, opts){
var _this = this;
this._storage = NSStorage.createNamespace(namespace, storage);
this._keys = {};
this._idx = 0;
this._keySet;
this._opts = {
maxKeys: 1000
};
_.extend(this._opts, opts);
this._cmds = {
DEL: {
fn: function(key){
var count = 0;
_this._keys[key] && count++;
delete _this._keys[key];
return count;
},
mutating: true
},
GET: {
fn: function(key){
return _this._getValExpectingType(key, 'string');
},
mutating: false
},
SET: {
fn: function(key, val){
_this._keys[key] = {
val: val,
type: 'string'
};
},
mutating: true
},
LPUSH: {
fn: function(key, val){
var list = _this._getOrCreateList(key);
list.unshift(val);
return list.length;
},
mutating: true
},
LPOP: {
fn: function(key){
var list = _this._getValExpectingType(key, 'list');
var ret = null;
if(list && list.length){
ret = list.shift();
}
return ret;
},
mutating: false
},
RPUSH: {
fn: function(key, val){
var list = _this._getOrCreateList(key);
list.push(val);
return list.length;
},
mutating: true
},
RPOP: {
fn: function(key){
var list = _this._getValExpectingType(key, 'list');
var ret = null;
if(list && list.length){
ret = list.pop();
}
return ret;
},
mutating: false
},
SADD: {
fn: function(key, val){
var numAdded = 0;
var set = _this._getOrCreateSet(key);
if(!(val in set)){
numAdded++;
set[val] = true;
}
return numAdded;
},
mutating: true
},
SMEMBERS: {
fn: function(key){
var set = _this._getValExpectingType(key, 'set');
var ret = null;
if(set){
ret = Object.keys(set);
}
return ret;
},
mutating: false
},
SISMEMBER: {
fn: function(key, val){
var set = _this._getValExpectingType(key, 'set');
return !!(set && set[val]);
},
mutating: false
},
SREM: {
fn: function(key, val){
var numRemoved = 0;
var set = _this._getOrCreateSet(key);
if(val in set){
numRemoved++;
delete set[val];
}
return numRemoved;
},
mutating: true
},
_LOAD: {
fn: function(data){
_this._keys = data;
},
mutating: true
}
};
this._load();
}
Barn.prototype._getVal = function(key){
return this._keys[key];
};
Barn.prototype._getValExpectingType = function(key, type){
var val = this._getVal(key);
if(val){
if(val.type !== type)
throw new TypeError('Expected key '+key+' to be of type '+type);
return val.val;
}else{
return null;
}
};
Barn.prototype._getOrCreateList = function(key){
var val = this._getValExpectingType(key, 'list');
if(!val){
val = [];
this._keys[key] = {
type: 'list',
val: val
};
}
return val;
};
Barn.prototype._getOrCreateSet = function(key){
var val = this._getValExpectingType(key, 'set');
if(!val){
val = {};
this._keys[key] = {
type: 'set',
val: val
};
}
return val;
};
Barn.prototype._loadKeySet = function(){
this._keySet = this._storage.getItem('KEYSET');
if(!this._keySet) this._setKeySet(0);
};
Barn.prototype._setKeySet = function(val){
this._storage.setItem('KEYSET', val);
this._keySet = val;
};
Barn.prototype._isGarbage = function(key){
return key.indexOf(this._keySet) !== 0 && key !== 'KEYSET';
};
Barn.prototype._buildKey = function(ks, i){
return ks + '_' + i;
};
Barn.prototype._load = function(){
this._loadKeySet();
this._keys = {};
this._idx = 0;
var op;
do{
var key = this._buildKey(this._keySet, this._idx);
op = this._storage.getItem(key);
if(op){
this._idx++;
this._exec(JSON.parse(op));
}
}while(op);
};
Barn.prototype._exec = function(op){
var cmd = this._cmds[op.cmd].fn;
if(!cmd) throw new Error('Invalid operation');
return cmd.apply(null, op.args);
};
Barn.prototype._save = function(ks, i, op){
var key = this._buildKey(ks, i);
var val = JSON.stringify(op);
this._storage.setItem(key, val);
};
Barn.prototype._isMutating = function(cmd){
return this._cmds[cmd].mutating;
};
// High level API
Barn.prototype.execCmd = function(){
var args = Array.prototype.slice.call(arguments);
var cmd = args.shift();
var op = {
cmd: cmd,
args: args
};
var ret = this._exec(op);
if(this._isMutating(cmd)){
this._save(this._keySet, this._idx, op);
this._idx++;
if(this._idx>this._opts.maxKeys){
this.condense();
}
}
return ret;
};
Barn.prototype._gc = function(){
var _this = this;
var garbage = [];
var key;
for(var i=0; i<this._storage.length; i++){
key = this._storage.key(i);
if(this._isGarbage(key)){
garbage.push(key);
}
}
garbage.forEach(function(it){
_this._storage.removeItem(it);
});
};
Barn.prototype.condense = function(){
var op = {
cmd: '_LOAD',
args: [this._keys]
};
this._save(+this._keySet+1, 0, op);
this._setKeySet(+this._keySet+1);
this._idx = 1;
this._gc();
};
module.exports = Barn;
},{"nsstorage":3,"underscore":4}],3:[function(require,module,exports){
'use strict';
// package module for different environments
function packageModule(global, name, api) {
if (global.define && global.define.amd) {
define([], api);
} else if (typeof exports !== "undefined") {
module.exports = api;
} else {
global[name] = api;
}
}
// SNStorage constructor
function NSStorage(namespace, storage){
this._ns = namespace;
this._nsRegex = new RegExp(''+namespace+'_');
this._storage = storage;
this._keyCache = null;
this.length = this._keys().length;
}
// Generate an namespaced key
NSStorage.prototype._genKey = function(key){
return this._ns + '_' + key;
};
// Check if key is in namespace
NSStorage.prototype._inNamespace = function(key){
return key && (key.indexOf(this._ns) === 0);
};
// Check if key exists
NSStorage.prototype._exists = function(key){
return !!this.getItem(key);
};
// Get all keys in this namespace
NSStorage.prototype._keys = function(){
if(this._keyCache){
return this._keyCache;
}else{
var keys = [];
for(var i=0, len=this._storage.length; i<len; i++) {
var key = this._storage.key(i);
if(this._inNamespace(key)) keys.push(key.replace(this._nsRegex, ''));
}
this._keyCache = keys;
return keys;
}
};
NSStorage.prototype._invalidateCache = function(){
this._keyCache = null;
};
//
// STORAGE API
// Spec here: http://dev.w3.org/html5/webstorage/#storage-0
//
// Get the key of index idx
NSStorage.prototype.key = function(idx){
return this._keys()[idx] || null;
};
// Get item for key
NSStorage.prototype.getItem = function(key){
return this._storage.getItem(this._genKey(key));
};
// Set value of key to val
NSStorage.prototype.setItem = function(key, val){
if(!this._exists(key)){
this.length++;
this._invalidateCache();
}
this._storage.setItem(this._genKey(key), val);
};
// Remove item from storage
NSStorage.prototype.removeItem = function(key){
if(this._exists(key)){
this.length--;
this._invalidateCache();
}
this._storage.removeItem(this._genKey(key));
};
// Clear storage
NSStorage.prototype.clear = function(){
var _this = this;
this._keys().forEach(function(key){
_this.removeItem(key);
});
this._invalidateCache();
};
//
// API
//
var API = {
createNamespace: function(namespace, storage){
return new NSStorage(namespace, storage);
}
};
// Module packaging
packageModule(this, 'NSStorage', API);
},{}],4:[function(require,module,exports){
// Underscore.js 1.7.0
// http://underscorejs.org
// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.7.0';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var createCallback = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
_.iteratee = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return createCallback(value, context, argCount);
if (_.isObject(value)) return _.matches(value);
return _.property(value);
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
if (obj == null) return obj;
iteratee = createCallback(iteratee, context);
var i, length = obj.length;
if (length === +length) {
for (i = 0; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
if (obj == null) return [];
iteratee = _.iteratee(iteratee, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
results = Array(length),
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index = 0, currentKey;
if (arguments.length < 3) {
if (!length) throw new TypeError(reduceError);
memo = obj[keys ? keys[index++] : index++];
}
for (; index < length; index++) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== + obj.length && _.keys(obj),
index = (keys || obj).length,
currentKey;
if (arguments.length < 3) {
if (!index) throw new TypeError(reduceError);
memo = obj[keys ? keys[--index] : --index];
}
while (index--) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var result;
predicate = _.iteratee(predicate, context);
_.some(obj, function(value, index, list) {
if (predicate(value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
if (obj == null) return results;
predicate = _.iteratee(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(_.iteratee(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
if (obj == null) return true;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
if (obj == null) return false;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// 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 (obj.length !== +obj.length) obj = _.values(obj);
return _.indexOf(obj, target) >= 0;
};
// 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, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matches(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = obj && obj.length === +obj.length ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (obj.length !== +obj.length) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(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;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
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 = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = 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 = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// 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, iteratee, context) {
iteratee = _.iteratee(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = array.length;
while (low < high) {
var mid = low + high >>> 1;
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.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;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = _.iteratee(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// 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;
if (n == null || guard) return array[0];
if (n < 0) return [];
return slice.call(array, 0, n);
};
// 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, Math.max(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 array[array.length - 1];
return slice.call(array, Math.max(array.length - n, 0));
};
// 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, strict, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
for (var i = 0, length = input.length; i < length; i++) {
var value = input[i];
if (!_.isArray(value) && !_.isArguments(value)) {
if (!strict) output.push(value);
} else if (shallow) {
push.apply(output, value);
} else {
flatten(value, shallow, strict, output);
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false, []);
};
// 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, iteratee, context) {
if (array == null) return [];
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = _.iteratee(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = array.length; i < length; i++) {
var value = array[i];
if (isSorted) {
if (!i || seen !== value) result.push(value);
seen = value;
} else if (iteratee) {
var computed = iteratee(value, i, array);
if (_.indexOf(seen, computed) < 0) {
seen.push(computed);
result.push(value);
}
} else if (_.indexOf(result, value) < 0) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true, []));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
if (array == null) return [];
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = array.length; i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// 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 = flatten(slice.call(arguments, 1), true, true, []);
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(array) {
if (array == null) return [];
var length = _.max(arguments, 'length').length;
var results = Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, 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, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// 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, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var idx = array.length;
if (typeof from == 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
while (--idx >= 0) if (array[idx] === item) return idx;
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 = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var Ctor = function(){};
// 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) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
args = slice.call(arguments, 2);
bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
Ctor.prototype = func.prototype;
var self = new Ctor;
Ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (_.isObject(result)) return result;
return self;
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
return function() {
var position = 0;
var args = boundArgs.slice();
for (var i = 0, length = args.length; i < length; i++) {
if (args[i] === _) args[i] = arguments[position++];
}
while (position < arguments.length) args.push(arguments[position++]);
return func.apply(this, args);
};
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = hasher ? hasher.apply(this, arguments) : key;
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// 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. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
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, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// 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 _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// 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 args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed before being called N times.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
} else {
func = null;
}
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
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) {
if (!_.isObject(obj)) return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (hasOwnProperty.call(source, prop)) {
obj[prop] = source[prop];
}
}
}
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj, iteratee, context) {
var result = {}, key;
if (obj == null) return result;
if (_.isFunction(iteratee)) {
iteratee = createCallback(iteratee, context);
for (key in obj) {
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
} else {
var keys = concat.apply([], slice.call(arguments, 1));
obj = new Object(obj);
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (key in obj) result[key] = obj[key];
}
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
if (!_.isObject(obj)) return obj;
for (var i = 1, length = arguments.length; i < length; i++) {
var source = arguments[i];
for (var prop in source) {
if (obj[prop] === void 0) 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, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +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;
}
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;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (
aCtor !== bCtor &&
// Handle Object.create(x) cases
'constructor' in a && 'constructor' in b &&
!(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size, result;
// 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 {
// Deep compare objects.
var keys = _.keys(a), key;
size = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
result = _.keys(b).length === size;
if (result) {
while (size--) {
// Deep compare each member
key = keys[size];
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
}
// 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) || _.isArguments(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) {
var type = typeof obj;
return type === 'function' || type === '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 _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around an IE 11 bug.
if (typeof /./ !== 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// 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 obj != null && 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 iteratees.
_.identity = function(value) {
return value;
};
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = function(key) {
return function(obj) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
var pairs = _.pairs(attrs), length = pairs.length;
return function(obj) {
if (obj == null) return !length;
obj = new Object(obj);
for (var i = 0; i < length; i++) {
var pair = pairs[i], key = pair[0];
if (pair[1] !== obj[key] || !(key in obj)) return false;
}
return true;
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = createCallback(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(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));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? object[property]() : value;
};
// 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',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = 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, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
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 {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// 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 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));
};
});
};
// 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));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
},{}]},{},[1])(1)
}); |
YUI.add('profiler', function (Y, NAME) {
/**
* The YUI JavaScript profiler.
* @module profiler
*/
//-------------------------------------------------------------------------
// Private Variables and Functions
//-------------------------------------------------------------------------
var container = {}, //Container object on which to put the original unprofiled methods.
report = {}, //Profiling information for functions
stopwatches = {}, //Additional stopwatch information
WATCH_STARTED = 0,
WATCH_STOPPED = 1,
WATCH_PAUSED = 2,
//shortcuts
L = Y.Lang;
/* (intentionally not documented)
* Creates a report object with the given name.
* @param {String} name The name to store for the report object.
* @return {Void}
* @method createReport
* @private
*/
function createReport(name){
report[name] = {
calls: 0,
max: 0,
min: 0,
avg: 0,
points: []
};
return report[name];
}
/* (intentionally not documented)
* Called when a method ends execution. Marks the start and end time of the
* method so it can calculate how long the function took to execute. Also
* updates min/max/avg calculations for the function.
* @param {String} name The name of the function to mark as stopped.
* @param {int} duration The number of milliseconds it took the function to
* execute.
* @return {Void}
* @method saveDataPoint
* @private
* @static
*/
function saveDataPoint(name, duration){
//get the function data
var functionData /*:Object*/ = report[name];
//just in case clear() was called
if (!functionData){
functionData = createReport(name);
}
//increment the calls
functionData.calls++;
functionData.points.push(duration);
//if it's already been called at least once, do more complex calculations
if (functionData.calls > 1) {
functionData.avg = ((functionData.avg*(functionData.calls-1))+duration)/functionData.calls;
functionData.min = Math.min(functionData.min, duration);
functionData.max = Math.max(functionData.max, duration);
} else {
functionData.avg = duration;
functionData.min = duration;
functionData.max = duration;
}
}
//-------------------------------------------------------------------------
// Public Interface
//-------------------------------------------------------------------------
/**
* Profiles functions in JavaScript.
* @class Profiler
* @static
*/
Y.Profiler = {
//-------------------------------------------------------------------------
// Utility Methods
//-------------------------------------------------------------------------
/**
* Removes all report data from the profiler.
* @param {String} name (Optional) The name of the report to clear. If
* omitted, then all report data is cleared.
* @return {Void}
* @method clear
* @static
*/
clear: function(name){
if (L.isString(name)){
delete report[name];
delete stopwatches[name];
} else {
report = {};
stopwatches = {};
}
},
/**
* Returns the uninstrumented version of a function/object.
* @param {String} name The name of the function/object to retrieve.
* @return {Function|Object} The uninstrumented version of a function/object.
* @method getOriginal
* @static
*/
getOriginal: function(name){
return container[name];
},
/**
* Instruments a method to have profiling calls.
* @param {String} name The name of the report for the function.
* @param {Function} method The function to instrument.
* @return {Function} An instrumented version of the function.
* @method instrument
* @static
*/
instrument: function(name, method){
//create instrumented version of function
var newMethod = function () {
var start = new Date(),
retval = method.apply(this, arguments),
stop = new Date();
saveDataPoint(name, stop-start);
return retval;
};
//copy the function properties over
Y.mix(newMethod, method);
//assign prototype and flag as being profiled
newMethod.__yuiProfiled = true;
newMethod.prototype = method.prototype;
//store original method
container[name] = method;
container[name].__yuiFuncName = name;
//create the report
createReport(name);
//return the new method
return newMethod;
},
//-------------------------------------------------------------------------
// Stopwatch Methods
//-------------------------------------------------------------------------
/**
* Pauses profiling information for a given name.
* @param {String} name The name of the data point.
* @return {Void}
* @method pause
* @static
*/
pause: function(name){
var now = new Date(),
stopwatch = stopwatches[name];
if (stopwatch && stopwatch.state == WATCH_STARTED){
stopwatch.total += (now - stopwatch.start);
stopwatch.start = 0;
stopwatch.state = WATCH_PAUSED;
}
},
/**
* Start profiling information for a given name. The name cannot be the name
* of a registered function or object. This is used to start timing for a
* particular block of code rather than instrumenting the entire function.
* @param {String} name The name of the data point.
* @return {Void}
* @method start
* @static
*/
start: function(name){
if(container[name]){
throw new Error("Cannot use '" + name + "' for profiling through start(), name is already in use.");
} else {
//create report if necessary
if (!report[name]){
createReport(name);
}
//create stopwatch object if necessary
if (!stopwatches[name]){
stopwatches[name] = {
state: WATCH_STOPPED,
start: 0,
total: 0
};
}
if (stopwatches[name].state == WATCH_STOPPED){
stopwatches[name].state = WATCH_STARTED;
stopwatches[name].start = new Date();
}
}
},
/**
* Stops profiling information for a given name.
* @param {String} name The name of the data point.
* @return {Void}
* @method stop
* @static
*/
stop: function(name){
var now = new Date(),
stopwatch = stopwatches[name];
if (stopwatch){
if (stopwatch.state == WATCH_STARTED){
saveDataPoint(name, stopwatch.total + (now - stopwatch.start));
} else if (stopwatch.state == WATCH_PAUSED){
saveDataPoint(name, stopwatch.total);
}
//reset stopwatch information
stopwatch.start = 0;
stopwatch.total = 0;
stopwatch.state = WATCH_STOPPED;
}
},
//-------------------------------------------------------------------------
// Reporting Methods
//-------------------------------------------------------------------------
/**
* Returns the average amount of time (in milliseconds) that the function
* with the given name takes to execute.
* @param {String} name The name of the function whose data should be returned.
* If an object type method, it should be 'constructor.prototype.methodName';
* a normal object method would just be 'object.methodName'.
* @return {float} The average time it takes the function to execute.
* @method getAverage
* @static
*/
getAverage : function (name /*:String*/) /*:float*/ {
return report[name].avg;
},
/**
* Returns the number of times that the given function has been called.
* @param {String} name The name of the function whose data should be returned.
* @return {int} The number of times the function was called.
* @method getCallCount
* @static
*/
getCallCount : function (name /*:String*/) /*:int*/ {
return report[name].calls;
},
/**
* Returns the maximum amount of time (in milliseconds) that the function
* with the given name takes to execute.
* @param {String} name The name of the function whose data should be returned.
* If an object type method, it should be 'constructor.prototype.methodName';
* a normal object method would just be 'object.methodName'.
* @return {float} The maximum time it takes the function to execute.
* @method getMax
* @static
*/
getMax : function (name /*:String*/) /*:int*/ {
return report[name].max;
},
/**
* Returns the minimum amount of time (in milliseconds) that the function
* with the given name takes to execute.
* @param {String} name The name of the function whose data should be returned.
* If an object type method, it should be 'constructor.prototype.methodName';
* a normal object method would just be 'object.methodName'.
* @return {float} The minimum time it takes the function to execute.
* @method getMin
* @static
*/
getMin : function (name /*:String*/) /*:int*/ {
return report[name].min;
},
/**
* Returns an object containing profiling data for a single function.
* The object has an entry for min, max, avg, calls, and points).
* @return {Object} An object containing profile data for a given function.
* @method getFunctionReport
* @static
* @deprecated Use getReport() instead.
*/
getFunctionReport : function (name /*:String*/) /*:Object*/ {
return report[name];
},
/**
* Returns an object containing profiling data for a single function.
* The object has an entry for min, max, avg, calls, and points).
* @return {Object} An object containing profile data for a given function.
* @method getReport
* @static
*/
getReport : function (name /*:String*/) /*:Object*/ {
return report[name];
},
/**
* Returns an object containing profiling data for all of the functions
* that were profiled. The object has an entry for each function and
* returns all information (min, max, average, calls, etc.) for each
* function.
* @return {Object} An object containing all profile data.
* @method getFullReport
* @static
*/
getFullReport : function (filter /*:Function*/) /*:Object*/ {
filter = filter || function(){return true;};
if (L.isFunction(filter)) {
var fullReport = {};
for (var name in report){
if (filter(report[name])){
fullReport[name] = report[name];
}
}
return fullReport;
}
},
//-------------------------------------------------------------------------
// Profiling Methods
//-------------------------------------------------------------------------
/**
* Sets up a constructor for profiling, including all properties and methods on the prototype.
* @param {string} name The fully-qualified name of the function including namespace information.
* @param {Object} owner (Optional) The object that owns the function (namespace or containing object).
* @return {Void}
* @method registerConstructor
* @static
*/
registerConstructor : function (name /*:String*/, owner /*:Object*/) /*:Void*/ {
this.registerFunction(name, owner, true);
},
/**
* Sets up a function for profiling. It essentially overwrites the function with one
* that has instrumentation data. This method also creates an entry for the function
* in the profile report. The original function is stored on the container object.
* @param {String} name The full name of the function including namespacing. This
* is the name of the function that is stored in the report.
* @param {Object} owner (Optional) The object that owns the function. If the function
* isn't global then this argument is required. This could be the namespace that
* the function belongs to or the object on which it's
* a method.
* @param {Boolean} registerPrototype (Optional) Indicates that the prototype should
* also be instrumented. Setting to true has the same effect as calling
* registerConstructor().
* @return {Void}
* @method registerFunction
* @static
*/
registerFunction : function(name /*:String*/, owner /*:Object*/, registerPrototype /*:Boolean*/) /*:Void*/{
//figure out the function name without namespacing
var funcName = (name.indexOf(".") > -1 ?
name.substring(name.lastIndexOf(".")+1) : name),
method,
prototype;
//if owner isn't an object, try to find it from the name
if (!L.isObject(owner)){
owner = eval(name.substring(0, name.lastIndexOf(".")));
}
//get the method and prototype
method = owner[funcName];
prototype = method.prototype;
//see if the method has already been registered
if (L.isFunction(method) && !method.__yuiProfiled){
//replace the function with the profiling one
owner[funcName] = this.instrument(name, method);
/*
* Store original function information. We store the actual
* function as well as the owner and the name used to identify
* the function so it can be restored later.
*/
container[name].__yuiOwner = owner;
container[name].__yuiFuncName = funcName; //overwrite with less-specific name
//register prototype if necessary
if (registerPrototype) {
this.registerObject(name + ".prototype", prototype);
}
}
},
/**
* Sets up an object for profiling. It takes the object and looks for functions.
* When a function is found, registerMethod() is called on it. If set to recrusive
* mode, it will also setup objects found inside of this object for profiling,
* using the same methodology.
* @param {String} name The name of the object to profile (shows up in report).
* @param {Object} owner (Optional) The object represented by the name.
* @param {Boolean} recurse (Optional) Determines if subobject methods are also profiled.
* @return {Void}
* @method registerObject
* @static
*/
registerObject : function (name /*:String*/, object /*:Object*/, recurse /*:Boolean*/) /*:Void*/{
//get the object
object = (L.isObject(object) ? object : eval(name));
//save the object
container[name] = object;
for (var prop in object) {
if (typeof object[prop] == "function"){
if (prop != "constructor" && prop != "superclass"){ //don't do constructor or superclass, it's recursive
this.registerFunction(name + "." + prop, object);
}
} else if (typeof object[prop] == "object" && recurse){
this.registerObject(name + "." + prop, object[prop], recurse);
}
}
},
/**
* Removes a constructor function from profiling. Reverses the registerConstructor() method.
* @param {String} name The full name of the function including namespacing. This
* is the name of the function that is stored in the report.
* @return {Void}
* @method unregisterFunction
* @static
*/
unregisterConstructor : function(name /*:String*/) /*:Void*/{
//see if the method has been registered
if (L.isFunction(container[name])){
this.unregisterFunction(name, true);
}
},
/**
* Removes function from profiling. Reverses the registerFunction() method.
* @param {String} name The full name of the function including namespacing. This
* is the name of the function that is stored in the report.
* @return {Void}
* @method unregisterFunction
* @static
*/
unregisterFunction : function(name /*:String*/, unregisterPrototype /*:Boolean*/) /*:Void*/{
//see if the method has been registered
if (L.isFunction(container[name])){
//check to see if you should unregister the prototype
if (unregisterPrototype){
this.unregisterObject(name + ".prototype", container[name].prototype);
}
//get original data
var owner /*:Object*/ = container[name].__yuiOwner,
funcName /*:String*/ = container[name].__yuiFuncName;
//delete extra information
delete container[name].__yuiOwner;
delete container[name].__yuiFuncName;
//replace instrumented function
owner[funcName] = container[name];
//delete supporting information
delete container[name];
}
},
/**
* Unregisters an object for profiling. It takes the object and looks for functions.
* When a function is found, unregisterMethod() is called on it. If set to recrusive
* mode, it will also unregister objects found inside of this object,
* using the same methodology.
* @param {String} name The name of the object to unregister.
* @param {Boolean} recurse (Optional) Determines if subobject methods should also be
* unregistered.
* @return {Void}
* @method unregisterObject
* @static
*/
unregisterObject : function (name /*:String*/, recurse /*:Boolean*/) /*:Void*/{
//get the object
if (L.isObject(container[name])){
var object = container[name];
for (var prop in object) {
if (typeof object[prop] == "function"){
this.unregisterFunction(name + "." + prop);
} else if (typeof object[prop] == "object" && recurse){
this.unregisterObject(name + "." + prop, recurse);
}
}
delete container[name];
}
}
};
}, '@VERSION@', {"requires": ["yui-base"]});
|
'use strict';
exports.LOCAL_FILE_HEADER = "PK\x03\x04";
exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
exports.DATA_DESCRIPTOR = "PK\x07\x08";
|
/*! Qoopido.js library 3.7.0, 2015-07-23 | https://github.com/dlueth/qoopido.js | (c) 2015 Dirk Lueth */
!function(o){window.qoopido.register("pool/module",o,["../pool","../function/unique/uuid"])}(function(o,u,n,t,e,i,r){"use strict";var l=o["function/unique/uuid"],d=o.pool.extend({_module:null,_destroy:null,_constructor:function(o,n,t){var e=this,i=o._quid||(o._quid=l()),r=t&&(u.pool||(u.pool={}))&&(u.pool.module||(u.pool.module={}));return t===!0&&r[i]?r[i]:(d._parent._constructor.call(e,n),e._module=o,"function"==typeof o._destroy&&(e._destroy=function(o){o._destroy()}),t===!0&&(r[i]=e),void 0)},_dispose:function(o){return o},_obtain:function(){return this._module.create.apply(this._module,arguments)}});return d}); |
/*!
* numbro.js language configuration
* language : Thai
* locale : Thailand
* author : Sathit Jittanupat : https://github.com/jojosati
*/
(function(){"use strict";var a={langLocaleCode:"th-TH",cultureCode:"th-TH",delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"พัน",million:"ล้าน",billion:"พันล้าน",trillion:"ล้านล้าน"},ordinal:function(){return"."},currency:{symbol:"฿",position:"postfix"},defaults:{currencyFormat:",4 a"},formats:{fourDigits:"4 a",fullWithTwoDecimals:",0.00 $",fullWithTwoDecimalsNoCurrency:",0.00",fullWithNoDecimals:",0 $"}};
// CommonJS
"undefined"!=typeof module&&module.exports&&(module.exports=a),
// Browser
"undefined"!=typeof window&&window.numbro&&window.numbro.culture&&window.numbro.culture(a.cultureCode,a)}).call("undefined"==typeof window?this:window); |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2012, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the English
* language. This is the base file for all translations.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['en'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>',
confirmCancel : 'Some of the options were changed. Are you sure you want to close the dialog window?',
ok : 'OK',
cancel : 'Cancel',
confirmationTitle : 'Confirmation',
messageTitle : 'Information',
inputTitle : 'Question',
undo : 'Undo',
redo : 'Redo',
skip : 'Skip',
skipAll : 'Skip all',
makeDecision : 'What action should be taken?',
rememberDecision: 'Remember my decision'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'en',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM','PM'],
// Folders
FoldersTitle : 'Folders',
FolderLoading : 'Loading...',
FolderNew : 'Please type the new folder name: ',
FolderRename : 'Please type the new folder name: ',
FolderDelete : 'Are you sure you want to delete the "%1" folder?',
FolderRenaming : ' (Renaming...)',
FolderDeleting : ' (Deleting...)',
DestinationFolder : 'Destination Folder',
// Files
FileRename : 'Please type the new file name: ',
FileRenameExt : 'Are you sure you want to change the file extension? The file may become unusable.',
FileRenaming : 'Renaming...',
FileDelete : 'Are you sure you want to delete the file "%1"?',
FilesDelete : 'Are you sure you want to delete %1 files?',
FilesLoading : 'Loading...',
FilesEmpty : 'The folder is empty.',
DestinationFile : 'Destination File',
SkippedFiles : 'List of skipped files:',
// Basket
BasketFolder : 'Basket',
BasketClear : 'Clear Basket',
BasketRemove : 'Remove from Basket',
BasketOpenFolder : 'Open Parent Folder',
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?',
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?',
BasketEmpty : 'No files in the basket, drag and drop some.',
BasketCopyFilesHere : 'Copy Files from Basket',
BasketMoveFilesHere : 'Move Files from Basket',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.',
OperationCompletedErrors : 'Operation completed with errors.',
FileError : '%s: %e',
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.',
CopiedFilesNumber : 'Number of files copied: %s.',
MoveFailedList : 'The following files could not be moved:<br />%s',
CopyFailedList : 'The following files could not be copied:<br />%s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Upload',
UploadTip : 'Upload New File',
Refresh : 'Refresh',
Settings : 'Settings',
Help : 'Help',
HelpTip : 'Help',
// Context Menus
Select : 'Select',
SelectThumbnail : 'Select Thumbnail',
View : 'View',
Download : 'Download',
NewSubFolder : 'New Subfolder',
Rename : 'Rename',
Delete : 'Delete',
DeleteFiles : 'Delete Files',
CopyDragDrop : 'Copy Here',
MoveDragDrop : 'Move Here',
// Dialogs
RenameDlgTitle : 'Rename',
NewNameDlgTitle : 'New Name',
FileExistsDlgTitle : 'File Already Exists',
SysErrorDlgTitle : 'System Error',
FileOverwrite : 'Overwrite',
FileAutorename : 'Auto-rename',
ManuallyRename : 'Manually rename',
// Generic
OkBtn : 'OK',
CancelBtn : 'Cancel',
CloseBtn : 'Close',
// Upload Panel
UploadTitle : 'Upload New File',
UploadSelectLbl : 'Select a file to upload',
UploadProgressLbl : '(Upload in progress, please wait...)',
UploadBtn : 'Upload Selected File',
UploadBtnCancel : 'Cancel',
UploadNoFileMsg : 'Please select a file from your computer.',
UploadNoFolder : 'Please select a folder before uploading.',
UploadNoPerms : 'File upload not allowed.',
UploadUnknError : 'Error sending the file.',
UploadExtIncorrect : 'File extension not allowed in this folder.',
// Flash Uploads
UploadLabel : 'Files to Upload',
UploadTotalFiles : 'Total Files:',
UploadTotalSize : 'Total Size:',
UploadSend : 'Upload',
UploadAddFiles : 'Add Files',
UploadClearFiles : 'Clear Files',
UploadCancel : 'Cancel Upload',
UploadRemove : 'Remove',
UploadRemoveTip : 'Remove !f',
UploadUploaded : 'Uploaded !n%',
UploadProcessing : 'Processing...',
// Settings Panel
SetTitle : 'Settings',
SetView : 'View:',
SetViewThumb : 'Thumbnails',
SetViewList : 'List',
SetDisplay : 'Display:',
SetDisplayName : 'File Name',
SetDisplayDate : 'Date',
SetDisplaySize : 'File Size',
SetSort : 'Sorting:',
SetSortName : 'by File Name',
SetSortDate : 'by Date',
SetSortSize : 'by Size',
SetSortExtension : 'by Extension',
// Status Bar
FilesCountEmpty : '<Empty Folder>',
FilesCountOne : '1 file',
FilesCountMany : '%1 files',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'It was not possible to complete the request. (Error %1)',
Errors :
{
10 : 'Invalid command.',
11 : 'The resource type was not specified in the request.',
12 : 'The requested resource type is not valid.',
102 : 'Invalid file or folder name.',
103 : 'It was not possible to complete the request due to authorization restrictions.',
104 : 'It was not possible to complete the request due to file system permission restrictions.',
105 : 'Invalid file extension.',
109 : 'Invalid request.',
110 : 'Unknown error.',
111 : 'It was not possible to complete the request due to resulting file size.',
115 : 'A file or folder with the same name already exists.',
116 : 'Folder not found. Please refresh and try again.',
117 : 'File not found. Please refresh the files list and try again.',
118 : 'Source and target paths are equal.',
201 : 'A file with the same name is already available. The uploaded file was renamed to "%1".',
202 : 'Invalid file.',
203 : 'Invalid file. The file size is too big.',
204 : 'The uploaded file is corrupt.',
205 : 'No temporary folder is available for upload in the server.',
206 : 'Upload cancelled due to security reasons. The file contains HTML-like data.',
207 : 'The uploaded file was renamed to "%1".',
300 : 'Moving file(s) failed.',
301 : 'Copying file(s) failed.',
500 : 'The file browser is disabled for security reasons. Please contact your system administrator and check the CKFinder configuration file.',
501 : 'The thumbnails support is disabled.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'The file name cannot be empty.',
FileExists : 'File %s already exists.',
FolderEmpty : 'The folder name cannot be empty.',
FolderExists : 'Folder %s already exists.',
FolderNameExists : 'Folder already exists.',
FileInvChar : 'The file name cannot contain any of the following characters: \n\\ / : * ? " < > |',
FolderInvChar : 'The folder name cannot contain any of the following characters: \n\\ / : * ? " < > |',
PopupBlockView : 'It was not possible to open the file in a new window. Please configure your browser and disable all popup blockers for this site.',
XmlError : 'It was not possible to properly load the XML response from the web server.',
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.',
XmlRawResponse : 'Raw response from the server: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s',
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).',
resizeSuccess : 'Image resized successfully.',
thumbnailNew : 'Create a new thumbnail',
thumbnailSmall : 'Small (%s)',
thumbnailMedium : 'Medium (%s)',
thumbnailLarge : 'Large (%s)',
newSize : 'Set a new size',
width : 'Width',
height : 'Height',
invalidHeight : 'Invalid height.',
invalidWidth : 'Invalid width.',
invalidName : 'Invalid file name.',
newImage : 'Create a new image',
noExtensionChange : 'File extension cannot be changed.',
imageSmall : 'Source image is too small.',
contextMenuName : 'Resize',
lockRatio : 'Lock ratio',
resetSize : 'Reset size'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save',
fileOpenError : 'Unable to open file.',
fileSaveSuccess : 'File saved successfully.',
contextMenuName : 'Edit',
loadingFile : 'Loading file, please wait...'
},
Maximize :
{
maximize : 'Maximize',
minimize : 'Minimize'
},
Gallery :
{
current : 'Image {current} of {total}'
},
Zip :
{
extractHereLabel : 'Extract here',
extractToLabel : 'Extract to...',
downloadZipLabel : 'Download as zip',
compressZipLabel : 'Compress to zip',
removeAndExtract : 'Remove existing and extract',
extractAndOverwrite : 'Extract overwriting existing files',
extractSuccess : 'File extracted successfully.'
}
};
|
import test from 'blue-tape';
import { percentile } from '../utils';
test('utils/percentile', t => {
t.test('throws without a list or percentile', t => {
t.throws( () => percentile(undefined, .5) );
t.throws( () => percentile([1,2,3,4,5], undefined) );
t.end()
})
t.test('percentileing the empty set is NaN', t => {
t.ok( isNaN(percentile([], .6)) );
t.end();
});
t.test('percentileing a single item set is that item', t => {
t.equal( percentile([1], .4), 1);
t.equal( percentile([1], .1), 1);
t.equal( percentile([1], .99), 1);
t.end();
});
t.test('can generate a proper percentile', t => {
t.equal( percentile([1,2,3,4,5], .1), 1);
t.equal( percentile([1,2,3,4,5], .2), 2);
t.equal( percentile([1,2,3,4,5], .5), 3);
t.equal( percentile([1,2,3,4,5], .8), 5);
t.equal( percentile([1,2,3,4,5], 1), 5);
t.end()
})
});
|
angular.module('app')
.controller('ApplicationCtrl', ['$scope', '$mdSidenav', function ($scope,$mdSidenav) {
var self = this;
self.title = "Created by SaKKo"
self.toggleSidenav = function(menuId) {
$mdSidenav(menuId).toggle();
}
}])
|
'use strict';
const http = require('http');
const url = require('url');
const BufferHelper = require('bufferhelper');
const proto = require('./proto.js');
const restriction = require('./restriction.js');
const Signer = require('./signer.js');
function setError(code, name, err) {
err.code = code;
err.name = name;
return err;
}
function noticeError(err, callback) {
if (callback)
return process.nextTick(function() {
callback(err);
});
throw err;
}
function Client(options) {
this.endpoint = options.endpoint;
this.accessKey = options.accessKey;
this.secretKey = options.secretKey;
this.xVersion = options.xVersion || '2016-03-01';
var address = url.parse(options.endpoint);
this.hostname = address.hostname;
this.port = address.port;
this.signer = new Signer({
accessKey: this.accessKey,
secretKey: this.secretKey
});
this.agent = new http.Agent({KeepAlive: true});
}
Client.prototype.request = function(action, param, callback) {
try {
var buff = action.serialize(param);
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
var http_options = {
host: this.hostname,
port: this.port,
path: '/TableService.' + action.name,
method: 'POST',
headers: {
'Content-Length': buff.byteLength.toString(),
'Connection': 'Keep-Alive',
'X-ACTION': action.name,
'X-VERSION': this.xVersion,
'X-Kws-Date': new Date().toISOString(),
'Content-Type': 'application/binary'
},
agent: this.agent
};
http_options.headers['Authorization'] = this.signer.sign(http_options.method, http_options.headers);
var req = http.request(http_options, function(res) {
res.on("error", function(err) {
return noticeError(setError(-2, 'requestFailed', err), callback);
});
var body = new BufferHelper();
res.on("data", function(data) {
body.concat(data);
});
res.on("end", function() {
try {
var pb = action.decode(body.toBuffer());
} catch (err) {
err.body = body.toString();
return noticeError(setError(-3, 'apiError', err), callback);
}
try {
proto.checkResponse(pb);
var result = action.unserialize(pb);
var info = action.getInfo(pb);
} catch (err) {
return noticeError(err, callback);
}
if (callback)
return callback(null, result, info);
});
});
req.on("error", function(err) {
return noticeError(setError(-2, 'requestError', err), callback);
});
req.write(buff);
req.end();
};
Client.prototype.createTable = function(tableName) {
var options = arguments.length >= 3
? arguments[1]
: {};
var callback = arguments.length >= 2
? arguments[arguments.length - 1]
: null;
var params = {tableName: tableName};
try {
params.schema = options.schema || {
partitionKeyType: "STRING",
rowKeyType: null
};
params.provisionedThroughput = options.provisionedThroughput || {
readCapacityUnits: 10,
writeCapacityUnits: 10
};
restriction.tableName(params.tableName);
restriction.schema(params.schema);
restriction.provisionedThroughput(params.provisionedThroughput);
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.CreateTable, params, callback);
};
Client.prototype.deleteTable = function(tableName, callback) {
try {
restriction.tableName(tableName);
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.DeleteTable, {tableName: tableName}, callback);
};
Client.prototype.describeTable = function(tableName, callback) {
try {
restriction.tableName(tableName);
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.DescribeTable, {tableName: tableName}, callback);
};
Client.prototype.listTables = function(callback) {
this.request(proto.ListTables, null, callback);
};
Client.prototype.putRow = function(tableName, row, callback) {
try {
restriction.tableName(tableName);
restriction.row(row);
var param = {
tableName: tableName,
key: row.key,
columns: []
};
for (var name in row.columns) {
if (row.columns.hasOwnProperty(name)) {
param.columns.push({
columnName: name,
columnValue: row.columns[name]
});
}
}
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.PutRow, param, callback);
};
Client.prototype.getRow = function(tableName, options, callback) {
try {
var param = {
tableName: tableName,
key: options.key,
strongConsistent: options.hasOwnProperty('strongConsistent')
? options.strongConsistent
: false,
columns: options.hasOwnProperty('columns')
? options.columns
: null,
filter: options.hasOwnProperty('filter')
? options.filter
: null
};
restriction.tableName(param.tableName);
restriction.primaryKey(param.key);
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.GetRow, param, callback);
};
Client.prototype.deleteRow = function(tableName, key, callback) {
try {
restriction.tableName(tableName);
restriction.primaryKey(key);
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.DeleteRow, {
tableName: tableName,
key: key
}, callback);
};
Client.prototype.scan = function(tableName) {
var options = arguments.length >= 3
? arguments[1]
: {};
var callback = arguments.length >= 2
? arguments[arguments.length - 1]
: null;
try {
restriction.tableName(tableName);
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.Scan, {
tableName: tableName,
strongConsistent: options.hasOwnProperty('strongConsistent')
? options.strongConsistent
: false,
limit: options.hasOwnProperty('limit')
? options.limit
: null,
startKey: options.hasOwnProperty('startKey')
? options.startKey
: null,
endKey: options.hasOwnProperty('endKey')
? options.endKey
: null,
columns: options.hasOwnProperty('columns')
? options.columns
: null,
filter: options.hasOwnProperty('filter')
? options.filter
: null
}, callback);
};
Client.prototype.batchWriteRow = function(tableName, rows, callback) {
try {
restriction.tableName(tableName);
for (var i = 0; i < rows.length; ++i) {
restriction.primaryKey(rows[i].key);
}
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.BatchWriteRow, {
tableName: tableName,
rows: rows
}, callback);
};
Client.prototype.batchGetRow = function(tableName, keys) {
var options = arguments.length >= 4
? arguments[2]
: {};
var callback = arguments.length >= 3
? arguments[arguments.length - 1]
: null;
try {
restriction.tableName(tableName);
for (var i = 0; i < keys.length; ++i) {
restriction.primaryKey(keys[i]);
}
} catch (err) {
return noticeError(setError(-1, 'parseParamError', err), callback);
}
this.request(proto.BatchGetRow, {
tableName: tableName,
keys: keys,
strongConsistent: options.hasOwnProperty('strongConsistent')
? options.strongConsistent
: false,
columns: options.hasOwnProperty('columns')
? options.columns
: null,
filter: options.hasOwnProperty('filter')
? options.filter
: null
}, callback);
};
module.exports = Client;
|
import resolve from 'rollup-plugin-node-resolve';
import serve from 'rollup-plugin-serve'
import livereload from 'rollup-plugin-livereload'
export default {
input: './src/index.js',
output: {
file: 'public/game.js',
format: 'iife',
},
plugins: [
resolve(),
serve({
contentBase: ['public']
}),
livereload({
watch: ['src', 'public']
})
],
};
|
var api = require('./api/api');
var express = require('express');
var path = require('path');
var morgan = require('morgan');
var argv = require('yargs')
.usage('Start the server')
.default('port', process.env.WEB_PORT || 3000)
.alias('port', 'p')
.describe('port', 'port to run on')
.argv;
var app = express();
app.use(express.static(path.join(__dirname, "/dist")));
app.use(api);
console.log("Now listening on port " + argv.port);
console.log("Connect to http://0.0.0.0:" + argv.port);
app.listen(argv.port);
|
/**
*
* Wait for an element (selected by css selector) for the provided amount of
* milliseconds to be (un)checked. If multiple elements get queryied by given
* selector, it returns true (or false if reverse flag is set) if at least one
* element is (un)checked.
*
* @param {String} selector element to wait for
* @param {Number=} ms time in ms (default: 500)
* @param {Boolean=} reverse if true it waits for the opposite (default: false)
*
* @uses action/selectorExecuteAsync, protocol/timeoutsAsyncScript
* @type utility
*
*/
var async = require('async'),
isCheckedFunc = require('../helpers/_isChecked'),
ErrorHandler = require('../utils/ErrorHandler');
module.exports = function waitForChecked(selector, ms, reverse) {
/*!
* make sure that callback contains chainit callback
*/
var callback = arguments[arguments.length - 1];
/*!
* parameter check
*/
if (typeof selector !== 'string') {
return callback(new ErrorHandler.CommandError('number or type of arguments don\'t agree with waitForChecked command'));
}
/*!
* ensure that ms is set properly
*/
if (typeof ms !== 'number') {
ms = this.options.waitforTimeout;
}
if (typeof reverse !== 'boolean') {
reverse = false;
}
var self = this,
response = {};
async.waterfall([
function(cb) {
self.timeoutsAsyncScript(ms, cb);
},
function(res, cb) {
response.timeoutsAsyncScript = res;
self.selectorExecuteAsync(selector, isCheckedFunc, reverse, cb);
},
function(result, res, cb) {
response.selectorExecuteAsync = res;
cb();
}
], function(err) {
callback(err, response.selectorExecuteAsync && response.selectorExecuteAsync.executeAsync ? response.selectorExecuteAsync.executeAsync.value : false, response);
});
}; |
/**
* DShare Client Configuration
*
* Copy this file to config.js and edit to suit your preferences.
*/
var Options = {
server: {
trace : true,
trusted: true,
local_signing: true,
servers: [
{ host: 's_west.ripple.com', port: 443, secure: true },
{ host: 's_east.ripple.com', port: 443, secure: true }
],
connection_offset: 0
},
blobvault : 'https://blobvault.payward.com',
// If set, login will persist across sessions (page reload). This is mostly
// intended for developers, be careful about using this in a real setting.
persistent_auth : false,
// Number of transactions each page has in balance tab notifications
transactions_per_page: 50,
// Configure bridges
bridge: {
out: {
// "bitcoin": "localhost:3000"
// "bitcoin": "https://www.bitstamp.net/ripple/bridge/out/bitcoin/"
}
},
mixpanel: {
"token": '',
// Don't track events by default
"track": false
},
zipzap: {
"requester": "zipzap/request.php"
}
};
// Load client-side overrides
if (store.enabled) {
$.extend(true, Options, JSON.parse(store.get('ripple_settings') || "{}"));
}
|
var assert = require('assert');
var Readable = require('stream').Readable;
var parsePage = require('./lib/page-parser.js');
module.exports = function (options) {
var fetchPage = options.fetcher || require('./lib/page-fetcher.js');
return {
comments: fetchComments
};
// support passing in a fetcher instead of using the built in one (for testing)
assert(typeof fetchPage === 'function');
function fetchComments(videoID) {
var readable = new Readable({
objectMode: true
});
var comments;
fetchPage(videoID, null, function (err, result) {
if (err) {
readable.emit('error', err);
return;
}
parsePage(result.html, function (err, result) {
if (err) {
readable.emit('error', err);
return;
}
if (result.comments) {
comments = comments || [];
result.comments.forEach(function (comment) {
comments.push(comment);
});
readable.push(comments.shift());
}
});
});
readable._read = function () {
if (comments === void 0) return;
if (comments.length) {
this.push(comments.shift());
} else {
this.push(null);
}
};
return readable;
}
}; |
/* @flow weak */
import _ from 'lodash';
import hash from '../../helpers/hash.js';
export type QuestionT = {
id:number,
condition:string,
choices:[string],
text:string
};
// Make questions for an email, describe choices.
export const InsubordinationScenarios = {
choices() {
return [
'ignore the behavior',
'make eye contact',
'make a facial expression or gesture',
'make a joke',
'encourage the student',
'redirect the student to the task',
'remind the student of class rules',
'ask the student to stay after class',
'send the student to the principal',
'call an administrator to class'
];
},
// Given an email, return a cohortKey.
cohortKey(email) {
const {conditions} = this.data();
return hash(email) % conditions.length;
},
data() {
// Read scenario
const conditions = [{child: 'Jake' }, {child: 'Greg'}, {child: 'Darnell'}, {child: 'DeShawn'}];
/* eslint-disable no-template-curly-in-string */
const questionTemplates = [
'Students are working independently on a proportions problem set. You circulate around the room.',
'${child} is sleeping in class.',
'He picks his head up. He chooses to rest it on his hand and continue to sleep.',
'${child} refuses to do work.',
'He refuses.'
];
/* eslint-enable no-template-curly-in-string */
return {conditions, questionTemplates};
},
// Return questions for cohortKey.
// This involves taking description from yaml and making it concrete.
questionsFor(cohortKey) {
const {conditions, questionTemplates} = this.data();
const condition = conditions[cohortKey];
const questions = questionTemplates.map((template, index) => {
const text = _.template(template)(condition);
const question:QuestionT = {
id: hash(text),
condition: condition,
choices: (index === 0) ? [] : this.choices(),
text: text
};
return question;
}, this);
return questions;
}
};
|
// ONLY WORKS WITH mongodb@1.4.2 mongoose@3.8.8
// NEWER VERSIONS DEPRECIATED MongoClient.open()
var MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var client = new MongoClient(new Server('localhost', 27017, {
socketOptions: {
connectTimeoutMS: 500
},
poolSize: 5,
auto_reconnect: true
}, {
numberOfRetries: 3,
retryMilliseconds: 500
}));
client.open(function(err, client) {
if (err) {
console.log('Connection Failed Via Client Object.');
} else {
var db = client.db('testDB');
if (db) {
console.log('Connected Via Client Object . . .');
db.authenticate('nodeadmin', 'password', function(err, results) {
if (err) {
console.log('Authentication failed . . .');
client.close();
console.log('Connection closed . . .');
} else {
console.log('Authenticated Via Client Object . . .');
db.logout(function(err, result) {
if (!err) {
console.log('Logged out Via Client Object . . .');
}
client.close();
console.log('Connection closed . . .');
});
}
});
}
}
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.factorialDependencies = void 0;
var _dependenciesGamma = require("./dependenciesGamma.generated");
var _dependenciesTyped = require("./dependenciesTyped.generated");
var _factoriesNumber = require("../../factoriesNumber.js");
/**
* THIS FILE IS AUTO-GENERATED
* DON'T MAKE CHANGES HERE
*/
var factorialDependencies = {
gammaDependencies: _dependenciesGamma.gammaDependencies,
typedDependencies: _dependenciesTyped.typedDependencies,
createFactorial: _factoriesNumber.createFactorial
};
exports.factorialDependencies = factorialDependencies; |
class AsyncFactory {
constructor(constructor: Function, ...args: Array<any>): void {
this._args = args;
this._constructor = constructor;
this._instance = null;
}
replaceConstructor(constructor: Function): void {
this._constructor = constructor;
this._instance = null;
}
getInstance(): Object {
return new Promise((resolve: Function, reject: Function): Promise => {
if (this._instance !== null) {
resolve(this._instance);
}
this._constructor(...this._args)
.then((instance: Object) => {
this._instance = instance;
resolve(instance);
})
.catch((error: any) => reject(error));
});
}
}
module.exports = AsyncFactory;
|
/*
Tracking position with draggable in angular.
http://stackoverflow.com/questions/15470666/angularjs-directive-attribute-binding-left-top-positions-after-dragging-with-ng
*/
angular.module('cardboard').controller('cards-board', ['$scope', 'cardboardService', 'modalService',
function($scope, cardboardService, modalService) {
const modalTemplateUrl = 'partials/card-modal.html';
$scope.addCard = function() {
modalService.showModal({
templateUrl: modalTemplateUrl
}, {
modalTitle: 'Add Card',
left: 30,
top: 100,
visible: true,
decks: cardboardService.decks,
defaultDeck: cardboardService.defaultDeck,
})
.then(function(result) {
result.deck_id = result.selectedDeck.id;
cardboardService.addCard(result);
});
}
function findCardById(id) {
return _.find($scope.cards, function(c) { return c.id === id; });
}
function editCard(id) {
var c = findCardById(id);
if (!c) return;
modalService.showModal({
templateUrl: modalTemplateUrl
}, {
modalTitle: 'Edit Card',
id: c.id,
left: c.left,
top: c.top,
visible: true,
title: c.title,
content: c.content,
decks: cardboardService.decks,
defaultDeck: cardboardService.defaultDeck,
selectedDeck: _.find(cardboardService.decks, function(d) { return d.id === c.deck_id; })
})
.then(function(result) {
result.deck_id = result.selectedDeck.id;
cardboardService.updateCard(result);
});
}
function hideCard(id) {
var c = findCardById(id);
if (!c) return;
cardboardService.updateCard({
id: id,
visible: false
});
}
function deleteCard(id) {
var c = findCardById(id);
if (c)
{
modalService.showModal({
templateUrl: 'partials/delete-card-modal.html'
}, {})
.then(function(result) {
cardboardService.deleteCard(c.id);
});
}
}
$scope.onMoveStop = function(attrs, left, top) {
cardboardService.updateCard({
id: parseInt(attrs.cardId),
left: left,
top: top
});
}
$scope.onContextClick = function(option, id) {
// Since this javascript turn is not initiated in something like ng-click, it's not
// automatically wrapped in an $apply. So, we need to tell angular that there's a chance
// that the model is being altered. We do this here.
$scope.$apply(function() {
switch (option) {
case "edit": editCard(id); break;
case "delete": deleteCard(id); break;
case "hide": hideCard(id); break;
}
});
}
$scope.search = '';
$scope.cards = cardboardService.cards;
}]);
|
/**
* A NodeJS module for interfacing with Foursquare.
* @module node-foursquare
* @version 0.1.3
* @author Clint Andrew Hall
* @description A NodeJS module for interacting with Foursquare.
* @param {Object} config A valid configuration.
*/
var qs = require('querystring'),
sys = require("util"),
defaultConfig = require("./config-default"),
log4js = require("log4js");
function mergeDefaults(o1, o2) {
for(var p in o2) {
try {
if(typeof o2[p] == "object") {
o1[p] = mergeDefaults(o1[p], o2[p]);
} else if(typeof o1[p] == "undefined") {
o1[p] = o2[p];
}
} catch(e) {
o1[p] = o2[p];
}
}
return o1;
}
module.exports = function(config) {
function getLogger(config) {
log4js.configure(config.log4js);
return log4js.getLogger("node-foursquare");
}
function configure(config) {
config = config || {};
mergeDefaults(config, defaultConfig);
var logger = getLogger(config);
if(!config.secrets || !config.secrets.clientId || !config.secrets.clientSecret || !config.secrets.redirectUrl) {
logger.error("Client configuration not supplied; add config.secrets information, (clientId, clientSecret, redirectUrl).");
throw new Error("Configuration Error: Client information not supplied.");
}
if(!config.foursquare.accessTokenUrl || !config.foursquare.apiUrl) {
logger.error("Foursquare configuration not supplied; add config.foursquare information, (accessTokenUrl, apiUrl)");
throw new TypeError("Configuration Error: Foursquare information not supplied.");
}
if(!config.foursquare.version || config.foursquare.version === "LATEST") {
var d = new Date(), month = d.getMonth() + 1, date = d.getDate();
config.foursquare.version = d.getFullYear() + ((month < 10 ? "0" : "") + month) + ((date < 10 ? "0" : "") + date);
logger.warn("Foursquare API version not defined in configuration; defaulting to latest: " + config.foursquare.version);
}
return config;
}
config = configure(config);
var logger = getLogger(config),
core = require("./core")(config);
logger.debug("Configuration: " + sys.inspect(config));
/**
* Exchange a user authorization code for an access token.
* @memberof module:node-foursquare
* @param {Object} params A collection of parameters for the Access Token request.
* @param {String} params.code The code provided by Foursquare as the result of the user redirect.
* @param {String} [params.grant_type="authorization_code"] The type of authorization to request.
* @param {Function} callback The function to call with results, function({Error} error, {Object} results).
* @see https://developer.foursquare.com/docs/oauth.html
*/
function getAccessToken(params, callback) {
params = params || {};
params.grant_type = params.grant_type || "authorization_code";
params.client_id = config.secrets.clientId;
params.client_secret = config.secrets.clientSecret;
params.redirect_uri = config.secrets.redirectUrl;
core.retrieve(config.foursquare.accessTokenUrl + "?" + qs.stringify(params),
function(error, status, result) {
if(error) {
callback(error);
}
else {
try {
callback(null, JSON.parse(result).access_token);
}
catch(e) {
callback(e);
}
}
});
}
/**
* Build and return an appropriate Authorization URL where the user can grant permission to the application.
* @memberof module:node-foursquare
*/
function getAuthClientRedirectUrl() {
return config.foursquare.authenticateUrl + "?client_id=" + config.secrets.clientId + "&response_type=code&redirect_uri=" + config.secrets.redirectUrl;
}
return {
"Users" : require("./users")(config),
"Venues" : require("./venues")(config),
"Checkins" : require("./checkins")(config),
"Tips" : require("./tips")(config),
"Lists" : require("./lists")(config),
"Photos" : require("./photos")(config),
"Settings" : require("./settings")(config),
"Specials" : require("./specials")(config),
"Updates" : require("./updates")(config),
"Events" : require("./events")(config),
"Core" : require("./core")(config),
"getAccessToken" : getAccessToken,
"getAuthClientRedirectUrl" : getAuthClientRedirectUrl
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:cbbbf2485e19370b114a4a9b47b068ad29d255d461990d29896e5f9960f0c6d8
size 32771
|
import React, { PropTypes } from 'react';
import classNames from 'classnames';
import mdlUpgrade from './utils/mdlUpgrade';
class Radio extends React.Component {
static propTypes = {
checked: PropTypes.bool,
className: PropTypes.string,
disabled: PropTypes.bool,
name: PropTypes.string,
onChange: PropTypes.func,
ripple: PropTypes.bool,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired
};
render() {
const { children, className, name, ripple, value, ...inputProps } = this.props;
const classes = classNames('mdl-radio mdl-js-radio', {
'mdl-js-ripple-effect': ripple
}, className);
return (
<label className={classes}>
<input
type="radio"
className="mdl-radio__button"
value={value}
name={name}
{ ...inputProps }
/>
<span className="mdl-radio__label">{children}</span>
</label>
);
}
}
export default mdlUpgrade(Radio);
|
(function(gulp, gulpLoadPlugins){
var $ = gulpLoadPlugins({
pattern: '*',
lazy: true
}),
_ = {
app: 'app',
dist: 'dist',
sass: 'app/sass',
tmpl: 'app/src',
js: 'app/js',
css: 'app/css',
img: 'app/img'
},
files = [
'app/*.html',
'app/css/**/*.css',
'app/img/**/*',
'app/js/**/*.js'
];
// 处理错误
function handleError(error){
console.log(error.message);
this.emit('end');
}
// gulp-jshint
// js代码校验
gulp.task('jshint', function() {
return gulp.src([ 'gulpfile.js' , _.js + '/**/*.js'])
.pipe($.jshint())
.pipe($.jshint().reporter('jshint-stylish'));
});
// gulp-scss-lint
// scss校验
gulp.task('scss-lint', function() {
return gulp.src([_.sass + '/**/*.{scss, sass}'])
.pipe($.scssLint({
'config': '.scsslintrc',
'customReport': $.scssLintStylish
}));
});
// gulp-css-spriter
// 制作雪碧图
// 单独制作雪碧图
gulp.task('sprite', function(){
// console.log(gulp.src(_.css + '/*.css'));
return gulp.src(_.css + '/*.css')
.pipe($.cssSpriter({
// 生成的spriter的位置
'spriteSheet': _.img + '/spriter.png',
// 生成样式文件图片引用地址的路径
'pathToSpriteSheetFromCSS': '../img/spriter.png'
}))
});
// // webpack打包js
// gulp.task('webpack', function () {
// gulp.src('./test.js')
// .pipe(webpack())
// .pipe(gulp.dest('dist/'))
// .pipe(rename('all.min.js'))
// .pipe(uglify())
// .pipe(gulp.dest('./dist'));
// });
// gulp-sass, gulp-autoprefixer, gulp-sourcemaps
// 将sass预处理为css,
// 使用autoprefixer来补全浏览器兼容的css
// 使用sourcemaps 检查错误
gulp.task('sass', function(){
return gulp.src(_.sass + '/*.scss')
.pipe($.plumber({ errorHandler: handleError}))
.pipe($.sourcemaps.init())
.pipe($.sass({
outputStyle: 'expanded',
includePaths: [ './bower_components/' ]
}))
.pipe($.cssSpriter())
.pipe($.autoprefixer({
browers: ['last 2 versions','safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4']
}))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(_.css))
.pipe($.size({
title: 'CSS files:'
})
);
});
// 渲染html文件模板
// 使用gulp-file-include合并模板文件
gulp.task('html', function() {
return gulp.src([_.tmpl + '/*.html'])
.pipe($.plumber())
.pipe($.fileInclude({
prefix: '@@',
basepath: '@file'
}))
.pipe(gulp.dest(_.app + '/'))
.pipe($.size({
title: 'HTML files:'
})
);
});
// browser-sync
// 实时将修改信息渲染到浏览器
gulp.task('browser-sync', function(){
$.browserSync.init(files,{
server: {
baseDir: './app'
},
port: 9000
});
});
// 监听修改信息
gulp.task('watch', function(){
// 监听css修改
$.watch([_.sass + '/*.scss'], function(){
gulp.start('sass');
});
// 监听html修改
$.watch([_.tmpl + '/**/*.html'], function(){
gulp.start('html');
});
gulp.start('browser-sync');
});
// 上面是开发环境,下面是打包上线
// 图片压缩
gulp.task('image', function(){
return gulp.src(_.img + '/**/*')
.pipe($.cache($.imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe($.imagemin({
pregressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [$.imageminPngquant()]
}))
.pipe(gulp.dest(_.dist + '/img'))
.pipe($.size({
title: 'IMAGE files:'
}));
});
// 替换文件名
gulp.task('revcss', function(){
return gulp.src(_.css + '/*.css')
.pipe($.if('*.css', $.cssnano()))
.pipe($.if('*.css', $.rev()))
.pipe($.rev.manifest())
.pipe(gulp.dest(_.dist + '/css'));
});
// 替换文件名
gulp.task('revjs', function(){
return gulp.src(_.js + '/*.js')
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.js', $.rev()))
.pipe($.rev.manifest())
.pipe(gulp.dest(_.dist + '/js'));
});
// 替换文件名
gulp.task('rename', ['revcss', 'revjs'],function() {
gulp.src(['dist/*/*.json', 'app/*.html'])
.pipe($.revCollector({
replaceReved: true,
dirReplacements: {
'css': '/dist/css',
'/js/': '/dist/js/',
'cdn/': function(manifest_value) {
return '//cdn' + (Math.floor(Math.random() * 9) + 1) + '.' + 'exsample.dot' + '/img/' + manifest_value;
}
}
}))
.pipe(gulp.dest(_.dist));
});
// js、css、html压缩处理(可选)
// 打包到dist文件夹下
gulp.task('dist', ['image', 'rename'], function(){
return gulp.src('app/*.html')
.pipe($.plumber())
.pipe($.useref())
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.js', $.rev()))
.pipe($.if('*.css', $.cssnano()))
.pipe($.if('*.css', $.rev()))
.pipe(gulp.dest(_.dist));
});
// 删除dist文件夹
gulp.task('rimraf', function(){
return gulp.src(_.dist + '*', {read: false})
.pipe($.rimraf({force: true}));
});
// gulp-start
// 启动项目
gulp.task('start', ['watch', 'html', 'sass']);
// 检查css和js
gulp.task('test', ['jshint', 'scss-lint']);
// 默认
gulp.task('default', ['html', 'sass', 'rimraf'], function(){
gulp.start('dist');
});
})(require('gulp'), require('gulp-load-plugins'));
|
/**
* Created by ZHAN on 2016/3/25.
*/
//电极,不需要刷新
var ArcFurnace = ArcFurnace || {};
ArcFurnace.Actor = ArcFurnace.Actor || {};
ArcFurnace.Actor.Electrode = fabric.util.createClass(ActorsBase, {
initialize: function (canvas, X, Y, Width, Height, RotateAngle, Flip, centerPX, centerPY) {
this.callSuper('initialize', canvas);
this.defaultOptions = { //set special actor's options here
Height: 64, //used by actors,宽高比为34:20;等比变换
Width: 19.2, //used by actors
// ValveState: '中间态', //默认状态‘中间态’; public enum ValveState {关=0, 关到位=1, 开=2, 开到位=3, 未知(中间态)=4};
// FillColor: 'gray'
};
this.setOption(this.defaultOptions);
this.setoption(X, Y, Width, Height, RotateAngle, Flip, centerPX, centerPY);
this.refreshObjs = new Array(); // 刷新对象数组
// 下面三行为阀门颜色,根据ValveState值设置
// this.color1 = 'gray'; //开关默认颜色1
// this.color2 = 'white'; //开关默认颜色2
// this.ValveState = this.option.ValveState; //开关状态
this.topgroup = this.initializeobjs();
this.canvas.add(this.topgroup);
// this.canvas.renderAll();
},
//根据ValveState值设置阀门颜色
// _setcolor: function (value) {
// switch (value) {
// case '关':
// this.color1 = '#FF00FF'; //Magenta
// this.color2 = 'white';
// break;
// case '关到位':
// this.color1 = 'red';
// this.color2 = '#FF00FF'; //Magenta
// break;
// case '开':
// this.color1 = '#90EE90'; // LightGreen #90EE90
// this.color2 = 'white';
// break;
// case '开到位':
// this.color1 = '#006400'; //DarkGreen
// this.color2 = '#90EE90'; //LarkGreen
// break;
// default:
// this.color1 = 'gray';
// this.color2 = 'white';
// break;
// }
// },
initializeobjs: function () {
var iwidth = this.option.Width;
var iheight = this.option.Height;
var fillcolor = this.option.FillColor;
// this._setcolor(this.option.ValveState);
//original shape outline
var rect0 = new fabric.Rect({
left: 0,
top: 0,
height: iheight,
width: iwidth,
fill: 'yellow',
opacity: 0.3,
visible: false,
hasBorders: false,
originX: 'center',
originY: 'center'
});
this.topgroup.addWithUpdate(rect0);
var rectrotate = new fabric.Rect({
left: 0,
top: 0,
height: iheight,
width: iwidth,
fill: 'green',
opacity: 0.1,
visible: false,
hasBorders: false,
originX: 'center',
originY: 'center'
});
this.group.addWithUpdate(rectrotate);
//上面的三个矩形部分
var path1 = new fabric.Rect({
left: 0,
top: 0,
width: iwidth,
height: iheight * 89 / 150,
hasBorders: false,
originX: 'center',
originY: 'top'
});
path1.set({
left: 0,
top: -iheight / 2,
originX: 'center',
originY: 'top'
});
path1.setGradient('fill', {
x1: 0,
y1: 0,
x2: iwidth,
y2: 0,
colorStops: {
0: 'rgb(102,102,108)',
0.5: 'rgb(219,202,192)',
1: 'rgb(102,102,108)'
}
});
this.group.addWithUpdate(path1);
this._addToShape(path1);
var path2 = new fabric.Rect({
left: 6/45*iwidth,
top: 89/150*iheight,
width: 33/45*iwidth,
height: iheight * 8 / 150,
hasBorders: false,
originX: 'center',
originY: 'top'
});
path2.set({
left: 0,
top: iheight *14/ 150, //14=89-150/2
originX: 'center',
originY: 'top'
});
path2.setGradient('fill', {
x1: 0,
y1: 0,
x2:iwidth*33/45,
y2: 0,
colorStops: {
0: 'rgb(102,102,108)',
0.5: 'rgb(219,202,192)',
1: 'rgb(102,102,108)'
}
});
this.group.addWithUpdate(path2);
this._addToShape(path2);
var path3 = new fabric.Rect({
left: 12.5/45*iwidth,
top: 97/150*iheight,
width: iwidth*20/45,
height: iheight * 40 / 150,
hasBorders: false,
originX: 'center',
originY: 'top'
});
path3.set({
left: 0,
top: iheight *22/ 150, //22=97-150/2
originX: 'center',
originY: 'top'
});
path3.setGradient('fill', {
x1: 0,
y1: 0,
x2: iwidth*20/45,
y2: 0,
colorStops: {
0: 'rgb(102,102,108)',
0.5: 'rgb(219,202,192)',
1: 'rgb(102,102,108)'
}
});
this.group.addWithUpdate(path3);
this._addToShape(path3);
//下面的锥形部分
var pathstring = 'M' + iwidth * 12.5 / 45 + ',' + iheight * 137 / 150 + ' L' + iwidth * 22.5 / 45 + ',' + iheight + 'L' + iwidth * 32.5 / 45 + ',' + iheight*137/150 + 'L' + iwidth * 12.5 / 45 + ',' + iheight * 137 / 150 + '';
var path4 = new fabric.Path(pathstring);
path4.set({
left: 0,
top: iheight * 62 / 150,
hasBorders: false,
strokeWidth: 0.3,
stroke: 'black',
originX: 'center',
originY: 'top'
});
path4.setGradient('fill', {
x1: 0,
y1: 0,
x2: iwidth*20/45,
y2: 0,
colorStops: {
0: 'rgb(102,102,108)',
0.5: 'rgb(219,202,192)',
1: 'rgb(102,102,108)'
}
});
this.group.addWithUpdate(path4);
this._addToShape(path4);
this._setGroupOptions();
this._setTopgroupOptions();
return this.topgroup;
},
refresh: function (options) { //每次刷新根据ValveState改变开关颜色
this.setOption(options);
this._renderRefresh();
},
toString: function () {
return ' 电极 Electrode';
}
});
|
const util = require("util")
const config = require("config")
const user = config.has("browserstack_user")
? config.get("browserstack_user")
: process.env.BROWSERSTACK_USER
const key = config.has("browserstack_key")
? config.get("browserstack_key")
: process.env.BROWSERSTACK_ACCESS_KEY
const localIdentifier = config.has("browserstack_localIdentifier")
? config.get("browserstack_localIdentifier")
: process.env.BROWSERSTACK_LOCAL_IDENTIFIER
const debug = config.has("browserstack_debug")
? config.get("browserstack_debug")
: process.env.BROWSERSTACK_DEBUG
// Note: if the official timezone is "America/New_York", BrowserStack uses just "New_York"!
const moment = require("moment-timezone")
const localTz = moment.tz.guess()
const tzParts = localTz.split("/")
const bsTz = tzParts[tzParts.length - 1]
const bstackOptions = {
os: "Windows",
osVersion: "10",
resolution: "2048x1536",
projectName: "ANET",
// Use the local timezone on BrowserStack
timezone: bsTz,
// Credentials for BrowserStack:
userName: user,
accessKey: key,
// This requires that BrowserStackLocal is running!
local: "true"
}
const capabilities = {
maxInstances: 1,
browserName: "Chrome",
browserVersion: "latest",
"goog:chromeOptions": {
// Maximize the window so we can see what's going on
args: ["--start-maximized"]
},
"bstack:options": bstackOptions
}
if (debug) {
bstackOptions.debug = debug
}
if (localIdentifier) {
// For GitHub Actions
bstackOptions.localIdentifier = localIdentifier
}
bstackOptions.buildName = util.format(
require("git-describe").gitDescribeSync(".", { match: "[0-9]*" })
.semverString,
bstackOptions.os,
bstackOptions.osVersion,
capabilities.browserName,
capabilities.browserVersion
)
module.exports = capabilities
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import { Router } from 'express';
import User from '../db/models/user.js';
const router = new Router();
router.post('/check', async (req, res, next) => {
if (req.session.user) {
res.status(200).json(req.session.user);
} else {
res.status(401).json({
message: 'Unauthorized!'
});
}
});
router.post('/create', async (req, res, next) => {
try {
const { username, password } = req.body;
let errors = [];
if (!username.trim()) {
errors.push({
field: 'username',
message: 'Please enter your username'
});
}
if (!password.trim()) {
errors.push({
field: 'password',
message: 'Please enter your password'
});
}
if (!errors.length) {
User.findOne({username, password}, (err, user) => {
if (err) { next(err); }
if (user) {
req.session.user = user;
res.status(201).json(user);
} else {
res.status(401).json({
field: '*',
message: 'Wrong username/password combination!'
});
}
});
} else {
res.status(400).json(errors);
}
} catch (err) {
next(err);
}
});
router.post('/destroy', async (req, res, next) => {
if (req.session.user) {
delete req.session.user;
res.status(200).json({
message: 'Logout successful!'
});
} else {
res.status(401).json({
message: 'Unauthorized!'
});
}
});
export default router;
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addTicket } from '../actions'
class AddTicket extends Component {
render() {
return (
<div>
<button label="ADD" onClick ={ () => {
this.props.dispatch(addTicket('hogeee1',this.props.boardType));
}} >add</button>
</div>
)
}
}
AddTicket.childContextTypes = {
// muiTheme: React.PropTypes.object.isRequired,
};
export default AddTicket = connect()(AddTicket);
|
import React, {Component} from "react";
import NameForm from "./components/NameForm";
export default class Start extends Component {
render() {
return (
<NameForm/>
);
}
} |
angular.module('starter.services')
.factory('Chats', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: 'Hey, it\'s me',
face: 'https://avatars3.githubusercontent.com/u/11214?v=3&s=460'
},{
id: 2,
name: 'Adam Bradleyson',
lastText: 'I should buy a boat',
face: 'https://pbs.twimg.com/profile_images/479090794058379264/84TKj_qa.jpeg'
}, {
id: 3,
name: 'Perry Governor',
lastText: 'Look at my mukluks!',
face: 'https://pbs.twimg.com/profile_images/598205061232103424/3j5HUXMY.png'
}, {
id: 4,
name: 'Mike Harrington',
lastText: 'This is wicked good ice cream.',
face: 'https://pbs.twimg.com/profile_images/578237281384841216/R3ae1n61.png'
}];
return {
all: function() {
return chats;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
}) |
'use strict';
var _ = require('../utils/lodash');
var Command = require('../command');
var SubscriptionSet = require('../subscription_set');
var debug = require('../utils/debug')('ioredis:reply');
var Parser = require('redis-parser');
var ReplyError = require('../reply_error');
/**
* Init the parser
*
* @method _initParser
* @memberOf Redis#
* @private
*/
exports.initParser = function () {
var _this = this;
this.replyParser = new Parser({
stringNumbers: this.options.stringNumbers,
returnBuffers: !this.options.dropBufferSupport,
returnError: function (err) {
_this.returnError(new ReplyError(err.message));
},
returnReply: function (reply) {
_this.returnReply(reply);
},
returnFatalError: function (err) {
_this.flushQueue(err, { offlineQueue: false });
_this.silentEmit('error', new Error('Redis parser fatal error: ' + err.stack));
_this.disconnect(true);
}
});
};
exports.returnError = function (err) {
var item = this.commandQueue.shift();
err.command = {
name: item.command.name,
args: item.command.args
};
var needReconnect = false;
if (this.options.reconnectOnError) {
needReconnect = this.options.reconnectOnError(err);
}
switch (needReconnect) {
case 1:
case true:
if (this.status !== 'reconnecting') {
this.disconnect(true);
}
item.command.reject(err);
break;
case 2:
if (this.status !== 'reconnecting') {
this.disconnect(true);
}
if (this.condition.select !== item.select && item.command.name !== 'select') {
this.select(item.select);
}
this.sendCommand(item.command);
break;
default:
item.command.reject(err);
}
};
var sharedBuffers = {};
_.forEach(['message', 'pmessage', 'subscribe', 'psubscribe', 'unsubscribe', 'punsubscribe'], function (str) {
sharedBuffers[str] = new Buffer(str);
});
exports.returnReply = function (reply) {
if (this.status === 'monitoring') {
// Valid commands in the monitoring mode are AUTH and MONITOR,
// both of which always reply with 'OK'.
var replyStr = reply.toString();
// If not the reply to AUTH & MONITOR
if (replyStr !== 'OK') {
// Since commands sent in the monitoring mode will trigger an exception,
// any replies we received in the monitoring mode should consider to be
// realtime monitor data instead of result of commands.
var len = replyStr.indexOf(' ');
var timestamp = replyStr.slice(0, len);
var argindex = replyStr.indexOf('"');
var args = replyStr.slice(argindex + 1, -1).split('" "').map(function (elem) {
return elem.replace(/\\"/g, '"');
});
var dbAndSource = replyStr.slice(len + 2, argindex - 2).split(' ');
this.emit('monitor', timestamp, args, dbAndSource[1], dbAndSource[0]);
return;
}
}
var item, channel, count;
if (this.condition.subscriber) {
var replyType = Array.isArray(reply) ? reply[0].toString() : null;
debug('receive reply "%s" in subscriber mode', replyType);
switch (replyType) {
case 'message':
if (this.listeners('message').length > 0) {
this.emit('message', reply[1].toString(), reply[2].toString());
}
if (this.listeners('messageBuffer').length > 0) {
this.emit('messageBuffer', reply[1], reply[2]);
}
break;
case 'pmessage':
var pattern = reply[1].toString();
if (this.listeners('pmessage').length > 0) {
this.emit('pmessage', pattern, reply[2].toString(), reply[3].toString());
}
if (this.listeners('pmessageBuffer').length > 0) {
this.emit('pmessageBuffer', pattern, reply[2], reply[3]);
}
break;
case 'subscribe':
case 'psubscribe':
channel = reply[1].toString();
this.condition.subscriber.add(replyType, channel);
item = this.commandQueue.shift();
if (!fillSubCommand(item.command, reply[2])) {
this.commandQueue.unshift(item);
}
break;
case 'unsubscribe':
case 'punsubscribe':
channel = reply[1] ? reply[1].toString() : null;
if (channel) {
this.condition.subscriber.del(replyType, channel);
}
count = reply[2];
if (count === 0) {
this.condition.subscriber = false;
}
item = this.commandQueue.shift();
if (!fillUnsubCommand(item.command, count)) {
this.commandQueue.unshift(item);
}
break;
default:
item = this.commandQueue.shift();
item.command.resolve(reply);
}
} else {
item = this.commandQueue.shift();
if (!item) {
return this.emit('error',
new Error('Command queue state error. If you can reproduce this, please report it. Last reply: ' +
reply.toString()));
}
if (Command.checkFlag('ENTER_SUBSCRIBER_MODE', item.command.name)) {
this.condition.subscriber = new SubscriptionSet();
this.condition.subscriber.add(item.command.name, reply[1].toString());
if (!fillSubCommand(item.command, reply[2])) {
this.commandQueue.unshift(item);
}
} else if (Command.checkFlag('EXIT_SUBSCRIBER_MODE', item.command.name)) {
if (!fillUnsubCommand(item.command, reply[2])) {
this.commandQueue.unshift(item);
}
} else {
item.command.resolve(reply);
}
}
function fillSubCommand(command, count) {
if (typeof command.remainReplies === 'undefined') {
command.remainReplies = command.args.length;
}
if (--command.remainReplies === 0) {
command.resolve(count);
return true;
}
return false;
}
function fillUnsubCommand(command, count) {
if (typeof command.remainReplies === 'undefined') {
command.remainReplies = command.args.length;
}
if (command.remainReplies === 0) {
if (count === 0) {
command.resolve(reply[2]);
return true;
}
return false;
}
if (--command.remainReplies === 0) {
command.resolve(reply[2]);
return true;
}
return false;
}
};
|
"use strict";
var domain = require("domain"),
util = require("util"),
Room = require("../models/Room"),
ScoresList = require("../models/ScoresList");
// Private helpers.
function bySession(session, room) {
return room.session === session;
}
function updateScoreOnlyForPlayer(nick, score, player) {
if (player.nick === nick) {
player.score = score;
return false;
}
return true;
}
// Constructor.
function Commands(rooms, scores) {
this.roomsProvider = rooms;
this.scoresProvider = scores;
}
// Public methods.
Commands.prototype.createRoom = function (roomName, player, continuation) {
var newRoom = new Room(roomName);
newRoom.addPlayer(player);
this.roomsProvider.add(newRoom, function (error) {
/* istanbul ignore if: Untestable */
if (error) {
continuation(error);
return;
}
continuation(null, newRoom.session);
});
};
Commands.prototype.deleteRoom = function (session, continuation) {
this.roomsProvider.remove(session, continuation);
};
Commands.prototype.joinRoom = function (session, player, continuation) {
var owner = this,
handler = domain.create();
handler.on("error", continuation);
this.roomsProvider.get(handler.intercept(function (results) {
results = results.filter(bySession.bind(null, session))[0];
if (results) {
results.addPlayer(player);
owner.roomsProvider.atomicUpdate(session, results, handler.intercept(function () {
continuation(null, results);
}));
} else {
continuation(new Error(util.format("There is no session '%s'!", session)));
}
}));
};
Commands.prototype.leaveRoom = function (session, player, continuation) {
var owner = this,
handler = domain.create();
handler.on("error", continuation);
this.roomsProvider.get(handler.intercept(function (results) {
results = results.filter(bySession.bind(null, session))[0];
if (results) {
results.removePlayer(player.nick);
owner.roomsProvider.atomicUpdate(session, results, handler.intercept(function () {
continuation(null, results);
}));
} else {
continuation(new Error(util.format("There is no session '%s'!", session)));
}
}));
};
Commands.prototype.lockRoom = function (session, continuation) {
var owner = this,
handler = domain.create();
handler.on("error", continuation);
this.roomsProvider.get(handler.intercept(function (results) {
results = results.filter(bySession.bind(null, session))[0];
if (results) {
if (results.available) {
results.lock();
owner.roomsProvider.atomicUpdate(session, results, handler.intercept(continuation));
} else {
continuation(new Error(util.format("Session '%s' is already unavailable!", session)));
}
} else {
continuation(new Error(util.format("There is no session '%s'!", session)));
}
}));
};
Commands.prototype.updateScore = function (session, nick, score, continuation) {
var owner = this,
handler = domain.create();
handler.on("error", continuation);
this.roomsProvider.get(handler.intercept(function (results) {
results = results.filter(bySession.bind(null, session))[0];
if (results) {
if (!results.available) {
results.players.every(updateScoreOnlyForPlayer.bind(null, nick, score));
owner.roomsProvider.atomicUpdate(session, results, handler.intercept(function () {
continuation(null, score);
}));
} else {
continuation(new Error(util.format("Session '%s' was not locked!", session)));
}
} else {
continuation(new Error(util.format("There is no session '%s'!", session)));
}
}));
};
Commands.prototype.closeContest = function (session, continuation) {
var owner = this,
handler = domain.create();
handler.on("error", continuation);
this.roomsProvider.get(handler.intercept(function (results) {
results = results.filter(bySession.bind(null, session))[0];
if (results) {
if (!results.available) {
owner.scoresProvider.add(new ScoresList(results), handler.intercept(continuation));
} else {
continuation(new Error(util.format("Session '%s' was not locked!", session)));
}
} else {
continuation(new Error(util.format("There is no session '%s'!", session)));
}
}));
};
module.exports = exports = Commands; |
declare module 'history' {
declare type HistoryOptions = Object;
declare type Action = 'PUSH' | 'REPLACE' | 'POP';
declare type Hash = string;
declare type Href = string;
declare type Path = string;
declare type Pathname = string;
declare type Query = Object;
declare type Search = string;
declare type LocationKey = string;
declare type LocationState = ?Object;
declare type Location = {
pathname: Pathname;
search: Search;
query: Query;
state: LocationState;
action: Action;
key: LocationKey;
};
declare type LocationDescriptorObject = {
pathname: Pathname;
search?: Search;
query?: Query;
state?: LocationState;
};
declare type LocationDescriptor = LocationDescriptorObject | Path;
declare type LocationListener = (location: Location) => void;
declare type TransitionHook = (location: Location, callback: ?Function) => any;
declare type History = {
listenBefore: (hook: TransitionHook) => Function,
listen: (listener: LocationListener) => Function,
transitionTo: (location: Location) => void,
push: (location: LocationDescriptor) => void,
replace: (location: LocationDescriptor) => void,
go: (n: number) => void,
goBack: () => void,
goForward: () => void,
createKey: () => LocationKey,
createPath: (location: LocationDescriptor) => Path,
createHref: (location: LocationDescriptor) => Href,
createLocation: (location: LocationDescriptor, action: ?Action, key: ?LocationKey) => Location
};
declare type BeforeUnloadHook = () => ?string;
declare type CreateHistory = (options: ?HistoryOptions) => History;
declare type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory;
}
|
test("activate navigation tabs", function() {
$('#lineup .js-tabitem').each(function() {
$(this).trigger('click');
var $that = $(this);
ok($that.hasClass('t-tab__navitem--active'),
'The clicked navigation item has the correct active class');
$('.js-tabitem').not($that).each(function() {
ok(!$(this).hasClass('t-tab__navitem--active'),
'Inactive item does not have active class');
});
});
}); |
var inflection = require('../app/lib/inflection');
var fs = require('fs');
var path = require('path');
var fileExists = fs.existsSync || path.exists;
/**
* Some TrinteBridge method that will server requests from
* routing map to application
*
* @param {String} namespace
* @param {String} controller
* @param {String} action
* @return {Function} responseHandler
*/
function TrinteBridge(namespace, controller, action) {
var responseHandler;
if (typeof action === 'function') {
return action;
}
try {
if (/\//.test(controller)) {
var cnts = controller.split('/');
namespace = cnts[0] + '/';
controller = cnts[1];
}
namespace = typeof namespace === 'string' ? namespace.toString().toLowerCase() : '';
controller = controller.pluralize().capitalize();
var crtRoot = './../app/controllers/';
['', 'es', 'ses'].forEach(function (prf) {
var ctlFile = crtRoot + namespace + controller + prf + 'Controller';
if (fileExists(path.resolve(__dirname, ctlFile) + '.js')) {
responseHandler = require(ctlFile)[action];
}
});
} catch (e) {
// console.log( 'Error Route Action: ' + action );
console.log(e);
}
if (!responseHandler) console.log('Bridge not found for ' + namespace + controller + '#' + action);
return responseHandler || function (req, res) {
res.send('Bridge not found for ' + namespace + controller + '#' + action);
};
}
/**
* Routing map drawer. Encapsulates all logic required for drawing maps:
* namespaces, resources, get, post, put, ..., all requests
*
* @param {Object} app - TrinteJS application
* routing map to application
*/
function Resource(app) {
if (!(this instanceof Resource)) return new Resource(app, TrinteBridge);
this.app = app;
this.use = app.use;
this.bridge = TrinteBridge;
this.paths = [];
this.ns = '';
this.globPath = '/';
this.pathTo = {};
this.dump = [];
this.middlewareStack = [];
this.middleware = [];
this.inflection = inflection;
}
/**
* Calculate url helper name for given path and action
*
* @param {String} path
* @param {String} action
* @return {String} helperName
*/
Resource.prototype.urlHelperName = function (path, action) {
if (path instanceof RegExp) {
path = path.toString().replace(/[^a-z]+/ig, '/');
}
// handle root paths
if (path === '' || path === '/') return 'root';
// remove trailing slashes and split to parts
path = path.replace(/^\/|\/$/g, '').split('/');
var helperName = [];
path.forEach(function (token, index, all) {
// skip variables
if (token[0] === ':' || token === 'subdomain') return;
var nextToken = all[index + 1] || '';
// current token is last?
if (index === all.length - 1) {
token = token.replace(/\.:format\??$/, '');
if (token === action) {
helperName.unshift(token);
return;
} else {
}
}
if ((nextToken[0] === ':' && nextToken !== ':from-:to.:format?') || nextToken === 'new.:format?') {
token = token.singularize() || token;
} else if (action === 'destroyall') {
token = token.pluralize() || token;
}
switch (action) {
case 'create':
case 'show':
case 'destroy':
case 'update':
helperName.unshift(action);
break;
case 'destroyall':
helperName.unshift('destroy');
break;
case 'index':
if (/:from/.test(nextToken)) {
helperName.unshift('paging');
}
break;
default:
}
helperName = helperName.filter(function (el, i, a) {
if (i === a.indexOf(el))return 1;
return 0;
});
helperName.push(token);
});
return helperName.join('_');
};
/**
* Resource root url
* @param {Function} handler
* @param {Function|Array} middleware
* @param {Object} options
*/
Resource.prototype.root = function (handler, middleware, options) {
this.get('/', handler, middleware, options);
};
/**
* Set router middleware
* @param {Function} handler
* @param {Function|Array} middleware
* @param {Object} options
*/
Resource.prototype.use = function (middleware) {
// only accept functions in before filter when it's an array
if (middleware instanceof Array) {
var beforeFilterFunctions = middleware.filter(function (filter) {
return (typeof filter === 'function');
});
middleware = beforeFilterFunctions.length > 0 ? beforeFilterFunctions : null;
for (var i = 0; i < middleware.length; i += 1) {
this.middlewareStack.push(middleware[i]);
}
} else if (typeof middleware === 'function') {
this.middlewareStack.push(middleware);
}
};
/**
* Map methods for router
*/
['get', 'post', 'put', 'delete', 'all'].forEach(function (method) {
Resource.prototype[method] = function (subpath, handler, middleware, options) {
var controller, action, path;
if (typeof handler === 'string') {
controller = handler.split('#')[0];
action = handler.split('#')[1];
} else if (typeof handler === 'function') {
action = handler;
}
if (typeof subpath === 'string') {
path = this.globPath + subpath.replace(/^\/|\/$/, '');
} else { // regex???
path = subpath;
}
// only accept functions in before filter when it's an array
if (middleware instanceof Array) {
var beforeFilterFunctions = middleware.filter(function (filter) {
return (typeof filter === 'function');
});
middleware = beforeFilterFunctions.length > 0 ? beforeFilterFunctions : null;
}
if (!(typeof middleware === 'function' || (middleware instanceof Array)) && typeof options === 'undefined') {
options = middleware;
middleware = null;
}
if (!options) {
options = {};
}
path = options.collection ? path.replace(/\/:.*_id/, '') : path;
var args = [path];
if (middleware) {
args = args.concat(this.middlewareStack.concat(middleware));
} else if (this.middlewareStack.length) {
args = args.concat(this.middlewareStack);
}
if (typeof controller === 'undefined' && typeof action === 'undefined') {
if (handler instanceof Array) {
middleware = [];
for (var i in handler) {
if (i < (handler.length - 2)) {
middleware.push(handler[i]);
} else {
action = handler[i];
}
}
args = args.concat(this.middlewareStack.concat(middleware));
}
}
args = args.concat(this.bridge(this.ns, controller, action, options));
this.dump.push({
helper: options.as || this.urlHelperName(path, action),
method: method,
path: path,
file: this.ns + controller,
name: controller,
action: action
});
this.addPath(path, action, options.as);
this.app[method].apply(this.app, args);
if (method.toLowerCase() === 'get' && action === 'index') {
/(.*).:format?/i.test(path);
var pagingPath = RegExp.$1 + '/:from-:to.:format?';
// options.as = 'paging_' + controller;
this.dump.push({
helper: options.as || this.urlHelperName(pagingPath, action),
method: method,
path: pagingPath,
file: this.ns + controller,
name: controller,
action: action
});
this.addPath(pagingPath, action, options.as);
args[0] = pagingPath;
this.app[method].apply(this.app, args);
}
};
});
/**
* Add path helper to `pathTo` collection
* @param {String} templatePath
* @param {Function} action
* @param {String} helperName
*/
Resource.prototype.addPath = function (templatePath, action, helperName) {
var app = this.app;
if (templatePath instanceof RegExp) {
// TODO: think about adding to `path_to` routes by reg ex
return;
}
var paramNames = [];
var paramsLength = templatePath.match(/\/:\w*|\-:\w*/g);
if (paramsLength) {
paramNames = paramsLength.map(function (p) {
return p.substr(2);
});
}
paramsLength = paramsLength === null ? 0 : paramsLength.length;
// /\/:\w*\?/
var optionalParamsLength = templatePath.match(/:\w*/g);
if (optionalParamsLength) {
optionalParamsLength = optionalParamsLength ? optionalParamsLength.length : 0;
}
helperName = helperName || this.urlHelperName(templatePath, action);
// already defined? not need to redefine
if (helperName in this.pathTo) return;
this.pathTo[helperName] = function (objParam) {
// TODO: thing about removing or rewriting it
// if (arguments.length < (paramsLength - optionalParamsLength) || ) {
// return '';
// throw new Error('Expected at least ' + paramsLength + ' params for build path ' + templatePath + ' but only ' + arguments.length + ' passed');
// }
var value, arg, path = templatePath;
for (var i = 0; i < paramsLength; i += 1) {
value = null;
arg = arguments[i];
if (arg && typeof arg.toParam === 'function') {
value = arg.toParam();
} else if (arg && typeof arg === 'object' && arg.id && arg.constructor.name !== 'ObjectID') {
value = arg.id;
} else if (paramNames[i] && objParam && objParam[paramNames[i]]) {
value = objParam[paramNames[i]];
} else {
value = arg && arg.toString ? arg.toString() : arg;
}
var matchOptional = path.match(/:(\w*\??)/);
if (matchOptional && matchOptional[1].substr(-1) === '?' && !value) {
path = path.replace(/\/:\w*\??/, '');
} else {
path = path.replace(/:\w*\??/, '' + value);
}
}
if (arguments[paramsLength]) {
var query = [];
for (var key in arguments[paramsLength]) {
if (key === 'format' && path.match(/\.:format\??$/)) {
path = path.replace(/\.:format\??$/, '.' + arguments[paramsLength][key]);
} else {
query.push(key + '=' + arguments[paramsLength][key]);
}
}
if (query.length) {
path += '?' + query.join('&');
}
}
path = path.replace(/\.:format\?/, '');
// add ability to hook url handling via app
if (this.app.hooks && this.app.hooks.path) {
this.app.hooks.path.forEach(function (hook) {
path = hook(path);
});
}
var appprefix = '';
if (app.path) {
appprefix = app.path();
} else {
appprefix = app.set('basepath') || '';
}
return appprefix + path;
}.bind(this);
this.pathTo[helperName].toString = function () {
return this.pathTo[helperName]();
}.bind(this);
};
/**
* Resources mapper
*
* @param {String} name
* @param {Object} params
* @param {Function|Array} actions
*
* Example
* map.resources('users');
*/
Resource.prototype.resources = function (name, params, actions) {
var self = this;
// params are optional
params = params || {};
// if params arg omitted, second arg may be `actions`
if (typeof params === 'function') {
actions = params;
params = {};
}
if (!params.middleware) {
params.middleware = [];
}
params.middleware = self.middlewareStack.concat(params.middleware);
params.appendFormat = ('appendFormat' in params) ? params.appendFormat : true;
// If resource uses the path param, it's subroutes should be
// prefixed by path, not the resource's name
// i.e.:
// map.resource('users', {path: ':username'}, function(user) {
// user.resources('posts);
// });
//
// /:username/posts.:format?
// /:username/posts/new.:format?
// etc.
var prefix = params.path ? params.path : name;
// calculate set of routes based on params.only and params.except
function getActiveRoutes(params) {
var activeRoutes = {},
availableRoutes =
{
'index': 'GET /',
'create': 'POST /',
'new': 'GET /new',
'edit': 'GET /:id/edit',
'destroy': 'DELETE /:id',
'update': 'PUT /:id',
'show': 'GET /:id',
'destroyall': 'DELETE /'
},
availableRoutesSingleton =
{
'show': 'GET /show',
'create': 'POST /',
'new': 'GET /new',
'edit': 'GET /edit',
'destroy': 'DELETE /',
'update': 'PUT /',
'destroyall': 'DELETE /'
};
if (params.singleton) {
availableRoutes = availableRoutesSingleton;
}
// 1. only
if (params.only) {
if (typeof params.only === 'string') {
params.only = [params.only];
}
params.only.forEach(function (action) {
if (action in availableRoutes) {
activeRoutes[action] = availableRoutes[action];
}
});
}
// 2. except
else if (params.except) {
if (typeof params.except === 'string') {
params.except = [params.except];
}
for (var action1 in availableRoutes) {
if (params.except.indexOf(action1) === -1) {
activeRoutes[action1] = availableRoutes[action1];
}
}
}
// 3. all
else {
for (var action2 in availableRoutes) {
activeRoutes[action2] = availableRoutes[action2];
}
}
return activeRoutes;
}
// we have bunch of actions here, will create routes for them
var activeRoutes = getActiveRoutes(params);
// but first, create subroutes
if (typeof actions === 'function') {
if (params.singleton) {
self.subroutes(prefix, actions); // singletons don't need to specify an id
} else {
var sname = name.singularize() || name;
self.subroutes(prefix + '/:' + sname + '_id', actions);
}
}
function makeRoute(action) {
var route = activeRoutes[action].split(/\s+/);
var method = route[0];
var path = route[1];
// append format
if (params.appendFormat !== false) {
if (path === '/') {
path = '.:format?';
} else {
path += '.:format?';
}
}
// middleware logic (backward compatibility)
var middlewareExcept = params.middlewareExcept, skipMiddleware = false;
if (middlewareExcept) {
if (typeof middlewareExcept === 'string') {
middlewareExcept = [middlewareExcept];
}
middlewareExcept.forEach(function (a) {
if (a === action) {
skipMiddleware = true;
}
});
}
// params.path setting allows to override common path component
var effectivePath = (params.path || name) + path;
var controller = params.controller || name;
function getParams(action, params) {
var p = {};
var plural = true;// action === 'index' || action === 'create';
if (params.as) {
p.as = plural ? params.as : params.as.singularize();
p.as = self.urlHelperName(self.globPath + p.as);
if (action === 'new' || action === 'edit') {
p.as = action + '_' + p.as;
}
}
if (params.path && !p.as) {
var aname = plural ? name : name.singularize();
aname = self.urlHelperName(self.globPath + aname);
p.as = action === 'new' || action === 'edit' ? action + '_' + aname : aname;
}
if ('state' in params) {
p.state = params.state;
}
return p;
}
// and call map.{get|post|update|delete}
// with the path, controller, middleware and options
self[method.toLowerCase()].call(
self,
effectivePath,
controller + '#' + action,
skipMiddleware ? [] : params.middleware,
getParams(action, params)
);
}
// now let's walk through action routes
for (var action in activeRoutes) {
makeRoute(action);
}
};
/**
* Make Resource.
*
* @param {String} name
* @param {Object} params
* @param {Function} actions
* @returns {Resource}
*/
Resource.prototype.resource = function (name, params, actions) {
var self = this;
// params are optional
params = params || {};
// if params arg omitted, second arg may be `actions`
if (typeof params === 'function') {
actions = params;
params = {};
}
params.singleton = true;
return self.resources(name, params, actions);
};
/**
* Namespaces mapper.
*
* @param {String} name
* @param {Object} options
* @param {String} subroutes
*
* Example:
* map.namespace('admin', function (admin) {
* admin.resources('user');
* });
*/
Resource.prototype.namespace = function (name, options, subroutes) {
if (typeof options === 'function') {
subroutes = options;
options = {};
}
if (options && typeof options.middleware === 'function') {
options.middleware = [options.middleware];
}
// store previous ns
var oldNS = this.ns, oldGlobPath = this.globPath, prefix = '';
if (options && options.subdomain) {
prefix = 'subdomain/';
}
// add new ns to old (ensure tail slash present)
this.ns = oldNS + name.replace(/\/$/, '') + '/';
this.globPath = oldGlobPath + prefix + name.replace(/\/$/, '') + '/';
if (options && options.middleware) {
this.middlewareStack = this.middlewareStack.concat(options.middleware);
}
subroutes(this);
if (options && options.middleware) {
options.middleware.forEach([].pop.bind(this.middlewareStack));
}
this.ns = oldNS;
this.globPath = oldGlobPath;
};
/**
* Make subroutes.
*
* @param {String} name
* @param {Function} subroutes
* @returns {String}
*/
Resource.prototype.subroutes = function (name, subroutes) {
// store previous ns
var oldGlobPath = this.globPath;
// add new ns to old (ensure tail slash present)
this.globPath = oldGlobPath + name.replace(/\/$/, '') + '/';
subroutes(this);
this.globPath = oldGlobPath;
};
/**
* Load routing map from module at `path`. Module should have `routes` function
* or export single function:
*
* @param {String} path
* @param {Function} customBridge
*
* module.exports = function (map) {
* map.resources('books');
* });
*/
Resource.prototype.addRoutes = function (path, customBridge) {
var map = this, bridge;
var routes = require(path);
routes = routes.routes || routes;
if (typeof routes !== 'function') {
throw new Error('Routes is not defined in ' + path);
}
// temporarily change bridge
if (customBridge) {
bridge = map.bridge;
map.bridge = customBridge;
}
var r = routes(map);
if (customBridge) {
map.bridge = bridge;
}
return r;
};
exports.Resource = Resource; |
import BaseProxy from './BaseProxy';
class Auth extends BaseProxy {
constructor(parameters = {}) {
super('/api/v1', parameters);
}
async login(params = {}) {
return this.submit('post', '/login', params);
}
async register(params = {}) {
return this.submit('post', '/register', params);
}
async passwordEmail(params = {}) {
return this.submit('post', '/password/email', params);
}
async resetPassword(params = {}) {
return this.submit('post', '/reset/password', params);
}
async getCurrent() {
return this.submit('get', '/user/current');
}
}
export default Auth;
|
var bbt = require('beebotte');
var Pubsub = require('../lib/eventchannel');
var bclient = new bbt.Connector({
keyId: process.env.NODE_BEEBOTTEB_ACCESS_KEY,
secretKey: process.env.NODE_BEEBOTTEB_SECRET_KEY
});
var variables = {
t: 'temperature', //temperature
h: 'humidity', //humidity
l: 'light', //light
s: 'sound', //sound
m: 'movement', //motion
u: 'ultrasound_ranger' //ultra sound ranger
};
module.exports = function register(app, server){
Pubsub.on('live-tracker', function(data){
data = data || [];
if(!Array.isArray(data)) data = [data];
var sent = {};
data.map(sendValues);
function sendValues(values){
// console.log('VALUES', JSON.stringify(values, null, 4));
Object.keys(values).map(function(key){
if(!variables.hasOwnProperty(key)) return;
if(sent.hasOwnProperty(key)) return;
sent[key] = true;
if(key === 'm') values[key] = !!values[key];
console.log('SENDING', variables[key], values[key]);
bclient.write({
channel: 'sensornet',
resource: variables[key],
data: values[key]
}, function(err, res) {
if(err) console.log(err);
});
});
}
});
};
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class AndroidSubway extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M256,48c-93.864,0-176,10.668-176,85.334v213.332c0,41.604,33.062,74.666,74.667,74.666L128,448v16h256v-16l-26.667-26.668
c41.604,0,74.667-33.062,74.667-74.666V133.334C432,58.668,349.864,48,256,48z M160,384c-18.136,0-32-13.865-32-32
c0-18.137,13.864-32,32-32s32,13.863,32,32C192,370.135,178.136,384,160,384z M240,240H128v-96h112V240z M352,384
c-18.136,0-32-13.865-32-32c0-18.137,13.864-32,32-32s32,13.863,32,32C384,370.135,370.136,384,352,384z M384,240H272v-96h112V240z
"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M256,48c-93.864,0-176,10.668-176,85.334v213.332c0,41.604,33.062,74.666,74.667,74.666L128,448v16h256v-16l-26.667-26.668
c41.604,0,74.667-33.062,74.667-74.666V133.334C432,58.668,349.864,48,256,48z M160,384c-18.136,0-32-13.865-32-32
c0-18.137,13.864-32,32-32s32,13.863,32,32C192,370.135,178.136,384,160,384z M240,240H128v-96h112V240z M352,384
c-18.136,0-32-13.865-32-32c0-18.137,13.864-32,32-32s32,13.863,32,32C384,370.135,370.136,384,352,384z M384,240H272v-96h112V240z
"></path>
</g>
</IconBase>;
}
};AndroidSubway.defaultProps = {bare: false} |
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './CatalogItems.css';
import Link from '../Link';
class Park extends React.Component {
constructor(props) {
super(props);
this.state={
park: []
}
}
componentDidMount() {
fetch('http://maysternja.dataroot.co/catalog/park/')
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({
park: json
})
});
}
render() {
return (
<div className={s.park_container}>
<div className={s.inner_park_container}>
<p>Складні архітектурні вироби</p>
<div className={s.inner_parkr_container_wrapper}>
<div className={s.inner_park_container_wrapper_image}>
{this.state.park.map(function(park, index){
return(
<div className={s.image_container} key={index}>
<img src={park.img} alt={park.alt} />
</div>)})}
</div>
</div>
</div>
</div>
);
}
}
export default withStyles(s)(Park); |
var cloneSteal = function(System){
var loader = System || this.System;
var steal = makeSteal(loader.clone());
steal.loader.set("@steal", steal.loader.newModule({
"default": steal,
__useDefault: true
}));
steal.clone = cloneSteal;
return steal;
};
var ArraySet;
if(typeof Set === "function") {
ArraySet = Set;
} else {
ArraySet = function(){ this._items = []; };
ArraySet.prototype.has = function(item) {
return this._items.indexOf(item) !== -1;
};
ArraySet.prototype.add = function(item) {
if(!this.has(item)) {
this._items.push(item);
}
};
}
var makeSteal = function(System){
var addStealExtension = function (extensionFn) {
if (typeof System !== "undefined" && isFunction(extensionFn)) {
if (System._extensions) {
System._extensions.push(extensionFn);
}
extensionFn(System, steal);
}
};
System.set('@loader', System.newModule({
'default': System,
__useDefault: true
}));
System.set("less", System.newModule({
__useDefault: true,
default: {
fetch: function() {
throw new Error(
[
"steal-less plugin must be installed and configured properly",
"See https://stealjs.com/docs/steal-less.html"
].join("\n")
);
}
}
}));
System.config({
map: {
"@loader/@loader": "@loader",
"@steal/@steal": "@steal"
}
});
var configPromise,
devPromise,
appPromise;
var steal = function(){
var args = arguments;
var afterConfig = function(){
var imports = [];
var factory;
each(args, function(arg){
if(isString(arg)) {
imports.push( steal.System['import']( normalize(arg) ) );
} else if(typeof arg === "function") {
factory = arg;
}
});
var modules = Promise.all(imports);
if(factory) {
return modules.then(function(modules) {
return factory && factory.apply(null, modules);
});
} else {
return modules;
}
};
if(System.isEnv("production")) {
return afterConfig();
} else {
// wait until the config has loaded
return configPromise.then(afterConfig,afterConfig);
}
};
System.set("@steal", System.newModule({
"default": steal,
__useDefault:true
}));
System.Set = ArraySet;
var loaderClone = System.clone;
System.clone = function(){
var loader = loaderClone.apply(this, arguments);
loader.set("@loader", loader.newModule({
"default": loader,
__useDefault: true
}));
loader.set("@steal", loader.newModule({
"default": steal,
__useDefault: true
}));
loader.Set = ArraySet;
return loader;
};
// steal.System remains for backwards compat only
steal.System = steal.loader = System;
steal.parseURI = parseURI;
steal.joinURIs = joinURIs;
steal.normalize = normalize;
steal.relativeURI = relativeURI;
steal.addExtension = addStealExtension;
|
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { fetchArticlesIfNeeded, postArticle, viewArticle, changeScreen } from '../actions'
import Article from '../components/Article'
import Articles from '../components/Articles'
import ArticleEditor from '../components/ArticleEditor'
class App extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const { dispatch } = this.props
dispatch(fetchArticlesIfNeeded())
}
handlePublish = (article) => {
const { dispatch } = this.props
dispatch(postArticle({ ...article}))
}
handleView = (id) => {
const { dispatch } = this.props
dispatch(viewArticle(id))
}
handleIndex = () => {
const { dispatch } = this.props
dispatch(fetchArticlesIfNeeded())
dispatch(changeScreen('index'))
}
handleNew = (event) => {
event.preventDefault()
const { dispatch } = this.props
dispatch(changeScreen('new'))
}
render() {
const { items, isFetching, item, currentScreen } = this.props
switch (currentScreen.name) {
case 'index':
return (
<div>
Current Screen: {currentScreen.name}
<div>
<a href="" onClick={this.handleNew}>New Article</a>
</div>
{isFetching && items.length === 0 &&
<h2>Loading...</h2>
}
{!isFetching && items.length === 0 &&
<h2>Empty.</h2>
}
{items.length > 0 &&
<div>
<Articles articles={items} onView={this.handleView} />
</div>
}
</div>
)
case 'view':
return (
<div>
Current Screen: {currentScreen.name}
{isFetching && item === {} &&
<h2>Loading...</h2>
}
{!isFetching && item === {} &&
<h2>Missing.</h2>
}
{item !== {} &&
<div>
<Article article={item} onIndex={this.handleIndex} />
</div>
}
</div>
)
case 'new':
return (
<div>
Current Screen: {currentScreen.name}
<ArticleEditor onPublish={this.handlePublish} onIndex={this.handleIndex} />
</div>
)
default:
return (
<div>{currentScreen.name} screen does not exist</div>
)
}
}
}
App.propTypes = {
items: PropTypes.array.isRequired,
isFetching: PropTypes.bool.isRequired,
item: PropTypes.object.isRequired,
currentScreen: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired
}
function mapStateToProps(state) {
const items = state.articles.items || []
const isFetching = state.articles.isFetching || false
const item = state.articles.item || {}
const currentScreen = state.currentScreen || {}
return {
items,
isFetching,
item,
currentScreen
}
}
export default connect(mapStateToProps)(App)
|
define([
'./km-control-group',
'./km-date',
'./km-document-validation',
'./km-form-languages',
'./km-form-std-buttons',
'./km-form-material-buttons',
'./km-inputtext-list',
'./km-inputtext-ml',
'./km-link',
'./km-notes',
'./km-reference',
'./km-select',
'./km-tab',
'./km-terms-check',
'./km-terms-radio',
'./km-yes-no',
'./km-auto-complete-server-select',
'./km-long-Lat-selector',
'./km-address-block',
'./km-address',
'./select-contact',
'./info-bar',
'css!./info-bar'
], {});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.